问:
CSS calc not working for  width
I'd like Cell A to leave exactly 100px for the remain two cells.  I would think calc(100% - 100px) would be sufficient as this works just fine in many other situations.  Why isn't it working here?

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

td:first-child {
  width: calc(100% - 100px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table></code>```

答:
table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

td:first-child{
  width: calc(100% / 6 * 3.5);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table></code>```

Title: CSS calc not working for <td> width

Body:
I'd like Cell A to leave exactly 100px for the remain two cells.  I would think calc(100% - 100px) would be sufficient as this works just fine in many other situations.  Why isn't it working here?

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

td:first-child {
  width: calc(100% - 100px);
}

      Cell A
      Cell B
      Cell C

Body:
table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #555;
  font-family: sans-serif;
  table-layout: fixed;
}

td {
  padding: 10px;
  box-sizing: border-box;
  text-align: center
}

td+td {
  border-left: 1px solid #555;
}

td:first-child{
  width: calc(100% / 6 * 3.5);
}

<table>
  <tbody>
    <tr>
      <td>Cell A</td>
      <td>Cell B</td>
      <td>Cell C</td>
    </tr>
  </tbody>
</table>


来源: stackexchange

问:
How to count the length of a line in bash such that spaces for indentation are excluded?
I wish to enforce a rule that no line in a python code would be more than 80  characters in length. For this I count the length of the entire line in file using a bash script. However, I need to exclude the starting spaces used for indentation. I wish to start counting from where the first character is seen in the line, until the last character: e.g:

```<code>    this is an example line
</code>```

length() needs to return (31-8=23) rather than 31.

How do I accomplish this using a sed, awk, or grep query?

ContentLicense: CC BY-SA 3.0

Body:
I wish to enforce a rule that no line in a python code would be more than 80  characters in length. For this I count the length of the entire line in file using a bash script. However, I need to exclude the starting spaces used for indentation. I wish to start counting from where the first character is seen in the line, until the last character: e.g:

    this is an example line

length() needs to return (31-8=23) rather than 31.

How do I accomplish this using a sed, awk, or grep query?

Body: $ sed file.txt 's/^ *//' | sed 's/^\t*//' | wc -c


问:
Installing Java libraries
As I'm quite new to Java, I would like to know the proper procedure of installing new libraries (those that are no available in my linux dist repositories).
Where should I place them? and how to install them?
For instance, I downloaded openCsv (http://opencsv.sourceforge.net/), and I have no idea how to install it.</p>

答:
Be sure that the path, which you place the libaries at, is set in the $CLASSPATH Environment Variable.

For Eclipse: Project -> Properties -> Java Build Path -> Add JARs...

Title: Installing Java libraries

ContentLicense: CC BY-SA 2.5


问:
How to get the count of command line parameters in python regardless of python keyword?
I have a small sample program in python:

```<code>import sys
print ("This is the name of the script: "+ sys.argv[0])
print ("Number of arguments: " + str(len(sys.argv)))
print ("The arguments are: " + str(sys.argv))
</code>```

I run it in Windows CLI:

```<code>python args.py -a -b
</code>```

Output:

```<code>This is the name of the script: args.py
Number of arguments: 3
The arguments are: ['args.py', '-a', '-b']
</code>```

Looks good. Now I call it without specifying "python":

```<code>args.py -a -b
</code>```

Now the output is totally different:

```<code>This is the name of the script: C:\args.py
Number of arguments: 1
The arguments are: ['C:\\args.py']
</code>```

Shouldnt I be getting the same result? Why does it show a different argument count, even though python.exe is executing the program in both cases? How do I correct this?

答: Don't use sys.arg for any significant argument parsing. Use argparse.</p>

Body:
I have a small sample program in python:

import sys
print ("This is the name of the script: "+ sys.argv[0])
print ("Number of arguments: " + str(len(sys.argv)))
print ("The arguments are: " + str(sys.argv))

I run it in Windows CLI:

python args.py -a -b

Output:

This is the name of the script: args.py
Number of arguments: 3
The arguments are: ['args.py', '-a', '-b']

Looks good. Now I call it without specifying "python":

args.py -a -b

Now the output is totally different:

This is the name of the script: C:\args.py
Number of arguments: 1
The arguments are: ['C:\\args.py']

Shouldnt I be getting the same result? Why does it show a different argument count, even though python.exe is executing the program in both cases? How do I correct this?


问:
Wp_admin shows blank after udating wp_debug in wp_config
// Enable Debugging

```<code>define('WP_DEBUG', true);
</code>```

// Tell WordPress to log everything to /wp-content/debug.log

```<code>define('WP_DEBUG_LOG', true);
</code>```

// Turn off the display of error messages on your site

```<code>define('WP_DEBUG_DISPLAY', false);
</code>```

// For good measure, you can also add the follow code, which will hide errors from being displayed on-screen

```<code>@ini_set('display_errors', 0);
</code>```

wp-admin page shows blank after adding the above content to the wp_config.php in ftp to hide the errors that appear on the site page

is there any way this problem can be fixed

答:
Please remove that line

screen @ini_set('display_errors', 0);

you just change the line

define('WP_DEBUG', false);

Please try this

Body:
// Enable Debugging

define('WP_DEBUG', true);

// Tell WordPress to log everything to /wp-content/debug.log

define('WP_DEBUG_LOG', true);

// Turn off the display of error messages on your site

define('WP_DEBUG_DISPLAY', false);

// For good measure, you can also add the follow code, which will hide errors from being displayed on-screen

@ini_set('display_errors', 0);

wp-admin page shows blank after adding the above content to the wp_config.php in ftp to hide the errors that appear on the site page

is there any way this problem can be fixed


问:
MVVM Progress Bar EventTrigger
This is my sample code to animate progress bar during page loaded.

My question is, how can i start progress bar when button click?

```<code><ProgressBar Height="50" Minimum="0" Maximum="100" Value="0"
            RenderTransformOrigin="0.5,0.5"
            Margin="-113,0" Background="Transparent"
            BorderThickness="0" Foreground="DarkCyan">
     <ProgressBar.RenderTransform>
          <TransformGroup>
              <ScaleTransform/>
              <SkewTransform/>
              <RotateTransform Angle="-90"/>
              <TranslateTransform/>
          </TransformGroup>
     </ProgressBar.RenderTransform>
     <ProgressBar.Triggers>
          <EventTrigger RoutedEvent="FrameworkElement.Loaded">
               <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Value"
                                        From="0" To="{Binding Bar1}"
                                        Duration="{Binding Duration1}"/>
                     </Storyboard>
                </BeginStoryboard>
          </EventTrigger>
     </ProgressBar.Triggers>
</ProgressBar>
</code>```

答:
Steps:

Give <ProgressBar /> a name, and remove Triggers.

```<code><ProgressBar x:Name="MyProgressBar" Height="50" Minimum="0" Maximum="100" Value="0"
            RenderTransformOrigin="0.5,0.5"
            Margin="-113,0" Background="Transparent"
            BorderThickness="0" Foreground="DarkCyan">
     <ProgressBar.RenderTransform>
          <TransformGroup>
              <ScaleTransform/>
              <SkewTransform/>
              <RotateTransform Angle="-90"/>
              <TranslateTransform/>
          </TransformGroup>
     </ProgressBar.RenderTransform>
</ProgressBar>
</code>```

Add your <Button />, with Triggers, TargetName equal to <ProgressBar /> name.

```<code>    <Button Content="Press to trigger">
        <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Value" Storyboard.TargetName="MyProgressBar"
                            From="0" To="100"
                            Duration="0:0:1"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
        </Button.Triggers>
    </Button>
</code>```

Result:

Title: MVVM Progress Bar EventTrigger

Body:
This is my sample code to animate progress bar during page loaded.

My question is, how can i start progress bar when button click?

<ProgressBar Height="50" Minimum="0" Maximum="100" Value="0"
            RenderTransformOrigin="0.5,0.5"
            Margin="-113,0" Background="Transparent"
            BorderThickness="0" Foreground="DarkCyan">
     <ProgressBar.RenderTransform>
          <TransformGroup>
              <ScaleTransform/>
              <SkewTransform/>
              <RotateTransform Angle="-90"/>
              <TranslateTransform/>
          </TransformGroup>
     </ProgressBar.RenderTransform>
     <ProgressBar.Triggers>
          <EventTrigger RoutedEvent="FrameworkElement.Loaded">
               <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Value"
                                        From="0" To="{Binding Bar1}"
                                        Duration="{Binding Duration1}"/>
                     </Storyboard>
                </BeginStoryboard>
          </EventTrigger>
     </ProgressBar.Triggers>
</ProgressBar>

Body:
Steps:

Give <ProgressBar /> a name, and remove Triggers.

<ProgressBar x:Name="MyProgressBar" Height="50" Minimum="0" Maximum="100" Value="0"
            RenderTransformOrigin="0.5,0.5"
            Margin="-113,0" Background="Transparent"
            BorderThickness="0" Foreground="DarkCyan">
     <ProgressBar.RenderTransform>
          <TransformGroup>
              <ScaleTransform/>
              <SkewTransform/>
              <RotateTransform Angle="-90"/>
              <TranslateTransform/>
          </TransformGroup>
     </ProgressBar.RenderTransform>
</ProgressBar>

Add your <Button />, with Triggers, TargetName equal to <ProgressBar /> name.

    <Button Content="Press to trigger">
        <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Value" Storyboard.TargetName="MyProgressBar"
                            From="0" To="100"
                            Duration="0:0:1"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
        </Button.Triggers>
    </Button>

Result:


问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

答:
Here's a fun bit-twiddling version that doesn't have any conditional branches.</p>

```<code>int g = (int)"greater";
int l = (int)"less";
int e = (int)"equal";

int a = 7;
int b = 10;

char *result = (char*)((((a - b) >> 31) & l) | (((b - a) >> 31) & g) | ((~((a - b) | (b - a))) >> 31) & e);
cout << result;
</code>```

OwnerDisplayName: kvphxga

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga

Body:
Here's a fun bit-twiddling version that doesn't have any conditional branches.

int g = (int)"greater";
int l = (int)"less";
int e = (int)"equal";

int a = 7;
int b = 10;

char *result = (char*)((((a - b) >> 31) & l) | (((b - a) >> 31) & g) | ((~((a - b) | (b - a))) >> 31) & e);
cout << result;

OwnerDisplayName: Josh


答:
You can store them wherever you wish. You can store them within the JRE distribution directories, but I wouldn't recommend that.

Instead I would store them per-project (so you can have different versions for each project easily - some libraries have different names for each version, some don't) and adopt a standard such as a lib/ directory. That way you can have standard build scripts (Ant etc.) that can operate in the same way (if you're using Maven, then there's a standard place per-project - src/main/resources)

Title: Installing Java libraries

Body:
As I'm quite new to Java, I would like to know the proper procedure of installing new libraries (those that are no available in my linux dist repositories).
Where should I place them? and how to install them?
For instance, I downloaded openCsv (http://opencsv.sourceforge.net/), and I have no idea how to install it.


问:
Opposite of INT into STRING
What is the Opposite of this code in to string? </p>

```<code>int number = Integer.parseInt(input.getText().toString());
</code>```

答:
There are different methods to convert integer to string. Few of them are listed below.

Method 1

```<code>String.valueOf(int_value);
</code>```

Method 2

```<code>Integer.toString(int_value);
</code>```

Method 3

```<code>int_value.toString;
</code>```

Title: Opposite of INT into STRING

Body:
What is the Opposite of this code in to string?

int number = Integer.parseInt(input.getText().toString());

Body:
There are different methods to convert integer to string. Few of them are listed below.

Method 1

String.valueOf(int_value);

Method 2

Integer.toString(int_value);

Method 3

int_value.toString;


答:
Looks like there's a solution on this stackoverflow thread, reproduced below:

I search in regedit keyword "python" and found two keys missing %* after "C:\Python27\python.exe" "%1":

Computer\HKEY_CLASSES_ROOT\Applications\python.exe

Computer\HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

And .py is associated with py_auto_file even though I tried assoc .py Python.File

Changing the two keys fixed this issue, thanks!

Title: How to get the count of command line parameters in python regardless of python keyword?


问:
Why is my function executing twice?
A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this?

```<code># -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time

def displayIntro():
    print("Hello, there! Glad to meet you!")
    print("Welcome to the world of Pokémon!")
    print("My name is Maple.")
    print("People affectionately refer to me as the Pokémon Professor.")
    print("This world is inhabited far and wide by creatures called Pokémon.")
    print("For some people, Pokémon are pets.")
    print("Others use them for battling.")
    print("As for myself, I study Pokémon as a profession.")
    print("But first, tell me a little about yourself.")

def chooseGender():
    gender = ""
    while gender != "boy" and gender != "girl":
        gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")

    return gender

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")

    return answer
    if answer == "yes":
        print("I have a grandson.")
        print("He's been your rival since you both were babies.")
        print("...Erm, what was his name now?")
        # raw_input for their name
        print("...Er, was it") #raw_input for name
        # Let user pick yes or no
        # If yes, move on
        # If no, ask name again
        print("That's right! I remember now! His name is") #raw_input for name
        print("your name!") # raw_input for name
        print("Your very own Pokémon legend is about to unfold!")
        print("A world of dreams and adventures with Pokémon awaits! Let's go!")
    if answer == "no":
        chooseName()

displayIntro()
chooseGender()
chooseName()
nameConfirmation()
</code>```

I apologize for not posting the rest of the code sooner.
This is the output.

```<code>Let's begin with your name. What is it? Raven
Let's begin with your name. What is it? Raven
</code>```

答: Remove the chooseName( ) call below chooseGender( ) as it has already been called in nameConfirmation( ) definition. It worked for me.

Title: Why is my function executing twice?

Body:
A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this?

# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time

def displayIntro():
    print("Hello, there! Glad to meet you!")
    print("Welcome to the world of Pokémon!")
    print("My name is Maple.")
    print("People affectionately refer to me as the Pokémon Professor.")
    print("This world is inhabited far and wide by creatures called Pokémon.")
    print("For some people, Pokémon are pets.")
    print("Others use them for battling.")
    print("As for myself, I study Pokémon as a profession.")
    print("But first, tell me a little about yourself.")

def chooseGender():
    gender = ""
    while gender != "boy" and gender != "girl":
        gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")

    return gender

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    answer = ""
    while answer != "yes" and answer != "no":
        answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")

    return answer
    if answer == "yes":
        print("I have a grandson.")
        print("He's been your rival since you both were babies.")
        print("...Erm, what was his name now?")
        # raw_input for their name
        print("...Er, was it") #raw_input for name
        # Let user pick yes or no
        # If yes, move on
        # If no, ask name again
        print("That's right! I remember now! His name is") #raw_input for name
        print("your name!") # raw_input for name
        print("Your very own Pokémon legend is about to unfold!")
        print("A world of dreams and adventures with Pokémon awaits! Let's go!")
    if answer == "no":
        chooseName()

displayIntro()
chooseGender()
chooseName()
nameConfirmation()

I apologize for not posting the rest of the code sooner.
This is the output.

Let's begin with your name. What is it? Raven
Let's begin with your name. What is it? Raven


问:
Form does not read javascript before redirect to another page
I have a form, before submit the data to another page it needs to validate the input first. But the problem is the form redirect to another page without reading the javascript first.</p>

```<code><html>
<script>
    function fnValidate(){
     with document.frmAdd{
    var x;
    x = txtEmail.value;

    if( x.indexof("@")== -1)
    {   alert("A valid email address must contains @");
    return false; }
    if( isNaN(txtAge.value)== 1- )
    {   alert("Age must be filled out by number");
    return false; }
    if( txtPwd.value <> txtPwd2.value )
    {   alert("Password not matched!");
    return false; }

     } //end_with
    } //end_fnValidate()

</script>
<body>
    <form name="frmAdd" method="post" action="SaveNewUser.php" onSubmit="return fnValidate()">
        IC No    : <input type=text name="txtIc" size=20 required> <br>
        Name     : <input type=text name="txtName" size=50 required> <br>
        Email    : <input type=text name="txtEmail" size=50 required> <br>
        D.O.B    : <input type=date name="txtDOB" size=20 required> <br>
        Age      : <input type=text name="txtAge" size=5 maxlength=2 required>
        <br><br>
        Username         : <input type=text name="txtUserName" size=20
            required> <br>
        Password         : <input type=password name="txtPwd" size=20
            required> <br>
        Re-Enter Password: <input type=password name="txtPwd2" size=20
            required> <br><br>
        <input type=submit name=btnSubmit value=SAVE>
    </form>
</body>
</html>
</code>```

答:
You need to add return to your java script function at the end</p>

```<code>function fnValidate()
{
    with document.frmAdd{

    var x;
    x = txtEmail.value;

    if( x.indexof("@")== -1)
    {   alert("A valid email address must contains @");
        return false; }
    if( isNaN(txtAge.value)== 1- )
    {   alert("Age must be filled out by number");
        return false; }
    if( txtPwd.value <> txtPwd2.value )
    {   alert("Password not matched!");
        return false; }

    }

return false;
}
</code>```

Body:
I have a form, before submit the data to another page it needs to validate the input first. But the problem is the form redirect to another page without reading the javascript first.

    <form name="frmAdd" method="post" action="SaveNewUser.php" onSubmit="return fnValidate()">
        IC No    : <input type=text name="txtIc" size=20 required>

        Name     : <input type=text name="txtName" size=50 required>

        Email    : <input type=text name="txtEmail" size=50 required>

        D.O.B    : <input type=date name="txtDOB" size=20 required>

        Age      : <input type=text name="txtAge" size=5 maxlength=2 required>

        Username         : <input type=text name="txtUserName" size=20
            required>

        Password         : <input type=password name="txtPwd" size=20
            required>

        Re-Enter Password: <input type=password name="txtPwd2" size=20
            required>

        <input type=submit name=btnSubmit value=SAVE>
    </form>

Body:
You need to add return to your java script function at the end

function fnValidate()
{
    with document.frmAdd{

    var x;
    x = txtEmail.value;

    if( x.indexof("@")== -1)
    {   alert("A valid email address must contains @");
        return false; }
    if( isNaN(txtAge.value)== 1- )
    {   alert("Age must be filled out by number");
        return false; }
    if( txtPwd.value <> txtPwd2.value )
    {   alert("Password not matched!");
        return false; }

    }

return false;
}


问:
introduction to latex
what's a good website that has an introduction to latex for window users? I will be using it mainly to write math homework problems and probably then converting it to a PDF to print out. I'm hoping somebody has bookmarked a good link already so I don't have to search. Thanks!</p>

答:
You should start from this "not so short introduction to latex"
http://www.ctan.org/tex-archive/info/lshort/english/lshort.pdf</p>

Title: introduction to latex


问:
Dropdown Banner
How can I get a drop down banner for my website so that when a user goes to my home page a banner will drop down, cover a fourth of the page, and say something like, "Welcome too...." and then after a few seconds close

I've tried

```<code><style>
.dropdown-notification {
   height: 40px;
   line-height: 40px;
   position: relative;
   top: -40px;
   transition: top .2s; // don't forget to use prefixes
 background-color: #4CAF50;
}
.dropdown-notification.active {
   top: 0;
}
</style>

<body>

<div class="dropdown-notification text-center">
      Hi, I'm a drop down <button class="close">Close</button>
   </div>

</body>
</code>```

but I can't get the banner to go across the screen over or change the banner color to something more colorful.Thanks in advance for your help and please understand I am still very new at this so any advice would be much appreciated!

答:
First off, if you want to cover the page, the div needs position: absolute. I've also added a oneliner to make it disappear.

EDIT: it now slides in on page load.

document.body.onload = function() {
  var dd = document.getElementById("dropdown")
  dd.className = dd.className.replace("disabled", "")
}

function closeDropdown() {
  document.getElementById("dropdown").className += " disabled"
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 0;
  margin: 0;
}

.dropdown-notification {
   height: 40px;
   width: 100%;
   line-height: 40px;
   position: absolute;
   top: 0;
   transition: top .3s;
   background-color: #4CAF50;
}
.dropdown-notification.disabled {
   top: -40px;
}</code>```

      Hi, I'm a drop down Close

here goes the actual page text

here goes the actual page text

here goes the actual page text

here goes the actual page text

here goes the actual page text

here goes the actual page text

here goes the actual page text

here goes the actual page text

here goes the actual page text
```

Title: Dropdown Banner

Body:
How can I get a drop down banner for my website so that when a user goes to my home page a banner will drop down, cover a fourth of the page, and say something like, "Welcome too...." and then after a few seconds close

I've tried

      Hi, I'm a drop down <button class="close">Close</button>

but I can't get the banner to go across the screen over or change the banner color to something more colorful.Thanks in advance for your help and please understand I am still very new at this so any advice would be much appreciated!

Body:
First off, if you want to cover the page, the div needs position: absolute. I've also added a oneliner to make it disappear.

EDIT: it now slides in on page load.

document.body.onload = function() {
  var dd = document.getElementById("dropdown")
  dd.className = dd.className.replace("disabled", "")
}

function closeDropdown() {
  document.getElementById("dropdown").className += " disabled"
}

body {
  padding: 0;
  margin: 0;
}

.dropdown-notification {
   height: 40px;
   width: 100%;
   line-height: 40px;
   position: absolute;
   top: 0;
   transition: top .3s;
   background-color: #4CAF50;
}
.dropdown-notification.disabled {
   top: -40px;
}

<div class="dropdown-notification text-center disabled" id="dropdown">
      Hi, I'm a drop down <a class="close" href="javascript:closeDropdown()">Close</a>
</div>
here goes the actual page text<br>
here goes the actual page text<br>
here goes the actual page text<br>
here goes the actual page text<br>
here goes the actual page text<br>
here goes the actual page text<br>
here goes the actual page text<br>
here goes the actual page text<br>
here goes the actual page text<br>


问:
Python Spyder reset
I was using python(x,y), which came with Spyder. Yesterday, Spyder crashed I can't figure it out how to fix it. I uninstalled python(x,y) and reinstalled, still the same problem.

If I try to open Spyder I get this message:

```<code>Spyder crashed during last session

If Spyder does not start at all and before submitting a bug report, please try to reset setting to defaults by running Spyder with the command line option '--reset:

python spyder --reset
</code>```

Of course, I tried to do the above, but it doesn't seem like I have Spyder in my path. When I try to put

```<code>python spyder --reset
</code>```

in my command prompt window, I get this error message:

```<code>python: can't open file 'spyder': [Errno 2] No such file or directory
</code>```

I made some attempts of trying to add spyder to path, but they all failed. How should I go about adding Spyder to path?

I am using Windows Vista on a 32 bit system.

My Spyder Crash report looks like this:

```<code>Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\spyderlib\spyder.py", line 1547, in main
    mainwindow = run_spyder(app, options)
  File "C:\Python27\lib\site-packages\spyderlib\spyder.py", line 1472, in run_spyder
    main.setup()
  File "C:\Python27\lib\site-packages\spyderlib\spyder.py", line 555, in setup
    multithreaded=self.multithreaded)
  File "C:\Python27\lib\site-packages\spyderlib\plugins\console.py", line 54, in __init__
    light_background=light_background)
  File "C:\Python27\lib\site-packages\spyderlib\widgets\internalshell.py", line 101, in __init__
    debug, profile)
  File "C:\Python27\lib\site-packages\spyderlib\widgets\shell.py", line 698, in __init__
    ShellBaseWidget.__init__(self, parent, history_filename, debug, profile)
  File "C:\Python27\lib\site-packages\spyderlib\widgets\shell.py", line 61, in __init__
    self.history = self.load_history()
  File "C:\Python27\lib\site-packages\spyderlib\widgets\shell.py", line 500, in load_history
    if rawhistory[1] != self.INITHISTORY[1]:
IndexError: list index out of range
</code>```

I am terrible with this stuff, so I might be missing something completely obvious or doing something really stupid.

I am wondering if anyone else ran into a similar problem, or can just give suggestions on what to do, and how to do this "reset" thing, or maybe other advice.

Thank You in Advance

答: don't worry, it is very easy to reset the spyder. for windows 10 users, you all need to type 'spyder' in 'Cortana' then you can see in apps category something like 'reset spyder setting' just click on that and some black screen will open and your problem will be solved. now you can open your spyder.</p>

Title: Python Spyder reset

Body:
I was using python(x,y), which came with Spyder. Yesterday, Spyder crashed I can't figure it out how to fix it. I uninstalled python(x,y) and reinstalled, still the same problem.

If I try to open Spyder I get this message:

Spyder crashed during last session

If Spyder does not start at all and before submitting a bug report, please try to reset setting to defaults by running Spyder with the command line option '--reset:

python spyder --reset

Of course, I tried to do the above, but it doesn't seem like I have Spyder in my path. When I try to put

python spyder --reset

in my command prompt window, I get this error message:

python: can't open file 'spyder': [Errno 2] No such file or directory

I made some attempts of trying to add spyder to path, but they all failed. How should I go about adding Spyder to path?

I am using Windows Vista on a 32 bit system.

My Spyder Crash report looks like this:

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\spyderlib\spyder.py", line 1547, in main
    mainwindow = run_spyder(app, options)
  File "C:\Python27\lib\site-packages\spyderlib\spyder.py", line 1472, in run_spyder
    main.setup()
  File "C:\Python27\lib\site-packages\spyderlib\spyder.py", line 555, in setup
    multithreaded=self.multithreaded)
  File "C:\Python27\lib\site-packages\spyderlib\plugins\console.py", line 54, in __init__
    light_background=light_background)
  File "C:\Python27\lib\site-packages\spyderlib\widgets\internalshell.py", line 101, in __init__
    debug, profile)
  File "C:\Python27\lib\site-packages\spyderlib\widgets\shell.py", line 698, in __init__
    ShellBaseWidget.__init__(self, parent, history_filename, debug, profile)
  File "C:\Python27\lib\site-packages\spyderlib\widgets\shell.py", line 61, in __init__
    self.history = self.load_history()
  File "C:\Python27\lib\site-packages\spyderlib\widgets\shell.py", line 500, in load_history
    if rawhistory[1] != self.INITHISTORY[1]:
IndexError: list index out of range

I am terrible with this stuff, so I might be missing something completely obvious or doing something really stupid.

I am wondering if anyone else ran into a similar problem, or can just give suggestions on what to do, and how to do this "reset" thing, or maybe other advice.

Thank You in Advance


问:
How to use findViewById in a public class ItemThreeFragment extends Fragment
I want to display another fragment within my fragment that has been showed and when I Run it it will show an error  Error:(31, 75) error: cannot find symbol method findViewById(int), is their some kind of way that I can use the findViewByID in a fragment class not AppCompatActivity ?

```<code>ItemThreeFragment.java

public class ItemThreeFragment extends Fragment {

private BottomNavigationView bottomNavigationView;

public static ItemThreeFragment newInstance() {
    ItemThreeFragment fragment = new ItemThreeFragment();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.NavGroup);

    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener(){

                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment1 = null;
                    switch (item.getItemId()){
                        case R.id.groupJoined:
                            selectedFragment1 = GroupOne.newInstance();
                            break;
                        case R.id.createGroup:
                            selectedFragment1 = GroupTwo.newInstance();
                            break;
                    }

                    FragmentTransaction trans = getChildFragmentManager().beginTransaction();
                    trans.replace(R.id.groupFrame_layout, selectedFragment1);
                    trans.commit();
                    return true;

                }
            });

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_item_three, container, false);

}
}
</code>```

Code for the fragment what Im calling

```<code>GroupOne.java

public class GroupOne extends Fragment {
public static GroupOne newInstance() {
    GroupOne fragment = new GroupOne();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_group_one, container, false);
}
}
</code>```

for    GroupTwo.java

```<code>public class GroupTwo extends Fragment {
public static GroupTwo newInstance() {
    GroupTwo fragment = new GroupTwo();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_group_two, container, false);
}
}
</code>```

This is my Main Activity

public class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.NavBot);

    bottomNavigationView.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.home:
                            selectedFragment = ItemOneFragment.newInstance();
                            break;
                        case R.id.search:
                            selectedFragment = ItemTwoFragment.newInstance();
                            break;
                        case R.id.groups:
                            selectedFragment = ItemThreeFragment.newInstance();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;
                }
            });

    //Manually displaying the first fragment - one time only
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout, ItemOneFragment.newInstance());
    transaction.commit();

    //Used to select an item programmatically
    //bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
</code>```

activity_main.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.MainActivity">

<FrameLayout
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/navigation"
    android:animateLayoutChanges="true"
    android:layout_below="@+id/bottomNavigationView">
</FrameLayout>

<android.support.design.widget.BottomNavigationView

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/NavBot"
    android:layout_gravity="bottom"
    app:menu="@menu/menu_nav"
    android:background="@color/Lime"
    app:itemIconTint="@android:color/white"
    app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>
</code>```

fragment_item_three.xml

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:weightSum="1">

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:id="@+id/searchGroup"
        android:scrollbarSize="10dp"/>

    <android.support.design.widget.BottomNavigationView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/NavGroup"
        android:layout_gravity="bottom"
        app:menu="@menu/menu_group"
        android:background="@color/Lime"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>

    <FrameLayout
        android:id="@+id/groupFrame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/navigation"
        android:animateLayoutChanges="true"
        android:layout_below="@+id/bottomNavigationView">
    </FrameLayout>

</LinearLayout>
</code>```

fragment_group_one.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.GroupOne">

<!-- TODO: Update blank fragment layout -->

<TextView
    android:text="Hay salamat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView3" />
</code>```

fragment_group_two.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.GroupTwo">

<!-- TODO: Update blank fragment layout -->
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hay Humana" />
</code>```

答:
Sample code </p>

```<code> @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_group_two, container, false);
    TextView tv = (TextView) view.findViewById(R.id.tv)
    return view;
}
</code>```

Body:
I want to display another fragment within my fragment that has been showed and when I Run it it will show an error  Error:(31, 75) error: cannot find symbol method findViewById(int), is their some kind of way that I can use the findViewByID in a fragment class not AppCompatActivity ?

ItemThreeFragment.java

public class ItemThreeFragment extends Fragment {

private BottomNavigationView bottomNavigationView;

public static ItemThreeFragment newInstance() {
    ItemThreeFragment fragment = new ItemThreeFragment();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.NavGroup);

    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener(){

                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment1 = null;
                    switch (item.getItemId()){
                        case R.id.groupJoined:
                            selectedFragment1 = GroupOne.newInstance();
                            break;
                        case R.id.createGroup:
                            selectedFragment1 = GroupTwo.newInstance();
                            break;
                    }

                    FragmentTransaction trans = getChildFragmentManager().beginTransaction();
                    trans.replace(R.id.groupFrame_layout, selectedFragment1);
                    trans.commit();
                    return true;

                }
            });

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_item_three, container, false);

}
}

Code for the fragment what Im calling

GroupOne.java

public class GroupOne extends Fragment {
public static GroupOne newInstance() {
    GroupOne fragment = new GroupOne();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_group_one, container, false);
}
}

for    GroupTwo.java

public class GroupTwo extends Fragment {
public static GroupTwo newInstance() {
    GroupTwo fragment = new GroupTwo();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_group_two, container, false);
}
}

This is my Main Activity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.NavBot);

    bottomNavigationView.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;
                    switch (item.getItemId()) {
                        case R.id.home:
                            selectedFragment = ItemOneFragment.newInstance();
                            break;
                        case R.id.search:
                            selectedFragment = ItemTwoFragment.newInstance();
                            break;
                        case R.id.groups:
                            selectedFragment = ItemThreeFragment.newInstance();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;
                }
            });

    //Manually displaying the first fragment - one time only
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout, ItemOneFragment.newInstance());
    transaction.commit();

    //Used to select an item programmatically
    //bottomNavigationView.getMenu().getItem(2).setChecked(true);
}

activity_main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.MainActivity">

<FrameLayout
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/navigation"
    android:animateLayoutChanges="true"
    android:layout_below="@+id/bottomNavigationView">
</FrameLayout>

<android.support.design.widget.BottomNavigationView

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/NavBot"
    android:layout_gravity="bottom"
    app:menu="@menu/menu_nav"
    android:background="@color/Lime"
    app:itemIconTint="@android:color/white"
    app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>

fragment_item_three.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:weightSum="1">

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:id="@+id/searchGroup"
        android:scrollbarSize="10dp"/>

    <android.support.design.widget.BottomNavigationView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/NavGroup"
        android:layout_gravity="bottom"
        app:menu="@menu/menu_group"
        android:background="@color/Lime"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>

    <FrameLayout
        android:id="@+id/groupFrame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/navigation"
        android:animateLayoutChanges="true"
        android:layout_below="@+id/bottomNavigationView">
    </FrameLayout>

</LinearLayout>

fragment_group_one.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.GroupOne">

<TextView
    android:text="Hay salamat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView3" />

fragment_group_two.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.findforme.www.myapplication.GroupTwo">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hay Humana" />

Body:
Sample code

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_group_two, container, false);
    TextView tv = (TextView) view.findViewById(R.id.tv)
    return view;
}


问:
Trying to create an array and instead creating an array within an array
I'm trying to create an array with information from a json file like so:

```<code>  var jsonPages = ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches.json', '/page/total_pages', 'noHeaders');

  var clan1Id = [];
  var clan1Name= [];
  var clan2Id =[];
  var clan2Name = [];
  var skillLevel = [];
  var week = [];
  var map =[];

  for (var i = 1; i<=jsonPages; ++i) {
    clan1Id = clan1Id.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan1/id', 'noHeaders'));
    clan1Name = clan1Name.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan1/name', 'noHeaders'));
    clan2Id = clan2Id.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan2/id', 'noHeaders'));
    clan2Name = clan2Name.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan2/name', 'noHeaders'));
    skillLevel = skillLevel.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/division/tier', 'noHeaders'));
    week = week.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/week', 'noHeaders'));
    map = map.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/maps', 'noHeaders'));
  }
  var array = [1, 2, 3, 4];

  Logger.log(array);
  Logger.log(clan1Id);
</code>```

This is the output I get to the Logs:

```<code>[17-12-07 04:46:51:235 GMT] [1.0, 2.0, 3.0, 4.0]
[17-12-07 04:46:51:236 GMT] [[23565], [25693], [28116], [18707], [18974], [27513], [27219], [19058], [29798], [23483], [18974], [28078], [29771]]
</code>```

As you can see, this creates an array within an array, how do I fix this?

答:
Per the documentation in ImportJSON, it returns a two-dimensional array (which actually means an array of arrays, since JS doesn't have two-dimensional arrays). This is probably meant to mimic the structure of spreadsheet data (rows of columns). Since each of the items in the array you're concating is itself an array, you'll get that nested structure.

You'll need to flatten. reduce can help with that:

```<code>const importedJSON = ImportJSON(`http://api.etf2l.org/competition/${competitionId}/matches/${i}.json`, '/matches/clan1/id', 'noHeaders');
clan1Id = importedJSON.reduce((result, row) => result.concat(row), clan1Id);
</code>```

...or simply this if you're assuming ImportJSON is returning a single row:

```<code>const url = `http://api.etf2l.org/competition/${competitionId}/matches/${i}.json`;
clan1Id = clan1Id.concat(ImportJSON(url, '/matches/clan1/id', 'noHeaders')[0])
</code>```

Body:
I'm trying to create an array with information from a json file like so:

  var jsonPages = ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches.json', '/page/total_pages', 'noHeaders');

  var clan1Id = [];
  var clan1Name= [];
  var clan2Id =[];
  var clan2Name = [];
  var skillLevel = [];
  var week = [];
  var map =[];

  for (var i = 1; i<=jsonPages; ++i) {
    clan1Id = clan1Id.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan1/id', 'noHeaders'));
    clan1Name = clan1Name.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan1/name', 'noHeaders'));
    clan2Id = clan2Id.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan2/id', 'noHeaders'));
    clan2Name = clan2Name.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan2/name', 'noHeaders'));
    skillLevel = skillLevel.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/division/tier', 'noHeaders'));
    week = week.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/week', 'noHeaders'));
    map = map.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/maps', 'noHeaders'));
  }
  var array = [1, 2, 3, 4];

  Logger.log(array);
  Logger.log(clan1Id);

This is the output I get to the Logs:

[17-12-07 04:46:51:235 GMT] [1.0, 2.0, 3.0, 4.0]
[17-12-07 04:46:51:236 GMT] [[23565], [25693], [28116], [18707], [18974], [27513], [27219], [19058], [29798], [23483], [18974], [28078], [29771]]

As you can see, this creates an array within an array, how do I fix this?

Body:
Per the documentation in ImportJSON, it returns a two-dimensional array (which actually means an array of arrays, since JS doesn't have two-dimensional arrays). This is probably meant to mimic the structure of spreadsheet data (rows of columns). Since each of the items in the array you're concating is itself an array, you'll get that nested structure.

You'll need to flatten. reduce can help with that:

const importedJSON = ImportJSON(`http://api.etf2l.org/competition/${competitionId}/matches/${i}.json`, '/matches/clan1/id', 'noHeaders');
clan1Id = importedJSON.reduce((result, row) => result.concat(row), clan1Id);

...or simply this if you're assuming ImportJSON is returning a single row:

const url = `http://api.etf2l.org/competition/${competitionId}/matches/${i}.json`;
clan1Id = clan1Id.concat(ImportJSON(url, '/matches/clan1/id', 'noHeaders')[0])


问:
How to convert a string to decimal within an IQueryable
Well, this sounds easier than it is! I have a table that contains amount stored as string values. But my code needs them as decimal values and it needs them to be casted to decimal as part of the query that IQueryable is making! Thus, the use of .ToList() is not possible. The cast needs to be done by the database behind it.

This IQueryable is basically part of a chain on IQueryables so a next query might want to add a filter on this amount to make a smaller selection, or do other kinds of math with the amount. The query that goes in might already be a subselection of all data.

Edit: Let me explain what I am working on here: I have something like this method to write:

```<code>public static IQueryable<PriceList> GetPriceList(this IQueryable<PriceData> query) => query.Select(d => new PriceList{Name = d.Item.Name, Price = decimal.Parse(d.Value)}).AsQueryable();
</code>```

And PriceData is a record containing a few fields and the prices as string values. But the PriceList record needs them as Decimal.

This method could then be used by another extension method for further selections, math and whatever. It's just that decimal.parse and other options don't work within an IQueryable...

答:
As already commented, what you are trying to do is not supported.

Your best bet is to change your database field type to what it actualy represents: Money/Decimal

If that is not possible, talk to the person, which has the ability to make it possible

If that is not possible, the closest workaround I can imagine is:

```<code>public class PriceList
{
    public string Price { get; set; }
    public decimal ParsedPrice => decimal.Parse(Price);
}
</code>```

And then:

```<code>.Select(d=>new PriceList
{
    Price = d.Price
});
</code>```

However, you can't execute any DbOperations on ParsedPrice then. Also note that you can't use a Constructor with parameters in EF6. That would be the next problem you would encounter.

EF works best for CRUD. For everything more you probably should have a Service, which is fetching the data only you need, materialize them and make a DTO or Businessobject out of it.

Something like that:

```<code>public class MyService
{
    public IEnumerable<PriceList> GetPriceList(Expression<Func<MyEntity, bool>> predicate)
    {
        var data = _context.MyEntity.Where(predicate).ToList();
        foreach (var item in data)
        {
            var dto = new PriceList {...}
            yield return dto;
        }
    }
}
</code>```

Body:
Well, this sounds easier than it is! I have a table that contains amount stored as string values. But my code needs them as decimal values and it needs them to be casted to decimal as part of the query that IQueryable is making! Thus, the use of .ToList() is not possible. The cast needs to be done by the database behind it.

This IQueryable is basically part of a chain on IQueryables so a next query might want to add a filter on this amount to make a smaller selection, or do other kinds of math with the amount. The query that goes in might already be a subselection of all data.

Edit: Let me explain what I am working on here: I have something like this method to write:

public static IQueryable<PriceList> GetPriceList(this IQueryable<PriceData> query) => query.Select(d => new PriceList{Name = d.Item.Name, Price = decimal.Parse(d.Value)}).AsQueryable();

And PriceData is a record containing a few fields and the prices as string values. But the PriceList record needs them as Decimal.

This method could then be used by another extension method for further selections, math and whatever. It's just that decimal.parse and other options don't work within an IQueryable...

Body:
As already commented, what you are trying to do is not supported.

Your best bet is to change your database field type to what it actualy represents: Money/Decimal

If that is not possible, talk to the person, which has the ability to make it possible

If that is not possible, the closest workaround I can imagine is:

public class PriceList
{
    public string Price { get; set; }
    public decimal ParsedPrice => decimal.Parse(Price);
}

And then:

.Select(d=>new PriceList
{
    Price = d.Price
});

However, you can't execute any DbOperations on ParsedPrice then. Also note that you can't use a Constructor with parameters in EF6. That would be the next problem you would encounter.

EF works best for CRUD. For everything more you probably should have a Service, which is fetching the data only you need, materialize them and make a DTO or Businessobject out of it.

Something like that:

public class MyService
{
    public IEnumerable<PriceList> GetPriceList(Expression<Func<MyEntity, bool>> predicate)
    {
        var data = _context.MyEntity.Where(predicate).ToList();
        foreach (var item in data)
        {
            var dto = new PriceList {...}
            yield return dto;
        }
    }
}


问:
Adding to integers in a list which is inside a dictionary
I have a dictionary which houses some integer values in a list:

```<code>d = {"Numbers": [5, 10, 15, 20]}
</code>```

How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this:

```<code>d = {"Numbers": [15, 20, 25, 30]}
</code>```

Thanks for the help!

答:
Everyone will give you same old approach using loop :

what about without loop :)

```<code>d = {"Numbers": [5, 10, 15, 20]}

list(map(lambda x:list((map(lambda y:x.__setitem__(x.index(y),y+10),x))),d.values()))
print(d)
</code>```

output:

```<code>{'Numbers': [25, 30, 15, 20]}
</code>```

Body:
I have a dictionary which houses some integer values in a list:

d = {"Numbers": [5, 10, 15, 20]}

How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this:

d = {"Numbers": [15, 20, 25, 30]}

Thanks for the help!

Body:
Everyone will give you same old approach using loop :

what about without loop :)

d = {"Numbers": [5, 10, 15, 20]}

list(map(lambda x:list((map(lambda y:x.__setitem__(x.index(y),y+10),x))),d.values()))
print(d)

output:

{'Numbers': [25, 30, 15, 20]}


问:
Supporting multiple instances of a plugin DLL with global data
Context: I converted a legacy standalone engine into a plugin component for a composition tool. Technically, this means that I compiled the engine code base to a C DLL which I invoke from a .NET wrapper using P/Invoke; the wrapper implements an interface defined by the composition tool. This works quite well, but now I receive the request to load multiple instances of the engine, for different projects. Since the engine keeps the project data in a set of global variables, and since the DLL with the engine code base is loaded only once, loading multiple projects means that the project data is overwritten.

I can see a number of solutions, but they all have some disadvantages:

You can create multiple DLLs with the same code, which are seen as different DLLs by Windows, so their code is not shared. Probably this already works if you have multiple copies of the engine DLL with different names. However, the engine is invoked from the wrapper using DllImport attributes and I think the name of the engine DLL needs to be known when compiling the wrapper. Obviously, if I have to compile different versions of the wrapper for each project, this is quite cumbersome.

The engine could run as a separate process. This means that the wrapper would launch a separate process for the engine when it loads a project, and it would use some form of IPC to communicate with this process. While this is a relatively clean solution, it requires some effort to get working, I don't now which IPC technology would be best to set-up this kind of construction. There may also be a significant overhead of the communication: the engine needs to frequently exchange arrays of floating-point numbers.

The engine could be adapted to support multiple projects. This means that the global variables should be put into a project structure, and every reference to the globals should be converted to a corresponding reference that is relative to a particular project. There are about 20-30 global variables, but as you can imagine, these global variables are referenced from all over the code base, so this conversion would need to be done in some automatic manner. A related problem is that you should be able to reference the "current" project structure in all places, but passing this along as an extra argument in each and every function signature is also cumbersome. Does there exist a technique (in C) to consider the current call stack and find the nearest enclosing instance of a relevant data value there?

Can the stackoverflow community give some advice on these (or other) solutions?

答:
Actually solution 3 is easier than it sounds. All other solutions are kind of patch and will break with time.

Create a .net class which will encapsulate all access to the legacy code. Make it IDisposable.

Change all the global variables to reside in a class named 'Context'

Have all the C++ interfaces get the context object and pass it around as the first argument. This is probably the longest stage and you can avoid it using the "thread-local-storage" method suggested by someone else, but I would vote against that solution: if your library has any working threads which it runs, the "thread-local-storage" solution will break. Just add the context object where it is needed.

Use the context object to access all global data.

Have the context object created from .net ctor (by p/invoking a new create_context function) and deleted by the .net Dispose() method.

Enjoy.


问:
Facebook Graph API, how to get users email?
I'm using the Graph API, but I can't figure out how to get a logged-in users email address.

The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday"

All well and good, but how do I access that info?

This is what I have so far:

```<code>$json = $facebook->api('/me');

$first = $json['first_name']; // gets first name
$last = $json['last_name'];
</code>```

答:
The following tools can be useful during development:

Access Token Debugger: Paste in an access token for details

https://developers.facebook.com/tools/debug/accesstoken/

Graph API Explorer: Test requests to the graph api after pasting in your access token

https://developers.facebook.com/tools/explorer

Body:
I'm using the Graph API, but I can't figure out how to get a logged-in users email address.

The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday"

All well and good, but how do I access that info?

This is what I have so far:

$json = $facebook->api('/me');

$first = $json['first_name']; // gets first name
$last = $json['last_name'];


问:
pandas.DataFrame.replace doesn't seems to work
I'm currently working on Kaggle's Titanic Survival Prediction.
There's a problem when I wanted to encode the 'Sex' feature to 0 or 1.
I've followed the official documentation on Pandas but it's does not help.

Edit: I've noticed that I wrote 'Male' instead of 'male' but still not working after i change to 'male'

Much Appreciated!

答:
Try this:

```<code>df['Sex'] = df['Sex'].replace(['male', 'female'], [1,0])
</code>```

or this

```<code>df['Sex'].replace(['male', 'female'], [1,0], inplace=True)
</code>```

The problem is that you've set inplace=True while performing an assignment. This will change the series in place (i.e., it will change the Series object itself), which returns None for the entire series, which is wrong. So put inplace=False, or make an assignment, but not both.
Using inplace=True changes the object and returns None, whereas inplace=False returns a new object.

Body:
Try this:

df['Sex'] = df['Sex'].replace(['male', 'female'], [1,0])

or this

df['Sex'].replace(['male', 'female'], [1,0], inplace=True)

The problem is that you've set inplace=True while performing an assignment. This will change the series in place (i.e., it will change the Series object itself), which returns None for the entire series, which is wrong. So put inplace=False, or make an assignment, but not both.
Using inplace=True changes the object and returns None, whereas inplace=False returns a new object.

ContentLicense: CC BY-SA 4.0


问:
Meteor: Force rendering an element
I have a generic template used several times in my app:

```<code><template name="genericCollapse">
  {{data-1}}
  <a href=# class='collapsed' data-toggle='collapse'
     data-target='#uniqueId'>Show/hide data-2</a>
  <div class='collapse' id='uniqueId'>
    {{data-2}}
  </div>
</template>
</code>```

By clicking somewhere else in the app, data-1 and data-2 change simultaneously (using Session Vars). However, in case the template is already on the screen, only data-1 and data-2 are changing but the collapse status of the div remains (obviously) unchanged. If it was open before, it remains open.

I want to achieve, that whenever data-1/data-2 changes, div as well as a are forced to be in status collapsed again.
I tried to add

```<code><a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})
</code>```

which is not only pretty ugly but also does not help, because the class of div still remains "collapse show" and even with a second helper for div, I can't get rid of "show".

Re-rendering the whole Template would be also acceptable, but I have difficulties to determine the parentNode for calling Blaze.render() - it is never the same - and I'm also not sure where to place such a call correctly.

How is this done?

答:
@Michel Floyd is right about fighting bootstrap.

However, since you said you're using Session vars, just use an autorun instead:

```<code>Template.genericCollapse.onRendered(function() {
  this.autorun(() => {
    const data1 = Session.get('data-1');
    const data2 = Session.get('data-2');
    if (data1 === someCondition || data2 === someOtherCondition) {
      this.$('.collapse').collapse('show');
    } else {
      this.$('.collapse').collapse('hide');
    }
});
</code>```

Any time either data-1 or data-2 changes, this function will re-run

Title: Meteor: Force rendering an element

Body:
I have a generic template used several times in my app:

<template name="genericCollapse">
  {{data-1}}
  Show/hide data-2

    {{data-2}}

</template>

By clicking somewhere else in the app, data-1 and data-2 change simultaneously (using Session Vars). However, in case the template is already on the screen, only data-1 and data-2 are changing but the collapse status of the div remains (obviously) unchanged. If it was open before, it remains open.

I want to achieve, that whenever data-1/data-2 changes, div as well as a are forced to be in status collapsed again.
I tried to add

<a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})

which is not only pretty ugly but also does not help, because the class of div still remains "collapse show" and even with a second helper for div, I can't get rid of "show".

Re-rendering the whole Template would be also acceptable, but I have difficulties to determine the parentNode for calling Blaze.render() - it is never the same - and I'm also not sure where to place such a call correctly.

How is this done?

Body:
@Michel Floyd is right about fighting bootstrap.

However, since you said you're using Session vars, just use an autorun instead:

Template.genericCollapse.onRendered(function() {
  this.autorun(() => {
    const data1 = Session.get('data-1');
    const data2 = Session.get('data-2');
    if (data1 === someCondition || data2 === someOtherCondition) {
      this.$('.collapse').collapse('show');
    } else {
      this.$('.collapse').collapse('hide');
    }
});

Any time either data-1 or data-2 changes, this function will re-run


问:
How to insert quotation marks properly into SQL Server in C# code behind
In SQL Server Management Studio, the query that I created is

```<code>CREATE TABLE MyTable
(
    EmployeeID int,
    EmployeeDivision varchar(25),
    EmployeeFName varchar(25),
    EmployeeLName varchar(25),
    EmployeeBudget1 int,
    EmployeeBudget2 int,
    EmployeeBudget3 int,
    EmployeeBudget4 int,
    EmployeeBudget5 int,
    EmployeeBudget6 int,
    EmployeeBudget7 int,
    EmployeeBudget8 int,
    EmployeeBudget9 int,
    EmployeeBudget10 int,
    EmployeeBudget11 int,
    EmployeeBudget12 int,
    EmployeeBudget13 int,
    EmployeeBudget14 int,
    EmployeeBudget15 int
);

INSERT INTO MyTable ('12345','DIVISION','FIRST','LAST','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' );
</code>```

My question is, how do I write this in C#?

I only created 4 set of textbox that will get that value of ID, Division, First Name, Last Name of each employee, and the rest will be null for Budgets 1-15

Here's my code:

```<code>SqlCommand cmd = new SqlCommand("insert into BUDGETTING_A values (' " + txtBoxEmpID.Text + "', + '" + cmbBoxDivision.Text + "','" + txtBoxFamilyName.Text + "', '" + txtBoxFirstName.Text + ' " +  '','','','','','','','','','','','','','','"')"+, con);
</code>```

I am having trouble in terms of doing this, any instructions in writing these off?

答:
If you dont have values dont specify them if they are nullable

```<code>INSERT INTO MyTable (EmployeeID ,EmployeeDivision ,EmployeeFName,EmployeeLName)
values ('12345','DIVISION','FIRST','LAST')
</code>```

Above query is just for your reference only. Write the query properly to work with db.

Body:
In SQL Server Management Studio, the query that I created is

CREATE TABLE MyTable
(
    EmployeeID int,
    EmployeeDivision varchar(25),
    EmployeeFName varchar(25),
    EmployeeLName varchar(25),
    EmployeeBudget1 int,
    EmployeeBudget2 int,
    EmployeeBudget3 int,
    EmployeeBudget4 int,
    EmployeeBudget5 int,
    EmployeeBudget6 int,
    EmployeeBudget7 int,
    EmployeeBudget8 int,
    EmployeeBudget9 int,
    EmployeeBudget10 int,
    EmployeeBudget11 int,
    EmployeeBudget12 int,
    EmployeeBudget13 int,
    EmployeeBudget14 int,
    EmployeeBudget15 int
);

INSERT INTO MyTable ('12345','DIVISION','FIRST','LAST','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' );

My question is, how do I write this in C#?

I only created 4 set of textbox that will get that value of ID, Division, First Name, Last Name of each employee, and the rest will be null for Budgets 1-15

Here's my code:

SqlCommand cmd = new SqlCommand("insert into BUDGETTING_A values (' " + txtBoxEmpID.Text + "', + '" + cmbBoxDivision.Text + "','" + txtBoxFamilyName.Text + "', '" + txtBoxFirstName.Text + ' " +  '','','','','','','','','','','','','','','"')"+, con);

I am having trouble in terms of doing this, any instructions in writing these off?

Body:
If you dont have values dont specify them if they are nullable

INSERT INTO MyTable (EmployeeID ,EmployeeDivision ,EmployeeFName,EmployeeLName)
values ('12345','DIVISION','FIRST','LAST')

Above query is just for your reference only. Write the query properly to work with db.


问:
autoClick at the same time error
i create two button in index.html. The two buttons will function differently. I'm trying to give the autoclick function to both, but I get an error.

```<code><html>

<head>
<script>
function autoClick(){
document.getElementById('linkToClick').click(); }
</script>

<script>
function autoClick(){
document.getElementById('linkToClick2').click();}
</script>
<head>

<body onload="setInterval('autoClick();',5000);">
<button  type="" id="showNotifications" >
<a id="linkToClick" target="_blank" >Bildirim yolla</a>
</button>
</body>

<body onload="setInterval('autoClick();',1000);">
<button  type="" id="showNotifications3" >
<a id="linkToClick2" target="_blank" >Bildirim</a>
</button>
</body>

</html>
</code>```

The two buttons are sending notifications. Haven't problem. But they are auto clicking at the same time. Why "showNotifications3" button doing an autoclick in 5 seconds, not in 1 second?

答:
You cannot have two js methods with same name. You can use something given below, Also I have removed two body tags.</p>

```<code><html>
<head>
<script>
function autoClick1(){
    // alert("1")
    document.getElementById('linkToClick').click();
}

function autoClick2(){
    // alert("2")
    document.getElementById('linkToClick2').click();
}
function callOnLoad(){
    setInterval('autoClick1();',5000);
    setInterval('autoClick2();',1000);
}
</script>
<head>

<body onload="Javascript: callOnLoad();">
<button  type="" id="showNotifications" >
<a id="linkToClick" target="_blank" >Bildirim yolla</a>
</button>
<button  type="" id="showNotifications3" >
<a id="linkToClick2" target="_blank" >Bildirim</a>
</button>
</body>

</html>
</code>```

Title: autoClick at the same time error

Body:
i create two button in index.html. The two buttons will function differently. I'm trying to give the autoclick function to both, but I get an error.

<button  type="" id="showNotifications" >
Bildirim yolla
</button>

<button  type="" id="showNotifications3" >
Bildirim
</button>

The two buttons are sending notifications. Haven't problem. But they are auto clicking at the same time. Why "showNotifications3" button doing an autoclick in 5 seconds, not in 1 second?

Body:
You cannot have two js methods with same name. You can use something given below, Also I have removed two body tags.

<html>
<head>
<script>
function autoClick1(){
    // alert("1")
    document.getElementById('linkToClick').click();
}

function autoClick2(){
    // alert("2")
    document.getElementById('linkToClick2').click();
}
function callOnLoad(){
    setInterval('autoClick1();',5000);
    setInterval('autoClick2();',1000);
}
</script>
<head>

<body onload="Javascript: callOnLoad();">
<button  type="" id="showNotifications" >
<a id="linkToClick" target="_blank" >Bildirim yolla</a>
</button>
<button  type="" id="showNotifications3" >
<a id="linkToClick2" target="_blank" >Bildirim</a>
</button>
</body>

</html>


问:
How to write and model a Reusable Business Logic in React Native
I have to develop 5 different mobile applications using React Native.
The Business requirements behind the applications are the same and they should connect to the same RESTful api, but each one of them will have a different UI/UX to fulfill a branding requirements.
What is the best practice to achieve extreme reusable business logic code for the applications.

Should I make the Redux as external node package and import it in each application, or should I merge the applications in one huge codebase and use a different nodejs script to build each one of them ?

答:
My advise would be to separate business logic. As you are planning to use Redux, you can create models and services into a separate package and import it wherever you need.

Models - define state, contain reducers and effects.
Services - actual functions to call RestFul APIs.

The Model <--> Services approach is very useful because they are not at all doing any UI stuff.

See an example of Model and Service below:

Model:

```<code>import {
  addPayment
} from '../services/paymentService'

import {
  updateAge
} from '../services/profileService'

export default {
  namespace: 'myProfile',
  state: {
     age
     },

  reducers: {
    set: (state, {payload: details}) => {
      return ({...state, ...details})
    },
  },
  effects: {
    *getAge (action, { call, put, simplePut }) {
      const {payload: age} = action
      try {
        const res = yield call(upadteAge, age)
        const { status } = res
        if (status === 200) {
          const json = yield res.json()
          yield simplePut('set', json)
        }
      } catch (error) {
        console.log(error)
      }
    },
  }
</code>```

Service:

```<code>export function updateAge ({age}) {
  return fetch('apiurl?age=' + age, {
    method: 'POST',
    headers: {
    }
  })
}
</code>```

I recently completed an application in which I have used the above approach and it worked like a charm.

Body:
My advise would be to separate business logic. As you are planning to use Redux, you can create models and services into a separate package and import it wherever you need.

Models - define state, contain reducers and effects.
Services - actual functions to call RestFul APIs.

The Model <--> Services approach is very useful because they are not at all doing any UI stuff.

See an example of Model and Service below:

Model:

import {
  addPayment
} from '../services/paymentService'

import {
  updateAge
} from '../services/profileService'

export default {
  namespace: 'myProfile',
  state: {
     age
     },

  reducers: {
    set: (state, {payload: details}) => {
      return ({...state, ...details})
    },
  },
  effects: {
    *getAge (action, { call, put, simplePut }) {
      const {payload: age} = action
      try {
        const res = yield call(upadteAge, age)
        const { status } = res
        if (status === 200) {
          const json = yield res.json()
          yield simplePut('set', json)
        }
      } catch (error) {
        console.log(error)
      }
    },
  }

Service:

export function updateAge ({age}) {
  return fetch('apiurl?age=' + age, {
    method: 'POST',
    headers: {
    }
  })
}

I recently completed an application in which I have used the above approach and it worked like a charm.


问:
How to change size of polygon stroke using Mapbox Android SDK
I am trying to increase the width of the 1px stroke around the outside of a polygon using Mapbox Android SDK version 4.2.0.beta4.

First I tried using the PolygonOptions but there was no option available.

```<code>public Polygon addPolygon(MapboxMap mapboxMap) {
    PolygonOptions polygonOptions = new PolygonOptions()
                    .addAll(latLngs)
                    .alpha(ALPHA_UNSELECTED)
                    .fillColor(FILL_COLOR)
                    .strokeColor(BORDER_COLOR);

    // no option for stroke width

    return mapboxMap.addPolygon(polygonOptions);
}
</code>```

I then tried using the using the new Runtime Style API as defined in the Style Spec but could not find a suitable layer ID, I tried "background"
https://www.mapbox.com/mapbox-gl-style-spec/

```<code>public void changeStrokeWidth(MapboxMap mapboxMap) {
        Layer styleLayer = mapboxMap.getLayer("background");

        styleLayer.setProperties(PropertyFactory.lineWidth(10f));
}
</code>```

Does anyone know how to make this work or do I just have to create my own set of polylines over the top of the polygon to emulate the behaviour?

答:
```<code>//Hi, Guys. Below is the simple example to change the properties of polygon border. Hope it will help you.//

{

List<LatLng> plotPolygon = new ArrayList<>();

List<com.mapbox.services.commons.models.Position> coordinates  = new ArrayList<>();

                    plotPolygon.add(new LatLng(18.9965099,75.7316343));
                    plotPolygon.add(new LatLng(20.8858018,74.7288414));
                    plotPolygon.add(new LatLng(21.1612315,79.0024702));
                    plotPolygon.add(new LatLng(18.7918749,78.899195));
                    plotPolygon.add(new LatLng(18.9965099,75.7316343));

                    Polygon polygon1 = mapboxMap.addPolygon(new PolygonOptions()
                            .addAll(plotPolygon)
                    );
                    polygon1.setFillColor(Color.parseColor("#3bb2d0"));
</code>```

Below we are creating a list of coordinates of polygon border.

```<code>                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(75.7316343 , 18.9965099));
                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(74.7288414 , 20.8858018));
                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(79.0024702 , 21.1612315));
                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(78.899195 , 18.7918749));
                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(75.7316343 , 18.9965099));

changeStrokeProperties(mapboxMap , coordinates);

}

public void changeStrokeProperties(MapboxMap mapboxMap , List<com.mapbox.services.commons.models.Position> coordinates) {

// Create the LineString from the list of coordinates and then make a GeoJSON//
// FeatureCollection so we can add the line to our map as a layer.//

    final Feature lineFeature =     Feature.fromGeometry(LineString.fromCoordinates(coordinates));

        final GeoJsonSource source = new GeoJsonSource(
                "route", FeatureCollection.fromFeatures(new Feature[] { lineFeature }));

            mapboxMap.addSource(source);

            LineLayer lineLayer = new LineLayer("linelayer", "route");

            lineLayer.setProperties(
                    PropertyFactory.lineDasharray(new Float[]{0.01f, 2f}),
                    PropertyFactory.lineCap(Property.LINE_CAP_ROUND),
                    PropertyFactory.lineJoin(Property.LINE_JOIN_ROUND),
                    PropertyFactory.lineWidth(5f),
                    PropertyFactory.lineColor(Color.parseColor("#e55e5e"))

            );
            mapboxMap.addLayer(lineLayer);

    }
</code>```

Body:
I am trying to increase the width of the 1px stroke around the outside of a polygon using Mapbox Android SDK version 4.2.0.beta4.

First I tried using the PolygonOptions but there was no option available.

public Polygon addPolygon(MapboxMap mapboxMap) {
    PolygonOptions polygonOptions = new PolygonOptions()
                    .addAll(latLngs)
                    .alpha(ALPHA_UNSELECTED)
                    .fillColor(FILL_COLOR)
                    .strokeColor(BORDER_COLOR);

    // no option for stroke width

    return mapboxMap.addPolygon(polygonOptions);
}

I then tried using the using the new Runtime Style API as defined in the Style Spec but could not find a suitable layer ID, I tried "background"
https://www.mapbox.com/mapbox-gl-style-spec/

public void changeStrokeWidth(MapboxMap mapboxMap) {
        Layer styleLayer = mapboxMap.getLayer("background");

        styleLayer.setProperties(PropertyFactory.lineWidth(10f));
}

Does anyone know how to make this work or do I just have to create my own set of polylines over the top of the polygon to emulate the behaviour?

Body:
//Hi, Guys. Below is the simple example to change the properties of polygon border. Hope it will help you.//

{

List<LatLng> plotPolygon = new ArrayList<>();

List<com.mapbox.services.commons.models.Position> coordinates  = new ArrayList<>();

                    plotPolygon.add(new LatLng(18.9965099,75.7316343));
                    plotPolygon.add(new LatLng(20.8858018,74.7288414));
                    plotPolygon.add(new LatLng(21.1612315,79.0024702));
                    plotPolygon.add(new LatLng(18.7918749,78.899195));
                    plotPolygon.add(new LatLng(18.9965099,75.7316343));

                    Polygon polygon1 = mapboxMap.addPolygon(new PolygonOptions()
                            .addAll(plotPolygon)
                    );
                    polygon1.setFillColor(Color.parseColor("#3bb2d0"));

Below we are creating a list of coordinates of polygon border.

                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(75.7316343 , 18.9965099));
                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(74.7288414 , 20.8858018));
                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(79.0024702 , 21.1612315));
                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(78.899195 , 18.7918749));
                    coordinates.add(com.mapbox.services.commons.models.Position.fromCoordinates(75.7316343 , 18.9965099));

changeStrokeProperties(mapboxMap , coordinates);

}

public void changeStrokeProperties(MapboxMap mapboxMap , List<com.mapbox.services.commons.models.Position> coordinates) {

// Create the LineString from the list of coordinates and then make a GeoJSON//
// FeatureCollection so we can add the line to our map as a layer.//

    final Feature lineFeature =     Feature.fromGeometry(LineString.fromCoordinates(coordinates));

        final GeoJsonSource source = new GeoJsonSource(
                "route", FeatureCollection.fromFeatures(new Feature[] { lineFeature }));

            mapboxMap.addSource(source);

            LineLayer lineLayer = new LineLayer("linelayer", "route");

            lineLayer.setProperties(
                    PropertyFactory.lineDasharray(new Float[]{0.01f, 2f}),
                    PropertyFactory.lineCap(Property.LINE_CAP_ROUND),
                    PropertyFactory.lineJoin(Property.LINE_JOIN_ROUND),
                    PropertyFactory.lineWidth(5f),
                    PropertyFactory.lineColor(Color.parseColor("#e55e5e"))

            );
            mapboxMap.addLayer(lineLayer);

    }


问:
Spring Configuration Server Cloud setup
I am using Spring Configuration server and currently my configurations are in git as per the documentations for configuration server. Now my problem is that my prod and stage env does not have access to git hence getting the properties from git directly is a problem as my git is hosted on prem.
The solution which I found is that to include all my properties in configuration server image itself (We have a docker image for each application including config server) . This is something which I dont want to do as this will require a new image deployment everytime the confgiuration value changes which is not the ideal use for configuration store. I can use a GCP bucket some other solution which can be used on Google Cloud and where I can deploy as a build packet.

Thanks,

Amol

答:
Here is what I did.

Used config server can access git either by URL or a system location.

I mounted a google cloud bucket on the server my application is running on using gcsfuse(I am using kubernetes and added gcsfuse inside container) and used that as a repo location in config server url like below

spring.cloud.config.server.git.repos.my-app.uri=file://${configuration.store.path}

Create a process(Jenkins job) inside my network which has access to git and mounted the same GCS bucket here as well. The Job keeps updating the bucket with the latest config from repo and it is automatically available to my Server.

Title: Spring Configuration Server Cloud setup


问:
Ruby group_by object?
I have an array or different objects and I want to group by objects. For example

```<code> => [#<Graphic id: 3...">, #<Collection id: 1....">, #<Category id:...">, #<Volume id: 15...">]
 all.size
 => 4
</code>```

I tried

```<code>all.group_by(Object)
</code>```

but that didn't work...any ideas on how to groupby objects in one array?

答:
Are you looking to do something like this?

```<code>all.group_by(&:class)
</code>```

Which will group the objects in array by their class name

EDIT for comment

```<code>all.group_by(&:class).each do |key, group|
   group.each{|item| puts item}
end
</code>```

Key is the grouping element and obj is the collection for the key, so this would loop through each group in the grouping and list the objects within that group

Also you could sort within the groupings pretty easily too

```<code>all.group_by(&:class).each do |key, group|
    group.sort_by(&:attribute).each{|item| puts item}
end
</code>```

Title: Ruby group_by object?

Body:
I have an array or different objects and I want to group by objects. For example

 => [#<Graphic id: 3...">, #<Collection id: 1....">, #<Category id:...">, #<Volume id: 15...">]
 all.size
 => 4

I tried

all.group_by(Object)

but that didn't work...any ideas on how to groupby objects in one array?

Body:
Are you looking to do something like this?

all.group_by(&:class)

Which will group the objects in array by their class name

EDIT for comment

all.group_by(&:class).each do |key, group|
   group.each{|item| puts item}
end

Key is the grouping element and obj is the collection for the key, so this would loop through each group in the grouping and list the objects within that group

Also you could sort within the groupings pretty easily too

all.group_by(&:class).each do |key, group|
    group.sort_by(&:attribute).each{|item| puts item}
end


答:
You could leverage a couple of css animations: one for the initial dropdown, the other for the fade out.

.dropdown-notification {
  height: 25vh;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  line-height: 40px;
  background-color: #4CAF50;
  animation: welcome-dropdown 2s ease, welcome-fadeout 1s 3s forwards;
}

@keyframes welcome-dropdown {
  from {
    transform: translateY(calc(-100vh));
  }
  to {
    transform: translateY(0);
  }
}

@keyframes welcome-fadeout {
  from {
    opacity: 1;
  }

  to {
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown-notification text-center">
  Hi, I'm a drop down <button class="close">Close</button>
</div></code>```

Title: Dropdown Banner

Body:
How can I get a drop down banner for my website so that when a user goes to my home page a banner will drop down, cover a fourth of the page, and say something like, "Welcome too...." and then after a few seconds close

I've tried

      Hi, I'm a drop down <button class="close">Close</button>

but I can't get the banner to go across the screen over or change the banner color to something more colorful.Thanks in advance for your help and please understand I am still very new at this so any advice would be much appreciated!

Body:
You could leverage a couple of css animations: one for the initial dropdown, the other for the fade out.

.dropdown-notification {
  height: 25vh;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  line-height: 40px;
  background-color: #4CAF50;
  animation: welcome-dropdown 2s ease, welcome-fadeout 1s 3s forwards;
}

@keyframes welcome-dropdown {
  from {
    transform: translateY(calc(-100vh));
  }
  to {
    transform: translateY(0);
  }
}

@keyframes welcome-fadeout {
  from {
    opacity: 1;
  }

  to {
    opacity: 0;
  }
}

<div class="dropdown-notification text-center">
  Hi, I'm a drop down <button class="close">Close</button>
</div>