Como funciona o algoritmo de criptografia leve LED?

Question: Gostaria de entender melhor o funcionamento do algoritmo LED passo a passo, principalmente o processo de substituição e permutação dos blocos e principalmente o uso das chaves em cada round.
As chaves em cada round são expansões de uma única chave ou são chaves diferentes?
Já consultei as fontes

https://www.cryptolux.org/index.php/Lightweight_Block_Ciphers#Zorro
https://sites.google.com/site/ledblockcipher/design
https://eprint.iacr.org/2012/600.pdf

Mas não consegui encontrar se cada round são expansões ou se são chaves diferentes.
Comment: Não conheço esse algoritmo, mas a primeira referência citada (sobre o LED mesmo, acima da descrição do Zorro) deixa bem claro que ao contrário da maioria das cifras de bloco o LED **não possui** expansão de chaves: "Uma característica interessante desse design é o escalonamento de chaves (ou ausência do mesmo): uma chave de 64 bits tal como está faz o 'ou exclusivo' - xor - com o estado interno, enquanto uma chave de 128 bits é dividida pela metade em duas sub-chaves de 64 bits que são usadas de forma alternada."
Comment: Bem vinda ao StackOverflow em Português =)
Comment: Valeu @Avelino :D
Comment: Obrigada pela observação @mgibsonbr
Answer: Estou pesquisando também sobre o assunto e lendo no [crypto.SO] achei esta reposta interessante, portanto vou adequar aqui, espero que atenda a nós.
Na página 3 da Proposta para o Algoritmo LED diz:

"Note that for a 64-bit key K, all subkeys are equal to K, while for a 128-bit key K, the subkeys are alternatively equal to the left part K^1 and to the right part K^2 of K."

Traduzindo:

Observe que para uma chave de 64-bits k, todas as sub-chaves são iguais a $k$, enquanto para uma chave de 128-bit k, as sub-chaves são alternadamente iguais a parte esquerda de k^1 e a parte direita k^2 de de k.

Basicamente a entrada da chave principal é dividida em lista ordenadas de nibbles, e quando o algoritmo precisa material para sub-chaves ele usa exatamente os nibbles diretamente da lista ordenada -- movendo cada nibble para o final da linha, para que todos os nibbles sejam usados em sucessão. Desde que o algoritmo manipula 64 bits de sub-chaves por vez (16 nibbles), para uma chave principal de 64-bit cada sub-chave  será simplesmente a chave principal, e para chaves de 128-bits o algoritmo usará os primeiros 16 nibbles da chave master, e então a segunda parte, os 16 nibbles restantes, e então o primeiros 16 novamente, e assim por diante. No topo da página 4 mostra o diagrama de como isso funciona para uma chave principal de 80-bits.
Considerando a pergunta original no qual esta resposta foi aplicada, o autor da resposta destaca que as sub-chaves não usadas em 'round' como destacado na questão, mas que entre cada passo, enquanto cada passo é composto de 4 rounds. Cada round consiste de 4 operações, muito similar ao usado no algoritmo AES -- primeiro você executa um xor em um round, então você substitui cada nibble usando uma operação de substituição não linear (o s-box do cipher), você transpõe os nibbles passando então através da mais alta permutação difusa linear, com um alto fator de ramificação (similar ao MixColumns no AES, porém optimizado para nibbles).
Com base na resposta: https://crypto.stackexchange.com/a/26013


How to run selinux sanbdox with access to /dev/urandom

Question: I'm trying to run my application inside an SELinux sandbox.
My application needs access to /dev/urandom, and the default sandbox policy does not allow that.
What is a simple method to allow my sandbox context access to /dev/urandom?
Thanks
Comment: Where did you get this "SELinux sandbox"?
Answer:
What is a simple method to allow my sandbox context access to /dev/urandom?

Any of the following, though the first is ideal.

Change your policy
Change the context of /dev/urandom
Change the context of your process
mknod a new /dev/urandom with  different name and appropriate context. Point your application at that.
Comment: right now I have my process running in the default sandbox_t context. Can I modify the policy to allow access to my process, but not to other sandboxed processes?
Comment: No, you'll have to copy the sandbox_t to another context name, bless the context to read `/dev/urandom`, and run your program in that new context.


Adding class to  based on Id and switch

Question: I have a table representing weekdays (only 5 days at a time). I would like to highlight the day of the week depending on what day it is. I am attempting to use a Switch function to select the element by its Id then add a class. Perhaps someone can identify the problem or provide a more elegant solution. Thank you!
HTML:

  CHANGES
  2
  3
  4
  5
  6

Javascript
// Set "today" to day of week abbreviation
var today = String(Date.today()).slice(0,3);

// Add class to td based on day of week.
switch (today) {
    case "Mon":
        jQuery("#mon").addClass("today");
        break;
    case "Tue":
        jQuery("#tues").addClass("today");
        break;
    case "Wed":
        jQuery("#wed").addClass("today");
        break;
    case "Thu":
        jQuery("#thurs").addClass("today");
        break;
    case "Fri":
        jQuery("#fri").addClass("today");
        break;
}

*Note: I am using Date.js lilbrary to get the current day.
Comment: looks fine - http://jsfiddle.net/arunpjohny/5fap6j2f/1/
Comment: Maybe it's a problem with my CSS. I have already applied styles to the table so would adding a class override the preset table styles?
Comment: I had my script in the wrong place. It worked when I moved it from the head to after the table. Thanks!
Answer: Try this

var today = new Date();
today = today.toString().slice(0,3).toLowerCase();
$('#'+today).addClass('today');
.today{
  color:red;
  }

  CHANGES
  2
  3
  4
  5
  6

You'll need to change the id of thursday to thu and tues to tue
3
5

Comment: This works great! Looks like on of my problems was that I had the script in my . I moved it to after the table and it is functioning properly. Many thanks!
Answer: If you can change HTML, than rename your id's as Mon, Tue, Wed, Thu, Fri, also add class days to all elements and than
var today = String(Date.today()).slice(0,3);
$('.days').removeDay('today');
$('#' + today).addClass('today');

Adding class to  based on Id and switch


Find the smallest number of toys that person had

Question: A person had a number of toys to distribute among children . At first he gave $2$ toys to each child , then $4$ , then $5$ ,and then $6$ , but was always left with one . But if he had given $7$ toys to each child , no toys would have been left with him . What is the smallest number of toys that he had?
Could someone give me hint as how to approach this problem. I am not able to understand it.
Comment: One approach would be to use the [Chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem) but in this case you can speed up the calculations by seeing that if he gave $60$ toys to each child he would have $1$ left over, so you are looking for an multiple of $7$ which is one more than a multiple of $60$
Comment: In other words, take LCM+1
Answer: So, we notice that if the number of toys is $k$, then $k=1\pmod{2}$, $k=1\pmod{4}$, $k=1\pmod{5}$, $k=1\pmod{6}$, and $k=0\pmod{7}$. As noted in the comments, the LCM of these numbers (other than $7$) is $60$, so we also have that $k=1\pmod{60}$. We then want to solve $60a+1=7b$ for integer $a,b$. You can solve this in a number of ways, using Euclid's Algorithm to solve the Diophantine Equiation $-60x+7y=1$.


When do complex number vectors add up to $0$?

Question: I came across a few problems in which three vectors in a triangle(which were also solutions to a cubic equation) or $6$ complex numbers - (heptagon - $7$ roots of unity) added up to $0$. When does this happen? Is it only when the numbers are solutions to an equation?
When do complex number vectors add up to $0$?
Comment: Your question is quite vague. Certainly one can say that three complex numbers add up to zero if they are the solution of the equation $z_1 + z_2 + z_3 = 0$.
Comment: There is nothing mysterious to this. They add up to 0 if and only if their sum is 0. Some such sums are kinda cool because the vanishing is a result of a symmetry. [A simple example](https://math.stackexchange.com/a/1905201/11619) (there of planar vectors, but we can choose to view them as complex roots of unity also).
Comment: Vieta relations do mean that $z_1+z_2+\cdots+z_n=0$ if and only if the numbers $z_i,i=1,2,\ldots,n,$ are the zeros of a polynomial of degree $n$ **without a term of degree $n-1$.**
Answer: Every finite set of complex numbers $\{z_1,z_2,\ldots,z_n\}$ is the set of roots of an equation:
$$ (z - z_1)(z - z_2)\cdots(z - z_n) = 0. $$
To get a set of $n$ complex numbers whose sum is $0,$
begin with any set of $n-1$ complex numbers
$\{z_1,z_2,\ldots,z_{n-1}\}.$
Then set
$$ z_n = -(z_1+z_2+\cdots+z_{n-1}). $$
There are certain highly symmetric sets of complex numbers that form regular polygons around $0$ in the complex plane, and those have interesting equations.
But you don't need any kind of symmetry to have the numbers add up to $0.$
They just need to add that way.


Not able to plug-in a custom cache manager via shared library to Spring Boot Service

Question: I am trying to add caching behaviour to the services using Spring @cacheable annotation and by using a custom cachemanager as part of configuration to enable/disable caching at runtime.
My custom configuration class works fine when used within the service project. But, when I make it part of a shared library and reference it in the service the caching behaviour does not work.
So, I have a shared library which is now referenced by my service. I want to use the shared library to so that I can change the cacheManager strategy by changing to some other cache manager without impacting the service client.
But, now caching does not work.Within the same service it works, but not as a shared library.
I am not sure if some other cache configuration is getting configured automatically or not.
I want to understand if I need to exclude some cache configuration classes or configure my configuration before some other configuration is getting created.
My configuration class is as below. I am using a string object delimited by (,) to create the caches in the class from application configuration.
@Configuration
@EnableCaching
@RefreshScope
@AutoConfigureBefore(CacheAutoConfiguration.class)
public class MyCustomCacheConfig {

/* Flag to Determine if Cache should be Enabled or not for the service */
    @Value("${cacheEnabled}")
    private boolean cacheEnabled;

    /* Name of the caches to be created */
    @Value("${caches}")
    private String caches;

    @Bean
    @Primary
    @RefreshScope
    CacheManager cacheManager() {

        //If Cache is Enabled then swap the cacheManager for SimpleCacheManager
        if (cacheEnabled) {
        List<String> cacheNameList = Arrays.asList(caches.split(","));
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        List<ConcurrentMapCache> conMapList = new ArrayList<>();
        for (int i = 0; i < cacheNameList.size(); i++) {
            conMapList.add(new ConcurrentMapCache(cacheNameList.get(i)));
        }

        cacheManager.setCaches(conMapList);

        return cacheManager;
        }else{
            CacheManager cacheManager = new NoOpCacheManager();
            return cacheManager;
        }

    }
}

I am using the standard spring boot autoconfiguration approach by having the below entry in path src/main/resources/META-INF/spring.factories of my shared library component.
**org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.demo.autoconfigure.MyCustomCacheConfig**

And so, I expect the configuration will be picked up on startup when the service starts up. I have the library added as a dependency to the service pom.xml
Since I have multiple services to which I want to have this feature of switching cache on/off  at run-time,I thought I can make the configuration as a shared library.
I also have shared the complete repository including the service, the caching-component,demo config service and the file base repo in the git repo below,
https://github.com/bsridhar123/cache-demo-repo
Can someone help me in identifying the cause of the issue.
Answer: I got the solution to my issue.
When I added an entry as below in application.properties in the shared library component and built it and referenced it in my service it worked fine.
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration

I also removed the @AutoConfigureBefore annotation I had earlier in my configuration class ins shared library.
Seems like explicitly excluding the autoconfiguration class rather than using the annotatio works,  though I had to add a application.properties to my library.
Answer: In my case, It dosen't work unless I set the application.properties to:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration


Is there a concern for multiple comparisons when ranking instead of using significance?

Question: Let's say I have many ANOVA tests on the same data using different factor variables each time.  Then, I want to rank the F-statistics for all of those tests.  Notice that I'm not interested in measuring significance (as is usually done with test statistics).  Rather, I'm ranking the results.
Is there a concern for multiple comparisons when ranking instead of using significance?
My intuition says yes, there still is a concern.  But I can't confidently back it up.  It seems to me like the $\alpha$ risk of a Type I error is present each time we rank the results, except it isn't always the same value.  So, even thought the value of $\alpha$ isn't always the same, it's still present.  Is this correct rationale to believe that multiple comparisons is still in play?
EDIT:  I just found in Elements of Statistical Learning, on page 79: "Other more traditional packages base the selection on F -statistics, adding "significant" terms, and dropping "non-significant" terms. These are out of fashion, since they do not take proper account of the multiple testing issues."
Comment: Okay, to wrap this up, what are the advantages/disadvantages of correcting for multiple testing and NOT correcting for multiple testing?  Also, have you seen the section in Elements of Statistical Learning I edited into the question?
Comment: What is the purpose of doing this? Deciding, which factors best predict things / ranking them as predictors? There clearly is a multiplicity issue or perhaps rather overfitting issue then and the relative ranking will potentially not be realiable (particularly if some factors are associated with different splits of the total sample size). Certainly, once you get into the realm of wanting to say that any of these factors are relevant (or deciding on this basis how to further analyze this data), you also end up getting a (potentially very severe) traditional type I error problem.
Comment: Yes, ranking the predictors is the application.  This also might simulate what the LASSO regression does, when the predictors are uncorrelated with each other.
Answer: If you are simply ranking the tests for the purposes of deciding which comparisons are of interest, then there is no possibility of a false positive decision and so type I error rates are not a relevant consideration.
If you are ranking the contrasts in order to make claims about some of them then some people would suggest that 'correction' for multiplicity is appropriate. Note, however, that there are many who do not consider adjustments for multiplicity to be 'corrections' so much as nonsense (see these http://www.bio.sdsu.edu/pub/stuart/2012LopsidedReasoning.pdf and http://www.stat.columbia.edu/~gelman/research/published/multiple2f.pdf).
Comment: How would it not be a problem to simply rank "the tests for the purposes of deciding which comparisons are of interest, then there is no possibility of a false positive decision and so type I error rates are not a relevant consideration." ? Surely, you are then potentially conducting all the possible comparisons, but are only picking out the "most signficant" and then doing them? Surely that's the very problem one should be concerned about.
Comment: @Björn In general one should be concerned about making correct inferences, not just with protecting against inflation of type I errors above an arbitrary nominal rate. There certainly are some circumstances where one might consider correction for multiple comparisons, but those circumstances are not those that pertain in an exploratory study intended to rank questions of interest for future investigation. If you don't want to read the full papers I linked, then try my short commentary in the supplementary material here: http://www.tandfonline.com/doi/suppl/10.1080/00031305.2016.1154108
Comment: okay.....now I'm thoroughly confused.
Comment: @Björn Buzzinolops, sorry, but I'm not surprised that you are confused. As far as I am concerned the confusion is a product of discussion between those who believe that multiplicity of comparisons should always be 'corrected' for in order to protect against inflation of type I errors, and those, like me, who feel that protection against inflated type I error rates is important in only some circumstances but always presents costs in terms of power and flexibility of design. It's a tradeoff, but not everyone sees the tradeoff as optional. I assume Björn is among the latter.
Comment: All I am saying is that there is definitely a multiplicity problem. The more things you rank, the more likely it is that you get at least some of the rankings wrong. Whether you you need something like stricty familywise type I error rate control is a totally different topic, of course. However, one cannot have the cake and eat it. I.e. pick out the most "significant" contrast and treat it like the sole contrast in a pre-specified hypothesis testing situation (equivalent to claiming that because the F-statistics are sufficiently apart between this factor a and factor b to be significant).
Comment: That's a pretty common thing, where people bring out some arguments on how multiplicity adjustments are not needed in some circumstances (e.g. like Gelman when you have some hierarchical model, or "it's an exploratory study"), but then pretend after testing any number of hypotheses that they have definite proof for some finding beyond any doubt, because one of 20 p-values is p<0.05.Not saying that you are specifically suggesting this, but it happens a lot... Additionally, correct inference/predictions/modeling are vulnerable to overfitting, which has some similar underlying issues.
Comment: @Björn I think that your suggestion "proof" "beyond doubt" is hyperbolic, and any element of truth that it contains comes from the use of frequentist acceptance methods rather than from evaluation of the evidence. Furthermore, I'm pretty sure that Gelman would be offended by the implication that he might be so naive. (Have you read my commentary on the ASA P-values statement? Its theme is exactly on the topic that we are dancing around here.)
Comment: I don't think your commentary is far away from what I am saying. I am just more concerned about people looking at data with an agenda. I see a lot of: "Treatment vs. control had p<=0.05 [or posterior P(efficacy)>90% etc.] for one comparison out of 10 clinical outcomes & 20 biomarkers, overall and in 20 subgroups. Thus, treatment is proven to be effective." A-priori it may be plausible the treatment works, but do you believe it? I'm not at all implying Gelman or you favor such an approach (in fact Gelman is pretty concerned about people doing that - see his "garden of forking path" articles).


LoadLevel does not work on iOS devices

Question: I used the latest Unity 4 with UnityScript (didn't want to upgrade to Unity 5 before releasing the game, just to avoid complications). Unfortunately, I had to upgrade to iOS 9 and to Xcode 7. The game was built in Unity then opened in Xcode, however during deployment on iPhone I started getting error:
clang: error: linker command failed with exit code 1 (use -v to see invocation)

After upgrading to Unity 5, Xcode deployment to phone works, however on the phone I'm not able to load another scene by clicking on GUI button or with timing, it just doesn't load, however works in the Unity editor.
Is there something wrong with Application.LoadLevel ("NewScene"); or perhaps something else needs to be done or done differently?
Also, for some reason, rotation of the object stopped working in Unity5 (even in editor)
transform.Translate(Vector3.left GameManager.speed/12 Time.deltaTime, Space.World);
GetComponent.().angularVelocity = direction * 500;

Is there anything can be done to fix both issues? Or perhaps I need to downgrade to Unity 4, then how do I fix Xcode error (above)?
Answer: Make sure you scene is included in Build Settings (File -> Build Settings...)
transform.Translate(Vector3.left GameManager.speed/12 Time.deltaTime, Space.World);
GetComponent.().angularVelocity = direction * 500;

This won't even compile because of numerous syntax errors, I bet you wanted something like this:
transform.Translate(Vector3.left * GameManager.speed / 12 * Time.deltaTime, Space.World);
GetComponent<Rigidbody>().angularVelocity = direction * 500;

If this doesn't work make sure you have Rigidbody attached, disabled Rotation Freeze on desired axis and check if direction has any value (not (0,0,0))
Also note that you shouldn't use angularVelocity directly. Unity Documentation states (http://docs.unity3d.com/ScriptReference/Rigidbody-angularVelocity.html):

In most cases you should not modify it directly, as this can result in unrealistic behaviour.

You could use http://docs.unity3d.com/ScriptReference/Rigidbody.AddRelativeTorque.html instead.
Answer: I had the same problem after upgrading to Unity 5.2 & Xcode 7 for iOS 9 , but I had to revert back because of random issues on Unity3d 5.2 of UI , Events Systems in my project.
Go to through below link request for the beta build.
http://forum.unity3d.com/threads/crash-upgrading-to-4-6-8p2-on-application-loadlevel.354899/#post-2315179

LoadLevel does not work on iOS devices


Title in node--article twig template

Question: In node--article.html.twig

  {{ created.content | date("d/m/Y") }}
  {{ content.title }}
  {{ content.body }}

The title is not displaying. How do I do this?
Answer: You can use:
{{ label }} or {{ node.label }} or {{ node.getTitle() }}.

Title in node--article twig template


CKEditor: *During* WYSIWYG edit, how to show caption beneath image?

Question: When editing a body field with image and caption, the caption does not display during editing. Once saved it is visible - when the content is viewed.
Implementation-wise, I've added a caption field to the Image entity via the Entity View Mode config pages - admin/structure/file-types/manage/image/fields
Any thoughts on how to get the caption to show during edit?
CKEditor 4.3 supports captions but there would need to be support for the Drupal side of the implementation.
Comment: Hey, I have two questions: 1) Do you need the caption when you're just attaching the image to the node or when you're embedding it into the body with the CKEditor image button?  And 2) when you say image caption, you're not talking about the image alt attribute, are you?
Comment: Thanks @Boriana for your interest in this question, my answers to your questions: 1) I don't use the image with the node like this, I use the Wysiwyg button for image to embed the image in the edit area. On clicking the button it asks for image source e.g. upload, library, etc. and then the caption. 2) Correct. I've added a caption field to the image entity by visiting the admin page admin/structure/file-types/manage/image/fields as mentioned.
Comment: hi, were u able to find a solution for ckeditor ?
Comment: Not yet. Once edit is complete and the content is saved the caption does appear but it would be nice if it appeared *while* editing. Having looked at few solutions it would appear that most people get stumped with this same issue.
Comment: Sorry to comment on such an old thread - but I'm trying to solve the same problem. I've got the caption working using the blog linked above in media manager itself, but the caption field does not even show if uploading direct through the 'embed media' button in the CKEditor. Did you get this element working in your solution?
Comment: Not a problem at all steve. Unfortunately not. We accepted the limitation. 8 months on from when this question was originally asked, I'm guessing that this is still the case with the current codebase given that you have looked at it about a day ago.
Comment: Have you seen the video at http://vimeo.com/69750074? This is a demo of work being done for Drupal 8 but maybe you could back-port. See https://drupal.org/node/2027181.
Comment: thanks it's a nice idea but I wasn't expecting to do a backport from Drupal 8 to solve my problem. I'd like to but I have limited time. I think I should explore other options, including my own answer before considering doing a backport
Answer: As of CKEditor 4.3, they now have widgets in the CKEditor side. They have introduced the Image2 plugin/widget, which supports image captions. The problem I've seen here is that Drupal has not caught up with this, so if you're using the media module for a file browser, it looks like that functionality is not yet ported to this newer version. However, if you just care about captions, it works.
See: http://ckeditor.com/addon/image2 for the plugin. I've been using it with the CKEditor Module, but it should work just as fine with WYSIWYG + Ckeditor Library.
Answer: After discussing with my colleagues (thanks folks!), their idea for a solution is to write a filter for the JSON generated by the WYSIWYG.
The caption text is present in the JSON. So, extending the existing filter ought to be the solution.
Answer: I've been doing some more research and I gather you have gone down the Media/File Entity/Entity View Modes route as described at http://www.58bits.com/blog/2013/03/06/how-to-add-captions-to-images-in-drupal.
That seems a heck of a lot of work to go to in order to write a caption under an image and it is still not wysiwyg.
So here is another answer using Wysiwyg/TinyMCE and the dev version of Caption Filter. See discussion at https://drupal.org/node/696734. (Edit. There was some work done on integrating with CKEditor too but I don't think this has been committed although there are some patches, should it be important for you to stick with CKEditor.)
The upshot is as shown below. I was pleased to find I could put html in the caption.
Comment: Thanks a lot but it does have to be CKEditor. I'm getting a little bit closer to a solution that involves media module filtering, either in its js or php.
Answer: There are conflicts between the CKeditor Image2 plugin and Media module. If you're looking to align + caption your images while maintaining the media tag in your WYSIWYG, the most current recipe can be found here: https://www.drupal.org/node/2843391


wireless access point location relative to switches and other routers

Question: any chance that wireless access point, wrt54g type with ddwrt, could cause a cisco router to go buggy and drop dhcp requests and other network issues?
looking for some advice as the units are within a foot of each other and this is turning into a blame game between two companies that installed the equipment.
thanks
gd
Answer: Are these hooked into the same network in anyway (wrt54g goes into the same switch as the router, or the router itself)?  If that is the case, maybe you have some IP conflicts.  If they are both in the same broadcast domain, and are both running dhcp, then when clients request IP addresses you don't know which will answer.
Since the dhcp servers won't know who is given what, you might end up with duplicate IPs.
Physically, the would not interfere with each other.
Comment: if ever there was a site that had a router and  a wifi box i would have turned off the dhcp scope on the wifi unit and made it a switch or just ap. there is no chance of ip conflicts, as well the layout is that one company has a cisco router and the other company has a wifi router box, they are seperate networks and isp setups. the complaint from the company that has the cisco box is that the wifi router, about 2.5 feet away, is causing their dhcp scope to not work on the mitel ip phones. i thought it was just an excuse for another issue they can't fix. thanks.
Answer: Logically, if configs are conflicting, sure. Physically located next to each other, I doubt it, unless the Linksys has some hardware malfunctioning in it. Is it possible to just shut off the Linksys temporarily?
Comment: that is my next step when i am back on site, i just wanted some feedback from others since i have these types of devices at over 100 locations without ever having an issue.gd
Answer: I once had a device with a flakey powersupply.  I don't understand exactly why, but it caused issues with other devices plugged into the same power distribution unit.  So, if they are plugged into the same circuit, it is possible you might see something there, but I don't see where the physical location of a Wireless AP would affect a non-wireless device.
THe other issue I have seen, is if a client has a wired and wireless connection, and the connections are set to Bridge for some reason,  you can get all kinds of wierd IP duplications with some hardware based DHCP servers.  My case was a SonicWall Firewall that I was using as a DHCP, and every time this one consultant was is in the office, I'd start getting IP conflict errors all over the network.  The issue was traced back to the consultant's laptop creating a second path in the network that messed with the processing of DHCP requests and acknowledgements.
Comment: just an update for everyone, there is no ip conflict, it is just dhcp scopes that don't work on one network, i really think it is something on their cisco box and they are just using the wifi unit as an excuse claiming rf interference.gd
Comment: You say in another comment that they are two separate networks, for two companies.  So I'm guessing that they share a phone closet in an office building or something.  Is it possible that someone plugs a patch cable between the two?
Comment: yes they do share the same location. they are not physically connected. the phone IT company says that the wifi box, being in close proximity rf-wise, is causing the cisco router to flub up. they are basically blaming wifi rf interference on the reason why the ip phones act up. this is why i was saying that it is more than likely their cisco hardware or linksys poe switch that is buggy. they are just looking for something to blame. i hope this makes sense now.gd
Answer: If these devices are 1 foot apart, how long is the patch cable connecting the wireless router to the network?  If it is running FastEthernet, there is a minimum 3 feet requirement for patch cables.  Anything shorter can cause network connectivity problems.  If it is connected to Gigabit, this "rule" doesn't apply, but should still be followed.  I would make sure there is a 10 foot patch cable connecting the wireless router to the network.
Comment: i thought fastethernet solved the "carrier sense multiple access with collision" issue.?
gd
Comment: No, 100Base-TX is a problem as well.  Here is the excerpt from Wikipedia.

All copper Ethernet segments that run the Collision Detect (CD) portion of CSMA/CD have a minimum cable length to function properly because of reflections. This applies only to 10BASE-T and 100BASE-TX standards; The 1000BASE-TX standard is covered at the end of this section.

http://en.wikipedia.org/wiki/Ethernet_physical_layer#Ethernet_minimum_cable_lengths


Tight And Simple Upper Bound for $\sum_{k=1}^N \frac 1 {ak^n - b}$ for arbitrary $n > 0$ and large $N$

Question: I wonder how to find a tight and simple upper bound for
$$\sum_{k=1}^N \frac 1 {ak^n - b}$$
What I thought to use was an integration comparison test
\begin{align}
\sum_{k=1}^{N} \frac 1 {ak^n - b} &\leq \int_{1}^{N} \frac 1 {a(x-1)^2 - b} dx \\
&= \left[ - \frac{\ln \left|\sqrt{\frac ab} (x-1) + 1\right| - \ln \left|\sqrt{\frac ab} (x-1) - 1\right|}{2\sqrt {ab}} \right]_{1}^N \\
&= - \frac{\ln \left|\sqrt{\frac ab} (N-1) + 1\right| - \ln \left|\sqrt{\frac ab} (N-1) - 1\right|}{2\sqrt {ab}}
\end{align}
If $n=2$. I find it hard to further simplify this expression for a polynomial form. Is there a better or simple way of developing the bound?
Comment: $x$ usualy denotes a real variable. It would be better to use, e.g., $k$ in place of $x$. You could also factor out $b\neq 0$ and call $a/b$ something (e.g., $c$).
Comment: It seems that your upper bound is negative which is a bit surprising. If $a>b$, you sum is positive.
Answer: If you want to use $$\sum_{k=1}^{N} \frac 1 {k^n - c} \leq \int_{1}^{N} \frac {dx} {(x-1)^n - c} =I $$ the integral is given in terms of the Gaussian hypergeometric function
$$I=\frac {N-1}c \,\,\, _2F_1\left(1,\frac{1}{n};1+\frac{1}{n};\frac{(N-1)^n}{c}\right)$$
But I think that you could compute the summations writing
$$k^n-c=\prod_{m=1}^n(k-r_m)$$ Using partial fraction decomposition
$$\frac 1{k^n-c}=\sum_{m=1}^n \frac {A_m}{k-r_m}$$ and using generalized harmonic numbers
$$\sum_{k=1}^{N} \frac 1 {k - r_m}=H_{N-r_m}-H_{-r_m}$$
Comment: Shouldn't you have $n$ in the integral somewhere? (And only one $dx$.)
Comment: Hi thanks for answering. It seems that this work only for integer $n$. What happens if it is more general like rational number. Is it still doable to develop the bound?


Legalese: What is a "live operating environment" (EULA)?

Question:
Possible Duplicate:
Can you help me with my software licensing question?

In the Windows 7 RC EULA, what is meant by "use ... in a live operating environment"?
I don't know if I am "in a live operating environment" or not. Has anyone encountered this question before?
In response to fretje, what would a "live environment" for a student at university be? Then, I probably shouldn't install it, "test" whether or not Office 2007 Home and Student installs ok, and then start blogging with it, posting to SO, and watching streaming anime pretty much daily? Should I not write emails to professors and type my term papers from within Windows 7?
Response: Thank you all for your wonderful responses so far. Many of you are hitting on the exact gem of why I ask this question: I hadn't tried Windows 7 yet, but it seemed like everyone was doing it, so I might as well, too. Hey, a new OS that's good 'til March, free? OK! But then I read the EULA, and it forbids running in a live operating environment. Where were all these success stories, and raves and reviews coming from? Most that I read seemed not to be coming from "solely for testing compatibility for upgrade path" machines. Sure, NVIDIA is testing rolling out their drivers, but this seems like a big gray area. If I make business contacts through email while utilizing the Windows 7 UI to organize my contacts, am I using Windows for business? I don't think anyone really knows.
It seems that there are plenty of scenarios which definitely fall off of the "not live environment end", and into the "definitely live environment" description:

Running a Web server such as IIS or others, especially if including Web applications, as an always-on, public, consumer-serving full-fledged server.
Deploying Windows 7 across the office onto X number of workstations to go about serious business.

Likewise, there are many innocent, harmless scenarios that seem pretty safely covered by the terms of the EULA:

Installing Windows 7. Period. Do the drivers work? Can I install my hardware? What is the install process like? etc. etc.
Developing software on a licensed Windows (not 7), and testing the installers on Windows 7.
Developing software on Windows 7. And not distributing it.
And, um... well, I'm not sure anymore...

What if:

I review my own experiences of Windows 7 "cool UI", and I post screenshots to a blog. And/or I happen to generate traffic revenue from the blog.
I evaluate how my work flow will be compared to "normal". I install Office, and I talk to my friends, family, and hey, maybe job interviews with VoIP. It shuts down next year by itself anyway. No matter what I do, that's got to be covered under evaluation use, right?

See? See the gray area? See how big it can get? Whew..
Answer: I think they mean

Don't use it in a production environment.

or more accurate to your question:

a live operating environment == a production environment, or production machines on which you do your daily business

Edit: Do you intend to install it on your personal laptop/desktop? Then I think it's no problem. As long as you don't make any money out of it, I don't think it counts as "production environment".
Off the record: I don't think they will send some lawyers after you when you do use it on a production machine as long as you don't ask for their support when in trouble.
(Heck it makes the same machine run twice as fast as with Vista... why wouldn't you install it? It's better for business! ;-)
Comment: Exactly... Windows 7 is still under development.  It should work fine, but it might eat all the cookies in your house or change your TV channel to the Home Shopping Network, or leave the cap off the toothpaste.  The "live operating environment" is just common sense... don't stick pre-release code on every PC in your business, and then freak out when you can't get support.
Answer: I'd suspect the sole reason that line exists is to give em something to point to if someone rolls out the beta across their company, it hoses everything, they lose millions, and say "Why didn't you warn me, Microsoft?"
Or if you lose a term paper to a bug, you can't sue them for a year's worth of tuition?  ;)
Answer: A live operating environment means you are using it to perform your basic daily tasks. Which is kind of funny since we are encouraged to test upgrades from Vista.
Comment: Install Vista on a virtual machine, spare desktop, or spare laptop; then upgrade.
Answer: What's the opposite of a "live operating environment"?  A test lab? definitely.  A development environment?  I think that would be OK as long as you're specifically targeting Windows 7 compatibility.
Answer: A live and/or production environment is one that either:

contains or processes any information that you or anyone else cares about
is at all customer or public facing

Basically this rules it out for anything but use in a testing environment.
There is an implied exception to not using it in a "live environment", in that MS seem to be  encouraging people to try it on their home machines.
Answer: A 'Live operating environment' is a production environment that you are using for operational tasks, as opposed to a machine that is used purely for development or testing.  A development server is probably not a 'Live operating environment' but a developer's PC usually is as it is being used for daily work.
Microsoft use the example of a PC that you use to read email as an example of a live operating environment.  As most developers read email on the PC that they use to develop software on the PC tends to qualify as a 'Live operating environment.'  A secondary PC used solely as a test environment is not a 'Live operating environment' per this definition.
Comment: Do you have a link to the Microsoft reference with this example? I'd love to see it.
Answer: If you're worried about it, ask a lawyer.  The Internet Is Not A Lawyer (TIINAL).


atribuir value ao input angular 2

Question: Tenho um objeto vindo do banco que mostro na view em um ngFor.
o que pretendo é passsar este [value] para o componente para salvar no banco e não estou sabendo como.

<form #f="ngForm">

      <ion-input type="hidden" [value]="item.nomeProduto"></ion-input>

{{item.nomeProduto}}

  <button ion-button full block color="danger">CADASTRAR</button>
</form>
Answer: tente fazer com [ngValue] ao invés de [value]

atribuir value ao input angular 2


AKS Container failed to start

Question: I updated my docker file to upgrade ubuntu but it started failing and I'm unsure why...
dockerfile:
# using digest for version 20.04 as there is multiple digest that used this tag#
FROM ubuntu@sha256:82becede498899ec668628e7cb0ad87b6e1c371cb8a1e597d83a47fac21d6af3

ENV DEBIAN_FRONTEND=noninteractive

RUN echo "APT::Get::Assume-Yes \"true\";" > /etc/apt/apt.conf.d/90assumeyes

#install tools
#removed for clarity

WORKDIR /azp

COPY ./start.sh .

RUN chmod +x start.sh

CMD ["./start.sh"]

my evens from the pod
Successfully assigned se-agents/agent-se-linux-5c9f647768-25p7v to aks-linag-56790600-vmss000002
Pulling image "compregistrynp.azurecr.io/agent-se-linux:25319"
Successfully pulled image "comregistrynp.azurecr.io/agent-se-linux:25319"
Created container agent-se-linux
Started container agent-se-linux
Back-off restarting failed container

When I check the error in the pod, I see the following message:
standard_init_linux.go:228: exec user process caused: no such file or directory

Not even sure where to look anymore. The only difference in the dockerfile was the ubuntu tag and I added 1 tool to install. I tried to deploy what was in Prod to dev and it's failing with the same error. I'm convinced there's something in my AKS...
Comment: do you happen to be on windows? it could be the line endings when you edited the file as mentioned in [this thread](https://unix.stackexchange.com/questions/433444/cant-run-script-file-in-docker-no-such-file-or-directory)
Comment: This was the exact issue.. when I deploy to my AKS, I'm going to put a task that will convert the shell script to Linux to avoid this problem in the future
Comment: glad it worked!
Answer: So the issue was that someone on my team had modified the shell script and didn't set the proper End of Line characters to Lf.
I will be running a script to convert the file to Linux to ensure this doesn't happen again in my pipeline!

AKS Container failed to start


Couldn't find product without ID using Stripe

Question: I am trying to complete my payment set up in Ruby but am struggling to gt the order confirmation screen to print. I have set up my partial for the payment as such.

My payment controller.
    class PaymentsController < ApplicationController
  before_action :authenticate_user!

  def create
    @product = Product.find(params[:product_id])
    @user = current_user
    token = params[:stripeToken]
    # Create the charge on Stripe's servers - this will charge the user's card
    begin
      charge = Stripe::Charge.create(
        amount: @product.price, # amount in cents, again
        currency: "eur",
        source: token,
        description: params[:stripeEmail]
      )

    if charge.paid
      UserMailer.order_confirmation(@user, @product).deliver_now
      Order.create!(
        :product_id => @product.id,
        :user_id => @user.id,
        :total => @product.price_show
      )
        flash[:success] = "Your payment was processed successfully"
    end

    rescue Stripe::CardError => e
      body = e.json_body
      err = body[:error]
      flash[:error] = "Unfortunately, there was an error processing your payment: #{err[:message]} Your card has not been charged. Please try again."
    end
    redirect_to product_path(@product), notice: "Thank you for your purchase."
  end
end

and my routes file.
Rails.application.routes.draw do
  devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout' },
  controllers: {registrations: "user_registrations"}

  resources :products do
    resources :comments
end

post 'payments/create'

  resources :users
  resources :orders, only: [:index, :show, :create, :destroy]
  resources :users, except: [:index]
  get 'simple_pages/about'
  get 'simple_pages/contact'
  root 'simple_pages#landing_page'
  post 'simple_pages/thank_you'
  mount ActionCable.server => '/cable'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

The form within product show.html.erb
<%= form_with(url: '/payments/create') do |form| %>
  <%= render partial: "shared/stripe_checkout_button" %>
   <%= hidden_field_tag(:product_id, @product.id) %>
<% end %>

However, when I try to complete a test payment, I have the action controller pop up with "Couldn't find Product without an ID". I thought this was defined in the create section but I am not sure how to rectify this. Any suggestions would be greatly appreciated.
Comment: What params are received in the controller?. The error that rails is throwing is because it cannot find a ActiveRecord object without its id while doing - `Product.find(params[:product_id])`
Comment: Can you pls share the new.html or the form? as @AlokSwain mentioned it seems that product_id is not set
Comment: Just added now.
Comment: @Jac89, the form looks correct. But the `product` data is not
Can you check the following
1) in your form, inspect and see what is the hidden value for `product_id` making sure it has value?
2) in your controllers' `def create`, print out `params[:product_id]` making sure it is a valid product id

it is more like a data issue, checking the above to make sure
Comment: @wsw Perfect! solved everything there. Thanks once again!
Comment: @Jac89, awesome.
Do you mind copying the answer and mark your question as resolved.
thank you.
Answer: The :product_id is not set in your form post,
1. Quick Solution:
your form url could be like this:
<%= form_with(url: "/email@example.com}") do |form| %>

2. Better Way:
configure you routes for payments already has product id:
# routes.rb

  resources :products do
    resources :comments
    resources :payments
  end

form url:
<%= form_with(url: product_payments_path(@product)) do |form| %>


Declared constant for Android contact photo size?

Question: Contact photos are 96x96 on my Nexus S. I really don't want to 'bake' that knowledge into my code - is there a constant somewhere that declares this? I've looked, but can't seem to find one.
Answer: In android 2.3+ there is a ThumbnailUtils class that has
<code>/**
 * Constant used to indicate the dimension of micro thumbnail.
 * @hide Only used by media framework and media provider internally.
 */
public static final int TARGET_SIZE_MICRO_THUMBNAIL = 96;
</code>
but that @hide hides it from us.
Looking at the Contacts app source code, file AttachImage.java I found another interesting thing:
<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
    // omitted

    if (requestCode == REQUEST_PICK_CONTACT) {
        // A contact was picked. Launch the cropper to get face detection, the right size, etc.
        // TODO: get these values from constants somewhere
        Intent myIntent = getIntent();
        Intent intent = new Intent("com.android.camera.action.CROP", myIntent.getData());
        if (myIntent.getStringExtra("mimeType") != null) {
            intent.setDataAndType(myIntent.getData(), myIntent.getStringExtra("mimeType"));
        }
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 96);
        intent.putExtra("outputY", 96);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
</code>
That TODO and those intent.putExtra say a lot, even if there is a thumbnail size constant, it isn't used in the contact app.


onDrop submit a form with a file (without using Ajax)

Question: This could be a limitation of the environment but what I am trying to do is drop a file then have it post a file direct to the server PHP (no Ajax)... but the $_FILES variable is not correctly populated... Method: as the drop occurs the file object is taken and appended to a form which is submitted... This is normally done using and append to Ajax, but this creates an extra process that I don't want or need...

function uploadFile(e) {

  file_obj = e.dataTransfer.files[0];

  uploadForm = document.getElementById("upload_form");

  // Add the input to the form
  uploadForm.append('file', file_obj);

  // Add the form to dom
  document.body.appendChild(uploadForm);

  // Just submit
  uploadForm.submit();

}
<form action="upload.php" id="upload_form" enctype="multipart/form-data" method="post">

Drop file here

   <input name="" type="submit">

</form>
Comment: Have you tried converting your file's data (text or binary) and converting it to a dataURL string and then using that dataURL to send to your form as a query argument? Might not work for large files.
Comment: I am fairly new to javascript how would i do this? lots of these form interaction things seem to be done asynchronously (waiting for an event) I think the root is timing or just things aren't hooked up to work this way?
Comment: You can try this, this is more straightforward then doing the text conversion: https://stackoverflow.com/questions/5628011/how-to-upload-a-file-to-my-server-using-html
Answer: You should try new FormData() in order to get files data.
Comment: Good advice, but could be better if you show how to do it with an example
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Assumptions of the Friedman Rank Test

Question: Let $X_i:= (X_{i,1}, ..., X_{i,k}) $ for $i =1...n$ be $\mathbb{R}^k$-valued random Variables with $k\geq2$.
I wonder what the exact assumptions are to apply the Friedman test to Realisations of these RVs. More specifically i have read in the book "Nonparametric Statistical methods" by Myles Hollander, Douglas A. Wolfe and Erick Chicken. that one assumption that must be met is that
$(X_{i,j}), i=1...n, j=1...k$ are mutually independent. But i somehow cannot belief that this must be the case as I think most standard examples of the test violate this assumption. One of the standard examples is that there are $n$ randomly chosen individuals that undergo $k $ different treatments.
$X_i(\omega)= (x_{1,1}, ..., x_{1,k})$ would then represent measurements on the same individual under various treatments. So it is hard for me to belief, that e.g. $X_{i,1}$ and $X_{i,2}$ can be mutually independent as they represent a measurement on the same individual. So either a lot of people are using the Friedman Test without meeting the assumptions, or I am wrong somewhere.
I also thought that I have read somewhere that it must only hold that: $X_i, i=1...n$ must be mutually independent.
I would be glad if you could point out which of the assumptions is the correct one and if it is the first one, why is the Friedman test still used in situations that (I think) violate the assumptions.
Furthermore in the book it says:
"2. More General Setting. We could replace Assumptions A1–A3 and $H_0$ (7.2) with
the more general null hypothesis that all possible $(k!)^n$ rank configurations for the $r_{ij}$'s are equally likely. Procedure (7.6) remains distribution-free for this more general hypothesis."
As I read this, this would mean that we can drop all 3 Assumptions (whatever they are) as long as $H_0$ is "All Rank configurations are equally likely"?
To your information: A1 -A3 are:
1) The $X_{i,j}$ are mutually independent
2) All the $X_{i,j}$ represent random samples from a continious distribution function $F_{i,j}$
3) The distribution Functions are connected via $F_{i,j}(u) = F(u-\beta_{i}-\tau_j)$
Where $\beta_i$ is the unknown block-effect of blocck $i$ and $\tau_j$ is the unknown treatment effect of block $j$.
Comment: Individuals are indep. chosen, observations for each individual are indep. (although each individual may have his/her own mean/median). // Analogous: At a wine tasting event, 5 wine experts are asked to rate each of 6  lots of wine (different vineyards). Tasters will have their individual standards (and random quirky preferences) and each vineyard will have it's own style. Testing if there are signif diff's amng 6 lots of wine is the purpose; Friedman gives P-value for that. [If data normal, simple ANOVA block design would give info on diff's among tasters; but Friedman doesn't.]
Comment: See [R documentation on Friedman](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/friedman.test.html) with baseball example, Method is main effect, Players are 'blocks'. Example may be similar to one in your text.
Answer: Conover, 1999, Practical Nonparametric Statistics, 3rd ed., simply has:

The b k-variate variables are mutually independent.  (The results
  within one block do not influence the results within the other
  blocks.)
Within each block the observations may be ranked according to some
  criterion of interest.

Ho: Each ranking of the random variables within a block is equally likely (i.e., the treatments have identical effects)

It sounds like this might be concordant with what you are describing as 2. More general setting.
It's not clear to me what situation is being described by Setting 1.
The term "mutually independent" may be tripping you up.  It just suggests that not only are pairs of observations independent, but also combinations of observations are independent.
There may also be an implication, e.g., that there is not serial autocorrelation. That is, that the observations within each block must also be independent in that way.  I'm not sure.
This all could probably be spelled out with more user-friendlyness, but that's not typical.
The upshot:  I think your understanding of how Friedman's test is usually used is correct, and that's the correct way to use it.  It's difficult to know what Hollander, et al. are getting at with their assumptions without reading the whole thing, but it sounds like their 'Setting 2' matches what I think of as Friedman's test.
In my experience, trying to sort out assumptions of the traditional nonparametric tests can be difficult.  One issue is that different authors may address the assumptions describing essentially the same situation very differently.  But also, authors will often make these tests more parametric by adding more assumptions about data distributions to satisfy other Ho's.  For example, with additional assumptions you can use Wilcoxon-Mann-Whitney as a test of medians. Some authors start with the idea that you want to use this test as a test of the median and so list the assumptions according.  The result is that us mortals end up reading twenty different websites, some saying the test requires that the distributions be similar in shape and spread, and some not saying this.

Assumptions of the Friedman Rank Test


How to return the inserted item in dynamoDB

Question: I am using nodeJS sdk to put the item to dynamoDB, The item is:
{
   "eventId": date + '-' + eventName + '-' + eventPurpose,
   "eventName": eventName,
   "eventPurpose": eventPurpose,
   "eventDates": eventDates,
   "attendees": attendees
 }

The present code for the putting the item in dynamoDB:
  const params = {
    TableName: "event",
    Item: {
        "eventId": date + '-' + eventName + '-' + eventPurpose,
        "eventName": eventName,
        "eventPurpose": eventPurpose,
        "eventDates": eventDates,
        "attendees": attendees
    },
    ReturnValues: "ALL_OLD"
  };

  dynamo.put(params, (err, data) => {
    console.log("coming here");
    if (err) {
      console.log("error : " + JSON.stringify(err));
    }
    console.log("data" + JSON.stringify(data));
    cb(null, data);
  });

The insertion happens correctly and the return value is an empty object.
I would like to return the inserted item. I found this doc. But this returns only in case of updating the old value. I could not find any other useful info other than this.
Is there any work around or we simply need to query using get method  with the primary key?
Comment: Note in your callback if you receive `err` you should definitely not call the lambda `callback` as if it was successful.  A regular `if/else` block will help remove confusion in the future!
Answer: The link you posted is, sadly, the only real answer at this time (API Version 2012-08-10). PutItem may return items just before they were updated or none at all.

The ReturnValues parameter is used by several DynamoDB operations; however, PutItem does not recognize any values other than NONE or ALL_OLD.

In short, the only reliable way to retrieve your inserted object is to GetItem, just as you surmised.
Comment: 2023 and, sadly, this answer is still correct...
Answer: Just pass the params.Item in the callback :
 dynamo.put(params, (err, data) => {
        if (err) {
          cb(err);
        }
        cb(null, params.Item);
      });

Pass the err in the callback too ;)
Comment: isn't that cheating? ... I mean I want the real data that was inserted in the db, right?
Comment: The actual object stored could be slightly different than the object that you wanted to store. While passing the err should allow for a failed creation of the object, this isn't really an answer to the question.
Comment: Where have you been all my life
Comment: Kind of. It depends on what do you want to return : the object that you want to store on the database or the actual stored object.
Comment: Aweesome hack!!
Answer: You can use UpdateItem instead of PutItem. UpdateItem creates a new item if it doesn't exist already, plus you can set ReturnValues to ALL_NEW to return the whole item as it appears in the database after the operation:
const params = {
    TableName: "event",
    Key: {
        "eventId": date + '-' + eventName + '-' + eventPurpose
    },
    UpdateExpression: "SET eventName = :eventName, eventPurpose = :eventPurpose, eventDates = :eventDates, attendees = :attendees",
    ExpressionAttributeValues: {
        ":eventName": eventName,
        ":eventPurpose": eventPurpose,
        ":eventDates": eventDates,
        ":attendees": attendees
    },
    ReturnValues: "ALL_NEW"
};

Using GetItem right after PutItem is not a good idea unless you are using strong consistency in DynamodDB. If you have eventual consistency (default) then GetItem right after PutItem can still return empty.
Comment: aws rocks.. thanks for sharing anyways!
Answer: Note that this is the item you are inserting, which you already have access to:
{
    "eventId": date + '-' + eventName + '-' + eventPurpose,
    "eventName": eventName,
    "eventPurpose": eventPurpose,
    "eventDates": eventDates,
    "attendees": attendees
}

You could simply change your code to this, and then you would have the inserted item in the item variable already:
var item = {
        "eventId": date + '-' + eventName + '-' + eventPurpose,
        "eventName": eventName,
        "eventPurpose": eventPurpose,
        "eventDates": eventDates,
        "attendees": attendees
    };

const params = {
    TableName: "event",
    Item: item,
    ReturnValues: "ALL_OLD"
  };

You seem to be confused about what you are inserting, because you start your question by showing an object you say you are inserting, but the code you posted is inserting a slightly different object.
Comment: ya you are correct. The first code snippet contains the request body. Somehow, I got confused and made it has object. Coming to the question, your solution is a good one but usually in mongoDB, it returns the inserted object and I thought there might be something similar in dynamoDB. **ReturnValues: "ALL_NEW"** is allowed only in update operations. In **put** operation only **NONE** or **ALL_OLD**. Thanks for the quick answer. I will follow as you said. Simple and elegant approach. Thanks mark!!


Salvando arquivos em txt com Android Studio

Question: Estou com problemas para salvar o nome digitado pelo usuário em um arquivo txt.
Quando eu aperto salvar, diz que foi criado, mas eu não consigo ler.
Context fileContext;
public BancoDeDados(Context fileContext) {
    this.fileContext = fileContext;
}

public void gravar(String nome) {
    try {
        FileOutputStream os = fileContext.getApplicationContext().openFileOutput("bdNome.txt", Context.MODE_PRIVATE);
        os.write(nome.getBytes());
        os.close();
        System.out.println("Salvou");
    } catch (IOException e) {
        System.out.println("Deu erro");
    }
}

Comment: E onde está seu método de leitura? O que já tentou fazer?
Comment: Já chegou as permissões?!
Answer: Gente, aqui está a resposta.
Eu consegui.
public void gravar ( String data ) {
        try {
            FileOutputStream fOut = fileContext.openFileOutput ( "arquivo.txt" , Context.MODE_PRIVATE ) ;
            OutputStreamWriter osw = new OutputStreamWriter ( fOut ) ;
            osw.write ( data ) ;
            osw.flush ( ) ;
            osw.close ( ) ;
            System.out.println("ok");
        } catch ( Exception e ) {
            e.printStackTrace ( ) ;
            System.out.println("Deu erro");
        }
    }

public String ler ( ) {
    StringBuffer datax = new StringBuffer("");
    try {
        FileInputStream fIn = fileContext.openFileInput ( "arquivo.txt" ) ;
        InputStreamReader isr = new InputStreamReader ( fIn ) ;
        BufferedReader buffreader = new BufferedReader ( isr ) ;

        String readString = buffreader.readLine ( ) ;
        while ( readString != null ) {
            datax.append(readString);
            readString = buffreader.readLine ( ) ;
        }

        isr.close ( ) ;
        System.out.println("ok");
    } catch ( IOException ioe ) {
        System.out.println("Deu erro");
        ioe.printStackTrace ( ) ;
    }
    return datax.toString() ;
}


Does $\lim_{n\rightarrow\infty}\sum_{k=1}^n\ln\left(\frac{k(1+\alpha)}{n-k+1+(n-k)\alpha}\right)$ exist?

Question: Does the limit
$$\lim_{n\rightarrow\infty}\sum_{k=1}^n\ln\left(\frac{k(1+\alpha)}{n-k+1+(n-k)\alpha}\right)$$
exist?
Background: I came across this limit when considering the rocket equation for a rocket with $n$ stages. Each stage has a dry mass $m_d$ and fuel mass $m_f$ and $\alpha\equiv m_f/m_d$. The limit calculates how much $\Delta v$ one gets given some $\alpha$. I was wondering if there's a limit to how much $\Delta v$ one can get out of a rocket by letting the number of stages go to infinity. For more background see this answer.
Comment: Assuming we're working in real numbers, your logarithm is not even defined for large $n$. Take a look at the [plot](https://www.desmos.com/calculator/tlubyy6lcm). That'd make the limit undefined as well.
Comment: Since you have a sum from $k=1$ to $n$ and a limit as $n\to\infty$, the logarithm needs to be defined for an arbitrarily large $k$. The plot shows this isn't the case. The logarithm is only defined for $k\le N$ where $N$ is some number.
Comment: @bjorn93 Are you sure that matters? You plotted for $k$ and $k$ is never larger than $m$. For $k\leq m$ it appears to be defined which you can see if you plot $x=m$.
Comment: Did you mean $n$ in the sum instead of $m$? Cause otherwise this question doesn't make sense
Comment: @QC_QAOA Oops I messed them up
Answer: Let $1+\alpha=\beta^{-1}$. We can rewrite the term within the logarithm as
$$
f(n,k,\beta)=\frac{k}{n-k+\beta}
$$
We can find the finite sum
$$
S_n(\beta)=\sum\limits_{k=1}^n \ln f(n,k,\beta)=\ln\left[\prod\limits_{k=1}^n f(n,k,\beta)  \right]
$$
Write out a few terms of the product
$$
\prod\limits_{k=1}^n f(n,k,\beta)=\frac{1}{n+\beta-1}\cdot
\frac{2}{n+\beta-2}\cdots \frac{n}{\beta}
$$
Which may be written as
$$
\prod\limits_{k=1}^n f(n,k,\beta)=\frac{\Gamma(n+1)}{\Gamma(n+\beta)/\Gamma(\beta)}
$$
So we have for the sum
$$
S_n(\beta)=\ln\left[\frac{\Gamma(n+1)\Gamma(\beta)}{\Gamma(n+\beta)} \right]
$$
Using the asymptotic expansion of $\Gamma$ for large argument with fixed $\beta$
$$
S_n(\beta)\sim (1-\beta)\ln n \qquad , \qquad n\to \infty
$$
So that the sum in logarithmically divergent unless $\beta=1$, in which case $S_n(1)=\ln\Gamma(1)=0$
Comment: Very nice! I think that $\beta^{-1}=1+\alpha$ is a very clever substitution. I have to think about the implications but it seems to imply that a rocket with inifinite stages could reach arbitrary velocities. Also it's nice that $beta=1$ corresponds to $\alpha=0$ meaning having zero fuel is the only exception because it gives you zero velocity.
Comment: @AccidentalTaylorExpansion Thank you! Taking the $n \to \infty$ limit means each stage has vanishing total mass; which, even abstractly, is difficult to imagine is feasible. I imagine there is something like an absolute minimal mass per stage. On the other hand, this 'continuum limit' corresponds to a rocket that is losing mass both to fuel *and* something else


How many hexagons can be made by joining the vertices of a 15 sided polygon if none of the sides of the hexagon is also the side of the 15-gon.

Question: How many hexagons can be constructed by joining the vertices of a 15 sided polygon if none of the sides of the hexagon is also the side of the 15-gon.
Suppose, we take a 9 sided polygon and use Gap Method (Gap and string method in permutations and combinations) to fill other 6 points to be filled in between the present 9 points in order to have a 15 sided polygon
Also, in order to make hexagon according to the question, we just have to choose 6 "gaps" between the present points and put the points in the places. So, by doing all this we will have a 15 sided polygon.
And in this way, no. of ways of making a 15 sided polygon will mean same as selecting 6 points from a 15 sided polygon which aren't adjacent. (which helps in the idea of making a hexagon which will have no side which is also a side of the 15 sided polygon)
[ "×" - present points, "_" - gaps]
<code>                    ×         _            ×
                  _                          _

                 ×                             ×
                  _                            _

                    ×                          ×
                      _                       _
                        ×                   ×
                            _            _
                                   ×
</code>
No. of gaps=9
So, now according to me,
No. of such Hexagons which can be formed = $\binom{9}{6}$
= 84
But, this is not the correct answer. What am I missing?
(Correct Answer- How many hexagons can be constructed by joining the vertices of a 15 sided polygon if none of the sides of the hexagon is also the side of the 15-gon.)
Comment: Why don't you thoroughly study the correct answer ? You can also refer to an answer to a similar problem: https://math.stackexchange.com/search?q=user%3A22388+heptagon
Comment: Oh yes. But I was just thinking what I lacked here which is why I asked. Thanks for the help!
Answer: The $15$-sided polygon is a fixed object.  You need a reference point.  Say it is vertex $A$.
There are two possibilities: vertex $A$ is a vertex of the hexagon, or it is not.
Suppose $A$ is not a vertex of the hexagon.  Arrange nine blue balls in the form of a circle.  Label one of those balls $A$.  Choose six of the nine gaps in which to place a green ball to ensure that no two green balls are adjacent.  Now label the vertices in alphabetical order as you proceed clockwise around the circle, starting at $A$.  The letters on the green balls are the vertices of the hexagon.  There are $\binom{9}{6}$ ways to do this, which agrees with your answer.
Now suppose $A$ is a vertex of the hexagon.  Color it green.  Arrange nine blue balls around $A$ to form a circle which includes the ball labeled $A$.  Doing so creates $10$ spaces in which to place a green ball, but two of these are adjacent to $A$, leaving eight spaces where a green ball could be placed so that it is not adjacent to $A$.  Choose five of these eight spaces in which to place a green ball to ensure that no two green balls are adjacent.  Now label the balls in alphabetical order as you proceed clockwise around the circle, starting at $A$.  The letters on the green balls are the vertices of the hexagon.  There are $\binom{8}{5}$ ways to do this, which you have not taken into account.
Since the two cases are mutually exclusive and exhaustive, the number of admissible hexagons is
$$\binom{9}{6} + \binom{8}{5}$$
which agrees with the linked answers provided by Andre Nicolas and Henry.
Answer: What you are missing is a multiplication factor of $\frac{15}{15-6}$
ie the answer should be $\binom96\times \frac{15}{9}$
The multiplication factor is arising because you are necessarily attaching a gap (clockwise, say) immediately after each vertex, which restricts the number of places the vertex-gap "blocks" can occupy.


Como especificar um espaço em branco no AWS CLI S3?

Question: Uso o PowerShell ou o CMD para executar um comando no AWS CLI S3, o comando que eu executo é esse:
aws s3 cp s3://repositorioimagens/ampliacao/BR/1022-IKON IMAGES/STOCK239/ . --recursive

O problema é que quando eu tenho uma pasta com espaço em branco em algum lugar eu recebo o erro
Unknown options: .
Pois ele entende que eu acabei uma parte do comando e estou configurando-o (assim como acontece depois de /STOCK239/ que eu coloco o . --recursive).
Como explicar para o CLI que eu quero um espaço em branco em 1022-IKON IMAGES > 1022-IKON(ESPAÇO EM BRANCO)IMAGES
Comment: Já tentou escapar o caractere com a barra invertida, `IKON\ IMAGES`?
Comment: Já, não funciona, o erro persiste.
Answer: Você precisa colocar toda string dentro de aspas duplas "".
aws s3 cp "s3://repositorioimagens/ampliacao/BR/1022-IKON IMAGES/STOCK239/" . --recursive
Comment: Valeu @Henrique, tinha descoberto mas acabei esquecendo de responder aqui. +1


How to filter or ignore some new logcat messages

Question: After update on Android Studio Electric Eel (maybe a bit earlier :) )
In my logcat I saw new messages:
<code>W set:488 set: Unset optional value from type SMPTE2086
W set:488 set: Unset optional value from type CTA861_3
W set:488 set: Unset optional value from type SMPTE2094_40
</code>
If I'm testing my app on android device with OS Android 5.1 log is clear without such messages, but when I'm using device with OS Android 12 or 13,  logcat always shown this messages, when my app shows progress dialogs or progress indicators.
This is warning messages, and I don't understand how to hide them, or do something to fix this warning.
I use real device to test my apps. If it is meaning.
Answer: I am seeing a lot of these logs on newer devices as well, not sure where they come from. But with the new logcat filtering, you can filter out these messages ( They all have the IMGMapper Tag), with the following:
<code> -tag:IMGMapper
</code>
As you can negate filter expressions (https://developer.android.com/studio/debug/logcat#negation-and-regex)
Comment: how to do this in flutter command line? really frustating seeing this.
Comment: not sure about flutter, I think this is an IDE feature


my action performed doesnt work and it compile easily

Question: i'm just making a assignment that connect database to jFrame and i need some help with this. i already try to compile the java and thats ok, but when i press the button nothing happen.
<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Assignment extends JFrame implements ActionListener{
JLabel label, l1, l2, l3, l4, l5;
JButton Add,Delete,Update,Display,Exit;
JTextField tf1, tf2, tf3, tf4, tf5;
Connection conn = null;
Statement stmt = null;
/**
 * Create the frame.
 */
Menu() {
    setVisible(true);
    setSize(500, 500);
    setLayout(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("JDBC");
    label = new JLabel("Database"); //Label
    Add = new JButton("Add Data"); //Button
    Delete = new JButton("Delete Data");
    Update = new JButton("Update Data");
    Display = new JButton("Display Data");
    Exit = new JButton("Exit");
    tf1 = new JTextField(); //textfield
    tf2 = new JTextField();
    tf3 = new JTextField();
    tf4 = new JTextField();
    /**
    * Set bounds.
    */
    Add.addActionListener(this);
    Delete.addActionListener(this);
    Update.addActionListener(this);
    Display.addActionListener(this);
    Exit.addActionListener(this);
    /**
    * add frame.
    */
}
public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("Add")){ //i already clicked on the button but it doesnt works
        Add();
    }
    else if(e.getActionCommand().equals("Delete")){} //i havent code for this
    else if(e.getActionCommand().equals("Update")){}
    else if(e.getActionCommand().equals("Display")){}
    else if(e.getActionCommand().equals("Exit")){
        System.exit(0);
    }
    }
/**
 * Create the second frame.
 */
public void Add() {
    JFrame frm = new JFrame();
    frm.setVisible(true);
    frm.setSize(500, 500);
    frm.setLayout(null);
    frm.setTitle("JDBC");
    l1 = new JLabel("ID : "); //Label
    l2 = new JLabel("Name : ");
    l3 = new JLabel("Adress : ");
    l4 = new JLabel("Gender : ");
    l5 = new JLabel("IP : ");
    /**
    * Set bounds.
    */
    /**
    * add frames.
    */
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost/academic", "root", "abc"); //connecting
        stmt = conn.createStatement();
        String sql;
        sql = "INSERT INTO student VALUES(" +
              "'" + tf1.getText() + "'," +
              "'" + tf2.getText() + "'," +
              "'" + tf3.getText() + "'," +
              "'" + tf4.getText() + "'," +
              tf5.getText() + ")";
        stmt.executeUpdate(sql);
        stmt.close();
        conn.close();
    }catch(SQLException se){
        se.printStackTrace();
    }catch(Exception e){
        e.printStackTrace();
    }
}
/**
* Launch the application.
*/
public static void main(String args[]) {
    new Menu();
}
}
</code>
any idea guys ? please help me
Comment: Aside from anything else, you should really, really **really** fix the SQL Injection attack in your code. Use parameterized SQL with `PreparedStatement`.
Comment: And how come you do not use the `@Override` notation for `actionPerformed` method. If you implement the ActionListener interface, you always have to override the method and add the `@override` notation to the method.
Comment: you are missing setActionCommand for your buttons
Comment: Variable names and method names should NOT start with an upper case character.
Comment: See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556)
Answer: You should be setting Action Command for your button
<code> Add = new JButton("Add Data"); //Button
 Add.setActionCommand("Add");
</code>
Same way for other buttons as well
Comment: (1+)  That is the action command for the button defaults to the text of the button. So you can either change your if statement to check for "Add Data" or you need to set the ActionCommand to "Add".
Comment: Yes right camickr. by default ActionCommand will be the same as the text
Comment: i already check about it.. but now my problem is i can't compile it anymore cause of Menu()
Answer: in main method when you say new Menu(), its creating an instance of Java.awt.Menu, if you need to call the menu() method in your code, you need to use Assignment instance and call Menu() method.
Comment: i dont really get it. can u give me a example ?


Extract a significant sample of data from a non-normal distribution before modelling a fitting curve

Question: Background: In my master thesis I am measuring how many areas(in square meter) are suitable for greening at different building height in an urban area. So I have two variable: Suitable Areas and Height. In the following plot is it shown how the amount of Suitable Area changes at different heights and I plot a curve that join those points (an automatic function of ggplot2 in R)
Now my supervisor required to model a fitting curve (and to find its formula) that describes the data(the distribution of suitables area at different height), but before doing so he suggest me to consider reducing my data. Therefore the question is at which height the 95 % of the total Suitable area are located and consequentially remove the rest from my distribution. I guess this would mean to cut the tail on the left of my plot.
I thought that this 95% of the measurement comes from the "68-95-99.7" rule (three-sigma rule) based on standard deviation. But the three-sigma rule works better for normal distribution, while my distribution is non-normal, and I fear that it would neglect values in the first meters, considering them as outliers.

Is a good practice at all to select a significant sample of my
distribution before modelling a fitting curve?
Which statistical methods are given to find significant sample of
my data?
Since I consider the measurements in the first
meters(highest frequency of suitable area) very important in my
distribution should I use a method not based on standard deviation?

Sorry if my question is unprecise but I have poor mathematical knowledge.
Comment: 1. could you clarify what the plot is showing? What are the variables on the axes? How are the points obtained? 2. The word significant has a particular kind of meaning in statistics that I don't think fits what you're trying to say here. i suggest avoiding jargon (instead choosing an ordinary English word or phrase) that conveys your intent; can you explain clearly what you're trying to achieve? What is it you're trying to find out from the data?
Comment: Yes, I need a formula for the curve, and I have to identify which curve mayf represent the relationship between those two variables, finding a good compromise between simplification and precision.
So in the end I would like to reproduce something like this: https://davetang.org/muse/2013/05/09/on-curve-fitting/
Comment: Ok, so a _range of heights_ in which 95%of the total Suitable areas are located. II would then exclude the heights in which the number of suitable areas is very small. Maybe there is a statistical formula that establishes the smallest group dimension in a given population to consider that group "important" in the total population. Eg. If I have 2000 measurements distributed among 5 groups. A group is overall "important" in the total population if at least 500 measurements.  belongs to it.
Comment: Hi Glen, thank you for answering.
I had a table with two columns, which represent two numeric continuous variable: height and areas. At each row, I have one height value and an amount of square meter (eg. at 6 height meter there are 18141 square meters). The point in the plot are the amount of square meter at that height(eg. 18141 at meter 6).
I don't want to prove any hypothesis(no inductive statistic). I just want to find a curve that has the best fit for those points.
Before modeling the curve, should I "clean" my data?
Comment: Your question is somewhat inscrutable because the graph itself includes an answer: the black curve already fits the points.  Are you looking for a formula for that curve?  Or, recognizing that it is not the only curve passing through the points, are you hoping to identify some such curve that is "best" in some sense?  What sense would that be?
Comment: "*the question is at which height the 95 % of the total Suitable area are located*" This is asking for a range of heights, not a single height, and it's not clear how you want to choose this range.
Answer: I extracted data from the scatterplot for analysis. Except for the first two data points, I see two separate models - one model for height below 16 meters and one model for height above 16 meters. Combining these two models would not require data reduction. I suspect that there might be some dominant effect above and below approximately 16 meters.
For height below 16 meters a hyperbolic type equation "y = (a + (b * x)) / (c + x)" seems to fit well, with parameters a = -3.6248957321627102E+04, b =  1.6715762703817916E+04, and c = -2.5094538863935254E+00 yielding RMSE = 149.6 and R-squared = 0.9908:

For height above 16 meters a Lorentzian peak type equation, " y = a/ (b + pow(x-c, d))" seems to be a possible candidate, with parameters a = 6.7383016504505267E+06, b = 4.0349701664549445E+02, c = 1.6059999999999995E+01, and d = 3.2099267050815645E+00 yielding RMSE = 374.0 and R-squared =  0.9957:

I did not model any overlap near 16 meters, adding one or two points of overlap between the two models would be a good idea. If you use the "two models" route, the values I have provided should be good initial parameter estimates for your own non-linear fitting with the actual data.
Comment: Hi James, thank you for your answer and the model!
May I ask you which steps in your methodology you made in order to get the formula?  Did you use some kind of model that you feed with my data, or a script in R?
Comment: No. Actually I dont see my supervisor so often and I´m still changing the dataset I will fit into the model. Still it was important to see your workflow and at the first equation is still usable :).
Comment: how were you able to find out the RMSE and R squared of the fit? To replicate your steps I used R but I am struggling to find a solution.
Comment: For RMSE, Root Mean Squared Error, A) Square the regression errors. B) Find the mean (average) of those squared values. C) Take the square root of that mean. For R-squared (R2) I use "R2 = 1.0 - (regression_error_variance / dependent_data_variance)".
Comment: A) Visually there are two distinct shapes to the data, split at 20 meters or so. B) Split the data at 20 meters and perform equation searches for simple equations. C) Initial results show 20 meter split is not optimal by model complexity. D) Iterate equation searches with different split points to find the two simplest models that give a good fit to both sections. Note that I used my zunzun.com "function finder" for the equation searches, it has a genetic algorithm to find initial parameter estimates for fitting non-linear equations. Mostly I was just clicking browser buttons on the web site.
Comment: In the question you mention your supervisor. Did they have any comment on this model?


Determining the percentile rank of a score w.r.t. a known distribution

Question: I have data from a SUS-survey (a standardized test for evaluating the usability of software) which gave me an average score of 73.25. As I understand, it is best practice to normalize the scores to produce a percentile ranking as indicated here.
I do not however understand how I would go about assigning a percentile rank to my score - if I understand correctly, I would require a reference distribution of SUS-Scores (or else there's no way of saying "my score is better or worse than X% of available scores", right?)
I have found that Bangor et al. have published the results from 10 years worth of SUS-evaluations, and here's the data they give:

Count: 2324
Mean: 70.14
Median: 75
Standard Deviation: 12.71

Is it possible to determine the percentile rank of the score of 73.25 with respect to this distribution, and how would I do that?
Answer: It depends on what you mean by distribution. Percentiles are expressed for a random variable and can be either empirically observed or theoretical. Empirical distributions would be published in some sort of long table in which you can look up for each score the corresponding percentile (rank). Theoretical distributions are those that follow a known functional form, such as the normal distribution.
Empirical distribution percentiles need to be published for distributions that do not follow a known functional form. For example if they are are skewed, multi-modal etc. it is more likely that it is very hard for statisticians to fit the observed distribution to a theoretical one without making crude approximations.
To attach a percentile rank to an observed value you need either of the two. In your example you only give first and second moment as well as the median of a distribution, but you do not say if this distribution is empirical or theoretical. If it is empirical, then there is not enough information to attach a percentile rank. Although you know the moments and median, it is not known how exactly the percentiles relate to these statistics. The only thing you know is that a score higher than 75 would have a percentile above 50, using the median which is the 50th percentile.
If the authors of that study tell you in addition that these statistics come from some sort of normal (super-)population you could perhaps use the mean and standard deviation as the parameter estimates for this normal distribution, and then use a normal distribution table or the R function pnorm to get percentiles. However I believe it is perhaps not very likely these data come from a normal distribution as the mean and median are not equal (they may of course be unequal due to sampling error but perhaps they deviate a bit too much here).
So the bottom line is that you need more information, either a better empirical distribution percentile table or knowledge on the true theoretical form that is reasonable to assume, in order to assign percentiles to your sample statistics.
Comment: I understand - that makes perfect sense. I have also found this book: https://measuringu.com/book/quantifying-the-user-experiencepractical-statistics-for-user-research/

It seems the authors had access to the original dataset I'm referring to, as they give a conversion table from SUS-score to percentile that has entries for scores of 73 and 74 respectively - which will probably be sufficient for my purpose.


Inverse Fourier transform of $\frac{\cos(x)}{x^2} $

Question: I am stuck in the integral of an inverse Fourier transform in an exercise of a graduate signals class.
I am trying to compute the inverse Fourier Transform for the signal given below. I tried regular integration techniques to calculate the inverse transform:
$$ x(t) = \frac{1}{2π} \int_{- \infty}^{+ \infty} { Χ(ω) e^{iωt} dω} = \frac{1}{2π} \int_{- \infty}^{+ \infty} { \frac{\cos(ω)}{ω^2} e^{iωt} dω}  $$
but they do not work. So what is the right answer?
Summarizing the question:
Find the signal whose Fourier transform is
$$ X(Ω) = \frac{\cos(Ω)}{Ω^2} $$
What is the inverse Fourier transform of the above X(Ω)?
Comment: What have you tried? Please include your attempts.
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: @CrSb0001 I tried integrating $\frac{cos(x)}{x^2}$ over x, but it does not go anywhere. Integrating by parts leaves more unsolved integrals, etc. I can include some here but I posted the question with no attempts to get a good answer.
Answer: Note that $f(x)=\frac{\cos(x)}{x^2}$ is not locally integrable and is not, therefore, a tempered distribution.  We can define, however, a distribution that permits our defining the Fourier Transform.  We define the distribution $\left(\psi\right)_{D}=\left(\frac{\cos(x)}{x^2}\right)_{D}$ such that for any $\phi\in \mathbb{S}$,
$$\left(\left(\psi\right)_{D},\phi\right)=\text{PV}\int_{-\infty}^\infty \frac{\cos(x)}{x^2}\left(\phi(x)-\phi(0)-\phi'(0)x\right)\,dx\tag1$$
Equipped with $(1)$, we proceed to find the Fourier Transform of $\left(\psi\right)_{D}$.

We see that
$$\begin{align}
\langle \mathscr{F}\{\left(\psi\right)_{D}\},\phi\rangle&=\langle \left(\psi\right)_{D},\mathscr{F}\{\phi\}\rangle\\\\
&=\text{PV}\int_{-\infty}^\infty \frac{\cos(x)}{x^2}\int_{-\infty}^\infty \phi(k)\left(e^{ikx}-1-ix\right)\,dk\,dx\\\\
&=2\int_0^\infty \frac{\cos(x)}{x^2} \int_{-\infty}^\infty \phi(k)\left(\cos(kx)-1\right)\,dk\,dx\\\\
&=-2\int_{-\infty}^\infty \phi(k)\int_0^\infty \frac{\cos(x)(1-\cos(kx))}{x^2}\,dx\,dk\\\\
&=-\int_{-\infty}^\infty \phi(k)\int_0^\infty \frac{\cos((k+1)x)+\cos((k-1)x)}{x}\,dx\,dk\\\\
&=-\int_{-\infty}^\infty \phi(k)\int_0^\infty \frac{(k+1)\sin((k+1)x)+(k-1)\sin((k-1)x)}{x}\,dx\,dk\\\\
&=-\int_{-\infty}^\infty \phi(k) \frac\pi 2\left((k+1)\text{sgn}(k+1)+(k-1)\text{sgn}(k-1)\right)\,dk
\end{align}$$
Therefore, in distribution we see that
$$\mathscr{F}\{\left(\psi\right)_{D}\}=-\frac\pi2 \left((k+1)\text{sgn}(k+1)+(k-1)\text{sgn}(k-1)\right)$$
Comment: Which can be written $-\frac{\pi}{2}(|k+1|+|k-1|).$
Comment: @md2perpe Indeed it can.
Comment: very interesting solution, thank you! I will upvote.
Comment: @spiros You're welcome.   My pleasure.
Answer: Here's a method that gives the solution up to an additive constant ($B$ in the result below).
I will skip constant factors. Some of those depend of the used definition of the Fourier transform.
The inverse Fourier transform of $\Omega^2 X(\Omega) = \cos\Omega$ is
$$-x''(t) = \delta(t-1)+\delta(t+1).$$
Therefore,
$$x(t) = -\frac12 (|t-1|+|t+1|) + At + B,$$
where $A$ and $B$ are constants. However, since $X(\Omega)$ is even, so must be $x(t).$ Therefore $A=0.$
Comment: Aren't you missing a $\frac12$ factor in the ODE?
Comment: @RodrigodeAzevedo. I have skipped several constant factors.
Comment: I read the "I will skip constant factors" part only now.  Why not use $\propto$ instead of the misleading $=$?
Comment: @RodrigodeAzevedo. Laziness.


Using offset and jQuery slider

Question: I am using offset() with the jquery slider and I am so close to achieving my goal, but it is off slighty. I have it animating using animate to the top CSS coordinates but if you check out: http://www.ryancoughlin.com/demos/interactive-slider/index.html - you will see what it is doing. My goal is to have it fadeIn() and display the value to the right of the handle. i know I can offset the text from the handle using a simple margin:0 0 0 20px.
The part is aligning #current_value to the right of the handle. Thoughts?
            var slide_int = null;
$(function(){

    $("h4.code").click(function () {
        $("div#info").toggle("slow");
    });

    $('#slider').slider({
        animate: true,
        step: 1,
        min: 1,
        orientation: 'vertical',
        max: 10,
        start: function(event, ui){
            $('#current_value').empty();
            slide_int = setInterval(update_slider, 10);
        },
        slide: function(event, ui){
            setTimeout(update_slider, 10);
        },
        stop: function(event, ui){
            clearInterval(slide_int);
            slide_int = null;
        }
    });
});
function update_slider(){
    var offset = $('.ui-slider-handle').offset();
    var value = $('#slider').slider('option', 'value');

    $('#current_value').text('Value is '+value).css({top:offset.top });
    $('#current_value').fadeIn();

}

I know I could use margin to offset it to match, but is there a better way?
Answer: There are two problems. The first, like Prestaul said, the slider event fires at the "beginning" of the move, not the end, so the offset is wrong.  You could fix this by setting a timeout:
$(function(){
    slide: function(event, ui){
        setTimeout(update_slider, 10);
    },
    ...
});
function update_slider()
{
    var offset = $('.ui-slider-handle').offset();
    var value = $('#slider').slider('option', 'value');
    $('#current_value').text('Value is '+value).animate({top:offset.top }, 1000 )
    $('#current_value').fadeIn();
}

The second problem is that the move is instantaneous, while the animation is not, meaning that the label will lag behind the slider.  The best I've come up with is this:
var slide_int = null;

$(function(){
    ...
    start: function(event, ui){
        $('#current_value').empty();
        // update the slider every 10ms
        slide_int = setInterval(update_slider, 10);
    },
    stop: function(event, ui){
        // remove the interval
        clearInterval(slide_int);
        slide_int = null;
    },
    ...
});

function update_slider()
{
    var offset = $('.ui-slider-handle').offset();
    var value = $('#slider').slider('option', 'value');

    $('#current_value').text('Value is '+value).css({top:offset.top });
    $('#current_value').fadeIn();
}

By using css instead of animate, you keep it always next to the slider, in exchange for smooth transitions.  Hope this helps!
Comment: Hey! Thank you for your help. I updated my question with my updated code and doesnt seem to be behaving correctly. Any ideas on what I did? It looks right, is it the location of my function? The value doesnt follow it with the new code. Thanks, Ryan
Comment: I've updated it accordingly.  Also slide_int should be outside of the $() function.
Comment: Hey Tyler, I updated my code again, it goes to say Step 1, then doesnt for the rest? Thoughts the function keeps calling every 10ms which makes it load to the eright of the handle correct? If it didnt it would be off? Just so im learning what is going on, thank you.
Comment: I got it working better now, I added in your .css instead of .animate, see if you click on the slider and the handle slides there but the label doesn't update until you click the handle again anyway to fix that? Also is it not possible to use animate? I kind of like that effect? Thanks a ton
Comment: The best I could get was for it to lag behind, or not be smooth (if the animate speed was too fast) like using .css. If you find a better way, let me know.
Comment: Ahh..I see. i will play around with it. Thanks again for all of your help on this.
Answer: I had the same problem: the visible value in Jquery Ui slider lags behind from internal value. Fixed the problem by changing the slider event from "slide" to "change".
Answer: You just need to use a different event.  "slide" fires before the handle is moved so your value is ending up at the previous handle position.  Try the "change" event and see if that gets you there.

Using offset and jQuery slider