Dojo Grid Template

Question: In asp.net the DataGrid supports templates. You can provide your own template and have the grid fill the data in your template.
With Dojo Grid, it seems like I can't make my own template outside of the the rigid simplistic cell style grid that Dojo provides.
Does anyone know a way to use a custom template with Dojo Grid? Specifically, with Dojo you're forced to use a cell that corresponds to a data item. I'm looking to use a table as a template with any styling that I choose (rows,columns,rowspans,colspans, more than one data items in a single cell, etc).
Any clues please?
Thanks
Answer: Firstly, it sounds like everything you want is available by customizing the grid. You can do nesting of cells and even have things like Filtering Selects in rows. Unfortunately the docs on this are not awesome so it takes Googling and trial and error if you want very customized features.
Secondly, because of the OO nature of Dojo you can always use inheritance to create mixes of various widgets. Specifically the _templated class allows you to specify an HTML template for your widget, which themselves can included templated widgets.
If that sounds non-trivial, you're right, which is why I would suggest digging deeper into the Enhanced grid and probably open up the code before trying to write something yourself.
I can tell you that I struggled getting it working correctly, but I have hence been pleasantly surprised by features that I needed that I thought I would need to build myself but were built into the grid.

Dojo Grid Template


TCP dump used for and how can it be used

Question: What are the advantages and benifits of TCP dump and how can this be used and in which environments it can be used
Comment: implementing an ethernet-to-rfc-1149 bridge?
Comment: @symcbean That's what shotguns with #8 birdshot is for: tcpdump on rfc-1149.
Answer: Packet sniffers are a very valuable tool. When coupled with a protocol decoder such as Wireshark, they can tell you in explicit detail what's actually happening on the network wire. Depending on what you're trying to figure out, they can show you the exact problem, or lead you into the right course of research for the actual problem. Learning to read packet traces is one of the skills most system administrators need at least a little of.
A brief list of things that a packet trace will display in gory detail:

DNS resolution problems. You'll see the full resolution failback process, and can highlight configuration problems (why are we hitting THAT server? Why are we attempting to resolve a dns domain that died 5 years ago? Why are we attempting to resolve IPv6 addresses before IPv4?)
TCP errors. Retransmits, bad windowing, packet corruption. All these things really slow connections down.
SMB Protocol negotiation problems. Of interest to Windows/Samba administrators, this will show protocol negotiation problems (NTLM? NTLMv2? Kerberos? LanMan?) between clients and the server.

And that's just the easy stuff that the dissectors tell you outright. Once you've learned how things are supposed to look, you'll start to see patterns in the traffic that the dissectors don't reveal.
However, not all problems can be broken by packet sniffing. Problems with SSL/TLS communication are almost by definition invisible. Sometimes the problem is with a higher layer protocol (such as a hand built web-API) and doesn't show any artifacts on the wire.
Comment: thanks for your answer.can you suggest me how to learn these and where to start learning
Comment: @developer The most accessible source is probably the [Wireshark Wiki](http://wiki.wireshark.org/). They even have example captures to download and look at, and pages to tell you what you are looking at. Example-based education!
Answer: You can use it

to see all the network traffic generated by application
to solve network problems
for security testing

Not to mention that they are extremely useful when starting to study computer networks, because you can see exactly what kind of information is flowing through the network and how this information is represented.


Allow a user to manage his/her own users and be able to assign roles

Question: I need to give access to a specific user with a specific role to be able to give the user role but not the administrator
My case is that the website I'm building needs different kinds of admins and roles, for the role I need to find a solution is for a sub-admin this person should be able to add users and assign roles and I also want this person to only be able to manage the users he adds not all the users.
I found that by using flags and roles might be the best way I found this answer to the question "Give a specific user role the ability to give a user a role but not the 'administrator' role". My problem is that I'm not proficient in Drupal and I'm not sure what to add in this window https://pasteboard.co/H7E7rX9.png I'm trying to learn more about rules seeing that probably I'll be using more of this on my project
Thank you so much for your help.
Comment: Please review the edit I applied to your question .... copying text from somewhere (which I happened to recognize ...) with no mention of its source is NOT allowed on this site ...
Answer: Have a look at the Group module (commonly perceived as an alternative for Organic Groups).
Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.
The way you described in your question how you imagine using the (great!) Flag module, translates more or less to "Is user X yes or no member of Group G?" combined with "What group roles does this user have". However, after you will understand / realize all the things you can do with the Group module (with zero custom code ...), you'll probably also understand that trying to do something similar with the Flag module, is going to take a lot of flags, and related Rules logic.
More info
Some more questions you may want to look at for more details:

How to configure access to courses for teachers and students?, which contains a sample configuration.
What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site.
What are the features of the Group module versus Organic Group module?

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Comment: Thank you for your help I'll take a look at all the information you just sent me :)


How to read these notes

Question: The below picture shoes a part of the notes from Mozart's Alla Turca. It occurs quite early on my note sheet, so it is likely to be found on the first page of whatever note sheet you may have it on.

The question is, how am I supposed to read this part? Am I supposed to repeat the entire part before it, but with three sharps added?
Comment: I got it from http://applesaucekids.com/Music/GenMusic/RondoAllaTurca-let.pdf. In another edition at http://www.mutopiaproject.org/ftp/MozartWA/KV331/KV331_3_RondoAllaTurca/KV331_3_RondoAllaTurca-a4.pdf, the error appears to have been corrected.
Comment: Please provide the edition in question -- and compare it with other editions, which may solidify Tim's answer.
Answer: Yes, you are, according to these dots !!! However, they're not exactly right, in that the part of the piece after the two note pick-up is in A major, but the repeat is still in A minor.The music is not really written well. You probably realised that the sharps relate to the next bit, and they should be in the next bar after the repeat, or possibly bracketed in the bar they're in.
Answer: The meaning of this notation is to indicate that you are to switch from the current key signature back to A major for the repetition (since the start of the repetition will not in general announce the key signature if it is not changed from before the beginning of the repetition).
If the start of the repeat is not actually in A major, this is a notation error.  There is no proper notation for "repeat but in a different key".  If that were desired it had to be spelled out explicitly, and it would be the kind of thing one does in a manuscript but never in a printed edition.
Printed editions need to cater for the "perfect sightreader" playing off material in a brainless manner.  "Substitute an entirely different key signature and reinterpret all accidentals accordingly" is not in the skill set pianists spend decades on perfecting.  So if you change the key for a repeated passage, you reprint it in the changed key.
Comment: In this case [it seems](http://imslp.org/wiki/Special:ImagefromIndex/286253) that it is a notation error: the key signature should come after the repeat mark, as Tim suggests in the other answer.

How to read these notes


How to call a function from one Dext to another Dext?

Question: i am trying to write a code to call a function from one dext to another dext.
i have gone through the below link, it has information about sext to dext communication.
How should "NewUserClient" be implemented
may i know any function(or class) for Dext to Dext communication?
how to call a function from one dext to another dext?
Answer: You need to have two iig, one is for your user space driver.
the other one is for your iouserclient.
These two iigs form a dext.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


authz_core keeps denying access

Question: I've configured a webserver more or less according to this tutorial (https://wiki.apache.org/httpd/PHP-FPM) and I can't get PHP to work. HTML-files are served fine. I get the following error message:
mod_authz_core.c(802): [client <myip>:36570] AH01626: authorization result of Require all denied: denied
mod_authz_core.c(802): [client <myip>:36570] AH01626: authorization result of <RequireAny>: denied
127.0.0.1 [client <myip>:36570] AH01630: client denied by server configuration: proxy:fcgi://127.0.0.1:9000/var/www/html/test.php

Here's my PHP file:
www@<server>:/var/www/html$ ls -l
-rw-rw----  1 www www-data    26 Sep  6 09:14 test.php

As you see the file is owned by "www". The webserver and "php-fpm" is running as "www-data".
Here's the basic configuration from the "apache.conf":
<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory>

<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>

<Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

Here's the config for my virtual host:
<VirtualHost *:80>
  ServerAdmin firstname.lastname@example.com

  DocumentRoot /var/www/html

  <Directory "/var/www/html">
    Options FollowSymLinks
    AllowOverride None
    Require all granted
  </Directory>

  ErrorLog /var/log/apache2/error.log

  # Possible values include: debug, info, notice, warn, error, crit,
  # alert, emerg.
  LogLevel debug

  CustomLog /var/log/apache2/access.log combined
  ServerSignature Off

  # Enable forwarding of php requests via php-fpm
  ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/$1
</VirtualHost>

I had the impression that the "Require all granted" part would prevent access to the php file and mod_authz would be happy with it.
I already checked that "php-fpm" is listening as is should:
www@<server>:/etc/php5/fpm/pool.d$ netstat -an | grep :9000
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN

Now I'm out of ideas on where to look next. Any suggestions?
Comment: Please make sure mod_php5 is disabled: `sudo a2dismod php5`
Comment: mod_php5 isn't even installed.
Comment: Your  blocks should not affect anything that is proxied as they only affect requests that Apache itself maps to a file system path (here it is the php-fpm process that is doing that). Look for any Location or Files blocks that are allowing/denying access. You shouldn't need it but you can try adding a  require all granted  to your virtual host.
Comment: Thank you, that did the trick. Time to start reading on  to really understand what's happening.
Comment: It was a check just to make sure, that's why I did not make an answer out of it. I spent some time reasoning on your question but did not find any evident issue @Unbeliever: please write your comment as answer. Glad it's sorted out!
Answer: As requested, here is the answer with some extra explanation.
The error "client denied by server configuration" has some very specific causes, all of which are detailed here http://wiki.apache.org/httpd/ClientDeniedByServerConfiguration
As I mentioned in the comment,  <Directory> blocks do not affect any request that is proxied as they only affect requests that Apache itself maps to a file system path.
Look for any Location or Files blocks that are allowing/denying access to thebase URI path or .php files.
The solution I proposed which seems to have worked was to add the following block to the virtual host.

<Location />
  require all granted
</Location>

I would still suggest looking for other Location/Files blocks in the remainder of your configuration as there should be something else that caused the requests to be denied originally. Adding this block allowed the requested to start working because of the way Apache merges these sorts of blocks, as described in the following link.
https://httpd.apache.org/docs/current/sections.html
Answer: It's very important to make the change in the section that is relevant to the Apache version that you run.
For example if you are running 2.4 then use the
2.4:

  Require all granted

authz_core keeps denying access


Calculate sum with binomial coefficients: $\sum_{k=0}^{n} \frac{1}{k+1} \binom nk x^{k+1}$

Question: I need help with finding the sum of $\sum \limits_{k=0}^{n} \frac{1}{k+1}{n\choose k}x^{k+1}$
Comment: Call it $f(x)$, differentiate. $f'(x)$ should look familiar. Integrate.
Comment: @DanielFischer: .. and remember to add a constant, in casu 1.
Answer: Hint
$$\sum \limits_{k=0}^{n} \frac{1}{k+1}{n\choose k}x^{k+1}=\int_0^x \sum \limits_{k=0}^{n} {n\choose k}t^{k}dt=\int_0^x(1+t)^ndt$$
Can you take it from here?


How can I have profile edit pages displayed in admin theme?

Question: Drupal 8- How to use admin theme for user profile edit page while editing the profile by an administrator.
Example: when admin takes the URL: www.mysite/profile/{id}/edit (This is the URL you get when admin edit a user profile from user profile list.) I need to show the edit form in admin theme
I am using below profile module
version: '8.x-1.0-rc6'
core: '8.x'
project: 'profile'
Answer: The profile form is already designated as an admin route, so you just need to change the permissions for relevant roles so they can view that theme.
The specific permission you're looking for is:

View the administration theme
Comment: Site default admin (administrator role) itself is trying to edit the profile and the page opens in default theme instead of admin theme. Currently i have adjusted it by creating custom module and implement ThemeNegotiatorInterface to display admin theme for that URL. Not sure why its not working in default!


Javascript simple toggle not working

Question: I know this has been asked before in various places but i cannot understand why this is working. On toggle it should show/hide the div. Can some tell me why? Thanks
JS:
jQuery('.box-toggle.fl.active').on('click', function(event) {
    jQuery('#box-content').toggle('show');
  });

fiddle: https://jsfiddle.net/amurray4/cwdt4xeL/
Answer: You need to include the jQuery library in your project

jsFiddle demo
also, since you use an anchor  to register the click, in order to prevent page-jump-to-top following an anchor use Event.preventDefault(), and to secure your jQuery $ alias use:
jQuery(function( $ ){ // Secured $ alias and DOM ready

  // Now use $ (for jQuery) freely:
  $('.box-toggle.fl.active').on('click', function(event) {
    event.preventDefault();
    $('#box-content').toggle('slow'); // Use "slow"
  });
  // other DO Mready code here

});

Comment: sorry... its not staying out for some reason? on toggle it flies out the flies back in. any ideas why?
Comment: @AlexMurray I have no clue. As you can see it works. That's all I can see :(
Comment: yeah weird... if i remove the display: none; it initially shows then flies in the flies out and shows again - so reversed. potentially something in my css
Comment: @AlexMurray :) I really cannot know, buy me a woodoo crystal globe and I'll be happy to help! (or simply post a fiddle with your new issue? :) )
Comment: ha i wish! i figured out that the javascript is running twice on click. any idea why that might be? cheers
Comment: @AlexMurray wait let me connect with your mind... ommmmm :D No, sorry I have no idea ;) Probably you have other handlers bound to that elements? Take a second look at all your code.

Javascript simple toggle not working


Don't know which music I want to play

Question: Ok, I know it sounds like a stupid question but I really mean it.
This is a continuation to my post on why I'm bad at playing guitar.
I picked up a guitar 10 year ago and self taught myself. Being only 18 back then, it was more about "I want to play the guitar" rather than "I want to create music". I cared less if I will play Beethoven or AC/DC, I just wanted to play the guitar as a goal.
I started learning Flamenco for I thought it had unique and impressive techniques. I learned the techniques but had no idea what I am actually playing, was totally dependent on tabs and had zero interest in the Spanish culture on which Flamenco is heavily based on.
I struggled a lot and made poor progress, and eventually decided to move to western music and an electric guitar for it will be easier to a self taught person like myself. I played Surf music for again, it seemed cool and non-mainstream, but after some years it became dull and boring. I tried learning some theory and licks from rock and blues, but didn't persist much for I couldn't relate myself to the music.
People tell me to play the music I like listening to. The problem is that I listen very little to music nowadays, and if I do, it can be anything from Celtic tunes to KISS.
That said, I don't want to put down the guitar. I think that playing music is very beneficial to oneself (develops agility, coordination, ear and according to scientists is good fro the brain in general), but I simply can't find anything fun I want to play, focus on learning or actually caring about.
Comment: I suspect that you just need a new hook, or a fresh kick of inspiration.

Sometimes new gear will do it for you.
I recommend that you get a guitar multi-effects pedal, or a decent (though inexpensive) guitar amplifier that is loaded with modeling amp tones and LOTS of guitar effects.

One I can recommend is the Peavey Vypyr VIP 2.
Once you plug into an amp like that, and begin to explore the bright tones, dark tones, mellow tones, chorus, delay, rotary speaker emulation, octaving, flanging, and phase shifting, you may find yourself transported to a whole new world of inspiration.
Comment: I think you should find something you're passionate about. If that's not even music, that's OK. Hearing and playing music is so deeply emotional, if you don't have passion for it, your playing will always be technical but never spiritual. And if you don't enjoy it, practicing will feel like work.
Comment: it doesn't matter what kind of music you like listening to- pick a favorite song, and you can find the chords online with a quick google search, and probably fingering as well. also, if you don't want to see a teacher, consider finding some more experience guitarists just to play with. this also might help with incentive.
Comment: So why aren't you learning all kinds of music from Celtic tunes to KISS? That's how I taught myself. Well I don't like KISS but my tastes are wide-ranging and I've learned a little bit of almost everything.
Comment: I did, but once I learned how to play it I never had the wish to play them again nor listening to.
Answer: The first that comes to mind is find yourself a teacher. It's said often and it really will make a difference, especially with a good inspirational teacher.
Learning by oneself sometimes works, but in your case, doesn't seem too productive. A teacher will put you right on any 'bad' habits you may have, will give you goals and expectations, and inspire you to greater things.
May even encourage you to take some exams - which, for guitar, could be acoustic, classical, electric, or bass. All of which actually focus one to get a lot of new stuff under one's belt. Very few of my students didn't want to continue down the exam route after taking their first - but never as the only stuff done in lessons. And I didn't (have to) push them - students or exams!
Playing in isolation isn't that good for a lot of players, so finding other like-minded players is another good idea. Might even start a band. It won't be the first time it's happened!
Comment: Great suggestion.  The right teacher will introduce the student to a variety of different styles of music.  A bad teacher might stick strictly to published method books and contribute to boredom and disinterest.   A friend and fellow songwriter who recently took up guitar found a great teacher who has introduced her to a wide variety of different styles of music and she finds the challenge of learning the suggested arrangements of the selected songs very stimulating.  Learning a wide range of types of material has helped her with her songwriting as well.
Answer: Check out yousician.  This is an app or computer program that "listens" to you play. You can learn by tab or traditional notation and it will teach you either chords, or lead guitar (or both), and is sort of like a video game in that the better you play the more stars and points you get.
It may not be as good as a private teacher but it may give you a little incentive to get better. If you are not trying to learn a specific song or style it may be hard to stay motivated as you don't have a good goal, such as "I want to be able to play this song" or "I want to be able to play guitar like this person".  At the very least this will give you a goal that is easily trackable such as "I want to finish this level with all gold stars".
You will find that as you get better at the "game" you will also become better at switching between chords as well as better at playing lead.
The downside is that it doesn't address the "but had no idea what I am actually playing" issue that you were having. To address that maybe try to learn some music theory.
All that being said I don't think you will ever really get hooked on guitar or music theory without being moved by music. Love of music is going to be the ultimate thing that gets you through the pain and frustration of learning to play the guitar. So this app may get you some of the things you want (learning for brain growth, and agility etc), but I think finding something that you love to listen to, even if it is one song, will help a ton. Find a song you love, and then set a goal of learning that song. Then find another. They don't have to be the same style.
edit: one note about the Yousician App: it is free to use for a limited amount of time per day. If you like it you can make it unlimited by paying for a subscription.
Comment: I'll sure check this app, sounds cool! I learned to play many songs I like, sometimes by ear only. However I noticed that after finishing learning a certain song (usually took me several days on average), exhausted from the process I neither listened nor played it anymore.
Comment: @Riddle-Master i understand that feeling completely. Maybe try writing the songs you figure out down, and then after some time away from the process of figuring them out come back to them. this will give you a book of songs that you like AND that you can play. One note about the app: it is free, but limited by the amount of time you can use it per day. if you like it you can get unlimited paid version. i will update post to reflect that. have fun!
Answer: I believe when you finally "discover" music that you really enjoy, you will develop a desire to learn to play that music and develop a passion for it.
But you will need to invest some time searching in order to "discover" the music that you will want to listen to and play.
You may stumble across something you like by randomly listening to a ton of music.  But a more focused, guided approach may help you accomplish your objective much sooner than a random, haphazard approach.
I would encourage you to find time to go to YouTube and start by listening to videos of music that you know you kind of like.  Then YouTube will suggest other videos that are similar.  By sampling the suggestions you will hopefully find other music you like which will trigger more suggestions to sample.  Keep repeating this process and favorite the vids you like best.
Also, streaming music sites (such as Spotify) will make suggestions for new music to sample based on what you indicate that you like.  These services use sophisticated computer algorithms to analyze aspects of every song in order to match common attributes to similar songs.  Most streaming sites offer free versions which integrate the new music suggestions described above.
These services will allow you to create custom playlist and they will also suggest playlists that mix in other music that their analytics software believes  you may like.  Besides using measurable and quantifiable characteristics of the music to render suggestions, their computer will also look at what other users (who like the music you favorite) also like.
By taking time to explore a great deal of new music in this way, you should eventually discover some music you really enjoy.
Then search YouTube for covers of some of the songs you like.  You will often find a YouTuber whose arrangement of a selected song for solo guitar you particularly like.  I get great ideas for unique and interesting ways to play particular songs by watching other musicians YouTube covers.  You can  spot the bad ones early in the vid so you don't waste time.  The better ones usually have more views but there are some gems among the less viewed vids that just have not been discovered or promoted as much.
I believe the music you will love is out there.  You just need to discover it through active, intentional, and focused exploratory listening. The more different music you listen to, the more you learn about what you like and even about music in general.  Hopefully you will enjoy the process.
I am confident that when you do find the music you love, your passion for playing and learning new material on your instrument will stimulate a deeper appreciation for what music can offer - both as a listener and a performer.  The newfound enjoyment for listening and playing music will enrich your life for as long as you choose to engage in playing or listening!
Good luck!
Answer: I'm going to suggest that finding and joining a band or bands, or music groups might be a better answer for you than starting with a teacher.
I came into music entirely self taught. While there were some musicians that inspired me to play certain instruments, I ended up playing with a number of different stylistic groups including Irish music and Folk dance bands that I wasn't particularly interested in initially, but led me to joining a large community that introduced me to many other styles of music.
There are often many opportunities to join a group, and being able to play basic chords along is usually enough to get started. Dance groups of all types are often always looking for more musicians.
Look for open sessions in traditional music like Old Time, Irish/Celtic, Swedish, any Traditional music really.
There is probably an International Folk Dance society near you, or you can use their online resources to find Dance groups in your area. You might become inspired by playing Russian or Greek dance music, or Middle Eastern music for Belly Dance, that you wouldn't have considered otherwise.
There are also music camps just about everywhere, some just for a weekend, some are weeks long. In many cases many different styles of music are represented. Usually there are workshops on the different styles, and open sessions to try the music out. You can also meet other musicians with whom you might want to start a playing group with.
Working with a group of musicians opens you up to different ideas that the other  members have, and can introduce you to their knowledge and ideas about what music is all about, and inspire you in different directions than you would go just working by yourself.
Answer: You can try to play along a recorded song, or to solo along an instrumental backing track, it is fun and useful to learn. Also you can join a band.
Comment: It is unclear to me how the suggestion to play along with recordings will help the OP to learn what kind of music they want to play, given that the whole point of the question is that they don't know what kind of music they want to play, and even that they "listen to very little music nowadays." Is this answer really just suggesting that the OP try some stuff?

Don't know which music I want to play


How to download string from HTTPS website in windows phone 8

Question: I am windows phone developer, I want to download string from HTTPS web site and I use
WebClient most_down_download = new WebClient();
most_down_download.DownloadStringCompleted += Most_down_download_DownloadStringCompleted;
most_down_download.DownloadStringAsync(new Uri(https_url));

but it is not working. Can you help me?
Answer: Maybe something like this? Using HTTP Client instead of web Client (8.1)
HttpClient http = new System.Net.Http.HttpClient();
HttpResponseMessage response = await http.GetAsync(https_url);
webresponse = await response.Content.ReadAsStringAsync();

Reference here
Comment: thanks you for your support, but it stils not working .
Comment: not error message,but output not fully html file behind
Answer: You need generate Most_down_download_DownloadStringCompleted event handler as below
void Most_down_download_DownloadStringCompleted(object sender,
                              System.Net.DownloadStringCompletedEventArgs e)
{
    try
    {
        if (e.Error == null)
        {
            string response = e.Result.ToString();
        }
    }
    catch (Exception ex)
    { }
}

And in e.Result.ToString() you are getting string from Web site


Prove Equivalence Relation in G

Question: Hei, guys!
I'm having some trouble with the next problem:
Let $A$ and $B$ be subgroups of $G$. Show that $\sim$ is an equivalence relation when it is
defined as follows:
$g\sim g'\Leftrightarrow g' = agb$ for some $a$ from $A$, $b$ from $B$.
Should I prove this is valid for any a and b? It says for some elements a and b. But I might as well take the unit element.
Could you give me a clue on how to solve it?
Cheers!
Comment: You can show your proposed relation is an equivalence relation by checking reflexivity, symmetry, and transitivity. Your note that $a$ and $b$ may be the identity element is particular useful for the first property.
Comment: Thanks for your comment! I thought a and b must be any elements of A and B, respectively. This makes it so easy!
Answer: We can show that by verifying 3 properties:

Reflexive- $x\sim x$ by using $a = b =e$ which obviously exists since $A,B$ are subgroups and therefore, $e \in A,B$.
Symmetric - $x\sim y$ then there exist $a\in A$ and $b\in B$ s.t. $y = axb$. $A, B$ are subgroups and therefore $a^{-1}\in A$ and $b^{-1}\in B$ and therefore $x = a^{-1}yb^{-1}$ which imply $ y\sim x$
Trasitive - $x\sim y$ and $y\sim z$ then there are $a,a'\in A, b,b'\in B$ s.t. $y=axb$ and $z=a'yb'$ and by subtitution of $y$ we get $z = aa'xb'b$ and because $A,B$ are subgroup and closed under multiplextion we get that $aa'\in A$ and $bb'\in B$ and therefore $x\sim z$
Comment: Thanks for the answer!  I guess I didn't really understand the concept of equivalence relation since I thought a and b must be any elements of A and B, respectively.
Answer: The problem says $ g \sim g' $ if and only if there are elements $ a \in A $ and $b \in B$ such that $ g' = agb  $
Reflexivity: For this the unit element which is present in both $A$ and $B$ is exactly what you need.
Symmetry: We need to show that if $ g \sim g'$ then $g' \sim g$. That is if there are elements $a \in A, b \in B $ such that $ g' = agb $ then there are elements $ a' \in A, b' \in B $ such that $ g = a'g'b' $. Try using the inverse elements of $a$ and $b$
Transitivity:  We are given that $ g \sim g' $ and $g' \sim g'' $ from which we need to prove that $ g \sim g'' $. From the assumption there are elements $ a, a' \in A $ and $b, b' \in B$ such that $g' = agb $ and $ g'' = a'g'b' $. Think of the most obvious substitution. Then think why there must be elements $ a'a \in A $ and $b'b \in B$ which give us the required relation between $g$ and $g''$
Answer: i. Reflexivity
$g \sim g$.  $\ \ \ $Indeed, for $\ \exists\ \  e_{A} \in A\ \    \text{and}\ \  e_{B} \in B\ \  \text{such that}\ \  g= e_{A}\ g\ e_{B} \Rightarrow g = g$.
ii. Symmetry
$g \sim g' \Rightarrow g'\sim g$. $\ \ \ $ Since there are $a \in A $ and $b \in B$ such that $g = a\ g\ b$ then as $A$ and $B$ are subgroups, there exist $a^{-1} \in A$ and $b^{-1} \in B$ such that $g=a\ g'\ b \Rightarrow g' = a^{-1}\ g \ b^{-1}   \Rightarrow g' \sim g $.
iii. Transitivity
$g \sim g''$ and $g'' \sim g' \Rightarrow g \sim g'$. $\ \ \ $In fact, there exist $a',a'' \in A$ and $b',b'' \in B$  such that $g = a''\ g''\ b''$ and $g'' = a'\  g'\ b'$, then $g = a'' \ (a'\ g' \ b') \ b'' \Rightarrow g = (a' a'')\ g'\ (b' \ b'')$. Let $a : = a'\ a'' \in A$, and $b := b'\ b'' \in B$ then we have $g = a\ g'\ b$ which means that $g \sim g'$.
A very important notion in Groups lies on this equivalence relation as follow
$$ y \sim x \Leftrightarrow \exists h \in H\ \  \text{such that}\ \ y = xh$$
As an exercise you could show that this is an equivalence relation. This set $ \lbrace y \in G ; y \sim x \rbrace = \lbrace xh ; h \in H \rbrace$ is denoted by $xH$ and is called left coset.
Comment: Hei! Thanks for the answer.  Can you please tell me why it is so important and whether you know any applications in physics?
Comment: Sure, anytime!!
Comment: Yes, search for something called Lie Groups. There are great applications in modern Physics. Check [here](http://www.physics.oregonstate.edu/~stetza/Lie.pdf).

Prove Equivalence Relation in G


Largest Difference within a list of integers

Question: I've been trying to write a recursive function which takes a list of numbers such as [5;6;7;8;2;3;4] and returns 3 by finding the largest difference between sequences of ascending numbers in a list but have no idea where to go.
Comment: What exactly are you referring to with the "difference between sequences of numbers"?
Comment: e.g. 5-8 = 3 is the greatest difference in a sequence of ascending numbers in this list
Comment: you should give at least a small piece of code showing that you actually tried it yourself
Answer: The function signature should take the lowest number of the current sequence, the highest number of the current sequence and the remainding sequence. If the head of the remaining list is bigger than the highest number of the current sequence, just recurse with the new highest number. Otherwise, return the maximum of the current difference and the recursive call for the remainder with the current head as minimum and maximum.


Field from form:select not being set in modelAttribute on form submit using Spring MVC

Question: Form class
 public class DocumentCaptureForm {
        private final static Logger logger = Logger.getLogger(DocumentCaptureForm.class);

        private String artifactCaptureJSON;
        private String isBackside;

        public String getArtifactCaptureJSON() {
            return artifactCaptureJSON;
        }

        public void setArtifactCaptureJSON(String artifactCaptureJSON) {
            this.artifactCaptureJSON = artifactCaptureJSON;
        }

        public String getIsBackside() {
            return isBackside;
        }

        public void setIsBackside(String isBackside) {
            this.isBackside = isBackside;
        }

JSP
<form:form modelAttribute="documentCaptureForm"  action="/capture" method="post" autocomplete="off">

<form:hidden path="artifactCaptureJSON" id="artifactCaptureJSON"/>

        Document Side<form:select id="isBackside" path="isBackside">
            <form:option selected="selected" value="Front">Front</form:option>
            <form:option value="Back">Back</form:option>
        </form:select>

        <input type="submit"  id="capturesave" value="Save" />
</form:form>

Controller
@RequestMapping(value="/capture", method=RequestMethod.POST)
public ModelAndView captureArtifacts(@PathVariable long applicationPKId,
        @ModelAttribute("documentCaptureForm") DocumentCaptureForm documentCaptureForm, BindingResult result,
        HttpServletRequest request){
    logger.debug("Entering captureArtifacts ...");

    ModelAndView mav = new ModelAndView(DOCUMENT_CAPTURE_VIEW);
    mav.addObject("title", "Capture Document");
    ArtifactCaptureData artifactData = documentCaptureForm.convertToJava();

    boolean isBackside = documentCaptureForm.getIsBackside().equals("Back");

artifact capture JSON has it's value set in a javascript function after the user does something on the page. That value is correctly populated when the form is posted to the controller. The field from the form select however appears to be ignored. isBackside is null no matter what I try
Answer: In <form:select> tag, besides a 'path' attribute you can add 'items' attribute with passing to it a  list with several options. So you can do something like this:
<form:select path="isBackside" items="${['Front','Back']}" />

This is the simplest way to do this.


Logic to find an object under cursor in screen

Question: I want to know general logic to find a screen object under a point.
Let there be various shapes on screen and I want to find a shape(or shapes) on some point, probably the mouse cursor point. If all those shapes are rectangles, it'll be a trivial question. But what about triangles and ovals and...
In other words, what is the general logic behind any gui systems which find out which object is clicked or under cursor? Or, what is the logic behind any games which find out which character is clicked or under cursor?
Probably this kind of question was asked before, but I couldn't find.
edit) At least I want to know the pixel-based 2D algorithm. I found there's Point-in-polygon problem, but it's not about ovals and other irregular shapes.
Comment: I read somewhere that's saying you can find an object by masking an object with a single color and check the cursor's hot point color. Probably this should be done by VGA as main cpu may not afford.
Answer: That's a bit broad... the general logic, would be to use the API of whatever you're interfacing with.
This would vary depending on what indeed it is you're dealing with - the general logic is going to be completely different for a 3D application compared to a 2D windowing system. Again, if you're dealing with a 2D application is this application full screen, so you only have to consider absolute X,Y values - or is it under a windowing system in which case you care more about X,Y in relation to the window as opposed to the entire screen.


customTabBarController not a structure or a union?

Question: I am geeting an error customTabBarController not a structure or union?
What the reason for this kind of error?
Many Thanks in advance for your help.
Answer: It's not defined in your class, or you did not #import the header.
Comment: i did imported the header file and not sure about the declearation part. Can you please explain. Thanks


MPMoviePlayerController not in UIView

Question: I am trying to add a MPMoviePlayerController to a UIView.
I am doing it, but it is appearing at the top of my view instead of the position the UIView has in my storyboard.
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
moviePlayer.controlStyle = MPMovieControlStyleNone;
moviePlayer.view.frame = videoView.bounds;
moviePlayer.scalingMode = MPMovieScalingModeFill;
moviePlayer.scalingMode = UIViewContentModeScaleAspectFit;
moviePlayer.repeatMode = MPMovieRepeatModeOne;
[self.view addSubview:moviePlayer.view];

Any ideas?
Comment: What is videoView?  What is self.view?  You set it to videoView.bounds, so the x,y origins are at o,o.
Answer: Change [self.view addSubview:moviePlayer.view]; to [videoView addSubview:moviePlayer.view];
If you want your moviePlayer to be at the position of your UIView, you have to add it as a subview to that particular UIView. If you add your moviePlayer to self.view it will be added on top of every other subview.
EDIT: If you want to add the moviePlayer as a subview to your main view, then change moviePlayer.view.frame = videoView.bounds; to moviePlayer.view.frame = videoView.frame;

MPMoviePlayerController not in UIView


How to prove there are $\frac{3^n-1}{2}$ couples $A,B \in \mathcal{P}([n])$ such that $A \cup B = [n]$, $A \neq B$.

Question: Consider the unordered couple of sets $A,B \in \mathcal{P}([n])$ such that $A \cup B = [n]$, $A \neq B$. I would like to prove that the number of such couples is:
$$\frac{3^n-1}{2}$$
I derived that expression by enumerating the solutions for the first values of $n$, and also considering the sum of the number of those couples for all different values of $n$ over $\mathcal{P}([m])$:
$${2^m \choose 2} = \sum_{n=0}^m {m \choose n}\frac{3^n-1}{2}$$
(this is easy to show using the binomial expansion).
I have checked OEIS A003462 where they count the number of couples $A,B \in \mathcal{P}([n])$ with $A \cap B = \emptyset$ and $A \neq \emptyset$ or $B \neq \emptyset$, with the same $\frac{3^n-1}{2}$ result, but it's not the same thing and I was not able to adapt that reasoning.
Comment: $[n] = \{1, 2, \ldots, n\}$. If you prefer, replace it with any other $n$-element set.
Comment: What does $[n]$ mean please?
Answer: You seem to treat $A,B$ as unordered... that for instance $A=\{1,2\}$ and $B=\{3,4,5,6\}$ to be the same result than $A=\{3,4,5,6\}$ and $B=\{1,2\}$.  For the time being let us go with the other interpretation that these are distinct outcomes as it makes the math far simpler.
Now... for each element $x$ in $[n]=\{1,2,3,\dots,n\}$ for it to be that $A\cup B=[n]$ as well as $A\subseteq [n]$ and $B\subseteq [n]$, exactly one of the following must be true:

$x\in A$ and $x\notin B$
$x\in B$ and $x\notin A$
$x\in A$ and $x\in B$

For each element choose which of these three it is.  Apply rule of product.  That gives $3\times 3\times 3\times \cdots \times 3 = 3^n$ different choices of $A,B$.
This included in it however the possibility that we answered $x\in A$ and $x\in B$ for every $x$ which would have meant that $A=B$.  You explicitly wanted to avoid this case, so subtracting $1$ will correct the count.
Finally, you seemed to be wanting to talk about unlabled pairs of sets rather than labeled pairs of sets.  Dividing by $2$ corrects that aspect of the count.  (Note that every outcome was counted twice.  The only outcome that might have been counted only once was the case where $A=B$ but that was already removed)
This gives, as expected, the final result of:
$$\frac{3^n-1}{2}$$
Answer: Alternatively, using what you found in OEIS, take $\{A,B\}$ with $A\cap B=\emptyset,$ $A,B\neq \emptyset$ and consider $C=[n]\setminus (A\cup B)$ counted by the expression. Now, consider mapping that set to $\{A\cup C,B\cup C\},$ check that the properties that you required are satisfied and, moreover, this mapping is a bijection. So both problems have the same number of solutions.
Answer: Note that $A\cup B=(A\setminus B)\cup(A\cap B)\cup(B\setminus A)$ is a disjoint union. Assign to each unordered couple $\{A,B\}$ the $n$-length ternary string $(a_1,a_2,\ldots,a_n)$ defined by $$a_j=\begin{cases}0\quad\text{if $a_j\in A\setminus B$}\\1\quad\text{if $a_j\in A\cap B$}\\2\quad\text{if $a_j\in B\setminus A$}\end{cases}$$


Moment.js not displaying results

Question: I'm having problem displaying 24hr time string converted to 12hr format using moment.js still looking for a solution
html code

Javascript

Update
Forgot to add CSS to styles
#showtime {
    font-size:30px;
}

Comment: http://jsfiddle.net/arunpjohny/4uvk6fm1/1/ - looks just fine
Comment: is there any error in your browser console - whether the script is placed after the element in your markup
Comment: Oh darn I had to make a CSS selector its all fixed. thanks
Answer: The problem was I forgot to add CSS to stylesheet updated code below
#showtime {
    font-size:30px;
}

Moment.js not displaying results


jquerytools toggle play/pause button on scrollable

Question: Hello im building a slide on Jquerytools , using this http://jquerytools.org/demos/scrollable/gallery.html
And autoscroll http://jquerytools.org/documentation/scrollable/autoscroll.html
http://jsfiddle.net/PcAwU/
My problem is i can merge the Play & Pause buttons so if play is active, pause is displayed, and vice versa..
http://jsfiddle.net/PcAwU/ Here you can find my code..
Also if you can tell me how to change the
<button type="button" onClick="api.play()">Play</button>

Whit the normal img link so i can make image buttons like

just with the correct syntax,
The last issue, is that in this part i try to replace de click with hover. but the first image wont show up when loading the page.. so i create a "malfunction" when i do that
this line is where i change "click" with "hover"
$(".items img").click(function() {

Answer: Solved using

And the buttons go like this:
<input type="image" src="images/atras.png" onclick="api.prev()" >

   <input type="image" src="images/pause.png" class="pause" onclick="toggle(this);" >

   <input type="image" src="images/adelante.png" onclick="api.next()" >

I hope this helps somebody


How can I make my voice sound like a breathy female?

Question: My vocal category is technically "Bass" (not Baritone). But I can hit some pretty high notes easily; I have a wide range. When I hit high notes though, it always sounds unmistakably male I think.
I'd like to sing my own vocals from some breathy high-pitched female parts... Do you have any recommendations about generally what effects chain and parameters I should use to get the most realistic quality? I don't want to sound falsetto or strained.
Comment: Audacity for pitch-shift, followed by 5% white-noise generator?  :-)
Answer: The breathy/husky female voice type is not a reasonable target for a bass.  To get a consistent range, you'll want to extent your falsetto as far down as possible.  It is different from "head voice" in that the larynx basically has two antagonistic muscle groups for pitch control: one is stretching the vocal folds long for increasing pitch, the other tenses the material of the folds themselves.
The mechanisms for chest voice has the fold muscles primarily responsible, the falsetto relaxes those and just relies on longitudinal tension.  There is no stable equilibrium in between.  The normal "head" voice used by tenors is usually an extension of the chest voice configuration, but navigating the unstable equilibrium with a "mixed voice" smoothly blending into actual falsetto takes years of practice.
For a bass-based countertenor, it's usually easiest to work your way from the falsetto downwards.  The low notes, once you get them in the falsetto configuration, are more of a raspy than husky sound quality.  Huskiness basically is a sign of bad vocal closure, and with bass vocal folds, you can't expect reasonable volume.  Microphones make a difference, of course, but they cannot do everything.
Think about finding a voice teacher who is willing to work with you and your range and possibilities.
Comment: "Falsetto" as such is not depending on the underlying voice type.  Where and when and how to get in and out of it, what range and volume you can access with it, and the "continuity" you build with it are.  When your aim is to "pass off as a female", that implies projecting a character and gives you the challenge of finding ways to access and combine your various registers in a manner consistent with your character.  It also means you need to work on a speech register consistent with your vocal image.  In contrast, an "art voice" separated from a "character" can focus on beauty instead of sex.
Comment: Interesting description of falsetto for a bass, it hadn't occurred to be that it would be different depending on your underlying voice.
Answer: Which genre? You explicitly mention not wanting to sound falsetto but I wouldn't give up on that completely. In the classical music scene there's been a big revival in the countertenor voice since it was popularised by Alfred Deller. One hugely talented contemporary practitioner is Andreas Scholl. Countertenors often approach repertoire that was written for castratos (don't go there) but which had mainly been taken over by sopranos. The male falsetto voice, or head voice, is weaker and has a smaller range than sopranos or castratos but these recent proponents have shown that with training they can approach the required range and power. One of my favourite pieces of Scholl singing has him drop, for a few beats, into his tenor voice - it's quite startling: "Pallido il sole" (from Hasse's 1730 opera Artaserse, the drop is 3:28 in), and here is another example of how beautiful he sounds: "Ombra mai fù" (the opening aria from Handel's 1738 opera Serse)
(N.B. I know this isn't an answer, it gets you no closer to the breathy female voice, but it felt too long for a comment.)
Comment: I think it's relevant, at at least covers the "female" aspect if not expressly "breathy".


Is there a way to divide an integer-sided square into integer-sided non-right triangles?

Question: Integer-sided right triangles will fit into a square:

but how about integer-sided non-right triangles?
Here's a near miss - they don't quite fit like this:

Is it possible?
Comment: It wasn't me that found it. Penny Drastik, a primary student at The Illawarra Grammar School in Australia, aged 10, found it: [link](http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Pythag/pythag.html#pythjigsaws)
Comment: It looks like the [British flag theorem](http://en.wikipedia.org/wiki/British_flag_theorem) might be useful.
Comment: How did you find the first case?
Answer:
I just used a hastily written electronic computer program:
<code>// gcc british_flag.c -o british_flag.exe -std=c99 -Wall -O3

#include <stdio.h>

static int square(int x);
static int is_square(int x, int* square_root);

#define MAX 50

int main() {
  int z11, z12, z21, z22;

  int solution_exists[MAX][MAX];

  for (int x = 0; x < MAX; x++) {
    for (int y = 0; y < MAX; y++) {
      solution_exists[x][y] = 0;
    }
  }

  for (int x = 1; x < MAX; x++)
  for (int y = 1; y < MAX; y++)
  for (int x2 = 1; x2 < x; x2++)
  for (int y2 = 1; y2 < y; y2++) {
    int x1 = x - x2;
    int y1 = y - y2;

    if (is_square(x1*x1 + y1*y1, &z11)
     && is_square(x2*x2 + y1*y1, &z21)
     && is_square(x1*x1 + y2*y2, &z12)
     && is_square(x2*x2 + y2*y2, &z22)
    ) {
      if ( square(x) == square(z11) + square(z21) ) continue;
      if ( square(x) == square(z12) + square(z22) ) continue;
      if ( square(y) == square(z11) + square(z12) ) continue;
      if ( square(y) == square(z21) + square(z22) ) continue;
      printf("(%d, %d) %d %d by %d %d\n", x, y, x1, x2, y1, y2);
      solution_exists[x][y] = 1;
    }
  }

  return 0;
}

static int square(int x) {
  return x*x;
}

static int is_square(int x, int* square_root) {
  int min = 0;
  int max = x;

  while(1) {
    *square_root = (min + max)/2;
    if (*square_root * *square_root == x) return 1;
    if (min >= max) return 0;

    if (*square_root * *square_root <  x) {
      min = *square_root + 1;
    }
    if (*square_root * *square_root >  x) {
      max = *square_root - 1;
    }
  }
}
</code>
Not very insightful but I suspect (and I'm sure someone can prove) that no solution exists which is only made of 4 triangle meeting at a single point in the middle.  It also leaves behind the question of what the fewest number of triangles possible is.


Remove 1 of 3 map overlays

Question: I have an app that displays points on a map. There are 3 map overlays (1) for the current user; (2) for the user's friends/contacts; (3) for other people. I am trying to allow the use to select what is displayed on the map. The goal is to allow them to display everyone (user, friends and others) or to filter the map to display just their friends/contacts.
I can add the different overlays to the map just fine. The problem is removing the overlays.
I tried the approach here -- How to refresh an activity? Map View refresh fails -- which suggests to remove items by index using the following code:
private void showFriends(){

mapOverlays = mapView.getOverlays();
int j = othersMapOverlay.size();
for(int i = friendsMapOverlay.size; i < j; i++){
    mapOverlays.remove(i);
}
mapView.invalidate();
}

My strategy here was to create a list of all overlays - mapOverlays and then, using the for loop, start from the end of the first overlay, friendsMapOverlay, and remove until I reached the end of the second map overlay, othersMapOverlay.
That didn't work.
I also tried to remove the list object using both
mapOverlays.remove(othersMapOverlay);

or
mapView.getOverlays().remove(othersMapOverlay);

but neither of these does the trick. Any idea how to fix this?
Answer: Ended up using the following. Its not really hiding or removing an overlay just clearing and redrawing. This has to be less efficient than what I want to do - i.e. just remove what's there but it works. . . for now.
private void showEveryone(){

    mapOverlays = mapView.getOverlays();
    mapOverlays.clear();
    mapView.invalidate();
    JSONArray friends = buildFriendList();
    JSONArray others = buildOthersList();
    getUserDataForMap(friends, "friends");
    getUserDataForMap(others, "others");

}

Remove 1 of 3 map overlays


Select all but first two divs

Question: I can use the following to select all divs that are not the first div among their siblings.
div:not(:nth-of-type(1))

Is there anyway I can select all div's that are not the first two?
Answer: You can use sequential :not pseudos, so: div:not(:nth-of-type(1)):not(:nth-of-type(2))
http://jsfiddle.net/akm4qnds/
OR
Even better, you can use sibilings selectors... Like div:condition ~ div that will select every sibiling divs that are after the one with the condition.
So: div:nth-of-type(2) ~ div will select every div that comes after the second child.
http://jsfiddle.net/akm4qnds/1/
Answer: You can use multiple :not to exclude multiple items
Example
div:not(:nth-child(1)):not(:nth-child(2)) {
    background: blue;
}

DEMO
Answer: It can even be dome more clear, without specifically writing out the not pseudo selector per element.
U can do this the get the same results:
:not(:nth-of-type(-n+2)) {

}

:not(:nth-child(-n+2)) {

}

I know its a late answer:P but maybe still usefull to somebody

Select all but first two divs


Can all possible pairs of comparison be planned comparisons in ANOVA?

Question: Let's say we have three intervention groups (condition A, condition B, and condition C/control) to be analyzed in ANOVA, and we are theoretically interested in the difference between each pair of all the possible comparisons (i.e., A and B, B and C, and A and C). Since the three comparisons are according to the hypotheses, I thought that it would be ok to describe this as planned comparisons. However, the planned comparisons do look like post-hoc tests (that test all possible comparisons for exploratory purposes). Is it still acceptable to consider it as planned comparisons without the necessity to adjust the p values? Or should I regard it as post-hoc tests and adjust the p values for multiple testing?
Summary of the suggestions:

I am starting to understand that what I described is not really how planned comparisons should be done. When I run planned contrasts, I may start from comparing intervention groups (A & B) vs. control group (C), followed by the comparison of the two intervention groups (A vs. B). Alternatively, I can focus on a specific pair, although the maximum number of contrasts should be k-1, as BruceET has suggested. (15/Sep/2021)
Thank you so much for your brilliant insights, Tanner! It is important to adjust significance level to avoid false findings when running multiple tests. Together with COOLSerdash's critical suggestions, I may not adjust the significance level when I have a specific hypothesis for each comparison (17/Sep/2021).
Comment: If you have a factor with $k$ levels, then that factor has $k-1$ degrees of freedom and you should be able to find $k-1$ orthogonal contrasts, all of which can be tested as a package of "pre-planned" orthogonal contrasts. [For exmp: If you have 3 levels ABC, then you could compare 'A vs B' and 'avg of A&B vs C'. Maybe google "orthogonal preplanned contrasts".] If you want to make more comparisons or non-orthogonal ones, the usual procedures of avoiding false discover in _ad hoc_ testing apply. // A separate issue is how many of the $k-1$ orthogonal contrasts are of practical interest to you.
Comment: Thank you so much for your advice! I am beginning to understand that I should do A & B vs. Control first. Then, I could move on to A vs. B. So it becomes two contrasts in total at most (3 factors -1 = 2 contrasts/degrees of freedom), out of which I can choose the contrasts of interest.
Answer: It's not only possible, it's explicitly recommended (see Ruxton & Beauchamp 2008).
First, if the omnibus-test of homogeneity across all groups is not of interest (e.g. the overall ANOVA $F$-test), consider not paying attention to it at all or not doing it in the first place. Second, if each planned comparison tests a different specific hypothesis, it is actually controversial if a formal control of the experimentwise type 1 error rate (EER) is required or not. Some text do not consider it necessary (Kirk 1995, Quinn & Keough 2002, Rothman 1990, Rubin 2021, Sokal & Rohlf 1995). Ruxton & Beauchamp (2008) recommend not controlling EER if the set of pre-planned contrasts is orthogonal. If all possible pairwise comparisons between groups are planned, the set of contrasts is not orthogonal and so, Ruxton & Beauchamp (2008) recommend controlling EER.
Rubin (2021) on the other hand argues that in the case of individual testing, no alpha adjustment should be done. He defines individual testing as tests, where each individual result must be significant in order to reject each associated individual null hypothesis. This seems to be the case here if you want to test each pairwise group difference individually. Personally, I find his arguments convincing and have subsequently changed my own opinion on the matter.
References
Kirk RE. 1995. Experimental design. Pacific Grove (CA): Brooks/Cole.
Quinn GP, Keough MJ. 2002. Experimental design and data analysis for biologists. Cambridge (UK): Cambridge University Press.
Rothman, K. J. (1990). No adjustments are needed for multiple comparisons. Epidemiology, 43-46. (link)
Rubin, M. (2021). When to adjust alpha during multiple testing: A consideration of disjunction, conjunction, and individual testing. Synthese, 1-32. (link)
Ruxton, G. D., & Beauchamp, G. (2008). Time for some a priori thinking about post hoc testing. Behavioral ecology, 19(3), 690-693. (link)
Sokal RR, Rohlf FJ. 1995. Biometry. 3rd ed. New York: WH Freeman.
Comment: Ok, I did not know that! I have done so for the people who contributed to this topic. Thank you so much for you comments and suggestions!
Comment: Thank you so much for your detailed comments on this topic and sharing your references, COOLSerdash. I see this is a hotly debated topic and will need to learn about whether/when control of significance level becomes necessary.
Comment: @Atsushi If you're satisfied with an answer (mine or any other), consider upvoting it by clicking on the "arrow up" symbol on the left. If you're feeling that this answers your question fully, consider accepting it by clicking on the check mark.
Answer: The need for P-value adjustments is not due to "planning vs. post-hoc" but about alpha inflation. If I understand your analysis plan correctly, you would like to do pairwise tests comparing the relationship between each pair: AB, BC, AC.
At an alpha of 0.05 (i.e. p-value threshold of .05) you are excepting a 5% risk of there NOT actually being a statistically significant difference between the groups even though you said there was. So if you run three tests, you are actually taking a 5% risk three times, and your "true" risk level is no longer 5%, it's closer to 15%.
This has nothing to do with whether you planned these tests ahead of time or not-- it is simple a matter of re-testing the same data 3 times. So, yes, you should use p-value adjustments.
Note: the true test risk is not exactly 15%. It can be calculated with the binomial distribution, but the intuition seemed sufficient to answer this question.
Comment: I'd tweak this to remove the mention of "statistically significant" in the second paragraph. (Do you see why?) Then this would get a +1 from me.
Comment: Then, why do researchers recommend we consider significance adjustment when there are no preplanned hypotheses? https://onlinelibrary.wiley.com/doi/full/10.1111/opo.12131


Extending the Windows Task Scheduler log file

Question: The windows task scheduler logs the results of each task run in a file named Schedlgu.txt in the windows directory.
This file is automatically rotated when it reaches a certain size. Is there any way to extend this to a larger file size, since I have a server with so many tasks running that I only have around 30 minutes worth of logging available.
Answer: Edit HKEY_LOCAL_MACHINE\Software\Microsoft\SchedulingAgent\MaxLogSizeKB DWord value


How to debug a check-in policy DLL that can not be loaded?

Question: I've written a series of check-in policies and based on principals of OOAD, I used some inheritance and stuff to reuse some code.
Now I've got this hierarchy:

General set of check-in policies
Specific set of check-in policies

Each is a class library project, and the specific class library references general class library.
Now I don't have problem in loading general set of check-in policies. But when I want to load specific set, Visual Studio complains that it can't load the DLL, and it's so dumb, that it doesn't give me more information there:

How can I debug it? I'm stuck at this step. I can't find why it can't load my DLL, and I can't find LoaderException details.
Comment: When combining projects you should never copy a dll from one project to another because the source code is no longer link to the dll.  When combining project always browse to the dll where the source code is located.  I usually use the Solution explorer and add an existing item to the project.  The best solution is to copy the bin folder in the main project and then delete the bin.  Then delete all the dlls in the Solution Explorer and add them again this time browsing to the folder where they were built.
Answer: If you want to debug your check-in policy. Go to the properties of your check-in policy class project and look under the debug tab, find a Start Action. Select to "Start external program" and browse to where you have visual studio installed. C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe

With this in place and the proper registry keys for loading the policy DLL from your debug folder all you need to do is hit Run and a second copy of VS will load up.
If you want to debug a class library (DLL) project in Visual Studio, please reference this How to debug a class library in Visual Studio
Comment: I did this, but just another instance of Visual Studio opens. I have a class library, thus I turned it into a Console application and in the entry main method, I wrote some code. But still my breakpoints are not hit. How to run code here?


Intantiating a viewmodel using dagger2 in BaseFragment

Question: I am sort of new to Dagger and still learning it. According to the tutorials and blogs I read, currently Android does not have a way of injecting dependencies into ViewModels hence we need to use a custom ViewModelProvider.Factory, that said, I managed to get my hands on this one
public class ViewModelProviderFactory implements ViewModelProvider.Factory {
private static final String TAG = ViewModelProviderFactory.class.getSimpleName();
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;

@Inject
public ViewModelProviderFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
    this.creators = creators;
}

@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
    Provider<? extends ViewModel> creator = creators.get(modelClass);
    if (creator == null) {
        for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
            if (modelClass.isAssignableFrom(entry.getKey())) {
                creator = entry.getValue();
                break;
            }
        }
    }

    if (creator == null) {
        throw new IllegalArgumentException("unknown model class " + modelClass);
    }

    try {
        return (T) creator.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
 }
}

It works, it has worked for many of my use cases until now. Originally I had to an instance of a ViewModel with something like this
public AFragment extends BaseFragment{

    @Inject
    ViewModelProviderFactory providerFactory;
    private MyViewModel viewModel;

    MyViewModel getViewModel(){
       return ViewModelProviders.of(this, providerFactory).get(MyViewModel.class);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      viewModel = getViewModel();
      tokenAuthenticator.setAuthenticatorListener(this);
    }

 }

But as the project grew I realized this was not neat, I had to do this in all my fragments so I opted for a different approach, I wanted to instantiate my ViewModel in my BaseFragment instead and I did this
public abstract class BaseFragment<T extends BaseViewModel, E extends ViewDataBinding> extends DaggerFragment implements TokenAuthenticator.AuthenticatorListener {
    private static final String TAG = BaseFragment.class.getSimpleName();
    public E binding;
    public final CompositeDisposable disposables = new CompositeDisposable();
    public T viewModel;
    @Inject
    ViewModelProviderFactory providerFactory;
    private int layoutId;

    /**
     * @return view model instance
     */

    public T getViewModel() {
        final Type[] types = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
        return ViewModelProviders.of(this, providerFactory).get((Class<T>)types[0]);
    }

}
This gives me  compile error
  A binding with matching key exists in component: xxx.xxx.core.base.dagger.builders.FragmentBuilderModule_ContributeDeliveryPlanFragment.DeliveryPlanFragmentSubcomponent
  .
  .
  .
  A binding with matching key exists in component: xxx.xxx.core.base.dagger.builders.FragmentBuilderModule_ContributePayWithMtmMobileMoneyFragment.PayWithMtmMobileMoneyFragmentSubcomponent
      java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> is injected at
         xxx.xxx.core.base.ViewModelProviderFactory(creators)
      xxx.xxx.core.base.ViewModelProviderFactory is injected at
          mika.e.mikaexpressstore.core.base.BaseFragment.providerFactory
      xxx.xxx.xxx.xxx.cashondelivery.CashOnDeliveryFragment is injected at
          dagger.android.AndroidInjector.inject(T) [xxx.xxx.core.base.dagger.component.AppComponent → xxx.xxx.core.base.dagger.builders.FragmentBuilderModule_ContributeCashOnDeliveryFragment.CashOnDeliveryFragmentSubcomponent]
2 errors

From the error message I can tell Dagger is complaining the ViewModelProviderFactory is being injected in the base but used in the child, I need help, is there a way to make this work? surely I want to reduce on boilerplate and repetitive code.
Answer: I finally fixed it, not how I wanted but better than having to instantiate each viewmodel from the child class. After reading this answer I came to a realization that this was not possible, so instead I removed @Inject annotation from ViewModelProviderFactory in my BaseFragment and it looked like
public abstract class BaseFragment<T extends BaseViewModel, E extends ViewDataBinding> extends DaggerFragment implements TokenAuthenticator.AuthenticatorListener {
    private static final String TAG = BaseFragment.class.getSimpleName();
    public E binding;
    public final CompositeDisposable disposables = new CompositeDisposable();
    public T viewModel;
    @Inject
    private ViewModelProviderFactory providerFactory;
    private int layoutId;

    /**
     * @return view model instance
     */

    public T getViewModel() {
        final Type[] types = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
        return ViewModelProviders.of(this, providerFactory).get((Class<T>)types[0]);
    }

    @MainThread
    protected final void setProviderFactory(ViewModelProviderFactory providerFactory) {
        this.providerFactory = providerFactory;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     viewModel = getViewModel();
   }

}

And injected the provider from the child fragments instead then called the setter from the BaseFragment
public AFragment extends BaseFragment{

    @Inject
    ViewModelProviderFactory providerFactory;
    private MyViewModel viewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setLayoutId(R.layout.layout_layout);
        setProviderFactory(providerFactory);
        super.onCreate(savedInstanceState);
    }

}

Key here is to call setProviderFactory(provider) before super.onCreate(savedInstanceState) because when super onCreate is called the provider should not be null, it should be set and ready to create the ViewModel


For a random matrix, shouldn't a SVD explain nothing at all? What am I doing wrong?

Question: If I construct a 2-D matrix composed entirely of random data, I would expect the PCA and SVD components to essentially explain nothing.
Instead, it seems like the the first SVD column appears to explain 75% of the data. How can this possibly be? What am I doing wrong?
Here is the plot:

Here is the R code:
set.seed(1)
rm(list=ls())
m <- matrix(runif(10000,min=0,max=25), nrow=100,ncol=100)
svd1 <- svd(m, LINPACK=T)
par(mfrow=c(1,4))
image(t(m)[,nrow(m):1])
plot(svd1$d,cex.lab=2, xlab="SVD Column",ylab="Singluar Value",pch=19)

percentVarianceExplained = svd1$d^2/sum(svd1$d^2) * 100
plot(percentVarianceExplained,ylim=c(0,100),cex.lab=2, xlab="SVD Column",ylab="Percent of variance explained",pch=19)

cumulativeVarianceExplained = cumsum(svd1$d^2/sum(svd1$d^2)) * 100
plot(cumulativeVarianceExplained,ylim=c(0,100),cex.lab=2, xlab="SVD column",ylab="Cumulative percent of variance explained",pch=19)

Update
Thankyou @Aaron. The fix, as you noted, was to add scaling to the matrix so that the numbers are centered around 0 (i.e. the mean is 0).
m <- scale(m, scale=FALSE)

Here is the corrected image, showing for a matrix with random data, the first SVD column is close to 0, as expected.
Comment: Your matrix approximates a uniform distribution on the unit cube $[0,1]^{100}$ in $\mathbb{R}^{100}$. SVD computes its  moments of inertia *about the origin*. In $\mathbb{R}^n$ the "total variance" must be $n$ times that of the unit interval, which is $1/3$. It is straightforward to compute that the moment along the main axis of the cube (emanating from the origin) equals $n/3-(n-1)/12$ and all the other moments--by virtue of symmetry--equal $1/12$. Therefore the first eigenvalue is $(n/3-(n-1)/12)/(n/3)=3/4+1/(4n)$ of the total. For $n=100$ that's $75.25$%, visible in the third plot.
Answer: The first PC is explaining that the variables are not centered around zero.  Scaling first or centering your random variables around zero will have the result you expect.  For example, either of these:
m <- matrix(runif(10000,min=0,max=25), nrow=100,ncol=100)
m <- scale(m, scale=FALSE)

m <- matrix(runif(10000,min=-25,max=25), nrow=100,ncol=100)

Comment: You raise a good point, but I think this only tells a part of the story. Indeed, I would guess that the OP would try each of these and *still* be surprised by the result. The fact of the matter is that because the singular values are *ordered* in the output, they will not appear (and indeed are not) uniformly distributed as might be naively expected from "random" data. The [Marchenko-Pastur distribution](http://en.wikipedia.org/wiki/Marchenko%E2%80%93Pastur_distribution) governs their behavior in this case.
Comment: @cardinal Thanks for your comment, you are absolutely right (see the graph produced by the corrected code, above). I believe the SVD values would become less uniformly distributed as the matrix gets smaller, as a smaller matrix would have more chance of having patterns that would not be squashed by the law of large numbers.
Comment: @Aaron Thank you, you were absolutely right. I've added a graph of the corrected output above to show how the beautiful the result is.
Answer: I'll add a more visual answer to your question, through use of a null model comparison. The procedure randomly shuffles the data in each column to preserve the overall variance while covariance between variables (columns) is lost. This is performed several times and the resulting distribution of singular values in the randomized matrix is compared to the original values.
I use prcomp instead of svd for the matrix decomposition, but the results are similar:
set.seed(1)
m <- matrix(runif(10000,min=0,max=25), nrow=100,ncol=100)

S <- svd(scale(m, center = TRUE, scale=FALSE))
P <- prcomp(m, center = TRUE, scale=FALSE)
plot(S$d, P$sdev) # linearly related

The null model comparison is performed on the centered matrix below:
library(sinkr) # https://github.com/marchtaylor/sinkr

# centred data
Pnull <- prcompNull(m, center = TRUE, scale=FALSE, nperm = 100)
Pnull$n.sig
boxplot(Pnull$Lambda[,1:20], ylim=range(Pnull$Lambda[,1:20], Pnull$Lambda.orig[1:20]), outline=FALSE, col=8, border="grey50", log="y", main=paste("m (center=FALSE); n sig. =", Pnull$n.sig))
lines(apply(Pnull$Lambda, 2, FUN=quantile, probs=0.95))
points(Pnull$Lambda.orig[1:20], pch=16)

The following is a boxplot of the permutated matrix with the 95 % quantile of each singular value shown as the solid line. The original values of PCA of m are the dots. all of which lie beneath the 95 % line - Thus their amplitude is indistinguishable from random noise.

The same procedure can be done on the un-centred version of m with the same result - No significant singular values:
# centred data
Pnull <- prcompNull(m, center = FALSE, scale=FALSE, nperm = 100)
Pnull$n.sig
boxplot(Pnull$Lambda[,1:20], ylim=range(Pnull$Lambda[,1:20], Pnull$Lambda.orig[1:20]), outline=FALSE, col=8, border="grey50", log="y", main=paste("m (center=TRUE); n sig. =", Pnull$n.sig))
lines(apply(Pnull$Lambda, 2, FUN=quantile, probs=0.95))
points(Pnull$Lambda.orig[1:20], pch=16)

For comparison, let's look at a dataset with a non-random dataset: iris
# iris dataset example
m <- iris[,1:4]
Pnull <- prcompNull(m, center = TRUE, scale=FALSE, nperm = 100)
Pnull$n.sig
boxplot(Pnull$Lambda, ylim=range(Pnull$Lambda, Pnull$Lambda.orig), outline=FALSE, col=8, border="grey50", log="y", main=paste("m (center=FALSE); n sig. =", Pnull$n.sig))
lines(apply(Pnull$Lambda, 2, FUN=quantile, probs=0.95))
points(Pnull$Lambda.orig[1:20], pch=16)

Here, the 1st singular value is significant, and explains over 92 % of the total variance:
P <- prcomp(m, center = TRUE)
P$sdev^2 / sum(P$sdev^2)
# [1] 0.924618723 0.053066483 0.017102610 0.005212184

Comment: +1. The example of Iris dataset is interesting, because looking at the first two PCs (as e.g. in your own post here http://stats.stackexchange.com/a/88092) it is quite clear that the second one does carry some signal. The permutation (aka shuffling) test indicates that only the 1st one is "significant" though. It is clear that shuffling tends to underestimate the number of PCs: the large variance of the first real PC will get "spread out" across shuffled PCs and will elevate all of them starting from the second. One can devise more sensitive tests that account for that but this is rarely done.
Comment: @amoeba - Excellent comment. I have been wondering about the "spreading out" effect for some time now. I suppose a cross-validation test might be one of the more sensitive ones that you reference (e.g. your answer [here](http://stats.stackexchange.com/a/85557/10675) )? Would be great if you could provide an example / reference.
Comment: I usually prefer to use cross-validation (based on reconstruction error, as per [my answer here](http://stats.stackexchange.com/questions/93845)), but I am actually not sure if it is not somehow suffering from the same kind of insensitivity or not. Might make sense to try it out on the Iris dataset. Regarding the shuffling-based approaches, I don't know any reference for accounting for this "spreading out", I just know some people who were working on it recently. I think they wanted to write it up soon. The idea is to introduce some downscaling factors for the variances of higher shuffled PCs.
Comment: @amoeba - Thanks for that link. It explains a lot for me. I found it especially interesting to see that cross validation in PCA makes use of methods that can operate on datasets with missing values. I made a few attempts on this approach and (as you state) the null model shuffling approach does indeed tend to underestimate the number of significant PCs. However, for the iris dataset, I consistently return a single PC for reconstruction error. Interesting given what you mentioned about the plot. Could be that if we were gauging error based on species predictions, results might be different.
Comment: Out of curiosity, I tried it out on the Iris data. Actually, I do get two significant PCs with the cross-validation method. I updated my linked post, please see there.
Comment: @amoeba - Thanks for that update and the code that you added. Looks like I was probably using the "Approximate method" - I will definitely try pseudoinverse approach in the future.


Unable to compile css with Aurora

Question: compass watch

Change detected at 02:13:25 to: style.scss
          error sass/style.scss (Line 20 of sass/partials/global/_base.scss: File to import not found or unreadable: aurora/susy-grid.
      Load paths:
        /Applications/MAMP/htdocs/txmo/sites/all/themes/txmo_aurora/sass
        /Users/davidfells/.rvm/gems/ruby-1.9.3-p362/gems/compass-0.12.2/frameworks/blueprint/stylesheets
        /Users/davidfells/.rvm/gems/ruby-1.9.3-p362/gems/compass-0.12.2/frameworks/compass/stylesheets
        Compass::SpriteImporter)

Running Ruby 1.9.3, latest versions of all gems freshly installed with JewelryBox. Other users on dev team are able to build this with matching gem versions.
Answer: The problem turned out to be that the "aurora" gem cannot be installed alongside compass & compass-aurora for all this to work properly.

Unable to compile css with Aurora


Is there a VNC viewer that works to and from a headless server and a headless client?

Question: I want a really simple VNC viewer that runs on a headless machine and connects to a headless machine, like a simple command line application, similar to the OpenSSH client.
I have looked online and in the Ubuntu and Debian repos but everything is geared towards opening up an X11 client.  I see no reason for that as I am not connecting to an X11 display but only to a console based login.
Comment: I'm confused. What purpose whould a VNC connection between two headless systems have?
Comment: A "regular command line environment" is exactly what SSH is for.
Comment: It sounds like you're looking for a text-mode remote-console-viewer. Is that the case?
Comment: I think you're at the mercy of your VPC provider at this point.  I have a 4 buck a month VPS running Ubuntu and have console access from my client web portal; works fine for the once a year `do-release-upgrade`.
Comment: @user1538951 I'm not sure how many people telling you "Your question is unclear and we need more details" it takes; but I'll add another name to the long list. If you'd like to discuss why this is an unclear question [please drop into chat again](http://chat.stackexchange.com/rooms/4732/discussion-between-user1538951-and-gravyface). This is getting locked.
Comment: That is exactly what I am looking for - a text-mode remote-console-viewer
Comment: Are you wanting this at the OS level, or the hardware level? At the hardware level, some KVM switches can do this, but that does not work if the machine is headless since the KVM switches would connect to the video card. A terminal server (hardware, not to be confused with certain misnamed software) can connect to the headless machine's serial port, but VNC won't help (need SSH). Otherwise a VNC server in the OS, but all of those emulate X. If the machine is headless, you either run X in software or SSH to a shell. What do you expect to see in your VNC client?
Comment: I just want to see a regular command line environment like I would see if I opened a shell on my local machine.
Comment: In theory a VNC server could be made (implemented) to serve up text. I've never seen this except for QEMU driven virtual machines running in text mode (you didn't say you were running a virtual machine so I assume this does not apply to your case). Most people would just use ssh as it is more efficient, more secure, and gives extra features.
Comment: Yes, the servers I am connecting to are KVM based VPS's and yes I believe that the OpenSSH client should be able to do that.  I have successfully connected to a VNC server using OpenSSH but all I get back is "RFB 003.008" I do not have admin access to the VNC server as I am renting VPS servers and the KVC server is supplied by the rental agent
Comment: @user1538951 what OS is running on your VPS servers?
Comment: The reason for the VNC requirement is because a VPS connection through a normal ssh user@host does not connect to the console.  When installing a new version of the OS the sshd server is not running and so a virtual console connection through VNC is required.  The servers are running various flacors of Linux and BSD - no windows servers at all.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/4732/discussion-between-user1538951-and-gravyface)
Comment: My impression from these comments is that people are not even fully reading the question and are unhappy if they cannot give an informed answer.  I'm done with serverfault for good.
Comment: @user1538951 I'm sorry if you feel that way - the comments all appear to be attempting to clarify what is a poorly asked question (You don't tell us enough to give you an *informed* answer. We don't like to guess here).  If you would care to edit your question to (a) include some of the information explained in your comments, and (b) explain *why* you feel VNC is the right solution for this you may get "better" answers, but ultimately I think Michael Hampton has given you the best answer you're likely to get: You need to see what console-equivalent access your VPS provider offers.
Comment: My question is perfectly clear.  I guess it would be unclear if you were not familiar with the issue.  Maybe people unfamiliar with the issue should not comment.
Answer: You're using a virtual server. You're limited to the remote console access provided by the service provider; contact them for details on how to use it.
Comment: Further, most provide VPS Serial access via SSH or something similar (also commonly web browser based) for doing upgrades and such.


Memory size exhausted when trying to run cron manually

Question: On my Drupal 6 website, when I run manually cron, I get this error message.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4181580 bytes) in /dirname/includes/database.mysql-common.inc on line 34

Cron is set to automatically run every night; the last few days it wasn't running, so I tried it manually.
Where should I increase memory, in the settings.php file, in the php.ini file for PHP, or somewhere else? I'm using AWS RDS and EC2 instances.
I have this line in the settings.php file.
ini_set('memory_limit', '128M');

Comment: be sure also to see https://drupal.stackexchange.com/questions/46293/increase-memory-limit-doesnt-help-in-fatal-error-allowed-memory-size-of-mo, which covers other possible causes and fixes
Answer: All you need to do is increase your PHP Memory Limit from 128M to 265M, for example adding the following line in the settings.php file.
ini_set('memory_limit', '256M')

For more information on other ways to change it, see Changing PHP memory limits.


Circle overlay to map-distance conversion

Question: I have a circular overlay that can change according to the user's preferences: they have a circle of radius 'r' around them and a slider can change 'r' accordingly. So far it works perfectly well.
My problem is I don't know how to find the proper conversion from the circle's radius to the map's metric. As an example, given the circle below, what is the distance covered with the given radius?
Comment: Actually, I'm sorta following [this](https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/ScaleBarOverlay.java?r=1152) right now and I think it's the solution to my problem... I'll update this thread when/if I get it figured out.
Answer: You must know what is the scale of the map you are showing. Having scale of the map you could convert pixels size to metric size. And having this proportion you can convert radius given in pixels to meters.
Answer: So here's how you do it...
Jedil is correct you have to find your screen width/height, the dpi of the screen, etc. So, looking through this old osmdroid source I sorta figured out this:
//Get the x and y dpi
this.xdpi = this.context.getResources().getDisplayMetrics().xdpi;
this.ydpi = this.context.getResources().getDisplayMetrics().ydpi;

//Get the screen width/height
this.screenWidth = this.context.getResources().getDisplayMetrics().widthPixels;
this.screenHeight = this.context.getResources().getDisplayMetrics().heightPixels;

 // DPI corrections for specific models
 String manufacturer = null;
 try {
       final Field field = android.os.Build.class.getField("MANUFACTURER");
        manufacturer = (String) field.get(null);
      } catch (final Exception ignore) {
      }

 if ("motorola".equals(manufacturer) && "DROIDX".equals(android.os.Build.MODEL)) {

 // If the screen is rotated, flip the x and y dpi values
 WindowManager windowManager = (WindowManager) this.context
                       .getSystemService(Context.WINDOW_SERVICE);
 if (windowManager.getDefaultDisplay().getOrientation() > 0) {
     this.xdpi = (float) (this.screenWidth / 3.75);
     this.ydpi = (float) (this.screenHeight / 2.1);
 } else {
       this.xdpi = (float) (this.screenWidth / 2.1);
       this.ydpi = (float) (this.screenHeight / 3.75);
 }

 } else if ("motorola".equals(manufacturer) && "Droid".equals(android.os.Build.MODEL)) {
     // http://firstname.lastname@example.com/msg109497.html
     this.xdpi = 264;
     this.ydpi = 264;
 }

 // set default max length to 1 inch
 maxLength = 2.54f;

That's how you get the 'constants' (at least in the device's eyes). To convert...
 // calculate dots per centimeter
 int xdpcm = (int) ((float) xdpi / 2.54);
 int ydpcm = (int) ((float) ydpi / 2.54);

 // get length in pixel
 int xLen = (int) (maxLength * xdpcm);
 int yLen = (int) (maxLength * ydpcm);

 // Two points, xLen apart, at scale bar screen location
 IGeoPoint p1 = projection.fromPixels((screenWidth / 2) - (xLen / 2), yOffset);
 IGeoPoint p2 = projection.fromPixels((screenWidth / 2) + (xLen / 2), yOffset);

 // get distance in meters between points
 final int xMeters = ((GeoPoint) p1).distanceTo(p2);

...and it's a similar, if not near-identical, matter to get the yMeters (hint: use screenHeight).
Admittedly, I'm not totally sure of what the lines IGeoPoint... are doing but I realize the conversion is there. Hoping this helps someone out in the future. For a better understanding of the above code, please see the link I've posted.
Answer: I think what you're looking for is a meters-to-pixels calculation. You can get this from the projection:
// Get projection
Projection proj = mMapView.getProjection();
// How many pixels in 100 meters for this zoom level
float pixels = proj.metersToPixels(100);
// How many meters in 100 pixels for this zoom level
float meters = 1 / proj.metersToPixels(1 / 100);
// You could also get a raw meters-per-pixels value by using TileSystem.GroundResolution()

Two things to remember - this value will change not only based on what zoom level but based on what latitude you are at on the maps.


Infusing AdSense into Joomla Template using JQuery Masonry

Question: I'm aware of the JoomlArt JA Wall template but it doesn't appear to meet our use case as we have the need to include tiles in the feed that are Adsense banners.  I've read up on JQuery Masonry and see that it uses the infinite scroll feature.
Is it possible to create a Joomla template using Masonry that also will take Adsense banners ?
Answer: Of course it's possible, just make sure you add the class you choose for masonry to each element; depending on what kind of elements you want to align: modules? blog items? it should be fairly easy; if you want to apply masonry to items across the whole page, just make sure you don't enclose modules and blog items in their own div groups.
Comment: I am using a Custom HTML module for the Adsense script. Does the template take care of assigning the class to the correct module?


Configuração do Eclipse

Question: Tenho um projeto android criado no eclipse. Neste projeto na tabela de Problems tenho alguns warmings (907) como mostra na figura abaixo:

Como percebemos, consta desta forma:

0 errors, 907 warnings, 0 others (Filter matched 100 of 907 items)

Utilizo o Eclipse Mars 2, e gostaria de saber se tem como configura-lo para mostrar mais que 100 itens na lista de Problems? Se sim, como?
Exemplo: (Filter matched 200 of 907 items)
Answer: Para mudar o número de itens exibidos nesse grid, primeiro click com o botão esquerdo na seta para baixo no canto inferior direito.

Acesso menu Configure Contents, na caixa de configura que aparecer olhe na parte de inferior, altere o item Number of items visibles per group. Para confirmar as alterações de OK.

Configuração do Eclipse


This document already has a ' DocumentElement ' node

Question: I'm adding a new node at the end of a file, but I get a write error:

This document already has a 'DocumentElement' node.

My code:
XmlDocument doc = new XmlDocument();
doc.Load(directory);
XmlNode refElem = doc.LastChild; // Last node

foreach (MoneyEnter myList in list)
{
    XmlElement entryElement = doc.CreateElement("entry");
    entryElement.SetAttribute("type", myList.TypeAmount);

    XmlElement amountElement = doc.CreateElement("amount");
    amountElement.InnerText = Convert.ToString(myList.Amount);

    XmlElement dateElement = doc.CreateElement("date");
    dateElement.InnerText = Convert.ToString(myList.Date);

    XmlElement descriptionElement = doc.CreateElement("description");
    XmlCDataSection cdataDescription = doc.CreateCDataSection(myList.Description);
    descriptionElement.AppendChild(cdataDescription);

    XmlElement categoryElement = doc.CreateElement("category");
    categoryElement.InnerText = myList.Category;

    entryElement.AppendChild(amountElement);
    entryElement.AppendChild(dateElement);
    entryElement.AppendChild(descriptionElement);
    entryElement.AppendChild(categoryElement);
    doc.InsertAfter(entryElement, refElem); //add new node in end of file
}
doc.Save(directory);

My XML file:
<?xml version="1.0" encoding="utf-8" ?>
<entries>
    <entry type="debit">
        <amount>5</amount>
        <date>01.01.0001 0:00:00</date>
        <description>ffvfd</description>
        <category>fdvfvf</category>
    </entry>
    <entry type="debit">
        <amount>5</amount>
        <date>01.01.0001 0:00:00</date>
        <description>fvfv</description>
        <category>fvfdvfd</category>
    </entry>
    <entry type="debit">
        <amount>5</amount>
        <date>01.01.0001 0:00:00</date>
        <description>fv gfv</description>
        <category>dscdcd</category>
    </entry>
    <entry type="debit">
        <amount>5</amount>
        <date>01.01.0001 0:00:00</date>
        <description>vfvfv</description>
        <category>cfcfc</category>
    </entry>
    <entry type="debit">
        <amount>7</amount>
        <date>01.01.0001 0:00:00</date>
        <description>gfbvgv</description>
        <category>gfbgfb</category>
    </entry>
</entries>

Answer: You should use
XmlNode refElem = doc.DocumentElement.LastChild;

and
doc.DocumentElement.InsertAfter(entryElement, refElem);

EDIT
You may also use
doc.DocumentElement.AppendChild(entryElement);

In this case refElem is not needed.
Comment: You could also use `doc.DocumentElement.AppendChild(entryElement)` without the need of the referenced element.
Comment: because after inserting the first new Node, refElem isn't the last child any longer. Then you need to write `doc.DocumentElement.InsertAfter(entryElement, doc.DocumentElement.LastChild)` which inserts after the current last child.
Comment: thanks, works, but adds a new node why not at the end of the file?


Adding a custom Token so i can use in Webforms

Question: I am having the smart-ip module installed. It allows me to get User country, city etc very easily like this:
echo $_SESSION['smart_ip']['location']['country_code'];

I want to use this as a token replacement in webforms field. But I have no idea how to do it.
Got confused after googling. I should do the hooking in template.php? How do i do it? :/
Comment: What exactly do you want to do? Use the custom value as a _default_ component value?
Answer: Create your own tokens!
You could create a small module that implements the token hooks (D6, but D7 should be similar), like so:
function YOURMODULE_token_list($type = 'all') {
  $list = array();

  $list['smart-ip']['smart-ip-country-code'] = t("The Country code");
  // ...etc

  return $list;
}

function YOURMODULE_token_values($type, $object = NULL, $options = array()) {
  $tokens = array();

  $tokens['smart-ip-country-code'] = $_SESSION['smart_ip']['location']['country_code'];
  // ...etc

  return $tokens;
}

Or, even better, add these hooks to the smart_ip.module file and submit a patch to the module maintainer :-). Tokens are really great, and it would certainly be a good addition to the smart_ip module.
Answer: install a module called webform_tokens
and what u can do after that is adding your custom token to the module by altering it.
Comment: This is not correct.  Webform Tokens is a helper module for pulling information OUT of webforms, not for putting information INTO Webforms.


How to apply auto-complete functionality to the cell of ag-grid?

Question: Auto-complete functionality needs to suggest function names which is in a json format and mentioned below:
{
 "id": 260,
 "title": "p_active(Power: number, PowerAngle: number)",
 "type": "PR",
 "category": "AL",
 "structure": "p_active(Power: number, PowerAngle: number)"
}

Here, p_active is a function name, which needs to be included in the suggestion.
Answer: I don't think ag-grid has support for autocomplete out of the box, with that being said there are 2 possible solutions I can think of:

Create a custom Cell Renderer component. This allows you to customize your cell with any component however you want, in this case what you can do is have an input there with auto complete. More info about this:
https://www.ag-grid.com/javascript-grid-cell-rendering-components/

Use a ready solution/package - here's a package I found:
https://www.npmjs.com/package/ag-grid-autocomplete-editor

Here's a stackblitz with the implementation of autocomplete:
https://stackblitz.com/edit/ag-grid-autocomplete-editor
Answer: I'm using Material Autocomplete with Angular.  I wrap it in a class I created named AutocompleteCellRendererComponent which implements AG Grid's ICellRendererAngularComp.  It seems to work fairly well so far (I don't have all the kinks out yet).  I would put the code here if there was anything weird, but it really is just a very straight forward wrapping of a Material Autocomplete in an Angular component with this as the template:
<mat-form-field>
    <input type="text" matInput [matAutocomplete]="auto" [formControl]="filterInput" panelWidth>
    <mat-autocomplete
        #auto="matAutocomplete"
        [panelWidth]="panelWidth"
    >
        <mat-option class="mat-row" *ngFor="let row of filteredRowData" [value]="getValue(row)">
            {{getText(row)}}
        </mat-option>

    </mat-autocomplete>
</mat-form-field>

Then the AG Grid column def looks like this for showing an employee autocomplete list in the AG Grid:
columnDefs: [
    {
      headerName: 'Employee',
      field: 'employee.name',
      cellRenderer: AutocompleteCellRendererComponent,
      cellRendererParams: {
        autocomplete: {
          source: this.employeeService.getAll(),
          formatter: this.formatEmployeeAutocomplete,
          panelWidth: '320px'
        }
      }
    },

As a side note, if you happen to be showing the grid in an NgbModal, I had to add this to my stylesheet:
.cdk-overlay-container {
  z-index: 1056;
}

...otherwise the autocomplete list shows up behind the modal.