问:
Android TextInputLayout Styling programmatically
I'm working on an app that has full UI customization. If you look at  a EditText wrapped in an TextInputLayout, the EditText's default text hint color and line color are the same as the color textPrimaryColor defined in styles. When the EditText receives focus however, the line becomes the color of the accent defined in styles, the hint goes through the floating hint animation and changes to the accent color. It's pretty easy to do with styles.xml and themes.xml, however, I can't quite get it programmatically.

The current method I have set up is this:

```<code>public static void setInputTextLayoutColor(final int accent, final int text, TextInputLayout textInputLayout, AppCompatEditText edit) {
    edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            AppCompatEditText editText = (AppCompatEditText) v;
            editText.getBackground().clearColorFilter();
            if(hasFocus) editText.getBackground().setColorFilter(accent, PorterDuff.Mode.SRC_IN);
            else editText.getBackground().setColorFilter(text, PorterDuff.Mode.SRC_IN);
        }
    });

    setCursorColor(edit, accent);

    try {
        Field field = textInputLayout.getClass().getDeclaredField("mFocusedTextColor");
        field.setAccessible(true);
        int[][] states = new int[][]{
                new int[]{}
        };
        int[] colors = new int[]{
                accent
        };
        ColorStateList myList = new ColorStateList(states, colors);
        field.set(textInputLayout, myList);

        Field fDefaultTextColor = TextInputLayout.class.getDeclaredField("mDefaultTextColor");
        fDefaultTextColor.setAccessible(true);
        fDefaultTextColor.set(textInputLayout, myList);

        Method method = textInputLayout.getClass().getDeclaredMethod("updateLabelState", boolean.class);
        method.setAccessible(true);
        method.invoke(textInputLayout, true);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

The problem with this method is that A) the hint text is colored immediately to the accent color, it doesn't color to the accent when focus is received B) The EditText line starts off with the right color, but when it receives focus, it colorizes to accent defined in styles, not the programatically set color.

This is the non-focused picture (in reference to the "Event name" field). Here, the color of "event name" should be gray / white (like the text"):
<img src="https://i.stack.imgur.com/sy2AK.png" alt="Non-focused TextInputLayout">

This is the focused picture, here, everything is right except the color of the line, which should be green as well. <img src="https://i.stack.imgur.com/ndwXy.png" alt="Focused TextInputLayout">

答:
Wasn't able to figure out dynamically changing the hint color, but I got the line color to change with a listener:</p>

```<code>    AppCompatEditText edit = (AppCompatEditText)findViewById(R.id.event_create_name_edit);
    edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            AppCompatEditText edit2 = (AppCompatEditText)v;
            if(hasFocus) edit2.setSupportBackgroundTintList(ColorStateList.valueOf(rui.getAccent()));
            else edit2.setSupportBackgroundTintList(ColorStateList.valueOf(rui.getText()));
        }
    });
</code>```

Body:
I'm working on an app that has full UI customization. If you look at  a EditText wrapped in an TextInputLayout, the EditText's default text hint color and line color are the same as the color textPrimaryColor defined in styles. When the EditText receives focus however, the line becomes the color of the accent defined in styles, the hint goes through the floating hint animation and changes to the accent color. It's pretty easy to do with styles.xml and themes.xml, however, I can't quite get it programmatically.

The current method I have set up is this:

public static void setInputTextLayoutColor(final int accent, final int text, TextInputLayout textInputLayout, AppCompatEditText edit) {
    edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            AppCompatEditText editText = (AppCompatEditText) v;
            editText.getBackground().clearColorFilter();
            if(hasFocus) editText.getBackground().setColorFilter(accent, PorterDuff.Mode.SRC_IN);
            else editText.getBackground().setColorFilter(text, PorterDuff.Mode.SRC_IN);
        }
    });

    setCursorColor(edit, accent);

    try {
        Field field = textInputLayout.getClass().getDeclaredField("mFocusedTextColor");
        field.setAccessible(true);
        int[][] states = new int[][]{
                new int[]{}
        };
        int[] colors = new int[]{
                accent
        };
        ColorStateList myList = new ColorStateList(states, colors);
        field.set(textInputLayout, myList);

        Field fDefaultTextColor = TextInputLayout.class.getDeclaredField("mDefaultTextColor");
        fDefaultTextColor.setAccessible(true);
        fDefaultTextColor.set(textInputLayout, myList);

        Method method = textInputLayout.getClass().getDeclaredMethod("updateLabelState", boolean.class);
        method.setAccessible(true);
        method.invoke(textInputLayout, true);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

The problem with this method is that A) the hint text is colored immediately to the accent color, it doesn't color to the accent when focus is received B) The EditText line starts off with the right color, but when it receives focus, it colorizes to accent defined in styles, not the programatically set color.

This is the non-focused picture (in reference to the "Event name" field). Here, the color of "event name" should be gray / white (like the text"):
<img src="https://i.stack.imgur.com/sy2AK.png" alt="Non-focused TextInputLayout">

This is the focused picture, here, everything is right except the color of the line, which should be green as well. <img src="https://i.stack.imgur.com/ndwXy.png" alt="Focused TextInputLayout">

Body:
Wasn't able to figure out dynamically changing the hint color, but I got the line color to change with a listener:

    AppCompatEditText edit = (AppCompatEditText)findViewById(R.id.event_create_name_edit);
    edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            AppCompatEditText edit2 = (AppCompatEditText)v;
            if(hasFocus) edit2.setSupportBackgroundTintList(ColorStateList.valueOf(rui.getAccent()));
            else edit2.setSupportBackgroundTintList(ColorStateList.valueOf(rui.getText()));
        }
    });


来源: stackexchange

问:
How to upgrade Git to latest version on macOS?
I just bought a new Mac with OS X Lion and I checked in the Terminal what version of git is installed by default. I got the answer

```<code>git --version
> git version 1.7.5.4
</code>```

I would like to upgrade git to the latest version 1.7.8.3, so I downloaded the dmg installer "git-1.7.8.3-intel-universal-snow-leopard.dmg" and I launched it.

After the install, the Terminal still says that the version is 1.7.5.4. What am I doing wrong?

答:
In order to keep both versions, I just changed the value of PATH environment variable by putting the new version's git path "/usr/local/git/bin/" at the beginning, it forces to use the newest version:

$ echo $PATH

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/

$ git --version

git version 2.4.9 (Apple Git-60)

original value: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/

new value: /usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

$ export PATH=/usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

$ git --version

git version 2.13.0

ContentLicense: CC BY-SA 4.0

Body:
I just bought a new Mac with OS X Lion and I checked in the Terminal what version of git is installed by default. I got the answer

git --version
> git version 1.7.5.4

I would like to upgrade git to the latest version 1.7.8.3, so I downloaded the dmg installer "git-1.7.8.3-intel-universal-snow-leopard.dmg" and I launched it.

After the install, the Terminal still says that the version is 1.7.5.4. What am I doing wrong?


问:
PHP: How to activate class "active" in pagination, If $_GET['page']==$pagenumber
This is my pagination code:

```<code><?php
   while($pagenumber != $totalpages)
     {
        echo"<a href='?page=" . ++$pagenumber. "' >" . $pagenumber. "</a>     ";
     }
 ?>
</code>```

The above code will look like this in normal html:

```<code><a href="?page=1">1</a>
<a href="?page=2">2</a>
</code>```

I want to add class="active" with this condition

```<code>If ($_GET['page'] == " . $pagenumber . ")
echo "class="active" ";
</code>```

I do not know, how to insert if statement inside echo command.

`

答:
Here you are:</p>

```<code><?php
while ($pagenumber != $totalpages) {
    ++$pagenumber;
    $class = ($_GET['page'] == $pagenumber) ? 'active' : '';
    echo "<a href='?page={$pagenumber}' class='{$class}'>{$pagenumber}</a>";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my pagination code:

<?php
   while($pagenumber != $totalpages)
     {
        echo"" . $pagenumber. "     ";
     }
 ?>

The above code will look like this in normal html:

1
2

I want to add class="active" with this condition

If ($_GET['page'] == " . $pagenumber . ")
echo "class="active" ";

I do not know, how to insert if statement inside echo command.

`

Body:
Here you are:

<?php
while ($pagenumber != $totalpages) {
    ++$pagenumber;
    $class = ($_GET['page'] == $pagenumber) ? 'active' : '';
    echo "<a href='?page={$pagenumber}' class='{$class}'>{$pagenumber}</a>";
}


问:
IP Don't fragment bit on Mac OS
I am writing a file transferring program over TCP.

I want to set the don't fragment flag on IP

On a socket this is what I want to do:

```<code>int val = 1;
setsockopt(sd, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val));
</code>```

However IP_DONTFRAG does not seem available on Mac OS.  Am I missing something? or did I forget to include it correctly?

Thanks in advance if anyone knows

--Sam

答:
The DF bit is typically used for path MTU (PMTU) discovery automatically by the operating system with TCP connections. If anything, you may have a socket option for disabling PMTU discovery which will have the effect of never setting DF (it's the IP_MTU_DISCOVER socket option on linux). If you leave PMTU discovery on, it will have the effect of always setting DF.

It wouldn't make sense to set/unset it on a packet-by-packet basis because you're using TCP and TCP operates on segments, not packets. If you want to set packet-level stuff, you need to use a lower-layer protocol.

ContentLicense: CC BY-SA 2.5

Title: IP Don't fragment bit on Mac OS

Body:
I am writing a file transferring program over TCP.

I want to set the don't fragment flag on IP

On a socket this is what I want to do:

int val = 1;
setsockopt(sd, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val));

However IP_DONTFRAG does not seem available on Mac OS.  Am I missing something? or did I forget to include it correctly?

Thanks in advance if anyone knows

--Sam


问:
NameError: name 'PlayerIG' is not defined
I have a problem here.

```<code>class Player:

    def __init__(self,name):
        self.armed = 0
        self.arms = 1
        self.bombs = 0
        self.exposed = 0
        self.foodDrink = 20
        self.gold = 350
        self.happy = 50
        self.heat = 0
        self.heatTier = 0
        self.month = 1
        self.name = name
        self.nameWait = 0
        self.path = 'None'
        self.poster = 5
        self.propa = 0
        self.raidPts = 0
        self.status = 'Citizen'
        self.successRiot = 0
        self.support = 0
        self.raidPts = 0
        self.triedVote = 0
# stuff, mainly for fixing variables down from here...
</code>```

Another, related block of code.

```<code>def nameType():
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()

        if confirmName == 'yes':
            PlayerIG = Player(CharName)
            print('► Crew Member: Thanks for travelling with us, and have a great time,',PlayerIG.name,'.')
            MainMenu()

        if confirmName == 'no':
            nameType()
        else:
            print('► Invalid Input!')
            nameType()
else:
    print('► Empty! Please type again.')
    nameType()
</code>```

And one last related one (there may be more).

```<code>def MainMenu():
    blankSmall()
    print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth',PlayerIG.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
    blankSmall()
    print('► You can buy items at the store by typing "store",\nadd propaganda by typing "propa",\nmanage the party by typing "manage", or if you have at least 1 bomb and 5 armed supporters,\nyou can conduct a raid by typing "raid".\nWhen you are done for the month, type "end".\nIf you are at rank President, you can participate in an election with "vote".\nIf you are Chief of Revolution, you can conduct a riot with "riot".\nTo save the game and leave, type "save".')
Option = input()
# Again, more stuff down here that may be included...
</code>```

The problem is, when I load the main menu with MainMenu(), it raises this error:

```<code>Traceback (most recent call last):
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 791, in <module>
    TitleScreen()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 144, in TitleScreen
    nameType()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 168, in nameType
    MainMenu()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 181, in MainMenu

 print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth',PlayerIG.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
NameError: name 'PlayerIG' is not defined
</code>```

Is there any solution to this?

EDIT: The MainMenu() function was supposed to be indented, but the formatting was a bit stubborn.

答:
Your issue is in the main menu method. You have never defined the PlayerIG variable inside the function.
See http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

Btw, please respect the naming convention for variables.
It should be player_ig

Use global variable is bad idea most of the time.
The nameType method should return player_ig, then once you call your method you affect the nameType method to a new variable like bellow.

```<code>def MainMenu():
    blankSmall()
    player_ig_in_main_menu_scope = nameType() # you can call it player_ig if you want
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth', player_ig_in_main_menu_scope.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
    blankSmall()
</code>```

Body:
I have a problem here.

class Player:

    def __init__(self,name):
        self.armed = 0
        self.arms = 1
        self.bombs = 0
        self.exposed = 0
        self.foodDrink = 20
        self.gold = 350
        self.happy = 50
        self.heat = 0
        self.heatTier = 0
        self.month = 1
        self.name = name
        self.nameWait = 0
        self.path = 'None'
        self.poster = 5
        self.propa = 0
        self.raidPts = 0
        self.status = 'Citizen'
        self.successRiot = 0
        self.support = 0
        self.raidPts = 0
        self.triedVote = 0
# stuff, mainly for fixing variables down from here...

Another, related block of code.

def nameType():
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()

        if confirmName == 'yes':
            PlayerIG = Player(CharName)
            print('► Crew Member: Thanks for travelling with us, and have a great time,',PlayerIG.name,'.')
            MainMenu()

        if confirmName == 'no':
            nameType()
        else:
            print('► Invalid Input!')
            nameType()
else:
    print('► Empty! Please type again.')
    nameType()

And one last related one (there may be more).

def MainMenu():
    blankSmall()
    print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth',PlayerIG.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
    blankSmall()
    print('► You can buy items at the store by typing "store",\nadd propaganda by typing "propa",\nmanage the party by typing "manage", or if you have at least 1 bomb and 5 armed supporters,\nyou can conduct a raid by typing "raid".\nWhen you are done for the month, type "end".\nIf you are at rank President, you can participate in an election with "vote".\nIf you are Chief of Revolution, you can conduct a riot with "riot".\nTo save the game and leave, type "save".')
Option = input()
# Again, more stuff down here that may be included...

The problem is, when I load the main menu with MainMenu(), it raises this error:

Traceback (most recent call last):
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 791, in <module>
    TitleScreen()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 144, in TitleScreen
    nameType()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 168, in nameType
    MainMenu()
  File "C:\Users\ONIE\AppData\Local\Programs\Python\Python36-
32\TheGameOfHierarchyAndAnarchy.py", line 181, in MainMenu

 print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth',PlayerIG.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
NameError: name 'PlayerIG' is not defined

Is there any solution to this?

EDIT: The MainMenu() function was supposed to be indented, but the formatting was a bit stubborn.

Body:
Your issue is in the main menu method. You have never defined the PlayerIG variable inside the function.
See http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

Btw, please respect the naming convention for variables.
It should be player_ig

Use global variable is bad idea most of the time.
The nameType method should return player_ig, then once you call your method you affect the nameType method to a new variable like bellow.

def MainMenu():
    blankSmall()
    player_ig_in_main_menu_scope = nameType() # you can call it player_ig if you want
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nMonth', player_ig_in_main_menu_scope.month,'\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
    blankSmall()


问:
More efficient algorithm to find OR of two sets
Given a matrix of n rows and m columns of 1's and 0's, it is required to find out the number of pairs of rows that can be selected so that their OR is 11111....m times.

Example:

```<code>1 0 1 0 1
0 1 0 0 1
1 1 1 1 0
</code>```

Answer:

```<code>2 ---> OR of row number [1,3] and [2,3]
</code>```

Given n and m can be an order upto <= 3000, how efficiently can this problem be solved?

PS: I already tried with a naive O(n*n*m) method. I was thinking of a better solution.

答:
Here's an off-the-wall idea that might have even worse asymptotic (or even average) behavior -- but it generalizes in an interesting way, and at least offers a different approach. This problem can be viewed as an exact cover problem. Each of the n rows contains a set of values S from the set {1,2,...,m}, corresponding to the column indices for which the row has the value 1. The task of the problem is to find a collection of rows whose sets form a disjoint partition of {1,2,...m}. When there are only two such rows in an exact cover, these rows are binary opposites of the kind that you are looking for. However, there are more complicated exact covers possible, such as one involving three rows:

```<code>0 1 0 0 1
1 0 0 0 0
0 0 1 1 0
</code>```

The exact cover problem looks for all such exact covers, and is an NP-complete problem. The canonical solution is Algorithm X, created by Donald Knuth.

Body:
Given a matrix of n rows and m columns of 1's and 0's, it is required to find out the number of pairs of rows that can be selected so that their OR is 11111....m times.

Example:

1 0 1 0 1
0 1 0 0 1
1 1 1 1 0

Answer:

2 ---> OR of row number [1,3] and [2,3]

Given n and m can be an order upto <= 3000, how efficiently can this problem be solved?

PS: I already tried with a naive O(n*n*m) method. I was thinking of a better solution.

Body:
Here's an off-the-wall idea that might have even worse asymptotic (or even average) behavior -- but it generalizes in an interesting way, and at least offers a different approach. This problem can be viewed as an exact cover problem. Each of the n rows contains a set of values S from the set {1,2,...,m}, corresponding to the column indices for which the row has the value 1. The task of the problem is to find a collection of rows whose sets form a disjoint partition of {1,2,...m}. When there are only two such rows in an exact cover, these rows are binary opposites of the kind that you are looking for. However, there are more complicated exact covers possible, such as one involving three rows:

0 1 0 0 1
1 0 0 0 0
0 0 1 1 0

The exact cover problem looks for all such exact covers, and is an NP-complete problem. The canonical solution is Algorithm X, created by Donald Knuth.


问:
Segmentation error due to allocation issues?
Hi so im preety new to coding and I have recently hit a brickwall

This program has a segmentation fault  debug and I think it has to do with allocating space for the buffer array or the input file , as those kept popping up as solutions in my search for an answer.
If you know what I did wrong I would appreciate if you told me rather than giving me the solution. Also Im completely lost on how to allocate memory to anything , so it would be great if someone explained how to allocate memory in context to the code.

It is supposed to read a file structured like this

```<code>2
3 4
3 4
</code>```

where 2 = how many files are downloading, 3 = the Kb/s of file( each line represents a file) , and 4 = time remaining until done. The program is supposed to output a file out that has the time needed for all the things to download(mind you when a file finishes the speed goes up to others)

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  FILE *in = fopen("download.in", "r");
  FILE *out = fopen("download.out", "w");
  int i, n, j, a, k, o;
  char buffer[100];

  fgets(buffer, 10, in);
  sscanf(buffer, "%d", &n);
  int tn[n];
  int xn[n];

  i = 0;
  while (i < n) {
    fgets(buffer, 100, in);
    sscanf(buffer, "%d %d", &tn[i], &xn[i]);
    ++i;
  }
  for (i = 0; i < n; ++i){
    for (j = i + 1; j < n; ++j){
      if (tn[i] > tn[j]){
        a =  tn[i];
        tn[i] = tn[j];
        tn[j] = a;

        a =  xn[i];
        xn[i] = xn[j];
        xn[j] = a;
      }
    }

  }
  i = 1;
  float b ;
  k = 0;
  o = 1;
  while(o < n){
    if(xn[o] == xn[o - 1]){
      k = tn[o] + tn[o - 1]
      ;
    }
    else{
      b = (tn[o] * xn[o]) / (tn[o] + tn[o - 1] + k);
      k = 0;
    }
    ++o;
  }

  fprintf( out, "%f", b  );

  fclose(in); fclose(out);

  return 0;
}
</code>```

I know the answer it gives is not accurate but I want to fix the segmentation fault first then deal with that

gdb r then gdb bt returns this

```<code>(gdb) r
Program received signal SIGSEGV, Segmentation fault.
_IO_fgets (buf=0x7fffffffeb30 "", n=10, fp=0x7fffffffeac0) at iofgets.c:50
50      iofgets.c: No such file or directory.
(gdb) bt
#0  _IO_fgets (buf=0x7fffffffeb30 "", n=10, fp=0x7fffffffeac0) at iofgets.c:50
#1  0x0000000000400766 in main () at main.c:11
</code>```

codeblocks says the code is ok and the site I am trying to give this says there is a segmentation fault aswell.

答:
Here is code with segfault fixed. I had to (1) specify absolute path and (2) change the loop to a for loop. </p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    FILE *in = fopen("/home/developer/CLionProjects/untitled4/download.in", "r");
    FILE *out = fopen("/home/developer/CLionProjects/untitled4/download.out", "w");
    int i, n, j, a, k, o;
    char buffer[100];

    fgets(buffer, 10, in);
    sscanf(buffer, "%d", &n);
    int tn[n];
    int xn[n];

    for (i = 0; i < n; i++) {
        if (!fgets(buffer, 100, in)) break;
        if (sscanf(buffer, "%d %d", &tn[i], &xn[i]) < 2) break;
    }

    for (i = 0; i < n; ++i) {
        for (j = i + 1; j < n; ++j) {
            if (tn[i] > tn[j]) {
                a = tn[i];
                tn[i] = tn[j];
                tn[j] = a;

                a = xn[i];
                xn[i] = xn[j];
                xn[j] = a;
            }
        }

    }
    i = 1;
    float b;
    k = 0;
    o = 1;
    while (o < n) {
        if (xn[o] == xn[o - 1]) {
            k = tn[o] + tn[o - 1];
            fprintf(out, "Some number: %d\n", k);
        } else {
            b = (tn[o] * xn[o]) / (tn[o] + tn[o - 1] + k);
            k = 0;
            fprintf(out, "Some number: %d\n", k);
        }
        ++o;
    }

    fclose(in);

    const char *text = "Write this to the file";
    fprintf(out, "Some text: %s\n", text);

    fclose(out);

    int c;

    FILE *file;
    file = fopen("/home/developer/CLionProjects/untitled4/download.out", "r");
    if (file) {
        while ((c = getc(file)) != EOF)
            putchar(c);
        fclose(file);
    }

    return 0;
}
</code>```

Body:
Hi so im preety new to coding and I have recently hit a brickwall

This program has a segmentation fault  debug and I think it has to do with allocating space for the buffer array or the input file , as those kept popping up as solutions in my search for an answer.
If you know what I did wrong I would appreciate if you told me rather than giving me the solution. Also Im completely lost on how to allocate memory to anything , so it would be great if someone explained how to allocate memory in context to the code.

It is supposed to read a file structured like this

2
3 4
3 4

where 2 = how many files are downloading, 3 = the Kb/s of file( each line represents a file) , and 4 = time remaining until done. The program is supposed to output a file out that has the time needed for all the things to download(mind you when a file finishes the speed goes up to others)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  FILE *in = fopen("download.in", "r");
  FILE *out = fopen("download.out", "w");
  int i, n, j, a, k, o;
  char buffer[100];

  fgets(buffer, 10, in);
  sscanf(buffer, "%d", &n);
  int tn[n];
  int xn[n];

  i = 0;
  while (i < n) {
    fgets(buffer, 100, in);
    sscanf(buffer, "%d %d", &tn[i], &xn[i]);
    ++i;
  }
  for (i = 0; i < n; ++i){
    for (j = i + 1; j < n; ++j){
      if (tn[i] > tn[j]){
        a =  tn[i];
        tn[i] = tn[j];
        tn[j] = a;

        a =  xn[i];
        xn[i] = xn[j];
        xn[j] = a;
      }
    }

  }
  i = 1;
  float b ;
  k = 0;
  o = 1;
  while(o < n){
    if(xn[o] == xn[o - 1]){
      k = tn[o] + tn[o - 1]
      ;
    }
    else{
      b = (tn[o] * xn[o]) / (tn[o] + tn[o - 1] + k);
      k = 0;
    }
    ++o;
  }

  fprintf( out, "%f", b  );

  fclose(in); fclose(out);

  return 0;
}

I know the answer it gives is not accurate but I want to fix the segmentation fault first then deal with that

gdb r then gdb bt returns this

(gdb) r
Program received signal SIGSEGV, Segmentation fault.
_IO_fgets (buf=0x7fffffffeb30 "", n=10, fp=0x7fffffffeac0) at iofgets.c:50
50      iofgets.c: No such file or directory.
(gdb) bt
#0  _IO_fgets (buf=0x7fffffffeb30 "", n=10, fp=0x7fffffffeac0) at iofgets.c:50
#1  0x0000000000400766 in main () at main.c:11

codeblocks says the code is ok and the site I am trying to give this says there is a segmentation fault aswell.

Body:
Here is code with segfault fixed. I had to (1) specify absolute path and (2) change the loop to a for loop.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    FILE *in = fopen("/home/developer/CLionProjects/untitled4/download.in", "r");
    FILE *out = fopen("/home/developer/CLionProjects/untitled4/download.out", "w");
    int i, n, j, a, k, o;
    char buffer[100];

    fgets(buffer, 10, in);
    sscanf(buffer, "%d", &n);
    int tn[n];
    int xn[n];

    for (i = 0; i < n; i++) {
        if (!fgets(buffer, 100, in)) break;
        if (sscanf(buffer, "%d %d", &tn[i], &xn[i]) < 2) break;
    }

    for (i = 0; i < n; ++i) {
        for (j = i + 1; j < n; ++j) {
            if (tn[i] > tn[j]) {
                a = tn[i];
                tn[i] = tn[j];
                tn[j] = a;

                a = xn[i];
                xn[i] = xn[j];
                xn[j] = a;
            }
        }

    }
    i = 1;
    float b;
    k = 0;
    o = 1;
    while (o < n) {
        if (xn[o] == xn[o - 1]) {
            k = tn[o] + tn[o - 1];
            fprintf(out, "Some number: %d\n", k);
        } else {
            b = (tn[o] * xn[o]) / (tn[o] + tn[o - 1] + k);
            k = 0;
            fprintf(out, "Some number: %d\n", k);
        }
        ++o;
    }

    fclose(in);

    const char *text = "Write this to the file";
    fprintf(out, "Some text: %s\n", text);

    fclose(out);

    int c;

    FILE *file;
    file = fopen("/home/developer/CLionProjects/untitled4/download.out", "r");
    if (file) {
        while ((c = getc(file)) != EOF)
            putchar(c);
        fclose(file);
    }

    return 0;
}


问:
Why does this code return None when I don't put the else statement, but it doesn't return None when I put the else statement?
Why does this return the country codes?

```<code>from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    return None

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates')
</code>```

Why doesn't this return the country codes?

```<code>from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
        return None

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates')
</code>```

The main difference is how I indented the 'return None.' Even if I put the else statement it doesn't return the codes. Can someone please explain this to me? I'm new in programming.

答: Ok JLH is correct.  In the second set of code: Since the else is in the for loop the first name in the list will trigger the else code (unless you are looking for the first 1 on the list) which will return none.  So unless the first element is the one you are looking for it will always return None.</p>

Body:
Why does this return the country codes?

from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    return None

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates')

Why doesn't this return the country codes?

from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
        return None

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates')

The main difference is how I indented the 'return None.' Even if I put the else statement it doesn't return the codes. Can someone please explain this to me? I'm new in programming.


问:
Is there a binary truth operator in Javascript?
What does this expression mean in Vuejs?

```<code>:class="{ expr1: expr2}"
</code>```

It appears be a truth expression, but is there a binary truth operator in Javascript?

答:
That is the object syntax for class bindings in Vue. If expr2 is a truthy value, then Vue will add the class, expr1 to the element.

:class is the shorthand for v-bind:class.

If that expression was on a div, for example,

```<code><div :class="{expr1: expr2}"></div>
</code>```

Then, if expr2 was truthy, the rendered output would be

```<code><div class="expr1"></div>
</code>```

Edit

Truthy values are often a cause of confusion and errors in javascript. There is however a strict equality operator that you can use to make sure that you have a true value.

```<code>:class="{expr1: true === expr2}"
</code>```

That will allow you to avoid cases where expr2 might be truthy but not true.

Example.

Body:
What does this expression mean in Vuejs?

:class="{ expr1: expr2}"

It appears be a truth expression, but is there a binary truth operator in Javascript?

Body:
That is the object syntax for class bindings in Vue. If expr2 is a truthy value, then Vue will add the class, expr1 to the element.

:class is the shorthand for v-bind:class.

If that expression was on a div, for example,

<div :class="{expr1: expr2}"></div>

Then, if expr2 was truthy, the rendered output would be

<div class="expr1"></div>

Edit

Truthy values are often a cause of confusion and errors in javascript. There is however a strict equality operator that you can use to make sure that you have a true value.

:class="{expr1: true === expr2}"

That will allow you to avoid cases where expr2 might be truthy but not true.

Example.


答:
It's a class binding which means the node will get the class expr1 when expr2 is truthy.

Read: https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax

Title: Is there a binary truth operator in Javascript?


问:
Seek UWP version of Dennis' solution on Download financial data from Yahoo Finance
I have an UWP App in Windows Store which download historical data from Yahoo Finance. I would like to use Dennis' solution in my App. I have hard time to make that solution working for UWP, especially the part of cookie and crumb. Code sample is very much appreciated. </p>

答: I have resolved the problem. Here is what I have learned: In .NET.core, in addition to use Async methods to replace their counterpart, the cookie is retrieved from HttpWebResponse.Headers. Once cookie is resolved, all rest are the same as that provided by Dennis' solution.  </p>


问:
How to include a webpack module to file protocol
I have a Electron webview, with preload script. Desired webview should look like this:

```<code><webview preload="file://./inject.js"></webview>
</code>```

Since I'm building my project using Webpack, inject.js has to be recognized by Webpack, thus included using:
requre('./inject.js')

But, since Electron webviews only accept local files using file:// protocol,

```<code>preload="require('./inject.js')
</code>```

is not an option.

How can I use require('./inject.js') with file:// protocol to include it in a webview preload attribute?

Edit: I forgot to mention I'm using electron-vue boilerplate (https://github.com/SimulatedGREG/electron-vue)

答:
My question was answered by electron-vue maintainer:
https://github.com/SimulatedGREG/electron-vue/issues/239</p>

Body:
I have a Electron webview, with preload script. Desired webview should look like this:

<webview preload="file://./inject.js"></webview>

Since I'm building my project using Webpack, inject.js has to be recognized by Webpack, thus included using:
requre('./inject.js')

But, since Electron webviews only accept local files using file:// protocol,

preload="require('./inject.js')

is not an option.

How can I use require('./inject.js') with file:// protocol to include it in a webview preload attribute?

Edit: I forgot to mention I'm using electron-vue boilerplate (https://github.com/SimulatedGREG/electron-vue)


问:
Waiting until IAM policy has been applied
I am creating shortlived users on AWS on the fly and while debugging why these newly created logins tended to fail with an InvalidAccessKeyId realised that just adding a small sleep solved the problem.

xref How long should I wait after applying an AWS IAM policy before it is valid? re: time for consistency throughout AWS

My follow up question to the above: is there a way to synchronously create a consistent IAM policy? Or at least a way to know they are ready to use?

答:
Amazon IAM is not designed for providing short-lived credentials. You should create IAM Users for long-lived requirements, such as logins for humans and logins for persistent applications.

An IAM User should not be used for application login purposes. For example, if you are creating an Instagram-like application, you should maintain your own database of users or utilize Amazon Cognito for user authentication.

So, how do you then grant users access to AWS resources? For example, if you have an Instagram-like application and you wish to grant application users the ability to upload/download their pictures in Amazon S3 but want to restrict access to a certain bucket and directory?...

The answer is to create temporary credentials using the AWS Security Token Service (STS). Credentials can be created with a given policy for a specific period of time. These credentials work immediately. For example, if an Instragram-like user logs into the app, the backend app could generate temporary credentials that allow the user to access a specific directory within a specific Amazon S3 bucket for a set period of time (eg 15 minutes). These credentials are then passed to the mobile app/web browser for direct access to AWS services.


问:
How to take an input that is equal to 10 and perform a function that says awesome to the screen
I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.</p>

```<code>    <!DOCTYPE html>
    <html>

    <head>
        <title>Fizzbuzz Input Field</title>
        <script src="scripts.js"></script>
    </head>

    <body>
        <form>
            <input type="number" id="userInput"></input>
            <button onclick="fizzBuzz()">Go</button>
        </form>
    </body>

    </html>

    window.onload = function() {
        alert("Page is loaded");
    };

    var fizzBuzz = function() {
    var userInput = document.getElementById("userInput");
        fizzBuzz.onclick = function() {
        if(userInput.value == 10) {
            document.write("awesome");
        };
        };
    }
</code>```

答:
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.

var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
  if (input.value === '10') {
    button.after("awesome");
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="userInput">
<button>Go</button></code>```

Body:
I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.

    <!DOCTYPE html>

        <title>Fizzbuzz Input Field</title>

        <form>
            <input type="number" id="userInput"></input>
            <button onclick="fizzBuzz()">Go</button>
        </form>

    window.onload = function() {
        alert("Page is loaded");
    };

    var fizzBuzz = function() {
    var userInput = document.getElementById("userInput");
        fizzBuzz.onclick = function() {
        if(userInput.value == 10) {
            document.write("awesome");
        };
        };
    }

Body:
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.

var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
  if (input.value === '10') {
    button.after("awesome");
  }
})

<input type="number" id="userInput">
<button>Go</button>


问:
Record selection conditional formula
I'm making a conditional formula in Crystal Reports for the record selection. The value of {IDENTITY_ADDRESS.ADDRESS_TYPE} can be either 1 (Present Street Address) or 3 (Present Mailing Address).

There will always be a Street Address (1) but I would prefer to use the Mailing Address (3) if one exists. How can I accomplish this?

答:
```<code>if {IDENTITY_ADDRESS.ADDRESS_TYPE} = Present Mailing Address
</code>```

then true,
else
 {IDENTITY_ADDRESS.ADDRESS_TYPE} = Present Street Address

Title: Record selection conditional formula

Body:
if {IDENTITY_ADDRESS.ADDRESS_TYPE} = Present Mailing Address

then true,
else
 {IDENTITY_ADDRESS.ADDRESS_TYPE} = Present Street Address


问:
Using AWK to replace some special codes
lets say I have a file called somedata.txt, I am trying to replace:

\"

with

"

i.e. removing the \
I am trying to do this using AWK. Can you please help?

答:
You will need to escape both characters \ and " like shown below

```<code>awk '{gsub("\\\\\"", "\"")}1' somedata.txt
</code>```

Or if you can use sed it becomes simpler

```<code>sed 's/\\"/"/g' somedata.txt
</code>```

sed also allows inplace editing (flag -i) to update original files

```<code>sed -i 's/\\"/"/g' somedata.txt
</code>```

Title: Using AWK to replace some special codes

Body:
You will need to escape both characters \ and " like shown below

awk '{gsub("\\\\\"", "\"")}1' somedata.txt

Or if you can use sed it becomes simpler

sed 's/\\"/"/g' somedata.txt

sed also allows inplace editing (flag -i) to update original files

sed -i 's/\\"/"/g' somedata.txt


问:
Regex href match a number
Well, here I am back at regex and my poor understanding of it. Spent more time learning it and this is what I came up with:

```<code>/<a href=\"travis.php?theTaco=([0-9999999])\">(.*)</a>
</code>```

I basically want the number in this string:

```<code><a href="travis.php?theTaco=510973">510973</a>
</code>```

My regex is almost good? my original was:

```<code>"/<a href=\"travis.php?theTaco(.*)\">(.*)<\/a>/";
</code>```

But sometimes it returned me huge strings. So, I just want to get numbers only.
I searched through other posts but there is such a large amount of unrelated material, please give an example, resource, or a link directing to a very related question.

Thank you.

答: To capture a number, you don't use a range like [0-99999], you capture by digit. Something like [0-9]+ is more like what you want for that section. Also, escaping is important like codaddict said.</p>

Title: Regex href match a number

Body:
Well, here I am back at regex and my poor understanding of it. Spent more time learning it and this is what I came up with:

/(.*)

I basically want the number in this string:

510973

My regex is almost good? my original was:

"/(.*)<\/a>/";

But sometimes it returned me huge strings. So, I just want to get numbers only.
I searched through other posts but there is such a large amount of unrelated material, please give an example, resource, or a link directing to a very related question.

Thank you.


问:
Match all keywords using like in group MySQL
I have a table of keywords (ID,ean,keyword) and another table with product details. I want the search to return EANs where all keywords match at least once, however the closest I have got is the following, but this returns matches that have the first term in them 3 times for example.

To give an example, let's say I have a product called 'Generic headphones - iPhone, iPad, iPod' and I searched 'gen%' 'hea%' 'ip%' it would come back as a match, but it would also match 'Apple headphones - iPhone, iPad, iPod' due to the 3 ip words, which is not desired.

SQL Fiddle
I want EAN 1 to match only, so matches need to be at least 1 for each term.

Any help would be much appreciated.

```
SELECT     Count(keywords.ean) AS cc,
           products.*
FROM       keywords
INNER JOIN products
ON         products.ean = keywords.ean
WHERE      (
                      keyword LIKE 'gen%'
                                 || keyword like 'ip%'
                                 || keyword LIKE 'hea%')
GROUP BY   (keywords.ean)
HAVING     cc>=3
ORDER BY   `products`.`ean` ASC
```

UPDATE: This gets the desired results, but there must be more efficient ways to do this.

```
SELECT products.*
FROM products
INNER JOIN (SELECT ean, count(*) as tc1
                    FROM keywords
                    WHERE ( keyword like 'gen%' )
                    GROUP BY ean
                    HAVING tc1 > 0 ) as t1 ON t1.ean = products.ean
INNER JOIN (SELECT ean, count(*) as tc2
                    FROM keywords
                    WHERE ( keyword like 'ip%' )
                    GROUP BY ean
                    HAVING tc2 > 0 ) as t2 ON t2.ean = products.ean
INNER JOIN (SELECT ean, count(*) as tc3
                    FROM keywords
                    WHERE ( keyword like 'hea%' )
                    GROUP BY ean
                    HAVING tc3 > 0  ) as t3 ON t3.ean = products.ean
ORDER BY products.ean
```

答:
This is how I'd do it in PostgreSQL.  MySQL may have a slightly different syntax.</p>

```<code>SELECT kc.cc AS cc,
       products.*
FROM products
INNER JOIN (  SELECT ean, count(*) AS cc
                    FROM keywords
                    WHERE ( keyword like 'ip%'
                           OR keyword like 'ai%'
                           OR keyword like 'bei%' )
                    GROUP BY ean
                    HAVING count(*) >= 3 ) AS kc
       ON kc.ean = products.ean
ORDER BY Products.ean;
</code>```

Body:
I have a table of keywords (ID,ean,keyword) and another table with product details. I want the search to return EANs where all keywords match at least once, however the closest I have got is the following, but this returns matches that have the first term in them 3 times for example.

To give an example, let's say I have a product called 'Generic headphones - iPhone, iPad, iPod' and I searched 'gen%' 'hea%' 'ip%' it would come back as a match, but it would also match 'Apple headphones - iPhone, iPad, iPod' due to the 3 ip words, which is not desired.

SQL Fiddle
I want EAN 1 to match only, so matches need to be at least 1 for each term.

Any help would be much appreciated.

SELECT     Count(keywords.ean) AS cc,
           products.*
FROM       keywords
INNER JOIN products
ON         products.ean = keywords.ean
WHERE      (
                      keyword LIKE 'gen%'
                                 || keyword like 'ip%'
                                 || keyword LIKE 'hea%')
GROUP BY   (keywords.ean)
HAVING     cc>=3
ORDER BY   `products`.`ean` ASC

UPDATE: This gets the desired results, but there must be more efficient ways to do this.

SELECT products.*
FROM products
INNER JOIN (SELECT ean, count(*) as tc1
                    FROM keywords
                    WHERE ( keyword like 'gen%' )
                    GROUP BY ean
                    HAVING tc1 > 0 ) as t1 ON t1.ean = products.ean
INNER JOIN (SELECT ean, count(*) as tc2
                    FROM keywords
                    WHERE ( keyword like 'ip%' )
                    GROUP BY ean
                    HAVING tc2 > 0 ) as t2 ON t2.ean = products.ean
INNER JOIN (SELECT ean, count(*) as tc3
                    FROM keywords
                    WHERE ( keyword like 'hea%' )
                    GROUP BY ean
                    HAVING tc3 > 0  ) as t3 ON t3.ean = products.ean
ORDER BY products.ean

Body:
This is how I'd do it in PostgreSQL.  MySQL may have a slightly different syntax.

SELECT kc.cc AS cc,
       products.*
FROM products
INNER JOIN (  SELECT ean, count(*) AS cc
                    FROM keywords
                    WHERE ( keyword like 'ip%'
                           OR keyword like 'ai%'
                           OR keyword like 'bei%' )
                    GROUP BY ean
                    HAVING count(*) >= 3 ) AS kc
       ON kc.ean = products.ean
ORDER BY Products.ean;


答:
What you want is something like this:

```<code>var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
    // First we get the numeric value written to the input (or NaN if it's not a number)
    var inputValue = parseInt(document.getElementById('userInput').value, 10);
    // Define the element to which write the text (you usually want a DIV for this)
    var outputElement = document.getElementById('outputDiv');

    if ( ! isNaN(inputValue) ) {
        outputElement.innerHTML = "awesome!";
    }
    else {
        // The value is not a number, so just clean the result
        outputElement.innerHTML = "";
    }
});
</code>```

Of course, for this to work, you should have at least:

```<code><input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
</code>```

Title: How to take an input that is equal to 10 and perform a function that says awesome to the screen

Body:
What you want is something like this:

var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
    // First we get the numeric value written to the input (or NaN if it's not a number)
    var inputValue = parseInt(document.getElementById('userInput').value, 10);
    // Define the element to which write the text (you usually want a DIV for this)
    var outputElement = document.getElementById('outputDiv');

    if ( ! isNaN(inputValue) ) {
        outputElement.innerHTML = "awesome!";
    }
    else {
        // The value is not a number, so just clean the result
        outputElement.innerHTML = "";
    }
});

Of course, for this to work, you should have at least:

<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>


问:
OpenGL ES 2.0 GL_DEPTH_COMPONENT and glTexImage2D
The Chapter 12 of OpenGL ES 2.0 programming guide book has an example, which called Example 12-2 Render to Depth Texture.
This example calls glTexImage2D API, and the internalformat parameter is GL_DEPTH_COMPONENT.

But using GL_DEPTH_COMPONENT is not allowed according to https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glTexImage2D.xml.

So I have 2 questions about OpenGL ES 2.0.

If the example is not proper, how to render to depth texture? If the example is proper, why not match the description of www.khronos.org?

Which API will use GL_DEPTH_COMPONENT enumeration?

答:
Which API will use GL_DEPTH_COMPONENT enumeration?

glRenderbufferStorage uses GL_DEPTH_COMPONENT, specifically GL_DEPTH_COMPONENT16

```<code>    glGenRenderbuffers(1, (GLuint*)&_nRenderTargetRboDepthId);
    glBindRenderbuffer(GL_RENDERBUFFER, _nRenderTargetRboDepthId);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, nTexWidth, nTexHeight);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _nRenderTargetRboDepthId);

    GLenum err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(err != GL_FRAMEBUFFER_COMPLETE) { // error!
         // format harddrive
    }
</code>```

Body:
Which API will use GL_DEPTH_COMPONENT enumeration?

glRenderbufferStorage uses GL_DEPTH_COMPONENT, specifically GL_DEPTH_COMPONENT16

    glGenRenderbuffers(1, (GLuint*)&_nRenderTargetRboDepthId);
    glBindRenderbuffer(GL_RENDERBUFFER, _nRenderTargetRboDepthId);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, nTexWidth, nTexHeight);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _nRenderTargetRboDepthId);

    GLenum err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(err != GL_FRAMEBUFFER_COMPLETE) { // error!
         // format harddrive
    }


问:
How do you get number_format() to add two decimal points on integers less than 10?
The price is in cents, but whenever the price is less than $10 its not adding .00!

```<code>              $price = (float)($cents/100);
              $price = number_format($price,2);
</code>```

I want to be able to represent 0.00 and 0.01 and 1.01 not sure how to do this if number_format() doesnt work!

Body:
The price is in cents, but whenever the price is less than $10 its not adding .00!

              $price = (float)($cents/100);
              $price = number_format($price,2);

I want to be able to represent 0.00 and 0.01 and 1.01 not sure how to do this if number_format() doesnt work!

Body:
Take a look at money_format.

<?php

$prices = array(100, 10, 1, 0.10, 0.01);
foreach ($prices as $price) {
    echo money_format('%.2n', $price) . "\n";
}

// 100.00
// 10.00
// 1.00
// 0.10
// 0.01
?>


问:
The output of this is 3 can anybody tell me how?
```<code>int main()
{

    long int a = scanf("%ld %ld %ld",&a,&a,&a);
    printf("%ld",a);
    return 0;
}
</code>```

The output of this is 3 can anybody tell me how?

答: Yes, @Pras is correct.  Since you (apparently) successfully read three value from the input, the return value from scanf is three.  But it is very bad programming practice to use the set the value of the same variable more than once in a single statement.  In this example, you set the value of "a" four times, three as a result of scanf'ing from the input, and the fourth as the assignment of the return value.  If you had not assigned a to be the return value from the call, the value of "a" would be unpredictable, since the order that arguments are processed is implementation dependent.  If you typed in "11 22 33", "a" could be 11 or 33... or even 22, depending on how your compiler handles scanf.

Body:
int main()
{

    long int a = scanf("%ld %ld %ld",&a,&a,&a);
    printf("%ld",a);
    return 0;
}

The output of this is 3 can anybody tell me how?


问:
About compiling Firefox
My question is two fold:

Firefox browser

I compiled firefox source-code in releases :
https://archive.mozilla.org/pub/firefox/releases/52.0/source/

but after I finish compiling, I met Nightly, not Firefox browser.

I would execute Firefox.

Might be there is any option to build Firefox?
( I searched the build configuration, but cannot find the option about browser)

If anyone have an experience about compiling Firefox from its source code, please help :)

Rust dependency
When I compiled Firefox, I encountered error below:

0:06.97    Compiling mp4parse_capi v0.6.0 (file:///home/signal/Desktop/firefox_source/firefox-53.0/media/libstagefright/binding/mp4parse_capi)
0:06.97      Running /home/signal/.cargo/bin/rustc --crate-name build_script_build /home/signal/Desktop/firefox_source/firefox-53.0/media/libstagefright/binding/mp4parse_capi/build.rs --color always --crate-type bin --emit=dep-info,link -C opt-level=2 -C codegen-units=1 -C debuginfo=2 -C metadata=2476a8a7a86fe109 -C extra-filename=-2476a8a7a86fe109 --out-dir /home/signal/Desktop/firefox_source/firefox-53.0/obj-x86_64-pc-linux-gnu/toolkit/library/gtest/rust/./release/build/mp4parse_capi-2476a8a7a86fe109 -L dependency=/home/signal/Desktop/firefox_source/firefox-53.0/obj-x86_64-pc-linux-gnu/toolkit/library/gtest/rust/./release/deps
0:07.05 error[E0463]: can't find crate for cheddar
0:07.05  --> /home/signal/Desktop/firefox_source/firefox-53.0/media/libstagefright/binding/mp4parse_capi/build.rs:1:1
0:07.05   |
0:07.05 1 | extern crate cheddar;
0:07.05   | ^^^^^^^^^^^^^^^^^^^^^ can't find crate
0:07.05
0:07.05 error: aborting due to previous error
0:07.05
0:07.06 error: Could not compile mp4parse_capi.
0:07.06
0:07.06 Caused by:
0:07.06   process didn't exit successfully: /home/signal/.cargo/bin/rustc --crate-name build_script_build /home/signal/Desktop/firefox_source/firefox-53.0/media/libstagefright/binding/mp4parse_capi/build.rs --color always --crate-type bin --emit=dep-info,link -C opt-level=2 -C codegen-units=1 -C debuginfo=2 -C metadata=2476a8a7a86fe109 -C extra-filename=-2476a8a7a86fe109 --out-dir /home/signal/Desktop/firefox_source/firefox-53.0/obj-x86_64-pc-linux-gnu/toolkit/library/gtest/rust/./release/build/mp4parse_capi-2476a8a7a86fe109 -L dependency=/home/signal/Desktop/firefox_source/firefox-53.0/obj-x86_64-pc-linux-gnu/toolkit/library/gtest/rust/./release/deps (exit code: 101)
0:07.06 Build failed, waiting for other jobs to finish...
0:08.68 error: build failed
0:08.68 /home/signal/Desktop/firefox_source/firefox-53.0/config/rules.mk:966: recipe for target 'force-cargo-library-build' failed
0:08.68 make[5]: *** [force-cargo-library-build] Error 101
0:08.68 /home/signal/Desktop/firefox_source/firefox-53.0/config/recurse.mk:71: recipe for target 'toolkit/library/gtest/rust/target' failed

That seems I need a rust package to resolve dependecny.
But in the latest version, I could complie firefox without any error.

Could anyone give any advice?

答:
Adding

```<code>build = false
</code>```

to media/libstagefright/binding/mp4parse_capi/Cargo.toml fixed the issue.
More info here: don't try to build mp4parse

Title: About compiling Firefox

Body:
Adding

build = false

to media/libstagefright/binding/mp4parse_capi/Cargo.toml fixed the issue.
More info here: don't try to build mp4parse


问:
expected declaration before '}' token
I know this error message from when there is an extra { or }. But my editor does highlight brackets and shows it matches. The problem is at the last bracket right after #endif.

```<code> #ifndef PROYECTO_H
 #define PROYECTO_H

 #include<stdio.h>
 #include<stdlib.h>
 #include <fstream>
 #include <iostream>
 #include <string>
 #include <cassert>
 #include <cstddef>

using namespace std;
namespace lulz{

template<class T>
struct Contacto {
string Cname;
string Apellidos;
string NumTel;
string email;
T sexo;
Contacto *Proximo;
};

template<class T>
class Lista {
public:
Lista();
~Lista();
bool ContactoVacio();
void InsertContact(Contacto<T> Temp);
void InsertPosition(Contacto<T> Temp, Contacto<T>* Posicion);
void BuscarContact(string Name, string Lastname);
Contacto<T>* BuscarPosicion(int pos);
void Display(ofstream& salida, Lista<T> Cabezalista);
void Deletes();
friend ofstream& operator << (ofstream&salida, const Lista<T>& Cabezalista){
Contacto<T>* ContactList;
int Pos=0;
for(ContactList = Cabezalista.Cabeza; (ContactList != NULL) && (ContactList-
>Proximo != NULL); ContactList = ContactList->Proximo)
 {
cout << ' ' << Pos+1 << ". " << ContactList->Cname << ' ' << ContactList-
>Apellidos << ' ';
cout << ContactList->NumTel << ' ' << ContactList->email << ' ' <<
ContactList->sexo << ' ' << endl;
   Pos++;
}
cout << "Cantidad de nodos" << ' ' << Cabezalista.numNodos << endl;
return salida;
}

private:
Contacto<T>* Cabeza;
int numNodos;
};

template<class T>
ifstream& operator >>(ifstream& entrada, Contacto<T>& Temp);

template<class T>
bool Validacion(Contacto<T> Temp);

void Opening(ifstream& entrada);
void Closing(ifstream& entrada);
void Menu();

#endif // PROYECTO_H
}
</code>```

It was running fine before I added the templates and added the implementation of the overloaded operator <<. Am I missing something?

答: Just move the #endif to after the last }.

Title: expected declaration before '}' token

Body:
I know this error message from when there is an extra { or }. But my editor does highlight brackets and shows it matches. The problem is at the last bracket right after #endif.

 #ifndef PROYECTO_H
 #define PROYECTO_H

 #include<stdio.h>
 #include<stdlib.h>
 #include <fstream>
 #include <iostream>
 #include <string>
 #include <cassert>
 #include <cstddef>

using namespace std;
namespace lulz{

template<class T>
struct Contacto {
string Cname;
string Apellidos;
string NumTel;
string email;
T sexo;
Contacto *Proximo;
};

template<class T>
class Lista {
public:
Lista();
~Lista();
bool ContactoVacio();
void InsertContact(Contacto<T> Temp);
void InsertPosition(Contacto<T> Temp, Contacto<T>* Posicion);
void BuscarContact(string Name, string Lastname);
Contacto<T>* BuscarPosicion(int pos);
void Display(ofstream& salida, Lista<T> Cabezalista);
void Deletes();
friend ofstream& operator << (ofstream&salida, const Lista<T>& Cabezalista){
Contacto<T>* ContactList;
int Pos=0;
for(ContactList = Cabezalista.Cabeza; (ContactList != NULL) && (ContactList-
>Proximo != NULL); ContactList = ContactList->Proximo)
 {
cout << ' ' << Pos+1 << ". " << ContactList->Cname << ' ' << ContactList-
>Apellidos << ' ';
cout << ContactList->NumTel << ' ' << ContactList->email << ' ' <<
ContactList->sexo << ' ' << endl;
   Pos++;
}
cout << "Cantidad de nodos" << ' ' << Cabezalista.numNodos << endl;
return salida;
}

private:
Contacto<T>* Cabeza;
int numNodos;
};

template<class T>
ifstream& operator >>(ifstream& entrada, Contacto<T>& Temp);

template<class T>
bool Validacion(Contacto<T> Temp);

void Opening(ifstream& entrada);
void Closing(ifstream& entrada);
void Menu();

#endif // PROYECTO_H
}

It was running fine before I added the templates and added the implementation of the overloaded operator <<. Am I missing something?


问:
Code indentation on RichTextEditor in C#
I'm working on my own basic syntax highlight editor in C#. I've already completed the automatic coloring of keywords, functions etc etc. I don't need any other fancy stuff like automatic code indentation.

However, I do wish to have a code minify / maxify button. Nothing fancy. I just want it to automaticly set a newline before any opening bracket and one behind it with either tab characters or changing the SelectionIndent Property.

So something like this:

```<code>test { test { test } test }
</code>```

Becomes:

```<code>test
{
    test
    {
        test
    }
}
</code>```

And of course the minify button should do the exact opposite, putting everything on 1 line.

I've already tried working with the Regex.Replace Method. I didn't quite get it to work, but thinking about that approach, it would cause issues if the opening and closing brackets get mixed up. Anyway, this is what I had untill I gave up and decided to ask you guys for some help:

```<code>string tabs = "";

private void btnMax_Click(object sender, EventArgs e)
{
    var count = codeRichTextBox.Text.Count(x => x == '{');
    for(int i=1; i<= count; i++)
    {
        // The idea was to add \t to tabs here on each iteration
    }
    string pattern = "{";
    string replacement = "\n{\n\t";
    Regex rgx = new Regex(pattern);
    string result = rgx.Replace(codeRichTextBox.Text, replacement);

    codeRichTextBox.Text = result;
}
</code>```

Obviously that solution is the wrong approach and isn't going to work. So what should I do instead?

Edit: Although it would be nice, it doesn't have to take into account that part of the string already has code indentation. The maxify button only needs to work on a string that's on a single line.

答:
My idea:  You'll need to parse the text, counting the current nesting level of { and } .

For each { or } found, decide on the proper whitespace-string-before (prefix) and whitespace-string-after (suffix) based on the current nesting level (for example just \n { \n for the first level).

See if the desired prefix is already there.  If not, delete any existing whitespace then add the prefix.  Do the same for the suffix.

Body:
I'm working on my own basic syntax highlight editor in C#. I've already completed the automatic coloring of keywords, functions etc etc. I don't need any other fancy stuff like automatic code indentation.

However, I do wish to have a code minify / maxify button. Nothing fancy. I just want it to automaticly set a newline before any opening bracket and one behind it with either tab characters or changing the SelectionIndent Property.

So something like this:

test { test { test } test }

Becomes:

test
{
    test
    {
        test
    }
}

And of course the minify button should do the exact opposite, putting everything on 1 line.

I've already tried working with the Regex.Replace Method. I didn't quite get it to work, but thinking about that approach, it would cause issues if the opening and closing brackets get mixed up. Anyway, this is what I had untill I gave up and decided to ask you guys for some help:

string tabs = "";

private void btnMax_Click(object sender, EventArgs e)
{
    var count = codeRichTextBox.Text.Count(x => x == '{');
    for(int i=1; i<= count; i++)
    {
        // The idea was to add \t to tabs here on each iteration
    }
    string pattern = "{";
    string replacement = "\n{\n\t";
    Regex rgx = new Regex(pattern);
    string result = rgx.Replace(codeRichTextBox.Text, replacement);

    codeRichTextBox.Text = result;
}

Obviously that solution is the wrong approach and isn't going to work. So what should I do instead?

Edit: Although it would be nice, it doesn't have to take into account that part of the string already has code indentation. The maxify button only needs to work on a string that's on a single line.


问:
Refresh Kendo dropdownlist after event change of another dropdownlist
When I change the value from the first ddl I get the data from Ajax of the other ddl but it doesnt refresh.

This is my grid

```<code>$("#grid").kendoGrid({
        dataSource:
height: 500,
                toolbar: ["create"],
                columns: [
                     { command: ["edit"], title: " ", width: "150px", locked: true },
                    { field: "RowLabels", title: "Row Labels", width: "180px", locked: true },
                    { field: "IdValueStream", title: "VS", width: "90px", locked: true, editor: vsDropDownEditor, template: "#=getVsName(IdValueStream)#" }, //, template: "#=IdValueStream.ValueStream#"
                    { field: "IdLine", title: "Line", width: "180px", locked: true, editor: linesDropDownEditor }, //, template: "#=getLineName(IdLine)#"
                       { field: "W1", title: Weeks[0].W1.substring(0, 10), width: "98px" }, //
                       { field: "W2", title: Weeks[0].W2.substring(0, 10), width: "90px" },
                       { field: "W3", title: Weeks[0].W3.substring(0, 10), width: "90px" },
                       { field: "W4", title: Weeks[0].W4.substring(0, 10), width: "90px" },
                       { field: "W5", title: Weeks[0].W5.substring(0, 10), width: "90px" },
                       { field: "W6", title: Weeks[0].W6.substring(0, 10), width: "90px" },
                       { field: "W7", title: Weeks[0].W7.substring(0, 10), width: "90px" },
                       { field: "W8", title: Weeks[0].W8.substring(0, 10), width: "90px" },
                       { field: "W9", title: Weeks[0].W9.substring(0, 10), width: "90px" },
                       { field: "W10", title: Weeks[0].W10.substring(0, 10), width: "90px" },
                       { field: "W11", title: Weeks[0].W11.substring(0, 10), width: "90px" },
                       { field: "W12", title: Weeks[0].W12.substring(0, 10), width: "90px" },
                       { field: "W13", title: Weeks[0].W13.substring(0, 10), width: "90px" }
                ],
                editable: "inline"
            });
</code>```

This is the method from the editor of the first ddl

```<code>function vsDropDownEditor(container, options) {
    $('<input id="ddlVs" data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDropDownList({
                    dataTextField: "ValueStream",
                    dataValueField: "Id",
                    dataSource: categories,
                    select: onSelect
                });
}
</code>```

And this the other method from editor of the second ddl

```<code>function linesDropDownEditor(container, options) {

    $('<input data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDropDownList({
                    autoBind: false,
                    dataTextField: "Line",
                    dataValueField: "Id",
                    dataSource: lines
                });
}
</code>```

So when I select an item of the first ddl I want to refresh the second ddl

答:
Put an id attribute for your second dropdown then in onSelect function of ddVs you can add this line of code.

$("#nameOfYourSecondDropdownHere").data('kendoDropDownList').dataSource.read();

Body:
When I change the value from the first ddl I get the data from Ajax of the other ddl but it doesnt refresh.

This is my grid

$("#grid").kendoGrid({
        dataSource:
height: 500,
                toolbar: ["create"],
                columns: [
                     { command: ["edit"], title: " ", width: "150px", locked: true },
                    { field: "RowLabels", title: "Row Labels", width: "180px", locked: true },
                    { field: "IdValueStream", title: "VS", width: "90px", locked: true, editor: vsDropDownEditor, template: "#=getVsName(IdValueStream)#" }, //, template: "#=IdValueStream.ValueStream#"
                    { field: "IdLine", title: "Line", width: "180px", locked: true, editor: linesDropDownEditor }, //, template: "#=getLineName(IdLine)#"
                       { field: "W1", title: Weeks[0].W1.substring(0, 10), width: "98px" }, //
                       { field: "W2", title: Weeks[0].W2.substring(0, 10), width: "90px" },
                       { field: "W3", title: Weeks[0].W3.substring(0, 10), width: "90px" },
                       { field: "W4", title: Weeks[0].W4.substring(0, 10), width: "90px" },
                       { field: "W5", title: Weeks[0].W5.substring(0, 10), width: "90px" },
                       { field: "W6", title: Weeks[0].W6.substring(0, 10), width: "90px" },
                       { field: "W7", title: Weeks[0].W7.substring(0, 10), width: "90px" },
                       { field: "W8", title: Weeks[0].W8.substring(0, 10), width: "90px" },
                       { field: "W9", title: Weeks[0].W9.substring(0, 10), width: "90px" },
                       { field: "W10", title: Weeks[0].W10.substring(0, 10), width: "90px" },
                       { field: "W11", title: Weeks[0].W11.substring(0, 10), width: "90px" },
                       { field: "W12", title: Weeks[0].W12.substring(0, 10), width: "90px" },
                       { field: "W13", title: Weeks[0].W13.substring(0, 10), width: "90px" }
                ],
                editable: "inline"
            });

This is the method from the editor of the first ddl

function vsDropDownEditor(container, options) {
    $('<input id="ddlVs" data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDropDownList({
                    dataTextField: "ValueStream",
                    dataValueField: "Id",
                    dataSource: categories,
                    select: onSelect
                });
}

And this the other method from editor of the second ddl

function linesDropDownEditor(container, options) {

    $('<input data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDropDownList({
                    autoBind: false,
                    dataTextField: "Line",
                    dataValueField: "Id",
                    dataSource: lines
                });
}

So when I select an item of the first ddl I want to refresh the second ddl


问:
Redux - Combining multiple reducers result in state clearing
Fairly new to redux, and have gone through the official guides. Now I'm trying to do something solo. I have two reducers and am using react-thunk. When I dispatch an action after the first one it clears my collection of my other reducer. To illustrate what I mean is I have:

Actions.js

```<code>import axios from 'axios';

function fetchAtms() {
  return axios.get('http://localhost:4567');
}

export const recievedAtms = (atms) => {
  return {
    type: 'RECIEVED_ATMS',
    atms
  }
}

export const completed = () => {
  return {
    type: 'COMPLETED',
  }
}

export const loadMore = () => {
  return {
    type: 'LOAD_MORE',
  }
}

export const loadAtms = (forPerson) => {
  return function (dispatch) {
    return fetchAtms().then((response) => {
      let atms = response.data.map((item) => {return item['location']})
      dispatch(recievedAtms(atms));
      // When dispatch(completed()); is called
      // it is clears my app collection.
      dispatch(completed());
      // $r.store.getState() => Object {app: {atms: []}, isLoading: false, router: Object}
    }, (error) => {
        console.log('implement me');
    })
  }
}
</code>```

Reducers

```<code>import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

const app = (state = {}, action) => {
  switch (action.type) {
    case 'RECIEVED_ATMS':
      return {
        atms: action.atms
      }
    default:
      return {};
  }
}

const isLoading = (state = true, action) => {
  switch (action.type) {
    case 'COMPLETED':
      return !state;
    default:
      return state;
  }
}

const appReducer = combineReducers({
  app,
  isLoading,
  router: routerReducer
});

export default appReducer;
</code>```

Store.js

```<code>import { createStore, applyMiddleware } from 'redux';
import { routerMiddleware} from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import thunk from 'redux-thunk';

import appReducer from './reducers/app';

export const history = createHistory()

const middleware = routerMiddleware(history);

const store = createStore(appReducer, applyMiddleware(middleware, thunk));

export default store;
</code>```

If you hone in on Actions.js where in the loadAtms function I:

Fetch my atms

Dispatch receivedAtms

Dispatch Completed

When I dispatch completed() it clear my atms collection. I'm not entirely sure. I would not expect that since the states between the two reducers are separate. My expectation is:

After I've fired completed() I do not expect it to clear my collection of atms. The resulting state after calling completed() should look like this:

```<code>{
  isLoading: false,
  app: {atms: [{id: 1}, {id: 2}, {id: 3}]}
}
</code>```

currently what is happening is this:

```<code>{isLoading: false, app: {}}
</code>```

Any thoughts on what I may have done wrong here.

答:
Your atms reducer is returning {} if the action isn't one it is looking for. Instead, you should be returning state I believe. So:

```<code>const app = (state = {}, action) => {
  switch (action.type) {
    case 'RECIEVED_ATMS':
      return {
        atms: action.atms
      }
    default:
      return state;
  }
}
</code>```

Body:
Fairly new to redux, and have gone through the official guides. Now I'm trying to do something solo. I have two reducers and am using react-thunk. When I dispatch an action after the first one it clears my collection of my other reducer. To illustrate what I mean is I have:

Actions.js

import axios from 'axios';

function fetchAtms() {
  return axios.get('http://localhost:4567');
}

export const recievedAtms = (atms) => {
  return {
    type: 'RECIEVED_ATMS',
    atms
  }
}

export const completed = () => {
  return {
    type: 'COMPLETED',
  }
}

export const loadMore = () => {
  return {
    type: 'LOAD_MORE',
  }
}

export const loadAtms = (forPerson) => {
  return function (dispatch) {
    return fetchAtms().then((response) => {
      let atms = response.data.map((item) => {return item['location']})
      dispatch(recievedAtms(atms));
      // When dispatch(completed()); is called
      // it is clears my app collection.
      dispatch(completed());
      // $r.store.getState() => Object {app: {atms: []}, isLoading: false, router: Object}
    }, (error) => {
        console.log('implement me');
    })
  }
}

Reducers

import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

const app = (state = {}, action) => {
  switch (action.type) {
    case 'RECIEVED_ATMS':
      return {
        atms: action.atms
      }
    default:
      return {};
  }
}

const isLoading = (state = true, action) => {
  switch (action.type) {
    case 'COMPLETED':
      return !state;
    default:
      return state;
  }
}

const appReducer = combineReducers({
  app,
  isLoading,
  router: routerReducer
});

export default appReducer;

Store.js

import { createStore, applyMiddleware } from 'redux';
import { routerMiddleware} from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import thunk from 'redux-thunk';

import appReducer from './reducers/app';

export const history = createHistory()

const middleware = routerMiddleware(history);

const store = createStore(appReducer, applyMiddleware(middleware, thunk));

export default store;

If you hone in on Actions.js where in the loadAtms function I:

Fetch my atms

Dispatch receivedAtms

Dispatch Completed

When I dispatch completed() it clear my atms collection. I'm not entirely sure. I would not expect that since the states between the two reducers are separate. My expectation is:

After I've fired completed() I do not expect it to clear my collection of atms. The resulting state after calling completed() should look like this:

{
  isLoading: false,
  app: {atms: [{id: 1}, {id: 2}, {id: 3}]}
}

currently what is happening is this:

{isLoading: false, app: {}}

Any thoughts on what I may have done wrong here.

Body:
Your atms reducer is returning {} if the action isn't one it is looking for. Instead, you should be returning state I believe. So:

const app = (state = {}, action) => {
  switch (action.type) {
    case 'RECIEVED_ATMS':
      return {
        atms: action.atms
      }
    default:
      return state;
  }
}


问:
Understanding class variables in Java
The following is a simple Linked List from a popular YouTube video.

public class Link {

   public String bookName;
   public int millionsSold;

   public Link next;

   public Link(String bookName, int millionsSold) {
      this.bookName = bookName;
      this.millionsSold = millionsSold;
   }

   @Override
   public String toString() {
       return bookName;
   }

   public static void main(String[] args) {

      LinkList theLinkedList = new LinkList();

      theLinkedList.insertFirstLink("Don Quixote", 500);
      theLinkedList.insertFirstLink("A Tale of Two Cities", 200);
      theLinkedList.insertFirstLink("The Lord of the Rings", 150);
      theLinkedList.insertFirstLink("Harry Potter and the Sorcerer's Stone", 107);

      theLinkedList.removeLink("A Tale of Two Cities");
      System.out.println("\nA Tale of Two Cities Removed\n");
   }
}

class LinkList {
   public Link firstLink;

   LinkList() {
      firstLink = null;
   }

   public void insertFirstLink(String bookName, int millionsSold) {
      Link newLink = new Link(bookName, millionsSold);
      newLink.next = firstLink;
      firstLink = newLink;
   }

   public Link removeLink(String bookName) {

      Link currentLink = firstLink;
      Link previousLink = firstLink;

      while (currentLink.bookName != bookName) {
         if (currentLink.next == null)
            return null;
         else {
            previousLink = currentLink;
            currentLink = currentLink.next;
         }
       }

      if (currentLink == firstLink)
        firstLink = firstLink.next;
      else {
        previousLink.next = currentLink.next;
      }
      return currentLink;
   }
}
```

I am having trouble in understanding the removeLink method of LinkedList class. After executing the statement previousLink.next = currentLink.next in that method, why are the changes also reflected in firstLink variable?

EDIT:

As pointed out in comments and answer, I understand that object variable are reference variables and that more than one variable can refer to the same Object. Consequently changes in values to any one of the referencing variable would affect other variables to the same reference too.

In the above example, after executingpreviousLink.next = currentLink.next line, currentLink is also removed from firstLink, as both previousLink and firstLink point to same Object. Similarly, when currentLink = currentLink.next is executed why doesn't it have any effect on firstLink?

答:
The reason is that variables are nothing else other than named references to places in memory.

Let's assume that firstLink points to some Link object in memory

Then, when you say

```<code>Link currentLink = firstLink;
Link previousLink = firstLink;
</code>```

You are pointing currentLink and previousLink to that same object in memory. Now you have 3 differently named references to the same object.

This means that, after this assignment, unless any of the variables are pointed to another place in memory, changes to any of them will be reflected in the other two.

Title: Understanding class variables in Java

Body:
The following is a simple Linked List from a popular YouTube video.

public class Link {

   public String bookName;
   public int millionsSold;

   public Link next;

   public Link(String bookName, int millionsSold) {
      this.bookName = bookName;
      this.millionsSold = millionsSold;
   }

   @Override
   public String toString() {
       return bookName;
   }

   public static void main(String[] args) {

      LinkList theLinkedList = new LinkList();

      theLinkedList.insertFirstLink("Don Quixote", 500);
      theLinkedList.insertFirstLink("A Tale of Two Cities", 200);
      theLinkedList.insertFirstLink("The Lord of the Rings", 150);
      theLinkedList.insertFirstLink("Harry Potter and the Sorcerer's Stone", 107);

      theLinkedList.removeLink("A Tale of Two Cities");
      System.out.println("\nA Tale of Two Cities Removed\n");
   }
}

class LinkList {
   public Link firstLink;

   LinkList() {
      firstLink = null;
   }

   public void insertFirstLink(String bookName, int millionsSold) {
      Link newLink = new Link(bookName, millionsSold);
      newLink.next = firstLink;
      firstLink = newLink;
   }

   public Link removeLink(String bookName) {

      Link currentLink = firstLink;
      Link previousLink = firstLink;

      while (currentLink.bookName != bookName) {
         if (currentLink.next == null)
            return null;
         else {
            previousLink = currentLink;
            currentLink = currentLink.next;
         }
       }

      if (currentLink == firstLink)
        firstLink = firstLink.next;
      else {
        previousLink.next = currentLink.next;
      }
      return currentLink;
   }
}

I am having trouble in understanding the removeLink method of LinkedList class. After executing the statement previousLink.next = currentLink.next in that method, why are the changes also reflected in firstLink variable?

EDIT:

As pointed out in comments and answer, I understand that object variable are reference variables and that more than one variable can refer to the same Object. Consequently changes in values to any one of the referencing variable would affect other variables to the same reference too.

In the above example, after executingpreviousLink.next = currentLink.next line, currentLink is also removed from firstLink, as both previousLink and firstLink point to same Object. Similarly, when currentLink = currentLink.next is executed why doesn't it have any effect on firstLink?

Body:
The reason is that variables are nothing else other than named references to places in memory.

Let's assume that firstLink points to some Link object in memory

Then, when you say

Link currentLink = firstLink;
Link previousLink = firstLink;

You are pointing currentLink and previousLink to that same object in memory. Now you have 3 differently named references to the same object.

This means that, after this assignment, unless any of the variables are pointed to another place in memory, changes to any of them will be reflected in the other two.


问:
Bootstrap 4: Show element only when nav-tab is active
I'm making nav-tabs that need to have an element shown only on active one. In my case, it's the white arrow pointing down to the content. How can I make it vanish when you click on another tab? Or, how can i move it to that tab so it points to its content instead?

Here's the outline of my code:

.arrow-down {
    position: absolute;
    width: 0;
    height: 0;
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-top: 15px solid white;
  margin-left: 20px;
}
.nav-tabs {
    background-color: black;
}
.tab-content {
  background-color: #ccc
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

<ul class="nav nav-tabs" role="tablist">
  <li class="nav-item">
    Home
    <div class="arrow-down"></div>
  </li>
  <li class="nav-item">
    Profile
  </li>
  <li class="nav-item">
    Messages
  </li>
  <li class="nav-item">
    Settings
  </li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="home" role="tabpanel">...</div>
  <div class="tab-pane" id="profile" role="tabpanel">...</div>
  <div class="tab-pane" id="messages" role="tabpanel">...</div>
  <div class="tab-pane" id="settings" role="tabpanel">...</div>
</div></code>```

答:
Add a class to show the arrow, then add on click event to all menu, remove the previous arrow and add to the current tab.

```<code>.active-arrow {
  display: block;
}
</code>```

To center the arrow, you could use flexbox, and add margin-top to each arrow to position it right.

```<code>.nav-item {
  display: flex;
  align-items: center;
  justify-content: center;
}
</code>```

$('ul a.nav-link').on('click', function(e) {
  $('.arrow-down').removeClass('active-arrow');
  $(this).next('.arrow-down').addClass('active-arrow');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.arrow-down {
  position: absolute;
  width: 0;
  height: 0;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-top: 15px solid white;
  display: none;
  margin-top: 28px;
}

.nav-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.active-arrow {
  display: block;
}

.nav-tabs {
  background-color: black;
}

.tab-content {
  background-color: #ccc
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    Home

    Profile

    Messages

    Settings

1

2

3

4

```

Body:
I'm making nav-tabs that need to have an element shown only on active one. In my case, it's the white arrow pointing down to the content. How can I make it vanish when you click on another tab? Or, how can i move it to that tab so it points to its content instead?

Here's the outline of my code:

.arrow-down {
    position: absolute;
    width: 0;
    height: 0;
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-top: 15px solid white;
  margin-left: 20px;
}
.nav-tabs {
    background-color: black;
}
.tab-content {
  background-color: #ccc
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    Home

    Profile

    Messages

    Settings

...

...

...

...

Body:
Add a class to show the arrow, then add on click event to all menu, remove the previous arrow and add to the current tab.

.active-arrow {
  display: block;
}

To center the arrow, you could use flexbox, and add margin-top to each arrow to position it right.

.nav-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

$('ul a.nav-link').on('click', function(e) {
  $('.arrow-down').removeClass('active-arrow');
  $(this).next('.arrow-down').addClass('active-arrow');
})

.arrow-down {
  position: absolute;
  width: 0;
  height: 0;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-top: 15px solid white;
  display: none;
  margin-top: 28px;
}

.nav-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.active-arrow {
  display: block;
}

.nav-tabs {
  background-color: black;
}

.tab-content {
  background-color: #ccc
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

<ul class="nav nav-tabs" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="tab" href="#home" role="tab">Home</a>
    <div class="arrow-down active-arrow"></div>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#profile" role="tab">Profile</a>
    <div class="arrow-down"></div>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#messages" role="tab">Messages</a>
    <div class="arrow-down"></div>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#settings" role="tab">Settings</a>
    <div class="arrow-down"></div>
  </li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="home" role="tabpanel">1</div>
  <div class="tab-pane" id="profile" role="tabpanel">2</div>
  <div class="tab-pane" id="messages" role="tabpanel">3</div>
  <div class="tab-pane" id="settings" role="tabpanel">4</div>
</div>


问:
Java Swing JMenu Mnemonic
I have a menu that I created using JMenu. I want to assign a shortcut key Alt-F to this menu. I used setMnemonic('F') to do that, but the menu does not recognise the mnemonic.

What is the best way to troubleshoot or debug this problem ? I find that setting a break point does not help that much.

Thank you.

Code Snippet:

```<code>//higher up in variable declaration
/** Menus on the menu bar */
private JMenu uiFindMnu           = new JMenu("Find");
...
//inside the constructor
// set mnemonic for the Find menu
uiFindMnu.setMnemonic('F');
</code>```

答:
Use setMnemonic(KeyEvent.VK_F);

I recommend you to read this about JMenus : Howto use Menus

Here is an extract of this article :

Menus support two kinds of keyboard alternatives: mnemonics and
  accelerators. Mnemonics offer a way to use the keyboard to navigate
  the menu hierarchy, increasing the accessibility of programs.
  Accelerators, on the other hand, offer keyboard shortcuts to bypass
  navigating the menu hierarchy. Mnemonics are for all users;
  accelerators are for power users.

A mnemonic is a key that makes an already visible menu item be chosen.
  For example, in MenuDemo the first menu has the mnemonic A, and its
  second menu item has the mnemonic B. This means that, when you run
  MenuDemo with the Java look and feel, pressing the Alt and A keys
  makes the first menu appear. While the first menu is visible, pressing
  the B key (with or without Alt) makes the second menu item be chosen.
  A menu item generally displays its mnemonic by underlining the first
  occurrence of the mnemonic character in the menu item's text, as the
  following snapshot shows. B is the mnemonic character for this menu
  item

You can specify a mnemonic either when constructing the menu item or
  with the setMnemonic method. Here are examples of setting mnemonics
  and accelerators:

```<code>//Setting the mnemonic when constructing a menu item:
menuItem = new JMenuItem("A text-only menu item",
                         KeyEvent.VK_T);

//Setting the mnemonic after creation time:
menuItem.setMnemonic(KeyEvent.VK_T);
</code>```

As you can see, you set a mnemonic by specifying the KeyEvent constant
  corresponding to the key the user should press.

Title: Java Swing JMenu Mnemonic

Body:
I have a menu that I created using JMenu. I want to assign a shortcut key Alt-F to this menu. I used setMnemonic('F') to do that, but the menu does not recognise the mnemonic.

What is the best way to troubleshoot or debug this problem ? I find that setting a break point does not help that much.

Thank you.

Code Snippet:

//higher up in variable declaration
/** Menus on the menu bar */
private JMenu uiFindMnu           = new JMenu("Find");
...
//inside the constructor
// set mnemonic for the Find menu
uiFindMnu.setMnemonic('F');

Body:
Use setMnemonic(KeyEvent.VK_F);

I recommend you to read this about JMenus : Howto use Menus

Here is an extract of this article :

Menus support two kinds of keyboard alternatives: mnemonics and
  accelerators. Mnemonics offer a way to use the keyboard to navigate
  the menu hierarchy, increasing the accessibility of programs.
  Accelerators, on the other hand, offer keyboard shortcuts to bypass
  navigating the menu hierarchy. Mnemonics are for all users;
  accelerators are for power users.

A mnemonic is a key that makes an already visible menu item be chosen.
  For example, in MenuDemo the first menu has the mnemonic A, and its
  second menu item has the mnemonic B. This means that, when you run
  MenuDemo with the Java look and feel, pressing the Alt and A keys
  makes the first menu appear. While the first menu is visible, pressing
  the B key (with or without Alt) makes the second menu item be chosen.
  A menu item generally displays its mnemonic by underlining the first
  occurrence of the mnemonic character in the menu item's text, as the
  following snapshot shows. B is the mnemonic character for this menu
  item

You can specify a mnemonic either when constructing the menu item or
  with the setMnemonic method. Here are examples of setting mnemonics
  and accelerators:

//Setting the mnemonic when constructing a menu item:
menuItem = new JMenuItem("A text-only menu item",
                         KeyEvent.VK_T);

//Setting the mnemonic after creation time:
menuItem.setMnemonic(KeyEvent.VK_T);

As you can see, you set a mnemonic by specifying the KeyEvent constant
  corresponding to the key the user should press.