Bowing exercises confusion

Question: Either it was lost in translation or it is unclear(if mine, explain what I'm missing that makes it so obvious so I can learn from my mistake).

I will explain the error, or possible ambiguities, in the exercises.
How is this performed? The following image are 4 potential ways I could interpret this. Note these are my interpretations, some here think I am asking about how to play them, I know how to play them, as I created them using the above example. I am talking about how to interpret the example above with one single downbow on beat 1 and no other beats. The following are the possible interpretations. I am not saying they are "correct" but that without a correct/standardized rule, one cannot surely know, there are an infinite other interpretations, many not very logical too.

Or take one long bow, change when one wants?
The standard "method" is to down up down up on the quarters. But that is quite fast bowing. Or do we do a sort of "accent" while bowing in the same direction to get each subdivision?
Answer: You've answered your question yourself: what you call the "standard method" really is the standard method, unless indicated (or desired) otherwise.  But yes, all the other bowings you picture do exist: you can play each quarter note with a downbow, or play two down and two up, and so forth.  Each different bowing has its own sound and its own musical purpose.  But as others have said here, the default assumption is down/up/down/up.
Comment: Yes, the standard may be the standard, but that doesn't mean that the beginner knows that or that exercises are implying them. After all, with your logic, the down bow symbols are redundant because also with standard bowing we play downbows on down beats. You could say it is just being clear, but if one is going to be clear then why not show several markings? I don't think there is any justification for leaving out information that reduces ambiguity.
Comment: @AbstractDissonance I think generally because a score would look pretty messy if you had up- and down-bow symbols above every note, when you proceed using the left hand it is pretty much the same with fingerings. In the first lessons teaching books tend to have them above every note then only when the author or editor thinks it is appropriate. I think you are right in a sense that your book (maybe you wanna post title and author) should have told you about the fact about the `general assumption` ScottWallace mentioned before and maybe it did and you skipped it.
Comment: @AbstractDissonance When it comes to reading music and attaining  fluency, you'll come to understand that "less is more." More ink on paper with more instructions making music more rigid and procedural makes it tougher to 1. add personal expression, and 2. read natively because of the amount of information to process. You're essentially asking for the opposite of what music should look like for the opposite of what music should be. Think about that.
Comment: @AbstractDissonance - yes, you're quite correct about these excercises leaving out information.  It should have been explained somewhere what the rule/convention is to eliminate confusion.  Thanks, I should have mentioned that too.
Answer: Here are some score examples (of not being in a different context) meaning all the same, while you could say that for an advanced player example 1. would be fully enough to play it the way example 2. suggests, wile example 3. leaves no room for misinterpretation in terms of bowing direction.

As you proceed you will find that example 1. is very typical for a pickup measure on bowed instruments, while again in your words the standard "method" would be applied as being emphasized in 2. and 3.
Answer: Learning to play and read music depends some amount on intuition. If you've ever heard someone say that a mathematician's downfall is reading music, it is because there is open room for interpretation when reading it, whereas mathematics usually has only one form of doing it.
That being said, the standard method you yourself refer to is agreed upon based on this simple inference: If you draw the bow to play one note, the next note must change direction, in order to maintain balance in the amount of bow available. This is something that either must be explained in a lesson, or is present as text earlier in the book. Otherwise, the explanation is not complete.
Starting from that, once a string player sees example 1, the implication (that should have been learned) is to do a down bow, then an up bow, then a down bow, successively.
As for your variable example 1s, let's tackle them in order:
1-1 requires all down bows. To continue bowing multiple notes on the same down bow requires a different notation. Here, as the player you must be instructed to retake the bow at the frog (or near it) for each note for all notes where the down bow sign is. Otherwise, you'll end up playing either staccato (separated notes on a single down bow), or a tie (the down bow makes the notes flow into one another).
1-2 assumes the "standard method". It clues you in with the first down bow. Lack of signs means that you follow the standard style of bowing, which means to change direction with each note. To verify this, another down bow sign is introduced at the start of measure 2.
1-3 is an interruption of the standard method. The first four notes (on the 1st measure) are bowed in the standard method of down-up-down-up. Measure 2 begins on an up bow, so that means you should retake your bow to the tip, and bow upwards towards the frog, effectively reversing your bowing to up-down-up-down.
1-4 is explicit about bowing in the standard style. You must bow down-up-down-up in this order.
Answer: What the author of your method book had in mind for Line 1 of the scanned exercise is Down, Up, Down, Up -- as you indicated in Line 4 of your second image.
What they apparently didn't explain explicitly in your method book is that every time there is a separate note, your bow should change direction.  (Unless there is some other indication, such as a slur.)  They have written a "down bow" symbol above the first note in the phrase, to get you started; and then after that, you should continue in a Down, Up, Down, Up pattern until you're told to do something different.

do we do a sort of "accent" while bowing in the same direction to get each subdivision?

That's a worthwhile exercise -- but not what was desired on this particular page.
Answer: In classic violin play, you change bow direction every single note unless explicitly indicated otherwise.  This isn't an accordion.  There is a reason right-handed people do the bowing with the right hand and the fingering with the left.
If you think quarter notes without particular speed indication are fast, you are in for some surprise...
Comment: Left handed people also do the bowing with the right hand and the fingering with the left. I'm not sure what point you are trying to make there - there are plenty of good left-handed violinists around!  (Left handed pianists don't buy pianos that are a mirror image of the standard ones, either.) The bowing marked for the second line of the exercise is a good clue that you are supposed to use alternating up and down bows, one bow stroke per note. This should have been explained earlier in the book - maybe you missed it..
Comment: @alephzero Just a polite FYI left-handed violins are a thing!
Comment: There may be a reason right-handed people bow with the right hand, but it has nothing to do with this question.
Comment: @GeorgeTian I knew that already, but you won't find any professional orchestral players who play left handed, for example. IMHO selling left-handed violins is just a way for the unscrupulous to make a profit out of political correctness (or "differently abledness" as some people would insist on calling it!) - especially if the parents of the left handed wannabe violinist have more money than sense.
Comment: The occasional player who makes a religion out of being left-handed sets up a 'backwards' violin.  It involves more than reversing the bridge and re-stringing, there's the sound post and bass bar to re-position too.  And there's really no point.
Comment: Actually, although there may rarely be good reasons to set up a violin left-handed, including moving the soundpost and bass bar (which requires taking the violin apart), they do exist: a friend of mine, a fantastic violinist, is having me do exactly this, because she's developing a problem with her left hand which interferes with fingering, but still allows her to hold the bow left-handed.

Bowing exercises confusion


Read line with Scanner

Question: EDIT for further readers: the problem was that my input file was corrupted.
I don't understand what I'm doing wrong :
I was using this code :
    File f = new File("C:\\Temp\\dico.txt");
    BufferedReader r = null;
    try {
        r = new BufferedReader(new FileReader(f));
        String scan;
        while((scan=r.readLine())!=null) {
            if(scan.length()==0) {continue;}
            //treatment
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if(r!=null) try {
            r.close();
        } catch (IOException ex) {
            Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Which is working fine. Now, for some reason, I wanted to change for a Scanner. My code became :
    File f = new File("C:\\Temp\\dico.txt");
    Scanner r = null;
    try {
        r = new Scanner(f);
        String scan;
        while(r.hasNextLine()) {
            scan = r.nextLine();
            if(scan.length()==0) {continue;}
            //treatment
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Lexique.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if(r!=null) r.close();
    }

This time, we never enter the while, because r.hasNextLine() always returns "false". Any idea about what I'm doing wrong ?
I precise that nothing else changed, the file is still the same.
EDIT : I also precise that I tried with another file and got the same result, meaning it doesn't comes from the file apparently.
The file looks like this :
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
...

Edit 2 :
The content of the file seems to be problematic since the problem persists only if I copy/paste the content from my file to another. In clear, if I write the content myself, it works, if I use a part of the content of my dico.txt file, it doesn't work. Any explanation ?
Edit 3 :
These are the links to my files. I advice you to avoid the dico.txt which is very huge.
dico.txt : https://drive.google.com/file/d/0B0sroFy9HZlBNDl3MUwzVnh6VU0/edit?usp=sharing
test.txt : https://drive.google.com/file/d/0B0sroFy9HZlBemZjbXU1RmlmdjQ/edit?usp=sharing
Comment: Could you show the `dico.txt` file ?
Comment: I edited my question to include it. But anyway, why would the BufferedReader be able to read the line correctly and not the Scanner ? Did I missed something in the initialization ?
Answer: This code reads the file line by line.
public static void readFileByLine(String fileName) {
  try {
   File file = new File(fileName);
   Scanner scanner = new Scanner(file);
   while (scanner.hasNext()) {
    System.out.println(scanner.next());
   }
   scanner.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }

You can also set a delimiter as a line separator and then perform the same.
 scanner.useDelimiter(System.getProperty("line.separator"));

You have to check whether there is a next token available and then read the next token. You will also need to doublecheck the input given to the Scanner. i.e. dico.txt. By default, Scanner breaks its input based on whitespace. Please ensure that the input has the delimiters in right place
UPDATED ANSWER for your comment:
I just tried to create an input file with the content as below
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait

tried to read it with the below code.it just worked fine.
 File file = new File("/home/keerthivasan/Desktop/input.txt");
     Scanner scr = null;
         try {
            scr = new Scanner(file);
            while(scr.hasNext()){
                System.out.println("line : "+scr.next());
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
        }

Output:
line : a
line : à
line : abaissa
line : abaissable
line : abaissables
line : abaissai
line : abaissaient
line : abaissais
line : abaissait

so, I am sure that this should work. Since you work in Windows ennvironment, The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. if you set your Scanner instance to use delimiter as follows, it will pick up probably
 scr = new Scanner(file);
 scr.useDelimiter("\r\n");

and then do your looping to read lines. Hope this helps!
Comment: Your dico.txt file was corrupted. I just encoded it to UTF-8 again. it worked perfectly fine with my code. I am just uploading the new file. Make use of it. i am sharing the link - https://drive.google.com/file/d/0B-0YRK_ObuLVUUozV29fdmhqaVU/edit?usp=sharing Please use this file from now on. Please let me know what happens
Comment: @megido You are right. but, this requirement has just one word per line. so, it worked.
Comment: Sorry, I tried with and without the scanner.useDelimiter, and in both cases the scanner.hasNext() returns false. Sorry for my previous comment saying scanner.hasNext passed.
Comment: Ok, very weird. I tried your code, it didn't work. Then, I just rewrote the file manually (no copy/paste), and this time it worked. Then, I erased the content with a copy/paste from my file and it doesn't work. It means that the content from my file probably has a problem. But in this case, why does it work with BufferedReader ? Anyway, I still have a problem since my file is composed of thousands of lines and I can't rewrite everything !
Comment: BufferedReader.readLine() -  Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.But, Scanner depends entirely on the delimiters say space or the custom delimiter you choose. Did you try setting the delimiter with '\r\n'
Comment: Can you tell me the encoding of your input file?
Comment: Try to remove the formatting and special characters from the input file. Where do you actually copy it from? First of all, try to paste the content to Notepad and then to your input file. it really helps to find the unnecessary characters - Text sanitizer
Comment: I tried \n, \r and \r\n with no result. Sorry for being a noob, but how can I know the encoding ? Anyway, I'm only working with the notepad since the beginning. What do you want me to do exactly ? I already copied from dico.txt to test.txt and it didn't work better (cf my 2nd Edit)
Comment: Can you give a link to your file somewhere? I can take a look at it. Since you are working on a windows environment, try opening the file in command prompt. which version of operation system?
Comment: You make use of Notepad++ or PSPad to view the special characters and EOL characters and try removing the unnecessary characters.
Comment: Ok. You can get the files from my 3rd edit. I checked on notepad++. There is CR and LF at the end of each line.
Comment: Ok ! The new file worked ! Thanks a lot. But I still don't get it : what kind of corruption can fool the Scanner, but be transparent for the BufferedReader ? Anyway, Thanks again. My problem is solved.
Comment: I'm also really not sure about that difference.Do you think the same file was given as input to BufferedReader code as well.The file was not properly encoded.that was the problem. Happy for you :) Can you please accept my answer?Happy coding!
Comment: No. The file was exactly the same. I'm sure. I was able to see all the lines being written while executing the code and I had only one copy of this file, so there couldn't be any confusion.
Comment: scanner.next() is not reading the whole line, it just gets next word, nextLine() should be used instead.
Comment: `.next()` should be `.nextLine()`
Answer: next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Read article :Difference between next() and nextLine()
Replace your while loop with :
while(r.hasNext()) {
                scan = r.next();
                System.out.println(scan);
                if(scan.length()==0) {continue;}
                //treatment
            }

Using hasNext() and next() methods will resolve the issue.
Comment: No it isn't returning false at my end.
Comment: I put the files on my 3rd Edit. Could you try with these files? It seems it comes from the content of the files. Thank you for your help.
Comment: i cannot access google drive . mail me @ email@example.com
Comment: Thank you for your help. The file was corrupted. The problem has been solved by Keerthi Ramanathan.
Answer: /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ;
        int count = 0 ;
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt";

    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path));

        }
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile();
        r.openFile();
        r.readFile();
        r.closeFile();

    }
}

Answer:
For everybody who still can't read in a simple .txt file with the Java scanner.

I had the problem that the scanner couldn't read in the next line, when I Copy and Pasted the information, or when there was to much text in my file.
The solution is: Coder your .txt file into UTF-8.
This can be done fairly simple by saving opening the file again and changing the coding to UTF-8. (Under Win7 near the bottom right corner)
The Scanner shouldn't have any problem after this.
Comment: or define encoding like this:

    Scanner scanner = new Scanner(new File(csvFile), "Windows-1250");
Answer: Try to use r.hasNext() instead of r.hasNextLine():
while(r.hasNext()) {
        scan = r.next();

Comment: r.hasNext() makes me enter the loop, but the problem is that r.nextLine() throws a java.util.NoSuchElementException: No line found
Comment: Err, Sorry, actually, the r.hasNext() also returns false... I don't understand what's wrong

Read line with Scanner


Cocos2d-x : some sprites become invisible when a PhysicsWorld is set

Question: I'm currently trying to make a game with cocos2d-x engine. The game, as I imagine it, needs a scrolling background. What I did then is creating 2 background sprites in a table:
bool HelloWorld::init()
{
    ///////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    //creating "first" background
    background[0] = Sprite::create("fond.png");
    background[0]->setPosition(0, 0);
    background[0]->setAnchorPoint(Vec2(0, 0));
    this->addChild(background[0]);

    //creating "second" background
    background[1] = Sprite::create("fond.png");
    background[1]->setPosition(background[0]->getContentSize().width, 0);
    background[1]->setAnchorPoint(Vec2(0, 0));
    this->addChild(background[1]);

    this->scheduleUpdate();
    return true;
}

I then made them scroll in that way, in an update function:
void HelloWorld::update(float delta)
{
    for(int i = 0 ; i < 2 ; i++) { //scrolling background
        if (background[i]->getPositionX() <= 0) {
            background[i]->setPositionX(background[i]->getPositionX()-800*delta);
            background[1-i]->setPositionX(background[1-i]->getContentSize().width+(background[i]->getPositionX()));
        }
    }
}

So, now, I have my basic init() and update() functions, which is great :). Now I need to do my createScene() function which, at first, looks like this:
Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

And then it works perfectly! But sadly, for the rest of my game I need physics (you know, collisions and stuff), so I need to change this function to at least this:
Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::createWithPhysics();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

And there comes the problem: when I add PhysicsWorld (like there), background[1] becomes invisible, like when he has to appear on the screen, I have a beautiful black screen until background[0] comes.
I have the feeling to have tried almost everything but I can't find any solution... Do somebody have an idea of what I should do?
P.S: I did all my tests on the Linux platform for the moment and I have cocos2d-x 3.4 version.
Answer: I'm not sure about whether or not you are using SpriteBuilder or Cocos Studio alongside your project, but in more than one GUI used alongside Cocos2d I've seen that when you set some sprite's position relative to the screen size instead of using points or UI points, it will usually spawn a lot of bugs once you move the sprite in code afterwards.
Try setting relative positions in code from the moment they are loaded or do not use relative initial positioning for moving sprites in the GUI you are using.


time signatures in shuffle funk

Question: I am struggling at understanding how is called the time signature in funk where the eighth note is divided in 3 and only the 1st and 3rd are played...sixteenth note triplets.
In jazz it would be eighth note triplets I guess.
Is that shuffle ?
Thanks for your clarification.
Answer: Jazz is traditionally notated as straight 8s with a 'Swing' indication.  Jazz isn't triplets.   Shuffle just about is, so is more likely to be notated either as triplets, as 12/8 or as dotted 8th - 16th pairs.
Funk tends to use swung 16ths, written as straight 16ths.  Often straight 16ths too. But I think this question is about the sort of Funk that swings its 16ths.
Comment: Regarding your final statement, swing 16ths are fairly common nowadays but there are countless funk songs that use straight 16ths. The majority of EWF, TOP, Chic, James Brown, and that's just scratching the surface.
Answer: Almost all funk, whether shuffle or straight is written in 4/4 time so this is not really about time signatures but about how to represent this feel in 4/4. If you have a groove where you are playing the first and third notes of 16th note triplets this is most commonly written in 4/4 time with an indication at the beginning of the piece that says "swing 16ths" or "shuffle 16ths".
There are other ways of representing this literally. One way is to write all 16ths as triplets with alternating 8th and 16th notes. The other solution would be to write in 24/16 with alternating 8th and 16th notes. Neither solution is very practical, especially the second.
Since this type of feel is fairly common and musicians know the difference between straight and swing feels the solution in the first paragraph is acceptable, just like it has been acceptable to write "swing 8ths" or "shuffle 8ths" at the beginning of a piece and use regular 8th notes throughout.

time signatures in shuffle funk


brew doctor yields python config warning: should I remove these config files? (Mac)

Question: Mac seems to have Python installed already. brew doctor yields this:
<code>brew doctor
Warning: "config" scripts exist outside your system or Homebrew directories.
`./configure` scripts often look for *-config scripts to determine if
software packages are installed, and what additional flags to use when
compiling and linking.

Having additional scripts in your path can confuse software installed via
Homebrew if the config script overrides a system or Homebrew provided
script of the same name. We found the following "config" scripts:

    /Library/Frameworks/Python.framework/Versions/2.7/bin/python-config
    /Library/Frameworks/Python.framework/Versions/2.7/bin/python2-config
    /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
</code>
Should I remove these config files, or would that cause issues? For me:
<code>> which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
</code>
Also:
<code>$ ls /usr/bin/pyth*
-rwxr-xr-x  2 root  wheel  62752 Aug  6  2011 /usr/bin/python*
-rwxr-xr-x  6 root  wheel    925 Aug  6  2011 /usr/bin/python-config*
lrwxr-xr-x  1 root  wheel     75 Aug  6  2011 /usr/bin/python2.5@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5
lrwxr-xr-x  1 root  wheel     82 Aug  6  2011 /usr/bin/python2.5-config@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5-config
lrwxr-xr-x  1 root  wheel     75 Aug  6  2011 /usr/bin/python2.6@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6
lrwxr-xr-x  1 root  wheel     82 Aug  6  2011 /usr/bin/python2.6-config@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6-config
lrwxr-xr-x  1 root  wheel     75 Aug  6  2011 /usr/bin/python2.7@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82 Aug  6  2011 /usr/bin/python2.7-config@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
-rwxr-xr-x  2 root  wheel  62752 Aug  6  2011 /usr/bin/pythonw*
lrwxr-xr-x  1 root  wheel     76 Aug  6  2011 /usr/bin/pythonw2.5@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/pythonw2.5
lrwxr-xr-x  1 root  wheel     76 Aug  6  2011 /usr/bin/pythonw2.6@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.6/bin/pythonw2.6
lrwxr-xr-x  1 root  wheel     76 Aug  6  2011 /usr/bin/pythonw2.7@ -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/pythonw2.7
</code>
Thanks in advance.
Answer: Homebrew mainly uses built-in tools, so formulae generally should be built against system Python anyway. You shouldn't have any problem with them unless you override system Python with Homebrew ones (which is generally not recommended unless you need to do something special).
Comment: @bfontaine Things changed a bit since 2013. The line was accurate at the time, but Homebrew has changed their policies a bit, and now offers a lot of formulae that duplicates system libraries.
Comment: "which is generally not recommended unless you need to do something special" -> There's nothing wrong with installing Homebrew's Python; it's more up-to-date than the system's.
Answer: It hasn't been an issue for me (most of my configs are in my home, rather than in homebrew). I think it's fine. As long as they're in your path, python will be able to find them; the only issue would be from a package or program you want to install with brew that needs to modify those config files. It could happen, but probably shouldn't with well-developed programs.


React Maximum update depth exceeded in functional component

Question: In my react functional component, I have a function that is executed to toggle the checkboxes as selected or unselected. It works fine.
The function (inside Parent component) goes like this:
const ParentComponent = () => {

const { state, dispatch } = useContext(FilterContext);

const onChange = useCallback((value) => {
(item) => {
  const { name, selected } = item;

  // this "name" comes from another sibling component on the mount, and then from child component (sideAccordian) on click

  const selectedFilters = state.identifiers_checkbox.selected_checkboxes.find(
    (obj) => obj === name
  );

  const selected_checkboxes = selectedFilters
    ? state.identifiers_checkbox.selected_checkboxes.filter(
        (obj) => obj !== name
      )
    : [...state.identifiers_checkbox.selected_checkboxes, name];

  const toggled_checkboxes = {
    selected_checkboxes,
    options_checkbox: [
      ...state.identifiers_checkbox.options_checkbox.map((filter) => {
        return {
          ...filter,
          options: filter.options.map((option, i) => {
            return name === option.name
              ? {
                  ...option,
                  selected,
                }
              : option;
          }),
        };
      }),
    ],
  };

  dispatch({
    type: "update-checkboxes",
    payload: {
      checkboxSelected: true,
      selected_checkboxes: toggled_checkboxes.selected_checkboxes,
      options_checkbox: toggled_checkboxes.options_checkbox,
    },
  });
},
[
  dispatch,
  state.identifiers_checkbox.options_checkbox,
  state.identifiers_checkbox.selected_checkboxes,
]);

  useEffect(() => {
    if (info.prevui === "intervention") {
      if (state.identifiers_checkbox.options_checkbox.length > 1) {
        onChange({ name: info.abbr, selected: 1 });
      }
    }
  }, [
    info.abbr,
    info.prevui,
    dispatch,
    state.identifiers_checkbox.options_checkbox.length,
    // onChange,
  ]);

return (

        {
            state.identifiers_checkbox.options_checkbox.length > 1 ? (
             <SideAccordian
               filterstate={state.identifiers_checkbox}
               onChange={onChange}
             />
             ) : (

No Options Available

             )
         }

    )
}

Child Component
export default function SideAccordian(props) {
    const [options, setOptions] = useState([]);
    const classes = useStyles();

    useEffect(() => {
        setOptions(props.filterprop);
    }, [props]);

    return (

            {
                options.map((ele, id) => (
                    <Accordion key={id} defaultExpanded={true}>
                        <AccordionSummary
                            key={ele.key}
                            expandIcon={<ExpandMoreIcon />}
                            aria-controls="panel1a-content"
                            id="panel1a-header"
                        >
                        </AccordionSummary>
                        {ele.options.map((item, i) => {
                            return (
                                <AccordionDetails key={i}>
                                    <IndeterminateInput
                                        key={i}
                                        id={i}
                                        name={item.name}
                                        value={item.label}
                                        selected={item.selected}
                                        onChange={props.onChange}
                                    />
                                </AccordionDetails>
                            )
                        })}
                    </Accordion>
                ))
            }

    );
}

Additionally, I need to call onChange() function as the component mounts & then automatically mark any of the checkboxes as selected according to the name of the checkbox passed as an argument.
The handler function onChange() works fine on clicking the checkbox, but when trying to invoke it on mount on the basis of a particular condition, it doesn't work.
As soon as the component mounts:
If onChange() is included in the dependency array, it throws Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array or one of the dependencies changes on every render.
If removed from the dependency array, it works but keeps throwing error each Hook useEffect has a missing dependency: 'onChange'. Either include it or remove the dependency array.
Since, I need to execute this function only once on render also i.e. (when info.prevui === intervention' & info.prevui does not change every time ), this error behavior of useEffect() is out of my understanding.
Can anyone please help out to understand and provide any working hint/solution for the same?
Thanks
Comment: If `handleCheckboxChange` dispatches an action to update state that is a dependency in the effect which invokes `handleCheckboxChange` then that is likely the cause of your looping. You mention you want the effect to run when the component mounts, it does, but since you've added dependencies it will run any time a dependency updates. Does issue repro if you use an empty dependency array (`[]`)?
Comment: You *can* ignore warnings if you *truly* want an effect to run only once on mount. It sounds like the data you want though isn't immediately available when the component mounts, but rather comes a render cycle (or 2 or 3) later.
Comment: Completely, they are *just* warnings, afterall, but like any warning, you should use caution when deciding to ignore it. The most typical use-case I consider is the `componentDidMount` condition where you know with certainty you only want a hook to run once total during the life of the component and all data is available at *that* time. The linter can't possibly know your use-case so it is a very general blanket check.
Comment: You're right. I included state.identifiers_checkbox.options_checkbox.length already in the useEffect()
Comment: the error indicates that state is set in an infinite loop. maybe you can try implementing componentDidUpdate function?
Comment: @AkinoArchilles Since I am using functional component, using componentDidUpdate() has the same effect as hook useEffect()
Comment: @DrewReese. Nope, if I pass empty dependency array [ ], the looping stops. But then as usual, the warning msgs occur: `React Hook useEffect has missing dependencies: 'handleCheckboxChange' and 'info.abbr'. Either include them or remove the dependency array  react-hooks/exhaustive-deps`. And also, the checkbox which I need to get selected, e.g., `label1` (originally it is being passed from state 'info.abbr'), does not get `checked: true`
Comment: @DrewReese Ignoring the warnings is legitimate in case of react hooks? I mean, under what conditions, should this be followed?
Comment: Your hint did work. I changed like this:  `useEffect(() => {
        if (info.prevui === 'intervention') {
            if (state.identifiers_checkbox.options_checkbox.length > 1) {
                handleCheckboxChange(info.abbr);
            }
        }
    }, [info.abbr, state.identifiers_checkbox.options_checkbox.length, info.prevui]);`.      The functionality I required did work, but now I am just left with a warning : `React Hook useEffect has a missing dependency: 'handleCheckboxChange'. Either includes it or remove the dependency array`, which I think I can ignore now :D
Comment: If your IDE doesn't suggest it, `// eslint-disable-next-line react-hooks/exhaustive-deps` a line above the dependency array will stifle the warning, but again, caution should be used because if you ever update the hook logic and dependencies *do* change this will silently swallow them. You may also try a more specific dependency, `state.identifiers_checkbox.options_checkbox.length`?
Comment: @DrewReese The problem still exists somehow. Can you help a bit in-depth?
Comment: Is it possible for you to reproduce this issue into a *running* codesandbox? It doesn't need to be your entire codebase, but just enough to reproduce the render looping.
Comment: Sure. I will create one
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/222700/discussion-between-bubble-cord-and-drew-reese).
Answer: The reason why there's an infinite render loop in your code when you include the onChange handler in the effect dependencies is because when whenever the handleCheckboxChange function is called, the handleCheckboxChange function is redefined due to state.identifiers_checkbox.selected_checkboxes and state.identifiers_checkbox.options_checkbox in the dependency array since both of them are updated in the redux state every time handleCheckboxChange is called.
Then, when you pass onChange into the dependency array of the useEffect, it runs the effect every time the onChange changes which is every time handleCheckboxChange is run - hence the infinite render loop.
So, the easiest way of fixing this would be to put onChange into a ref in the child component so you don't need to include it in the dependency array, that way it remains up-to-date in the effect, and doesn't cause an infinite render loop of doom.
  const onChangeRef = useRef(onChange);
  useEffect(()=>{onChangeRef.current = onChange},[onChange])
  useEffect(() => {
    if (info.prevui === "intervention") {
      if (state.identifiers_checkbox.options_checkbox.length > 1) {
        onChangeRef.current({ name: info.abbr, selected: 1 });
      }
    }
  }, [
    info.abbr,
    info.prevui,
    dispatch,
    state.identifiers_checkbox.options_checkbox.length,
  ]);

For an example of this: The codesandbox you posted in the chat (with the handleCheckBoxChange in the useEffect which causes the infinite loop as handleCheckboxChange is created everytime the component re-renders:
https://codesandbox.io/s/react-functional-component-forked-g7vh1
  useEffect(() => {
    handleCheckboxChange("ornge");

    setTimeout(() => {
      handleCheckboxChange("tmto");
    }, 5000);
  }, [handleCheckboxChange]);

Then fixed:
https://codesandbox.io/s/infinite-loop-fix-4y6zm?file=/src/index.js
  const changeRef = useRef(handleCheckboxChange);
  useEffect(() => {
    changeRef.current = handleCheckboxChange;
  }, [handleCheckboxChange]);
  useEffect(() => {
    changeRef.current("ornge");

    setTimeout(() => {
      changeRef.current("tmto");
    }, 5000);
  }, []);

Elaboration as requested:
React's useRef hook returns a value that is mutable and will always remain referentially stable. Essentially for each render, changeRef always points to the same object in memory as it did before, thus what it refers to is stable. This is different than most things, because for instance []===[] returns false because the arrays refer to different objects in memory.
useRef is known by React to create these mutable referentially stable objects, so they don't make it a requirement to pass them into the dependency arrays of any of the hooks as they know it isn't necessary.
By stuffing the onChange function into a ref and then making sure to update that ref whenever onChange changes via shallow equality, now we have a way to refer to the latest version of onChange without having to worry about adding it to the dependencies of the effect.
The reason why React has these dependency arrays to re-run the various hooks is because of Closures - each time the function component renders, all the various functions and objects are recreated (although useMemo, useCallback, and useState allow for certain things to not be recreated every time). When a function is created, then it has a way to refer to all the variables in the scope that the function can see.
That's why something like the following works. Even though test goes out of scope before funct is called, funct has a closure around it so it can always see it as long as funct is in scope somewhere.
let funct;
{
 const test = 5;
 funct = ()=>{console.log(test)}
}
funct(); // logs 5

These closures are what React Hooks rely on to work as they do. It's also the reason why the eslint plugin react hooks has the exhaustive-deps piece, because if you don't include something, then by the time the value is used, it'll become stale.
React's useRef hook allows us to bypass the closures because the refs are able to be mutated, so using ref.current gives us whatever value has been put in there regardless of when the closure was created.
Comment: I was just refering to the component that has the `onChange` mentioned in the post as a child component, since you didn't post any component names or full code, I just had to guess.
Comment: My bad. I've updated my parent and child components accordingly. If now they help you out my query about passing in the child component
Comment: If I am not wrong, both of these code sandbox links are still giving error for missing handler ?
Comment: The second link's warning message is: `The 'handleCheckboxChange' function makes the dependencies of useEffect Hook (at line 66) change on every render.` which is basically them trying to be helpful in saying that the `useEffect` that I'm using to update the `changeRef` is running every time (which is intentional in this case) as it's a demonstration of things.
Comment: It worked. Thanks. The issue is now resolved! Not getting the dependency error anymore. Can you please help elaborate bitmore on how using ref worked exactly for this?
Comment: @bubble-cord, I've added a bunch of explanation and a couple links for you


Is $L^2(0,T;H^{-1}(\Omega)) \subset \mathcal{D}^*((0,T)\times \Omega)$?

Question: Let $\Omega \subset \mathbb{R}^n$ be a domain. Consider the space of test functions $\mathcal{D}((0,T)\times \Omega)$ and the space of distributions $\mathcal{D}^*((0,T)\times \Omega).$
Is it true that $L^2(0,T;H^1(\Omega))^* = L^2(0,T;H^{-1}(\Omega))$ is a subset of $\mathcal{D}^*((0,T)\times \Omega)$?
I've not been able to prove this. Given $f \in L^2(0,T;H^{-1}(\Omega))$, we have that $f \in \mathcal{D}^*((0,T)\times \Omega)$ if for $v_n \to v$ in $\mathcal{D}((0,T)\times \Omega)$, it holds that $f(v_n) \to f(v)$ in $\mathbb{R}$  (linearity is easy to check).
How to show this? We know that $D^\alpha v_n \to D^\alpha v$ uniformly for all multiindices $\alpha$, but I can't get $L^p$ convergence from this. Help appreciated.
Answer: $D((0,T)\times \Omega)\subset L^2((0,T);H^1(\Omega))\subset L^1_{loc}((0,T);H^1(\Omega))$.
Define $$f(v) = \int_0^Tdt \langle f(t,\cdot),v (t,\cdot)\rangle_{H^{-1};H^1},$$ then $$|f(v)|\le \int_0^Tdt \| f(t,\cdot)\|_{H^{-1}}\|v (t,\cdot)\|_{H^1} \le | K |\int_0^Tdt \| f(t,\cdot)\|_{H^{-1}}\sqrt{\|v (t,\cdot)\|_{L^\infty}^2+\|\nabla_x v (t,\cdot)\|_{L^\infty}^2 },$$
where $K$ is a projection of the support of $v$ on $\Omega$. Now we need only to deal with technical details
$$|f(v)|\le |K|T \|v\|_{C^1((0,T)\times\Omega)}  \int_0^Tdt \| f(t,\cdot)\|_{H^{-1}} \le  |K|T^{3/2} \|f\|_{L^2((0,T);H^{-1}(\Omega))}\|v\|_{C^1((0,T)\times\Omega)}   . $$
This proves that $f(v)$ is a distribution.
Comment: @maximumtag the inclusion of topological duals bases on the inclusion of topologies, the presence of the norm is irrelevant.
Comment: Thanks but I don't understand why this means that $f$ is a distribution. You've shown that $f \in (C^1((0,T)\times\Omega))^*$ but this doesn't mean $f \in \mathcal{D}^*((0,T)\times \Omega).$
Comment: $C^1((0,T)\times\Omega)\supset\mathcal{D} ((0,T)\times \Omega) $, hence $(C^1((0,T)\times\Omega))^\ast\subset\mathcal{D}^\ast ((0,T)\times \Omega) $.
Comment: Is that obvious? I know when $X \subset Y$ are normed spaces with continuous embedding that $Y^* \subset X^*$ but $\mathcal{D}^*$ is not a normed space.. it still holds?
Comment: @maximumtag $D^\ast$ are linear functionals continuous in the topology of multinorm given by seminorms $p_\alpha(\phi)=\sup_{\beta\le\alpha}\sup|D^\alpha\phi|$, $\alpha,\,\beta\in \Bbb N^d$. We proved that $f$ is a linear functional which is continuous in one of that seminorms (namely, $p_{1,1,\dots,1}$), hence it is continuous in the topology of multinorm.


How to restrict the maximum size of an element in a list in Python?

Question: Problem Statement:
There are 5 sockets and 6 phones. Each phone takes 60 minutes to charge completely. What is the least time required to charge all phones?
The phones can be interchanged along the sockets
What I've tried:
I've made a list with 6 elements whose initial value is 0. I've defined two functions. Switch function, which interchanges the phone one socket to the left. Charge function, which adds value 10(charging time assumed) to each element, except the last (as there are only 5 sockets). As the program proceeds, how do I restrict individual elements to 60, while other lower value elements still get added 10 until they attain the value of 60?
Comment: can't this be done here, if list element value gets greater than 60, limit to 60 considering you're modifying single element at a time.
Comment: `element = min(element + 10, 60)`
Comment: Try using an `if` conditional. Assuming you're iterating over the phones in a for loop with a local index variable `i`, then it could be something like `if phone_charge[i] == 60: # do nothing; else: phone_charge[i] += 10`
Answer: Charging is freely interchangeable, so this is a trivial algebra problem.
<code>6 * 60 charger minutes / 5 chargers = 72 minutes clock time to charge.
</code>
Each phone needs to be on some charger for 60 minutes total, and off for 12 minutes.  The rota is simple, but your 10-minute quanta will fail to find the solution.
Put 5 phones on the 5 chargers.  Every 12 minutes, swap out one phone that has been charging since the start, and swap in the idle phone.  This solution is extensible for any quantity of phones and chargers.
Answer: In the charge function, add an if condition that checks the value of the element.
I'm not sure what you're add function looks like exactly, but I would define the pseudocode to look something like this:
if element < 60:
add 10 to the element
This way, if an element is greater than or equal to 60, it won't get caught by the if condition and won't get anything added to it.
Answer: You cannot simply restrict the maximum element size. What you can do is check the element size with a if condition and terminate the process.
btw, answer is 6x60/5=72 mins.
Comment: sry, mistake, i have changed. it is 72 mins.


Serializing Properties With Same Name

Question: I have the following model structure:
public class A
{
    [JsonProperty("id")]
    public string Id { get { return "A:ID"; } }

    [JsonProperty("CompKey")]
    public string CompKey { get; set; }
}

public class B : A
{
    [JsonProperty("id")]
    public string Id { get { return "B:ID"; } }

    [JsonProperty("name")]
    public string Name { get; set; }
}

I want to serialize an instance of class B but only want the Id property of class A to be visible.
I created a contract resolver to pass to Newtonsoft:
public class DatabaseEntryResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        property.ShouldSerialize = instance => property.DeclaringType == typeof(A);
        return property;
    }
}

I use this in the following manner:
var someObject = new A();
var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings
{
    ContractResolver = new DatabaseEntryResolver()
});

However, neither of the ID properties are being created in the JSON structure. Anyone might shed some insight on this issue I am having?
Comment: Why `var someObject = new A();` instead of **`var someObject = new B();`**?  Isn't the issue that you need to get `A.Id` when you serialize an instance of `B`?
Answer: Json.NET will never serialize two properties with the same name.  If DefaultContractResolver encounters two identically named properties, it chooses to serialize the most derived property that is not ignored.  Notably, this decision is based on static metadata such as the presence of absence of [JsonIgnore] -- and not on runtime state such as the return from ShouldSerialize.
Thus, to make A.Id supersede B.Id when serializing an instance of B, you must override CreateProperty() as follows:
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
    var property = base.CreateProperty(member, memberSerialization);
    if (member.ReflectedType == typeof(B)) // Use (typeof(A).IsAssignableFrom(member.ReflectedType)) if you want this to apply to all subclasses of A
    {
        // Make A.Id supersede B.Id
        if (member.Name == nameof(A.Id) && member.DeclaringType != typeof(A))
            property.Ignored = true;
    }
    return property;
}

In addition, if you want really ony want the Id property of class A to be visible when serializing an instance of B, you must in addition remove or ignore everything else in CreateProperties():
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
    var properties = base.CreateProperties(type, memberSerialization);
    if (type == typeof(B)) // Use typeof(A).IsAssignableFrom(type)) if you want to only serialize the Id property of A and all its subclasses
    {
        // Remove everything except Id.  You could also Ignore everything except Id.
        properties = properties.Where(p => p.UnderlyingName == nameof(A.Id)).ToList();
    }
    return properties;
}

Notes:

Presumably Newtonsoft does not check ShouldSerialize to determine which Id property to bind to JSON because ShouldSerialize cannot be called during deserialization.

If you really just want to serialize { "id": "A:ID" } for every instance of A or any subclass of A, use typeof(A).IsAssignableFrom() where I mention it in code comments.

You should mark B.Id with the new modifier to avoid a compilation warning.
public class B : A
{
    [JsonProperty("id")]
    public new string Id { get { return "B:ID"; } } // Fixed compilation

For more see Knowing When to Use Override and New Keywords (C# Programming Guide).

Demo fiddle here;
Comment: Simply marking `B.Id` with `[JsonIgnore]` will work if you **never** want to serialize `B.Id`.  I inferred you were using a contract resolver so you could optionally serialize one or the other depending on your needs at runtime.
Comment: Very well explained. This solution might work. Got it to work by following what the guys over at Json.Net suggested: https://github.com/JamesNK/Newtonsoft.Json/issues/2544#issuecomment-858714841
Comment: No, actually that is what I perfectly want to do, sometimes I might need to serialize A.Id and sometimes B.Id. After looking at your code now, I can say that it is exactly what the guys at Json.Net proposed, however, their approach is simpler as it just overloads another method that is supposed to do the stuff you outlined in your response.
Answer: For whoever has encountered this issue, an explanation was given by the guys who developer Netwonsoft.JSON here, such that my new contract resolver is the following:
public class DatabaseEntryResolver : DefaultContractResolver
{
    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        return base.GetSerializableMembers(objectType).Where(member => member.DeclaringType == typeof(A);
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        property.ShouldSerialize = instance => property.DeclaringType == typeof(A);
        return property;
    }
}

Note how I still decided to leave the overloaded CreateProperty method, even though technically it is not needed as the overloaded GetSerializableMembers method already filters out the properties I need. I decided to this just in case but without it the solution still works.
Comment: While this may do what you need, it doesn't do exactly what you wrote in your question.  Your question states *I want to serialize an instance of class B but only want the Id property of class A to be visible.* but what this does is to serialize an instance of `B` as if it were an instance of `A`.  Which is a perfectly fine thing to want to do, just slightly different than stated.

Serializing Properties With Same Name


Override context-root of ear file in wildfly config

Question: We are using wildfly 8 and 9 in standalone mode to deploy our applications. In front of the wildfly there is a shared apache reverse proxy. The proxy maps /test/ to one wildfly and /test2/ to another system. Our application is using JSF which makes it necessary for it to "know" the context path. Therefore we have to create different deployment artifacts for the different wildfly instances now, because the application.xml has to define the context-root either as /test/ or /test2/
I was wondering now if it is possible to override the context-root from the appplication.xml in the wildfly configuration. E.g. our context-rot in the application.xml could be / for all environments while wildfly prepends it with either /test/ or /test2/ depending on the instance. Is this possible somehow?
Answer: You can add the parameter -Djboss.socket.binding.port-offset=<value> to your JVM_OPT.
With this you'll not use the Standard Port 8080 but 8080+value
 As an example:

application.xml context path is set to /
application 1 has -Djboss.socket.binding.port-offset=0
application 2 has -Djboss.socket.binding.port-offset=100

Result:
application 1: http://localhost:8080/
application 2: http://localhost:8180/
Comment: Unfortunately this won't help. I have to be able to map different "subfolders" on the apache to the wildfly instances. To make this work the context path has to be different on each of them. It's a JSF issue: path on the reverse proxy and the server that is behind the proxy has to be the same various things will break. (There is also a fix for the JSF side of this problem, but I'd like to avoid changes there)


Como posicionar uma imagem com vertical-align?

Question: Tenho um menu em que posiona a logomarca do site da seguinte forma:
html:

css:
header div a img.logo{
    top:50%;
    transform:translateY(-50%);
    position:relative;
    float:left;
}

Porem, essa forma de posiciona-la não funciona corretamente em todos os navegadores, e antes de eu decidir usar esse método de posicionamento, eu queria posicionar usando vertical-align. É possível?
Answer: Tem várias formas de fazer isso. Mas se é que eu entendi você quer fazer um vertical-align middle. Okay ?
Para usar o vertical-align independente do seu valor, deve-se usar a propriedade table, table-cell. Elas se relacionam.
Mas o que você pode fazer para facilitar é definir um line-height no seu HEADER.
Ficando assim:

header{
    line-height: 120px;
}

Automaticamente a imagem ficará no meio.
Comment: Gostei do seu método, testei aqui e deu certo, mas... tem um probleminha a tag  ficou alinhada bem ao meio, mas a tag  com a logomarca não ficou no meio, tentei resolver mudando os display's para outros, mas não deu certo. :( sabe como resolvo? [link] (http://i.imgur.com/eJKz3Vx.png) , aqui está o codigo no JSFiddle: [link] (https://jsfiddle.net/gerlandoprado/jmb17zwe/1/)
Answer: Como o Diego disse a única maneira de trabalhar com o vertical-align é usando table e table-cell. Caso você queira mesmo utilizar, tente fazer dessa forma.

html,body{
    margin: 0;
    padding: 0;
    height: 100%;
}

header {
    width: 100%;
    height: 100%;
    display: table
}

#conteudo {
    display: table-cell;
    vertical-align: middle
}


What are the pros and cons of using Acquia Drupal install packages?

Question: My firm is considering using the Acquia Drupal install packages at http://acquia.com/downloads as a default boilerplate to start with for new client sites. What are the pros and cons of taking this approach?
Comment: That's a good question; I was considering Acquia for awhile because of its ease of install on Microsoft Server platforms. I'm curious if anyone has any particularly good usage cases for it.
Answer: Boris Mann once described Drupal as a big box of Lego. Acquia Drupal is just a bigger box of Lego.  It still doesn't do anything out of the box, it just gives you more pieces.  Given how much stuff went into Drupal 7 core it is mostly redundant - download core, views, wysiwyg and admin and you can start building good sites.
In terms of pros for Acquia Drupal I'm struggling a little.  The first is that it helps inexperienced users get onto the Acquia Network.  The other is that you don't have to download everything, but this is also a con as you get everything Acquia thinks you need.
One of the biggest cons as I see it is that they dump all the modules under modules/ which is considered bad practice in the Drupal community.  Not only is this annoying if you decide to switch back to stock Drupal + contrib or Pressflow + conrib, but it teaches users bad practices from day 1.
I must admit I played with it once and decided against using it.  These days I assemble my code using drush make as it gives me only what I want and I'm not dependent on a third party to provide security releases after a module is updated I can just update my make file and reroll my stuff.
[rant]These days the community has moved on to building true distros, not just throwing more Lego pieces in a box.[/rant]
Comment: as Dave Hall says, look into using Drush Make instead for managing your boilerplate code. If you absolutely have to, install Aquia once and run `drush make-generate` on it, then move on. Dropping the modules into the /modules folder can be bad news when it comes time to update any of your modules, let alone Drupal core.
Answer: If I understand, according the datasheet of Acquia, http://acquia.com/files/marketing/Acquia_Overview_datasheet-web2.pdf Drupal Acquia has the same Drupal core, but include preinstalled modules and configurations to get versions of Drupal ready to common needs.
Accordign this, about pros, I think that with Drupal Aquia you will have guidance an experience in the selection of modules and configurations, also time savings. Cons, I do not see cons related specifically with your question.
It is my opinion. I will pending of other opinions to learn about other points of view.
see other opinions http://groups.drupal.org/node/17838
Answer: Pros would be a setup which is primed and ready for a number of uses including addtional contrib modules which are commonly useful...
Cons, its generic so it might include some configuration / modules which you will need to remove...
In most cases it will not be a problem and will give you a simple head start on development
Answer: Using Acquia Drupal is like having automatic transmission in your car.  It takes care of a bunch of things so that you don't have to worry about them.  However, if you'd like more control (e.g. specific versions of modules), then you better go with standard Drupal.
One of my clients wanted to go with Acquia, so we did, but it was necessary to drop it later because we needed more up-to-date versions of contributed modules.


Recursive text search with grep and file patterns

Question: Given this example folder structure:
/folder1/file1.txt
/folder1/file2.djd
/folder2/file3.txt
/folder2/file2.fha
How do I do a recursive text search on all *.txt files with grep from "/"?
("grep -r <pattern> *.txt" fails when run from "/", since there are no .txt files in that folder.)
Answer: My version of GNU Grep has a switch for this:
grep -R --include='*.txt' $Pattern

Described as follows:

--include=GLOB

Search  only  files whose base name matches GLOB (using wildcard matching as described under --exclude).
Answer: If you have a large number of files it would be useful to incorporate xargs into the command to avoid an 'Argument list too long' error.
find . -name '*.txt' -print | xargs grep <pattern>

Comment: If there are spaces in any of the file or directory names, use this form:
find . -name '*.txt' -print0 | xargs -0 grep
Comment: And of course there's the issue of filenames that start with `-`.
Comment: `grep` is faster of `find`.
Answer: you might be able to make use of your zsh's EXTENDED_GLOB option (docs)
grep <pattern> **/*.txt

Comment: Only if OP is using zsh, but interesting nonetheless.
Answer: You may want to take a look at ack at http://betterthangrep.com, which has facilities for selecting files to search by filetype.
Answer: find . -name '*.txt' -type f -exec grep <pattern> {} \;

Comment: you might want to use "find . -name '*.txt' -type f -exec grep  {} +" instead so that it rather behaves similiar the verision with from Mark Robinson - works only with GNU find to my knowledge
Answer: Mannis answer would fork a new grep-process for every textfile. If you have lots of textfiles there, you might consider grepping every file first and pick the .txt-files when thats done:
grep -r <pattern> * | grep \.txt:

That's more disk-intensive, but might be faster anyway.
Answer: It's 2019 and there's no way I would still use grep for recursive text searching.
IMHO todays answers should include ripgrep:
rg <pattern> -ttxt


AWS Oracle RDS backup / restore

Question: I have a huge Oracle Enterprise Edition RDS DB in AWS, aorund 6253 GB, that I will not used for some days. Is there a way to backup the DB and restore it after some days to avoid to pay (for the period I will not use the DB) the fee per GB-month of provisioned GP2 storage. Thanks
Answer: You can stop your RDS instance (announced June 1, 2017) for up to 7 days. If you do chose to snapshot your database and delete, update this thread as I am very curious on how long the snapshot will take for 6.2 TB.
The stop/start feature is available for database instances running in a Single-AZ deployment which are not part of a Read Replica (both source and replica) configuration.
Amazon RDS for MySQL, MariaDB, PostgreSQL, Oracle and SQL Server now allows you to easily stop and start your database instances. This makes it easy and affordable to use databases for development and test purposes, where the database is not required to be running all of the time.
Stopping and starting a database instance requires just a few clicks in the AWS Management Console, or a single call using the AWS API or AWS Command Line Interface, and takes just a few minutes. While your database instance is stopped, you are charged for provisioned storage, manual snapshots and automated backup storage within your specified retention window, but not for database instance hours.
Amazon RDS Supports Stopping and Starting of Database Instances
Comment: I think this is probably the best option. This still leaves a storage fee of around $700 if it was stopped for a month. Using snapshots / backups isn't much cheaper - general purpose RDS storage is $0.115/GB month, backup storage is $0.095c/GB month, so on 5TB you'd save an additional $100 per month using snapshots rather than stopping the instance. That doesn't take into account any other backup / snapshot storage.
Answer: AWS provides two ways to backup and restore Oracle RDS.
Automated Backups – This option is turned on by default. It allows point-in-time recovery for DB instance and will backup your database and transaction log. It stores both of them for a user-defined retention period. Due to this, you can restore DB instance anytime during the retention period, up to the last five minutes. You can configure the automatic backup retention period to up to 35 days.
DB Snapshots – This user-initiated backup option gets your full database stored by Amazon RDS until you delete them. It allows you to create a new DB Instance from a DB Snapshot anytime you want.
A third option is to use an AWS third party backup solution. These services provide a variety of backup options if you need a less hands on solution.  Yes, there is a cost; but the ROI depends on your particular business needs.

AWS Oracle RDS backup / restore


Custom content type with a gallery and its "subgalleries" (or categorized gallery) in D7

Question: I have a content type with some custom fields, and I would like to have a gallery in it, with the images grouped into predefined "categories" - like a "subgallery".
For example, I have a "building" content type, and I would like to categorize the photos of it depending on of which part of the building (house) these photos were made or if they are simply archive photos, etc.: you can think of categories e.g. like "Inside", "Outside", "Archive", "Misc."
I made a drawing to make it clearer:

What would be the best way to solve this problem?
Thanks for any kind of ideas!
Ask if anything is unclear.

In the meantime, I found a Media Gallery issue related to the topic:
New feature: Gallery containers (other related issues: Hierarchical galleries, Categorizing galleries)
Comment: IMHO it sounds like job for Node Reference. Did you check https://drupal.org/project/references? You can try to do it with taxonomy too.
Comment: @drupality: thanks for your answer, but how could I solve that when the end user creates a new content with this custom type, he/she would see an "in-place" uploading opportunity for the galleries? Or what alternatives can you imagine? I also thought about using [Media Gallery](http://drupal.org/project/media_gallery), but don't have a clue how to apply this for the given task.
Comment: If I remember good you can choose reference node from select list (e.g.) on your base node form.
Comment: @drupality: yes, OK, but my problem is that the user will be forced to create a gallery for the given content type **separately**, and later attach to this content, while this gallery doesn't really make sense on its own. So creating a separate gallery, and later attach to that node would be uncomfortable. :( Or do you know a good solution for that?
Comment: Sounds like you need to create custom module with form that allow you to create base node and gallery at once. Is this want you want?
Comment: @Sk8erPeter the [inline entity form](http://drupal.org/project/inline_entity_form) module will sort that bit out for you
Comment: @Clive: wow, that sounds great. If it is a possible solution, could you please post it as an answer? (Maybe a screenshot or two could be useful.) Thank you! Oh yeah, one more question. What about multiple languages? Do I have to create the galleries separately for all the enabled languages?
Comment: @Clive thanks guy to introduce inline entity form module which really was missed in Drupal 7. is there any plan for cover handling related models in D8?
Comment: Also if you have not complex sub-galleries, you can simply  create image field per sub-gallery.
Comment: @MohammadAliAkbari: I wouldn't have so complex galleries, I would like to have only exactly 6 of them. But even after attaching another gallery to the content type, I don't know how to categorize it well. Do you have any ideas?
Comment: @Clive: I opened a bounty for the question. If you could elaborate a little bit more on how to do the categorization exactly, it would be great, and I would gladly give the bounty to you. Inline Entity Form seems like a great start.
Comment: If you wont using inline entity form module and If your galleries is not complex (just images with their description), you can create one content type (gallery) with this fields:

 - title
 - body
 - custom field
 - gallery_archive (image field with unlimited cardinality)
 - gallery_outside (image field with unlimited cardinality)
 - 4 other galleries (image field with unlimited cardinality)
Comment: @MohammadAliAkbari: hmm, thanks for the idea, this seems like a good start! (In the meantime, I tried Inline Entity Form, but it seems like not working well for other content types which are not related to Commerce module.) But how to display the "subgalleries" (for example the images in the `gallery_archive` field) in a separate page? Maybe with Views, using arguments? What about multilingual content? Do I have to attach the images for each languages separately? Thanks!
Answer: I don't know how well exactly this will fit in with your use case, but this is how I'd do it:

Create a content type called "SubGallery", add an Image field to it with unlimited cardinality.
Create the content type you want to contain the sub-galleries ("Building")
Add an Entity reference field to the "Building" type that references an unlimited number of "SubGallery" nodes.
Choose "Inline Entity Form" as the widget for that field, which will allow users to create the "SubGallery" content types within the same form as the "Building".

You can make use of the standard node title field for the name of the sub-gallery, or you might add a vocabulary called "Gallery Type", and add a field referencing that to the "SubGallery" content type. Then when your users add a new sub-gallery via the inline edit form, they can choose one of your pre-defined gallery types to associate with it.
If you do add the vocabulary and no longer need a node title for the sub-galleries,you could use Automatic Nodetitles to fill it in automatically and hide it from the users.
Comment: Hi Clive, thanks for your answer and sorry for the late feedback. So, I have Entity Reference 7.x-1.0-rc3 and Inline Entity Form 7.x-1.0-beta3 installed. I created the "SubGallery" content type with an image field: http://i.imgur.com/HXoLZ.png. Then I created a "Building with subgalleries" content type with an Entity Reference field: http://i.imgur.com/e0Kxm.png. Here are the field settings: http://i.imgur.com/vOCci.png. BUT, when I try to create a node of the type "Building with subgalleries", the entity reference field doesn't show up: http://i.imgur.com/wA4pn.png. But why?!
Comment: Hmm that's odd, if you add a field it should definitely show up on the entity edit form. Could you try changing the widget to 'Image' instead of 'Media Selector' just to rule out any issue with that?
Comment: I tried that, changed the widget type to the regular Image: http://i.imgur.com/fg1Rb.png, but unfortunately the result is the same, the reference field doesn't show up. :( BUT after creating a SubGallery node, and changing the entity reference widget to e.g. "Select list" like this: http://i.imgur.com/h82KT.png, it shows up on the node creation form: http://i.imgur.com/ZBZ9S.png. But this way I can only reference **existing** nodes. So now it seems to me that Inline Entity Form doesn't work this way... I hope I'm not right! Any ideas? Have you tested it this way?
Comment: Just for testing, I installed Drupal Commerce, put a "Product reference" field in a test content type, set "Inline Entity Form" as a widget (like in the [screencast](http://commerceguys.com/blog/commerce-module-tuesday-inline-entity-form)), and with it, a product can be created "on-the-fly" without a problem. But unfortunately it seems like it doesn't work with "regular" entities like my "SubGallery"... So we are back again where we started... :( Do you have any alternative ideas? (or maybe a correction for the problem with Inline Entity Form)
Comment: +1. UPDATE: I found this issue: http://drupal.org/node/1713088, so others had similar problems like me; this problem seemed to have been solved in the Inline Entity Form **7.x-1.x-dev** version, BUT I still have a problem: I activated Automatic Nodetitles like this: http://i.imgur.com/bzT9L.png, which is correct (tried "separately", and works fine), but on the building node creation form, the title still appears, and while validation, I get this "mysterious" error: http://i.imgur.com/xgUgZ.png (mysterious, because I don't know which field is missing...).
Comment: Ah my bad, auto node title doesn't have support for IEF yet. There is [a patch](http://drupal.org/node/1719948) however, might be worth a try
Comment: ahh, thanks, I haven't seen this issue yet, I'll try that patch soon!
Comment: hmm, that's interesting, as a first try, now I simply disabled "Automatic title generation" for this content type: http://i.imgur.com/e3Tsb.png. But the validation error is just the same as before.... BTW, Theme developer is now completely DISABLED, so this can not be the source of the problem.
Comment: UPDATE (sorry for flooding you with comments :)): wow, after all it seems like Inline Entity Form DOES have an issue with Media module: after setting from [Media file selector](http://i.imgur.com/HXoLZ.png) back to [the regular Image field](http://i.imgur.com/fg1Rb.png), it seems to work perfectly as it should, look, here's a full screenshot: http://i.imgur.com/Kpn4o.png. "SubGallery" nodes can be edited and saved on-the-fly via AJAX, images can be added, categories can be selected with the radio buttons etc., so it seems very good! I think it was a good idea, I give you another feedback soon!
Comment: OK, first appearance: http://i.imgur.com/vAiK8.png, no thumbnails,etc. I enabled [Gallery formatter](http://bit.ly/9qiC4N),and set "Building with subgalleries" content type's display to "Rendered entity" like this: http://i.imgur.com/hfqUE.png,and set "SubGallery" type's Image field display to "jQuery Gallery": http://i.imgur.com/g3tXx.png. Now the result shows up like this: http://i.imgur.com/C8Sec.png. Close to what I would like to achieve! If you have any suggestions how to display exactly what I showed above, I'll be grateful if you tell me. But in fact you answered my question, thank you!
Comment: No probs :) There a probably a few different ways but I'd go with adding a new view mode for the gallery node (you can use [Entity View Mode](http://drupal.org/project/entity_view_mode) and providing a separate template for that view mode that mirrors exactly what you want to output. Then select that view mode in the manage display settings and you should be good to go


OpenVPN: Setup a virtual network that only contain Servers - Is this possible?

Question: All the examples about OpenVPN I have read so far either show "A client connecting to a Server(Point-To-Point)" or "Two networks are connected with each other(Bridge)".
What I want to achieve is, I want to connect 10 server-machines, each running at different ISPs. The connections between these server-machines should be secured. What I have not understood at all is, which of the server-machines will be the OpenVPN client and which one will be the OpenVPN server? The final solution should allow me to setup an infrastructre, where all the server-machines will have a private IP address and form their own "private/virtual network" (in the range 10.0.0.0/24):
<code>Server 1 (Public IP: xxx.xxx.xxx.xxx) => Private IP 10.0.0.1
Server 2 (Public IP: xxx.xxx.xxx.xxx) => Private IP 10.0.0.2
Server 3 (Public IP: xxx.xxx.xxx.xxx) => Private IP 10.0.0.3
Server 4 (Public IP: xxx.xxx.xxx.xxx) => Private IP 10.0.0.4
</code>
(So in the end a server-machine will have a public and a private IP). And whats so important in my case: The machine are not located in their own physical network (like an office), but rathere they are all spread over to different ISPs and can only be reached via their public IP => For this case I have not found any tutorials/documentation yet. (This seems to be some form of Multi-Point-to-Point?)
My question is: What do I have to do in OpenVPN to set this up? Will every server require both a client and server to be installed/configured? How do I have to do the "wiring" between them? Will every "server-machine" run an OpenVPN client and an OpenVPN server process, whereby the client will be connected to all the other server OpenVPN instances? So I have to configure on all server-machines the client to connect to all other server-machines (to the corresponding OpenVPN Server process)?
Thank you for your advice
Francois
Comment: Can I ask why you'd want to set this up? Fully meshing 10 remote servers on the same private subnet could eat a lot of bandwidth, and is going to be a security headache (one compromised server gives LAN access to all of the others).
Answer: The easiest way I can see to do this is to designate one server as the router. This runs the OpenVPN server. Then you set up each other server with the client software using a "road warrior" setup. If your router pushes the routing rules properly (big if) then all the clients should be able to communicate with each other.
Your "router" server will be the bottleneck, because all traffic will be going through it.
If you want a fully meshed setup then you will likely need each of your 10 servers to act both as a server (for the other 9 machines) and as a client (to the other 9 machines). I think this is possible but it looks hideous.


ScrollMagic - always animate first item first

Question: Is there a way to ensure that the first item that appears always scrolls in first - using this code? At the moment it fires depending on the order of the elements. I am asking because the order of the elements changes throughout the site - I would rather not create a new scene for every different scenario. Someone might see a clever way of doing this. Thanks for any help in advance.
<code>$('.data-scrollIn').each(function(index, elem) {
  // Init ScrollMagic Controller
  var controller = new ScrollMagic.Controller();

  // Create Animations
  h2 = $(elem).find('h2');
  h3 = $(elem).find('h3');
  btn = $(elem).find('.btn');
  p = $(elem).find('p');
  img = $(elem).find('img');
  span = $(elem).find('span.js-fade-order');

  var tl = new TimelineMax({
    pause: true
  });
  tl.add("start") // add timeline label

  .fromTo(span, 0.6, {
    opacity: 0,
    y: "40px",
  }, {
    opacity: 1,
    y: "0",
    ease: Power0.easeInOut
  },  0.3, "start")

    .fromTo(h2, 0.6, {
      opacity: 0,
      y: "40px",
    }, {
      opacity: 1,
      y: "0",
      ease: Power0.easeInOut
    },  0.6, "start")

    .fromTo(img, 0.6, {
      opacity: 0,
      y: "40px",
    }, {
      opacity: 1,
      y: "0",
      ease: Power0.easeInOut
    }, 0.9, "start")

    .fromTo(h3, 0.6, {
      opacity: 0,
      y: "40px",
    }, {
      opacity: 1,
      y: "0",
      ease: Power0.easeInOut
    }, 1.2, "start")

    .fromTo(p, 0.6, {
      opacity: 0,
      y: "40px",
    }, {
      opacity: 1,
      y: "0",
      ease: Power0.easeInOut
    }, 1.5, "start")

    .fromTo(btn, 0.6, {
      opacity: 0,
      y: "40px",
    }, {
      opacity: 1,
      y: "0",
      ease: Power0.easeInOut
    }, 1.8, "start")
   // Create the Scene and trigger when visible
    var sceneFade = new ScrollMagic.Scene({
      triggerElement: elem,
      offset: -100 /* offset the trigger Npx below scene's top */
    })
    .setTween(tl)
    .addTo(controller);
 });
</code>
Comment: sorry - I worked this out
Answer: <code> $('.data-scrollIn').each(function(index, elem) {
  // Init ScrollMagic Controller
  var controller = new ScrollMagic.Controller();

  // Create Animations
  fadeElem = $(elem).find('h2, h3, .btn, p, img, span.js-fade-order ');

  var tl = new TimelineMax({
    pause: true
  });
  tl.add("start") // add timeline label

    .staggerFromTo(fadeElem, 0.6, {
      opacity: 0,
      y: "40px",
    }, {
      opacity: 1,
      y: "0",
      ease: Power0.easeInOut
    },  0.6, "start")

  // Create the Scene and trigger when visible
    var sceneFade = new ScrollMagic.Scene({
      triggerElement: elem,
      offset: -100 /* offset the trigger Npx below scene's top */
    })
    .setTween(tl)
    .addTo(controller);
});
</code>


Can list comprehensions (ideally) do the equivalent of 'count(*)...group by...' in SQL?

Question: I think list comprehensions may give me this, but I'm not sure: any elegant solutions in Python (2.6) in general for selecting unique objects in a list and providing a count?
(I've defined an __eq__ to define uniqueness on my object definition).
So in RDBMS-land, something like this:
CREATE TABLE x(n NUMBER(1));
INSERT INTO x VALUES(1);
INSERT INTO x VALUES(1);
INSERT INTO x VALUES(1);
INSERT INTO x VALUES(2);

SELECT COUNT(*), n FROM x
GROUP BY n;

Which gives:
COUNT(*) n
==========
3        1
1        2

So , here's my equivalent list in Python:
[1,1,1,2]

And I want the same output as the SQL SELECT gives above.
EDIT: The example I gave here was simplified, I'm actually processing lists of user-defined object-instances: just for completeness I include the extra code I needed to get the whole thing to work:
import hashlib

def __hash__(self):
    md5=hashlib.md5()
    [md5.update(i) for i in self.my_list_of_stuff]
    return int(md5.hexdigest(),16)

The __hash__ method was needed to get the set conversion to work (I opted for the list-comprehension idea that works in 2.6 [despite the fact that I learnt that involves an inefficiency (see comments) - my data set is small enough for that not be an issue]). my_list_of_stuff above is a list of (Strings) on my object definition.
Answer: Lennart Regebro provided a nice one-liner that does what you want:
>>> values = [1,1,1,2]
>>> print [(x,values.count(x)) for x in set(values)]
[(1, 3), (2, 1)]

As S.Lott mentions, a defaultdict can do the same thing.
Comment: The defaultdict solution will do a lot better on larger `values` lists, because it will only loop the values once, instead of once plus once for each unique value.
Comment: A few hundred is quite a few :) A few hundred loops through a few hundred items will take a few hundred times longer than one loop through a few hundred items.
Comment: Actually (although very elegant code: so the tick-stays) , this is a little more tricky for instances of my user-defined objects, as it appears I have to define a '__hash__' method that returns an 'int' , which (in my particular case) is non-trivial (its a big lump of text) : I might try an MD5 checksum or something(suggestions?), but for now, I think I'll go with the (not-unelegant) 'def group_by(someList)' given by S.Lott.
Comment: @Thomas - understood, good point; in my case I have a few hundred items at most.
Comment: I appreciate everybody's concern about performance - but I'm not designing enterprise software here - I'm running a text filter against a few meg of logfiles.

At is happens , it runs just great for my needs. I might swap out the algorithm at some point, if the script has more than a one-off use.

In fact, the script completes in about a second, including the additional overhead of text-processing to generate my objects and to format the final report.

I believe off the top of my head, that the algorithm is 2*n, as opposed to 1*n: so it should scale in a linear fashion as it happens.
Answer: >>> from collections import Counter
>>> Counter([1,1,1,2])
Counter({1: 3, 2: 1})

Counter only available in py3.1, inherits from the dict.
Answer: Not easily doable as a list comprehension.
from collections import defaultdict
def group_by( someList ):
    counts = defaultdict(int)
    for value in someList:
        counts[value.aKey] += 1
    return counts

This is a very Pythonic solution.  But not a list comprehension.
Comment: @monojohnny: `>>> from collections import defaultdict`
Comment: This way works, even if it's not a list comprehension at all.
Comment: Very 'awk' like solution as it goes as well!

Small problem when running it on my system:

...
counts = defaultdict(int)
NameError: global name 'defaultdict' is not defined
...

( Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32 )
Comment: @Adam: Poster asked for list comprehension method, as you provided.  However, even without that, the most "Pythonic" solution would be to use the built-in Counter class rather than rolling out your own.
Comment: @BlueRaja: Counter is not available in py2.6, and OP is clearly misunderstands the list comprehensions. Because accepted solution has a piss-poor performance.
Comment: @SilentGhost; thanks I should have worked that out really !! Doh!
@BlueRaja - I have clarified the title  - I was aiming for List Comprehension (cos they look nice), but was accepting other ways as well.
Comment: @BlueRaja: I agree; the built-in solution is always preferable.
Comment: @SilentGhosht: re:"OP is clearly misunderstands the list comprehensions" - in fact as far OP is concerned I think they'd be better being referred to as 'list-UNcomprehensions'..yuk yuk :)
Comment: @monojohnny: they come directly from the set theory http://en.wikipedia.org/wiki/List_comprehension#Overview
Comment: Yeah, understood - was just trying a bit of self-deprecating humour :-)

Actually (I commented above on this also) - 'piss poor performance' might be a bit strong : I believe (somebody correct me if I'm wrong), that the accepted answer is 2*n as opposed to the optimum 1*n - not such a big deal: especially since I read that list-comps are faster in general than python loops.
Answer: You can use groupby from the itertools module:

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.

>>> a = [1,1,1,2]
>>> [(len(list(v)), key) for (key, v) in itertools.groupby(sorted(a))]
[(3, 1), (1, 2)]

I would assume its runtime is worse than the dict-based solutions by SilentGhost or S.Lott since it has to sort the input sequence, but you should time that yourself. It is a list comprehension, though. It should be faster than Adam Bernier's solution, since it doesn't have to do repeated linear scans of the input sequence. If needed, the sorted call can be avoided by sorting the input sequence in-line.
Comment: +1 for the effort, and I agree that either S.Lott or SilentGhost's solutions are superior.
Comment: good point :-)  To clarify, I agree based on the fact that those are built-in solutions; already tested and debugged for us.
Comment: @Adam: Sure, for 3.1, Counter is the way to go.
Answer: The following works in Python 2.4 and should therefore work in Python 2.6:
lst = [1,1,2,2,3,4,5,6,5]
lst_tmp = []
lst_dups = []

for item in lst:
    if item in lst_tmp:
        lst_dups.append(item)
    else:
        lst_tmp.append(item)

if len(lst_dups):
    lst_dups = sorted(set(lst_dups))
    for item in lst_dups:
        print str(lst.count(item)), "instances of", item
else:
    print "list is unique"


PWA - Programmatically check if installed in JavaScript

Question: Individuals will quickly want to mark this question as a duplicate, but, please read this question first.
I have a PWA. A user can successfully install this app from my website. However, they may visit the website again from their browser. If they do this, Chrome shows a "choose app" icon in place of the "install" icon in the address bar. My question is, can I programmatically detect if the app has been installed?
The common recommendation is to use window.matchMedia('(display-mode: standalone)').matches. However, in the scenario above, the display-mode will be "tab" (i.e. not 'standalone'). I would like to detect if the app is installed in my page and "open" the app just like Chrome does. Is this possible?
Comment: @Dai If the app is installed, the `display-mode` is `tab` *if* the user visits the source site in their browser. In this case, I want to provide an "open app" button in my site so they use the PWA instead of the website.
Comment: Does this answer your question? [check if user has already installed PWA to homescreen on Chrome?](https://stackoverflow.com/questions/51735869/check-if-user-has-already-installed-pwa-to-homescreen-on-chrome)
Comment: Why are you seeing `display-mode: tab` if it's installed?
Comment: @Dai - No. This points out the solution I mentioned above, which does not meet the case.
Comment: Have you looked at the `beforeinstallprompt` event? https://web.dev/customize-install/#listen_for_beforeinstallprompt
Comment: I think the Chrome UI is also causing some confusion here. You can "install" a PWA, then go to chrome://apps and right click it to not "Open as window". It then exists in a strange state where the app shows as installed but behaves more like a webpage. And the answer shown in @Dai's link no longer applies.
Answer: I have an Add to Homescreen library that tries to abstract away all the different browser/platform differences.
It now has a hook/callback in the library that will execute your code if the application can be installed. So, it should not fire that callback if the application is installed.
It also persist an add to homescreen state in localStorage because there is not a real way to really know if the app has been installed or not. The values persisted let A2HS know if the app has been installed from the library. In Edge and Chrome it will know because the beforeInstallPrompt event will not trigger.
https://love2dev.com/pwa/add-to-homescreen-library/
GitHub Repo - https://github.com/docluv/add-to-homescreen


General solution to ODE $ y''-Ay^5=0 $

Question: What is the solution of $$ y''-Ay^5=0  $$
I got the solution $ y = {(3/4A)}^{1/4} x^{-1/2}$ using trial and error but how to solve this type of problem in general?
Comment: $A$ is a matrix?
Comment: You can use the same way as I showed for other similiar question.http://math.stackexchange.com/questions/166981/closed-form-solutions-of-ddot-xt-xtn-0/167025#167025
Comment: It's a nonlinear equation and so asking for a 'general' solution is going to be tricky/not possible. Without a superposition principle, writing down an expression with the some number of unknowns that can describe every possible behavior of the solutions is mostly doomed before it even starts. In what context are you interested in solutions to this ODE? It is likely possible to find good approximate descriptions depending on what you need it for.
Comment: This is a solution if you forget possible integration constants, I suppose.
Comment: A is a scalar constant.
Answer: Let us try to replace the trial and error approach and assume that $y=ax^k$; so, replacing, we get $$a (k-1) k x^{k-2}-a^5 A x^{5 k}=0$$ So, you could set $k-2=5k$ (that is to say $k=-\frac 12$ and $a(k-1)k=a^5 A$ which leads to five different solutions for $a$, two of them being imaginary, and one of them being $0$. Among the real, one solution is your.
But, as said in comments, this is just a very particular solution.
The problem is very complex as showed in the link provided by Mathlover.
Answer: Set it to $$\frac{d^2y}{dx^2} = Ay^5$$
If we multiply this ODE by $2 \frac{dy}{dx}$ we get
$2 \frac{dy}{dx} \frac{d^2y}{dx^2} = 2A y^5 \frac{dy}{dx}$
Thus $\left( \frac{dy}{dx} \right)^2 = \frac{Ay^6}{6} + K$.
Now, in the simple case (where we say have initial conditions such as) when $y = 1$, $\frac{dy}{dx} = \frac{1}{\sqrt{3}}$ so $K = 0$.
i.e. $\displaystyle \left( \frac{dy}{dx} \right)^2 = \frac{y^6}{3} $
so  $ \left( \frac{dy}{dx} \right) = \frac{y^3}{\sqrt{3}} $
Separating, $\frac{dy}{y^3} = \frac{dx}{\sqrt{3}}$ so
$ - \frac{1}{2} y^{-2} = \frac{x}{\sqrt{3}} + A$.
As $y = 1$ when $x = 0$, $A = -\frac{1}{2}$ so
$ - \frac{1}{2} y^{-2} = \frac{x}{\sqrt{3}} -\frac{1}{2}$
i.e.  $ = \left( 1 - \frac{2x}{\sqrt{3}} \right)^{-1/2}$.
That would be a specific solution (which I've seen before which is why I mention it here, however life isn't that simple and you don't mention any inital conditions so it would amount to solving (which is trickier but not impossible)
\begin{equation}
\frac{dy}{dx} = \sqrt{\frac{Ay^{6}}{6} + K}
\end{equation}
Answer: In this equation, $x$ is missing and its solution is routine (check any DE textbooks). Let $u=y'$ and then $u'=y''$. Treating $u$ as a function of $y$ and then noting
$$ u'=\frac{du}{dx}=\frac{du}{dy}\frac{dy}{dx}=\frac{du}{dy}y'=\frac{du}{dy}u $$
we have
$$ \frac{du}{dy}u=Ay^5 $$
which is a separable DE whose solution is standard. I think you can handle it.

General solution to ODE $ y''-Ay^5=0 $


weights in multiplication

Question: I understand I have an equation of two fractions $0 < A, B < 1$.
$$R = \dfrac{A+B}2,$$ where $0 < R, A, B <1$. I understand how to bias towards A or B by inserting weights k1,k2 to the equation, like
$$R = \dfrac{k_1A + k_2B}2,$$ where $k_1+k_2=1$.
how do I bias towards a variable in a multiplication scenario, i.e., $R = AB$ ? I sense it should be something like $R = (A+k_1)(B+k_2)$ but I cannot find the boundary conditions and relationship for $k_1,k_2$. Would appreciate your help!
By the way my range for A, B is 1/7 -> 1, with a step of 1/7th.
So A*B should be 1/49 (or as close as possible)
Thanks,
Andreas
Comment: Not too sure what you are asking. Do you have any context for this?

I guess you can try
$$R=A^{k_1}B^{k_2}$$
with $k_1+k_2=1$.
Comment: Hi, its 0< R, A, B <1 , so this solution cannot be applied. Would I be looking at something like R = A^{1-k1}B^{1-k2} ?
Comment: The weighted arithmetic mean is simply $R = k_1A + k_2B,$ without dividing by $2.$ The equation $R = \frac{A+B}2$ then is what you get when $k_1=k_2=\frac12.$
Answer: Because you started your question by asking about a sum which is really an arithmetic mean, people who responded have tended to interpret your "multiplication" question as a question about the geometric mean,
because the geometric mean has the same relationship to multiplication that the arithmetic mean has to addition.
For a weighted geometric mean, you would choose $k_1$ and $k_2$ such that
$k_1+k_2=1,$ $0 \leq k_1 \leq 1,$ and $0 \leq k_2 \leq 1,$ and then the weighted geometric mean is
$$ R=A^{k_1}B^{k_2}.$$
Note that I wrote more conditions on $k_1$ and $k_2$ than you really need; in effect, I wrote four inequalities (two for $k_1,$ two for $k_2$) where only two are actually needed. For example, $0 \leq k_1$ and $0 \leq k_2$ would have been enough.
Alternatively, with the same conditions on $k_1$ and $k_2$ you could write
$$ R=A^{1 - k_1}B^{1 - k_2},$$
and this also would give a weighted geometric mean of the same kind, because the conditions imply that
$(1-k_1)+(1-k_2)=1,$ $0 \leq (1-k_1) \leq 1,$ and $0 \leq (1-k_2) \leq 1.$
The fact that $0 < R, A, B \leq 1$ is not a problem. These formulas work for any positive numbers.
Also observe that when $k_1 = k_2 = \frac12,$ you get the ordinary geometric mean,
$$ R = A^{1/2}B^{1/2} = \sqrt{AB}.$$
If you actually want a weighted product, so that equal weighting would give you
$R = AB,$ then you can simply double the exponents in the geometric mean.
For example, you can set
$$ R=A^{2k_1}B^{2k_2},$$
which gives you $R = AB$ when $k_1 = k_2 = \frac12.$
If you would prefer not to write the $2$ in each exponent, you can change the conditions so that $k_1+k_2=2,$ $0 \leq k_1 \leq 2,$ and $0 \leq k_2 \leq 2,$
and write
$$ R=A^{k_1}B^{k_2},$$
which gives you $R = AB$ when $k_1 = k_2 = 1$ and otherwise gives you a product weighted toward whichever factor has the greater exponent.
Answer: From your first example, it looks like you want a formula for $R = f(k,A,B)$ where $\lim_{k \to 1} R = A$, and $\lim_{k \to 0} R = B$. The following is one possibility: $R = A^k B^{1-k}$, but I am not sure if this will behave as you want for any $0<k<1$.
Since R is the mean of A,B in your first example, perhaps you are looking for a weighted geometric mean?
$R = e^{k \ln(A)+(1-k)\ln(B)}$
Comment: Hi, so you propose instead of using two weights just use one, and find the neutral solution (bias-wise) at k=0.5? So k=0.6 biases towards B and k=0.4 biases towards A?
Comment: Yup. Sticking with $k_2=1-k_1$ I just wrote $k$ and $1-k$ instead of $k_1$ and $k_2$, same thing.
Comment: Note for k=0.5, this doesn't give you back AB. So you'd have to do some tweaking.
Comment: Thanks a lot for your reply! The weighted mean does not give me AB rather than the mean of the two values for k=0.5, right? What do you mean by tweaking? On the weighted geometric mean or for the R=A^k*B^k ? I would need an equation that is close to that product when k=0.5, but I am not sure of how to approach this.
Comment: By the way my range for A, B is 1/7 -> 1, with a step of 1/7th.
So A*B should be 1/49 (or as close as possible)
Comment: By "tweaking" I meant setting it so that $R=AB$ for $k=0.5$, which turns out to be multiplying the exponents by 2: $R=A^{2k}B^{2(1-k)}$, as in @David K 's answer

weights in multiplication