问:
Exporting environment variables for local development and heroku deployment
I would like to setup some files for development, staging and production with environment variables, for example:

application_root/development.env

```<code>KEY1=value1
KEY2=value2
</code>```

There would be similar files staging.env and production.env.

I am looking for a couple different bash scripts which would allow the loading of all these variables in either development or staging/production.

In local development I want to effectively run export KEY1=value1 for each line in the file.

For staging/production I will be deploying to Heroku and would like to effectively run heroku config:set -a herokuappname KEY1=value1 for each line in the staging or production.env files.

I know there are some gems designed for doing this but it seems like this might be pretty simple. I also like the flexibility of having the .env files as simple lists of keys and values and not specifically being tied to any language/framework. If I would have to change something about the way these variables need to be loaded it would be a matter of changing the script but not the .env files.

答:
In the simplest form, you can load the key-value pairs into a bash array as follows:

```<code>IFS=$'\n' read -d '' -ra nameValuePairs < ./development.env
</code>```

In Bash v4+, it's even simpler:

```<code>readarray -t nameValuePairs < ./development.env
</code>```

You can then pass the resulting "${nameValuePairs[@]}" array to commands such as export or heroku config:set ...; e.g.:

```<code>export "${nameValuePairs[@]}"
</code>```

Note, however, that the above only works as intended if the input *.env file meets all of the following criteria:

the keys are syntactically valid shell variable names and the lines have the form <key>=<value>, with no whitespace around =

the lines contain no quoting and no leading or trailing whitespace

there are no empty/blank lines or comment lines in the file.

the values are confined to a single line each.

A different approach is needed with files that do not adhere to this strict format; for instance, this related question deals with files that may contain quoted values.

Below is the source code for a bash script named load_env (the .sh suffix is generally not necessary and ambiguous):

You'd invoke it with the *.env file of interest, and it would perform the appropriate action (running heroku config:set … or export) based on the filename.

However, as stated, you must source the script (using source or its effective bash alias, .) in order to create environment variables (export) visible to the current shell.

To prevent obscure failures, the script complains if you pass a development.env file and have invoked the script without sourcing.

Examples:

```<code>./load_env ./staging.dev
. ./load_env ./development.dev   # !! Note the need to source
</code>```

load_env source code

```<code>#!/usr/bin/env bash

# Helper function that keeps its aux. variables localized.
# Note that the function itself remains defined after sourced invocation, however.
configOrExport() {

  local envFile=$1 doConfig=0 doExport=0 appName

  case "$(basename "$envFile" '.env')" in
    staging)
      doConfig=1
      # Set the desired app name here.
      appName=stagingapp
      ;;
    production)
      doConfig=1
      # Set the desired app name here.
      appName=productionapp
      ;;
    development)
      doExport=1
      ;;
    *)
      echo "ERROR: Invalid or missing *.env file name: $(basename "$envFile" '.env')" >&2; exit 2
  esac

  # Make sure the file exists and is readable.
  [[ -r "$envFile" ]] || { echo "ERROR: *.env file not found or not readable: $envFile" >&2; exit 2; }

  # If variables must be exported, make sure the script is being sourced.
  [[ $doExport -eq 1 && $0 == "$BASH_SOURCE" ]] && { echo "ERROR: To define environment variables, you must *source* this script." >&2; exit 2; }

  # Read all key-value pairs from the *.env file into an array.
  # Note: This assumes that:
  #        - the keys are syntactically valid shell variable names
  #        - the lines contain no quoting and no leading or trailing whitespace
  #        - there are no empty/blank lines or comment lines in the file.
  IFS=$'\n' read -d '' -ra nameValuePairs < "$envFile"

  # Run configuration command.
  (( doConfig )) && { heroku config:set -a "$appName" "${nameValuePairs[@]}" || exit; }

  # Export variables (define as environment variables).
  (( doExport )) && { export "${nameValuePairs[@]}" || exit; }

}

# Invoke the helper function.
configOrExport "$@"
</code>```

Body:
I would like to setup some files for development, staging and production with environment variables, for example:

application_root/development.env

KEY1=value1
KEY2=value2

There would be similar files staging.env and production.env.

I am looking for a couple different bash scripts which would allow the loading of all these variables in either development or staging/production.

In local development I want to effectively run export KEY1=value1 for each line in the file.

For staging/production I will be deploying to Heroku and would like to effectively run heroku config:set -a herokuappname KEY1=value1 for each line in the staging or production.env files.

I know there are some gems designed for doing this but it seems like this might be pretty simple. I also like the flexibility of having the .env files as simple lists of keys and values and not specifically being tied to any language/framework. If I would have to change something about the way these variables need to be loaded it would be a matter of changing the script but not the .env files.

Body:
In the simplest form, you can load the key-value pairs into a bash array as follows:

IFS=$'\n' read -d '' -ra nameValuePairs < ./development.env

In Bash v4+, it's even simpler:

readarray -t nameValuePairs < ./development.env

You can then pass the resulting "${nameValuePairs[@]}" array to commands such as export or heroku config:set ...; e.g.:

export "${nameValuePairs[@]}"

Note, however, that the above only works as intended if the input *.env file meets all of the following criteria:

the keys are syntactically valid shell variable names and the lines have the form <key>=<value>, with no whitespace around =

the lines contain no quoting and no leading or trailing whitespace

there are no empty/blank lines or comment lines in the file.

the values are confined to a single line each.

A different approach is needed with files that do not adhere to this strict format; for instance, this related question deals with files that may contain quoted values.

Below is the source code for a bash script named load_env (the .sh suffix is generally not necessary and ambiguous):

You'd invoke it with the *.env file of interest, and it would perform the appropriate action (running heroku config:set … or export) based on the filename.

However, as stated, you must source the script (using source or its effective bash alias, .) in order to create environment variables (export) visible to the current shell.

To prevent obscure failures, the script complains if you pass a development.env file and have invoked the script without sourcing.

Examples:

./load_env ./staging.dev
. ./load_env ./development.dev   # !! Note the need to source

load_env source code

#!/usr/bin/env bash

# Helper function that keeps its aux. variables localized.
# Note that the function itself remains defined after sourced invocation, however.
configOrExport() {

  local envFile=$1 doConfig=0 doExport=0 appName

  case "$(basename "$envFile" '.env')" in
    staging)
      doConfig=1
      # Set the desired app name here.
      appName=stagingapp
      ;;
    production)
      doConfig=1
      # Set the desired app name here.
      appName=productionapp
      ;;
    development)
      doExport=1
      ;;
    *)
      echo "ERROR: Invalid or missing *.env file name: $(basename "$envFile" '.env')" >&2; exit 2
  esac

  # Make sure the file exists and is readable.
  [[ -r "$envFile" ]] || { echo "ERROR: *.env file not found or not readable: $envFile" >&2; exit 2; }

  # If variables must be exported, make sure the script is being sourced.
  [[ $doExport -eq 1 && $0 == "$BASH_SOURCE" ]] && { echo "ERROR: To define environment variables, you must *source* this script." >&2; exit 2; }

  # Read all key-value pairs from the *.env file into an array.
  # Note: This assumes that:
  #        - the keys are syntactically valid shell variable names
  #        - the lines contain no quoting and no leading or trailing whitespace
  #        - there are no empty/blank lines or comment lines in the file.
  IFS=$'\n' read -d '' -ra nameValuePairs < "$envFile"

  # Run configuration command.
  (( doConfig )) && { heroku config:set -a "$appName" "${nameValuePairs[@]}" || exit; }

  # Export variables (define as environment variables).
  (( doExport )) && { export "${nameValuePairs[@]}" || exit; }

}

# Invoke the helper function.
configOrExport "$@"


来源: stackexchange

问:
How to overwrite method from interface?
I have an interface:

```<code>interface ISqlite
{
     DataTable select(SQLiteDatabase db);
}
</code>```

And realization it:

```<code>public DataTable select(ISqlite s) {

    return s.select(driver);

}
</code>```

As you can see method select is described with DataTable type in return.

How do I overwite this method so that it doesn't return a DataTable, but rather an Array or any other type?

I mean the following:

```<code>public Array select(ISqlite s) {

    return s.select(driver);

}
</code>```

答:
You can't change  the return type of a method (ie "override" as you wrote in your question)
consider using abstract class if you dont need to inherit another class, you will have the Ability to specify default implementations of methods.

you will need to write a separate method for each return type.

ContentLicense: CC BY-SA 3.0

Title: How to overwrite method from interface?

Body:
I have an interface:

interface ISqlite
{
     DataTable select(SQLiteDatabase db);
}

And realization it:

public DataTable select(ISqlite s) {

    return s.select(driver);

}

As you can see method select is described with DataTable type in return.

How do I overwite this method so that it doesn't return a DataTable, but rather an Array or any other type?

I mean the following:

public Array select(ISqlite s) {

    return s.select(driver);

}


问:
python3 sort object list by attr same values
I have a problem with my sorting method.

This is my object contained in list:
Address class, with city attribute

My list looklike (simplified) :

```<code>[Address('Paris'), Address('Denver'), Address('Paris'), Address('Test'), Address('Denver')]
</code>```

For this example, i have two duplicates cities: Paris and Denver,

I want to have a result like:

```<code>[Address('Devenr'), Address('Denver'), Address('Paris'), Address('Paris'), Address('Test')]
</code>```

Sorted by duplicates count, and in case of same number, by alphanumeric order.

I tried:

```<code>self.dictionnary.sort(key=lambda address: len([x for x in self.dictionnary if address.city == x.city]))
</code>```

By this don't work...

Can anyone help me?

Thank you in advance !

答:
```<code>import collections
counts = collections.Counter(address.city for address in self.dictionnary)
self.dictionnary.sort(key=lambda address: (-counts[address.city], address.city))
</code>```

By using Counter to count the duplicates in a separate step, you save the overhead of scanning the list each time you need a new key. This can make a big difference in the run time for a long list. The key then becomes a tuple; by taking the negative of the count, the larger counts will come first in the sort order. The second part of the tuple, the city name itself, will only be considered when the counts are equal.

Body:
I have a problem with my sorting method.

This is my object contained in list:
Address class, with city attribute

My list looklike (simplified) :

[Address('Paris'), Address('Denver'), Address('Paris'), Address('Test'), Address('Denver')]

For this example, i have two duplicates cities: Paris and Denver,

I want to have a result like:

[Address('Devenr'), Address('Denver'), Address('Paris'), Address('Paris'), Address('Test')]

Sorted by duplicates count, and in case of same number, by alphanumeric order.

I tried:

self.dictionnary.sort(key=lambda address: len([x for x in self.dictionnary if address.city == x.city]))

By this don't work...

Can anyone help me?

Thank you in advance !

Body:
import collections
counts = collections.Counter(address.city for address in self.dictionnary)
self.dictionnary.sort(key=lambda address: (-counts[address.city], address.city))

By using Counter to count the duplicates in a separate step, you save the overhead of scanning the list each time you need a new key. This can make a big difference in the run time for a long list. The key then becomes a tuple; by taking the negative of the count, the larger counts will come first in the sort order. The second part of the tuple, the city name itself, will only be considered when the counts are equal.


问:
c strcmp source code
```<code>int strcmp(const char *s1, const char *s2)

{
  int ret = 0;

  while (!(ret = *(unsigned char *) s1 - *(unsigned char *) s2) && *s2) ++s1, ++s2;

  if (ret < 0)

    ret = -1;
  else if (ret > 0)

    ret = 1 ;

  return ret;
}
</code>```

I review the code from : http://www.jbox.dk/sanos/source/lib/string.c.html

I suppose that there're some problem.
If strlen(s2)>strlen(s1),then ++s1 may beyond the range. Unfortunately, then the function return error.

答: No, there's no such problem since the loop continues only while *s1 and *s2 are equal and *s2 is not 0. If s1 is shorter, once it gets to the \0 at the end of s1, the equality condition would break and the loop would stop.

ContentLicense: CC BY-SA 2.5

Title: c strcmp source code

Body:
int strcmp(const char *s1, const char *s2)

{
  int ret = 0;

  while (!(ret = *(unsigned char *) s1 - *(unsigned char *) s2) && *s2) ++s1, ++s2;

  if (ret < 0)

    ret = -1;
  else if (ret > 0)

    ret = 1 ;

  return ret;
}

I review the code from : http://www.jbox.dk/sanos/source/lib/string.c.html

I suppose that there're some problem.
If strlen(s2)>strlen(s1),then ++s1 may beyond the range. Unfortunately, then the function return error.


问:
NameNode startup error: No FileSystem for scheme: ht
I'm in HDP 2.6. When I try to start the NameNode I get the bellow error:

```<code>java.io.IOException: No FileSystem for scheme: http
        at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2786)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2793)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:99)
</code>```

and when I try hdfs ls command:

```<code>[hdfs@ambariserver ambari-agent]$ hdfs dfs -ls /
ls: No FileSystem for scheme: http
</code>```

Any suggestion?

答: The "No FileSystem for scheme: http" error occurs when fs.defaultFS property value in core-site.xml uses http protocol (instead of hdfs) i.e. value look like http://<host>:<port>.  Correct value is hdfs://<host>:<port>

Body:
I'm in HDP 2.6. When I try to start the NameNode I get the bellow error:

java.io.IOException: No FileSystem for scheme: http
        at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2786)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2793)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:99)

and when I try hdfs ls command:

[hdfs@ambariserver ambari-agent]$ hdfs dfs -ls /
ls: No FileSystem for scheme: http

Any suggestion?


问:
Can I write abc.ABC without resorting to metaclasses in Python 3.6?
Python 3.6 added PEP 487, which adds an __init_subclass__ method among other things.  Is it possible to write a version of ABC that doesn't use a metaclass?

答:
If all you care about is the check for abstract methods, then yes. Just move the abstract method set computation to the __init_subclass__ method:

```<code>def __init_subclass__(cls, **kwargs):
    super().__init_subclass__(**kwargs)
    # Compute set of abstract method names
    abstracts = {name
                 for name, value in vars(cls).items()
                 if getattr(value, "__isabstractmethod__", False)}
    for base in cls.__bases__:
        for name in getattr(base, "__abstractmethods__", set()):
            value = getattr(cls, name, None)
            if getattr(value, "__isabstractmethod__", False):
                abstracts.add(name)
    cls.__abstractmethods__ = frozenset(abstracts)
</code>```

The base object.__new__ implementation then uses an non-empty __abstractmethods__ set to prevent instantiation.

But ABCs also support virtual subclass registration; the two hook methods this requires have to be implemented on the metaclass.

Body:
If all you care about is the check for abstract methods, then yes. Just move the abstract method set computation to the __init_subclass__ method:

def __init_subclass__(cls, **kwargs):
    super().__init_subclass__(**kwargs)
    # Compute set of abstract method names
    abstracts = {name
                 for name, value in vars(cls).items()
                 if getattr(value, "__isabstractmethod__", False)}
    for base in cls.__bases__:
        for name in getattr(base, "__abstractmethods__", set()):
            value = getattr(cls, name, None)
            if getattr(value, "__isabstractmethod__", False):
                abstracts.add(name)
    cls.__abstractmethods__ = frozenset(abstracts)

The base object.__new__ implementation then uses an non-empty __abstractmethods__ set to prevent instantiation.

But ABCs also support virtual subclass registration; the two hook methods this requires have to be implemented on the metaclass.


问:
change color of button when carousel slide linked to it is clicked
I have a bootstrap carousel and a range of buttons on top it which represent certain services provided by an organization. I am trying to achieve 2 things here:

(This one is done) When user clicks on button A, then slide linked to button A appears and the color of button A changes indicating that its active.

(Having problem here) When slide A changes from slide B or whichever, then color of button A (which is linked to slide A) should automatically change indicating that its respective slide has been clicked.

As you can see in this image, when button clicked it turns blue and slide linked to it appears

But here, when I change the slide by using next/prev controllers, buttons are not activated

This is what my code looks like

```<code>    <nav1>
        <ul class="nav1">
            <li><a href="#" data-target="#myCarousel1" data-slide-to="0" class="image1"></a>
            <h4>Analytics & <br> Optimization</li>

            <li><a href="#" data-target="#myCarousel1" data-slide-to="1" class="image2"></a>
            <h4>Design<br> Services</h4></li>

            <li><a href="#" data-target="#myCarousel1" data-slide-to="2" class="image4"></a>
            <h4>Web & Mobile<br> Technology</h4></li>

            <li><a href="#" data-target="#myCarousel1" data-slide-to="3" class="image3"></a>
            <h4>Online <br> Marketing</h4></li>

            <li><a href="#" data-target="#myCarousel1" data-slide-to="4" class="image5"></a>
            <h4>Cyber<br> Security</h4></li>

            <li><a href="#" data-target="#myCarousel1" data-slide-to="5" class="image6"></a>
            <h4>Digital<br> Transformation</h4></li>
        </ul>
    </nav1>

    <div id="myCarousel1" class="carousel slide" data-ride="carousel" data-interval="false">
        <!-- Wrapper for slides -->
        <div class="carousel-inner">
    <div class="item active">
            <div class="clearfix"><img class="img2" src="assets/images/analysis.png">
        </div>
          </div>
</div>
</code>```

so on..

Style:

```<code>  .nav1 a:active, .nav1 a:focus {
  text-decoration: none;
  color: #8C9EFF;
  background: #80D8FF;
}
</code>```

I believe its got to do with slide.bs function but I am not able to figure out how!

答:
A Javascript example. This is limited as I don't have all the code.

Your going to tie into the slide action of the carousel then find the correct instance of the image class and add the active class to it and find the one with the active class already and remove it.

```<code>`$('#myCarousel1').on('slid.bs.carousel', function (event) {
    var nextactiveslide = $(event.relatedTarget).index();
    var $btns = $(".nav1");
    var $active = $btns.find("[data-slide-to='" + nextactiveslide + "']");
    $btns.find("div[class^='image']").removeClass("active");
    $active.find("div[class^='image']").addClass("active");
});`
</code>```

Note the orginal solution came from How to change customized carousel indicator background color? I just modified it to use your classes and IDs.

Body:
I have a bootstrap carousel and a range of buttons on top it which represent certain services provided by an organization. I am trying to achieve 2 things here:

(This one is done) When user clicks on button A, then slide linked to button A appears and the color of button A changes indicating that its active.

(Having problem here) When slide A changes from slide B or whichever, then color of button A (which is linked to slide A) should automatically change indicating that its respective slide has been clicked.

As you can see in this image, when button clicked it turns blue and slide linked to it appears

But here, when I change the slide by using next/prev controllers, buttons are not activated

This is what my code looks like

    <nav1>

Analytics &
 Optimization

Design
 Services

Web & Mobile
 Technology

Online
 Marketing

Cyber
 Security

Digital
 Transformation

    </nav1>

so on..

Style:

  .nav1 a:active, .nav1 a:focus {
  text-decoration: none;
  color: #8C9EFF;
  background: #80D8FF;
}

I believe its got to do with slide.bs function but I am not able to figure out how!

Body:
A Javascript example. This is limited as I don't have all the code.

Your going to tie into the slide action of the carousel then find the correct instance of the image class and add the active class to it and find the one with the active class already and remove it.

`$('#myCarousel1').on('slid.bs.carousel', function (event) {
    var nextactiveslide = $(event.relatedTarget).index();
    var $btns = $(".nav1");
    var $active = $btns.find("[data-slide-to='" + nextactiveslide + "']");
    $btns.find("div[class^='image']").removeClass("active");
    $active.find("div[class^='image']").addClass("active");
});`

Note the orginal solution came from How to change customized carousel indicator background color? I just modified it to use your classes and IDs.


问:
How can I orient divs properly within another div?
I am trying to create a side bar with an animated menu button.  I found an example online of the button I imagined and am trying to use it correctly but cant seem to get it where I want on my page. Why do the three divs that make up the animated button appear to the right of the trapezoid and not within it?

    #trap {
     position: absolute;
     left: 0px;
     top; 0px;
     height: 38px;
     width: 40px;
     border-left: 40px solid black;
     border-bottom: 5px solid transparent;
     border-top: 5px solid transparent;
     margin-left: 0;
     transition: 0.5s;
    }

    .container {
        display: inline-block;
        cursor: pointer;
    }

    .bar1, .bar2, .bar3 {
        width: 35px;
        height: 5px;
        background-color: #A4A4A4;
        margin: 6px 0;
        transition: 0.4s;
    }

    .change .bar1 {
        -webkit-transform: rotate(-45deg) translate(-9px, 6px) ;
        transform: rotate(-45deg) translate(-9px, 6px) ;
    }

    .change .bar2 {opacity: 0;}

    .change .bar3 {
        -webkit-transform: rotate(45deg) translate(-8px, -8px) ;
        transform: rotate(45deg) translate(-8px, -8px) ;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="trap" class="container" onclick="toggleNav(this)">
     <div class="bar1"></div>
     <div class="bar2"></div>
     <div class="bar3"></div>
    </div></code>```

答:
The #trap's border-left is pushing the bars to the right. One possible solution is to move the bars back left using position:relative.

UPDATE: the ghost-element was caused by the fact that you have both a border-width and a width on the #trap element. Because browsers' default is to not include the border's width in the width calculation, both were taken into account.

The simplest solution would be just to change width: 40px to width:0px, so that the border's width definition is the only one that's used, but my preferred situation (updated in the snippet) is to change the box-sizing property to border-box. This causes the width property to take into account the element's border width, so the two properties don't add to each other. I also had to increase the height to prevent the bottom from being clipped off.

#trap {
     position: absolute;
     left: 0px;
     top; 0px;
     height: 38px;
     width: 40px;
      box-sizing: border-box;
     border-left: 40px solid black;
     border-bottom: 5px solid transparent;
     border-top: 5px solid transparent;
     margin-left: 0;
     transition: 0.5s;
    }

    .container {
        display: inline-block;
        cursor: pointer;
    }

    .bar1, .bar2, .bar3 {
        width: 35px;
        height: 5px;
        background-color: #A4A4A4;
        margin: 6px 0;
        transition: 0.4s;
        left:-35px;
        position:relative;
    }

    .change .bar1 {
        -webkit-transform: rotate(-45deg) translate(-9px, 6px) ;
        transform: rotate(-45deg) translate(-9px, 6px) ;
    }

    .change .bar2 {opacity: 0;}

    .change .bar3 {
        -webkit-transform: rotate(45deg) translate(-8px, -8px) ;
        transform: rotate(45deg) translate(-8px, -8px) ;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="trap" class="container" onclick="toggleNav(this)">
     <div class="bar1"></div>
     <div class="bar2"></div>
     <div class="bar3"></div>
    </div></code>```

Body:
The #trap's border-left is pushing the bars to the right. One possible solution is to move the bars back left using position:relative.

UPDATE: the ghost-element was caused by the fact that you have both a border-width and a width on the #trap element. Because browsers' default is to not include the border's width in the width calculation, both were taken into account.

The simplest solution would be just to change width: 40px to width:0px, so that the border's width definition is the only one that's used, but my preferred situation (updated in the snippet) is to change the box-sizing property to border-box. This causes the width property to take into account the element's border width, so the two properties don't add to each other. I also had to increase the height to prevent the bottom from being clipped off.

#trap {
     position: absolute;
     left: 0px;
     top; 0px;
     height: 38px;
     width: 40px;
      box-sizing: border-box;
     border-left: 40px solid black;
     border-bottom: 5px solid transparent;
     border-top: 5px solid transparent;
     margin-left: 0;
     transition: 0.5s;
    }

    .container {
        display: inline-block;
        cursor: pointer;
    }

    .bar1, .bar2, .bar3 {
        width: 35px;
        height: 5px;
        background-color: #A4A4A4;
        margin: 6px 0;
        transition: 0.4s;
        left:-35px;
        position:relative;
    }

    .change .bar1 {
        -webkit-transform: rotate(-45deg) translate(-9px, 6px) ;
        transform: rotate(-45deg) translate(-9px, 6px) ;
    }

    .change .bar2 {opacity: 0;}

    .change .bar3 {
        -webkit-transform: rotate(45deg) translate(-8px, -8px) ;
        transform: rotate(45deg) translate(-8px, -8px) ;
    }

<div id="trap" class="container" onclick="toggleNav(this)">
     <div class="bar1"></div>
     <div class="bar2"></div>
     <div class="bar3"></div>
    </div>


问:
fix for NoReverseMatch error after integrating django package (django-audiotracks)
I'm relatively new to django.. I'm trying to integrate the audiotracks package with my project. I'm trying to integrate the audiotracks package but I'm getting  NoReverseMatch error.
The documentation states..

Add audiotracks to your app
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Edit settings.py and add audiotracks to your list of
INSTALLED_APPS. Then synchronize your database with::

```<code>$ python manage.py syncdb
</code>```

Edit your ROOT_URLCONF_ and add a piece of code similar to::

```<code>urlpatterns += patterns('',
    # Here we mount the app under /music. Feel free to use something else
    url("^music", include("audiotracks.urls")),
    # Some URLs require a Django username
    url("^(?P<username>[\w\._-]+)/music", include("audiotracks.urls")),
)
</code>```

Visit the URL /music/upload to upload your first track.

the error occurs when i try to access music/upload..

here's the full traceback.

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/music/upload

```<code>Django Version: 1.11.3
Python Version: 3.6.0
Installed Applications:
['account',
 'music',
 'audiotracks',
 'django.contrib.sites',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']
</code>```

Template error:
In template C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_audiotracks-0.2.5-py3.6.egg\audiotracks\templates\audiotracks\base.html, error at line 25
   Reverse for 'user_index' with arguments '('addemo1',)' not found. 2 pattern(s) tried: ['music/tracks/(?P\d)/?$', 'music/tracks$']

```<code>15 :       .errorlist { color: red; list-style: none; display: inline; }
   16 :     </style>
   17 :     {% block extra_head %}{% endblock %}
   18 :   </head>
   19 :   <body>
   20 :
   21 :   {% block subnav %}
   22 :       {% if user.is_authenticated %}
   23 :           <ul>
   24 :             <li><a href="{% url 'audiotracks' %}">{% trans 'Latest tracks' %}</a></li>
   25 :             <li><a href=" {% url 'user_index' user.username %} ">{% trans 'Your tracks' %}</a></li>
   26 :             <li><a href="{% url 'upload_track' %}">{% trans 'Upload track' %}</a></li>
   27 :           </ul>
   28 :       {% else %}
   29 :
   30 :       {% endif %}
   31 :   {% endblock %}
   32 :
   33 :   {% if messages %}
   34 :   <ul class="messages">
   35 :     {% for message in messages %}
</code>```

Traceback:

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_audiotracks-0.2.5-py3.6.egg\audiotracks\views.py" in upload_track
  109.     return render(request, "audiotracks/new.html", {'form': form})

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  207.                     return self._render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render
  322.                 return nodelist.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render
  458.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\base.py" in reverse
  91.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  497.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /music/upload
Exception Value: Reverse for 'user_index' with arguments '('addemo1',)' not found. 2 pattern(s) tried: ['music/tracks/(?P\d)/?$', 'music/tracks$']

答:
```<code>from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^account/', include('account.urls')),
    url(r'^music/', include('music.urls')),
    url(r'^music/', include('audiotracks.urls')),
    url(r'^(?P<username>[\w\._-]+)/music', include('audiotracks.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
    urlpatterns += [
        url(r'^site_media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT
        })
    ]
    urlpatterns += staticfiles_urlpatterns()
</code>```

Body:
I'm relatively new to django.. I'm trying to integrate the audiotracks package with my project. I'm trying to integrate the audiotracks package but I'm getting  NoReverseMatch error.
The documentation states..

Add audiotracks to your app
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Edit settings.py and add audiotracks to your list of
INSTALLED_APPS. Then synchronize your database with::

$ python manage.py syncdb

Edit your ROOT_URLCONF_ and add a piece of code similar to::

urlpatterns += patterns('',
    # Here we mount the app under /music. Feel free to use something else
    url("^music", include("audiotracks.urls")),
    # Some URLs require a Django username
    url("^(?P<username>[\w\._-]+)/music", include("audiotracks.urls")),
)

Visit the URL /music/upload to upload your first track.

the error occurs when i try to access music/upload..

here's the full traceback.

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/music/upload

Django Version: 1.11.3
Python Version: 3.6.0
Installed Applications:
['account',
 'music',
 'audiotracks',
 'django.contrib.sites',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_audiotracks-0.2.5-py3.6.egg\audiotracks\templates\audiotracks\base.html, error at line 25
   Reverse for 'user_index' with arguments '('addemo1',)' not found. 2 pattern(s) tried: ['music/tracks/(?P\d)/?$', 'music/tracks$']

15 :       .errorlist { color: red; list-style: none; display: inline; }
   16 :     </style>
   17 :     {% block extra_head %}{% endblock %}
   18 :
   19 :
   20 :
   21 :   {% block subnav %}
   22 :       {% if user.is_authenticated %}
   23 :

   24 :
{% trans 'Latest tracks' %}

   25 :
{% trans 'Your tracks' %}

   26 :
{% trans 'Upload track' %}

   27 :

   28 :       {% else %}
   29 :
   30 :       {% endif %}
   31 :   {% endblock %}
   32 :
   33 :   {% if messages %}
   34 :

   35 :     {% for message in messages %}

Traceback:

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_audiotracks-0.2.5-py3.6.egg\audiotracks\views.py" in upload_track
  109.     return render(request, "audiotracks/new.html", {'form': form})

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  207.                     return self._render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render
  322.                 return nodelist.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render
  458.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\base.py" in reverse
  91.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  497.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /music/upload
Exception Value: Reverse for 'user_index' with arguments '('addemo1',)' not found. 2 pattern(s) tried: ['music/tracks/(?P\d)/?$', 'music/tracks$']


问:
PHP - DEFINE array with string on end
I'm creating an array for user levels and want to make them secure by adding a secret 10 digit string to the end of each of the user levels in the array UserLevels. I'm using the code below but I can't seem to add a string to an array when using the PHP term define.

My code is below:

```<code>//Change the 10 digits of the $secret definition to a randomised string
$secret = '0000000000';

define('UserLevels', array(
    'Owner'.$secret,
    'Admin'.$secret,
    'Staff'.$secret
));
</code>```

I was going to make it hash / check the user levels to make them more secure then use something to check the hash later in each page.

答:
If you dont use PHP 7</p>

```<code>define('ARRAY_EXAMPLE', serialize(array(1, 2, 3, 4, 5)));

unserialize(ARRAY_EXAMPLE);
</code>```

Title: PHP - DEFINE array with string on end

Body:
I'm creating an array for user levels and want to make them secure by adding a secret 10 digit string to the end of each of the user levels in the array UserLevels. I'm using the code below but I can't seem to add a string to an array when using the PHP term define.

My code is below:

//Change the 10 digits of the $secret definition to a randomised string
$secret = '0000000000';

define('UserLevels', array(
    'Owner'.$secret,
    'Admin'.$secret,
    'Staff'.$secret
));

I was going to make it hash / check the user levels to make them more secure then use something to check the hash later in each page.

Body:
If you dont use PHP 7

define('ARRAY_EXAMPLE', serialize(array(1, 2, 3, 4, 5)));

unserialize(ARRAY_EXAMPLE);


问:
Keras: Functional API -- Layer Datatype Error
I am trying to separate each of the outputs of a keras Conv2D layer using a for loop, and then adding another layer to it through the Functional API, but I am getting a type error. The code is:

```<code>import keras
from keras.models import Sequential, Model
from keras.layers import Flatten, Dense, Dropout, Input, Activation
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D
from keras.layers.merge import Add
from keras.optimizers import SGD
import cv2, numpy as np
import glob
import csv

def conv_layer:
    input = Input(shape=(3,224,224))
    k = 64
    x = np.empty(k, dtype=object)
    y = np.empty(k, dtype=object)
    z = np.empty(k, dtype=object)
    for i in range(0,k):
        x[i] = Conv2D(1, (3,3), data_format='channels_first', padding='same')(input)
        y[i] = Conv2D(1, (3,3), data_format='channels_first', padding='same')(x[i])
        z[i] = keras.layers.add([x[i], y[i]])
    out = Activation('relu')(z)
    model = Model(inputs, out, name='split-layer-model')

    return model
</code>```

But, it is throwing the following error:

```<code>Traceback (most recent call last):
  File "vgg16-local-connections.py", line 352, in <module>
    model = VGG_16_local_connections()
  File "vgg16-local-connections.py", line 40, in VGG_16_local_connections
    out = Activation('relu')(z)
  File "/Users/klab/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 519, in __call__
    input_shapes.append(K.int_shape(x_elem))
  File "/Users/klab/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 409, in int_shape
    shape = x.get_shape()
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'
</code>```

So, the datatype of z does not match the one of the Functional API. How can I fix this? Any help will be deeply appreciated!

答:
Since I had defined z[i]-s as separate layers, I thought z would effectively be a stack of those z[i]-s. But, they basically had to be concatenated to make the stack I wanted,

```<code>z = keras.layers.concatenate([z[i] for i in range (0,k)], axis=1)
out = Activation('relu')(z)
</code>```

Since I was using data_format='channels_first', the concatenation was done with axis=1, but for the more common, data_format='channels_last', the concatenation has to be done with axis=3.

Body:
I am trying to separate each of the outputs of a keras Conv2D layer using a for loop, and then adding another layer to it through the Functional API, but I am getting a type error. The code is:

import keras
from keras.models import Sequential, Model
from keras.layers import Flatten, Dense, Dropout, Input, Activation
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D
from keras.layers.merge import Add
from keras.optimizers import SGD
import cv2, numpy as np
import glob
import csv

def conv_layer:
    input = Input(shape=(3,224,224))
    k = 64
    x = np.empty(k, dtype=object)
    y = np.empty(k, dtype=object)
    z = np.empty(k, dtype=object)
    for i in range(0,k):
        x[i] = Conv2D(1, (3,3), data_format='channels_first', padding='same')(input)
        y[i] = Conv2D(1, (3,3), data_format='channels_first', padding='same')(x[i])
        z[i] = keras.layers.add([x[i], y[i]])
    out = Activation('relu')(z)
    model = Model(inputs, out, name='split-layer-model')

    return model

But, it is throwing the following error:

Traceback (most recent call last):
  File "vgg16-local-connections.py", line 352, in <module>
    model = VGG_16_local_connections()
  File "vgg16-local-connections.py", line 40, in VGG_16_local_connections
    out = Activation('relu')(z)
  File "/Users/klab/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 519, in __call__
    input_shapes.append(K.int_shape(x_elem))
  File "/Users/klab/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 409, in int_shape
    shape = x.get_shape()
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

So, the datatype of z does not match the one of the Functional API. How can I fix this? Any help will be deeply appreciated!

Body:
Since I had defined z[i]-s as separate layers, I thought z would effectively be a stack of those z[i]-s. But, they basically had to be concatenated to make the stack I wanted,

z = keras.layers.concatenate([z[i] for i in range (0,k)], axis=1)
out = Activation('relu')(z)

Since I was using data_format='channels_first', the concatenation was done with axis=1, but for the more common, data_format='channels_last', the concatenation has to be done with axis=3.


问:
Add new environment to an existing release-build
I have release build that has been kicked off already, this build was kicked-off it went through QA and staging environment successfully, the users were happy with the app on both these environments. I then added the last environment that is production. Now my question is, is there a way of getting the current build to see that there is an extra environment added, at the moment it looks like the production deployment does not exist yet I know its there, here is the screenshot of the prod environment that was added

The below screen illustrate that the app deployed succcessfully to the other environments but the prod environment does not appear, the area highlighted in red is where I am expecting my prod environment to appear

I understand queuing or kicking off a new build would make the prod environment appear but I wonder if is there a way to let the current release that there is new environment added.

答: No. The pipeline is locked in when the release is created. You can create a new release using the same build that you'd previously deployed to lower environments.  That will pick up the production environment that you added to the release definition.</p>


问:
Docker Anonymous Volumes
I've seen Docker volume definitions in docker-compose.yml files like so:

```<code>-v /path/on/host/modules:/var/www/html/modules
</code>```

I noticed that Drupal's official image, their docker-compose.yml file is using anonymous volumes.

Notice the comments:

```<code>volumes:
  - /var/www/html/modules
  - /var/www/html/profiles
  - /var/www/html/themes
  # this takes advantage of the feature in Docker that a new anonymous
  # volume (which is what we're creating here) will be initialized with the
  # existing content of the image at the same location
  - /var/www/html/sites
</code>```

Is there a way to associate an anonymous volume with a path on the host machine after the container is running? If not, what is the point of having anonymous volumes?

Full docker-compose.yml example:

```<code>version: '3.1'

services:

  drupal:
    image: drupal:8.2-apache
    ports:
      - 8080:80
    volumes:
      - /var/www/html/modules
      - /var/www/html/profiles
      - /var/www/html/themes
      # this takes advantage of the feature in Docker that a new anonymous
      # volume (which is what we're creating here) will be initialized with the
      # existing content of the image at the same location
      - /var/www/html/sites
    restart: always

  postgres:
    image: postgres:9.6
    environment:
      POSTGRES_PASSWORD: example
    restart: always
</code>```

答:
Anonymous volumes are equivalent to having these directories defined as VOLUME's in the image's Dockerfile.  In fact, directories defined as VOLUME's in a Dockerfile are anonymous volumes if they are not explicitly mapped to the host.

The point of having them is added flexibility.

PD:
Anonymous volumes already reside in the host somewhere in /var/lib/docker (or whatever directory you configured).  To see where they are:

docker inspect --type container -f '{{range $i, $v := .Mounts }}{{printf "%v\n" $v}}{{end}}' $CONTAINER

Note: Substitute $CONTAINER with the container's name.

ContentLicense: CC BY-SA 4.0

Title: Docker Anonymous Volumes

Body:
I've seen Docker volume definitions in docker-compose.yml files like so:

-v /path/on/host/modules:/var/www/html/modules

I noticed that Drupal's official image, their docker-compose.yml file is using anonymous volumes.

Notice the comments:

volumes:
  - /var/www/html/modules
  - /var/www/html/profiles
  - /var/www/html/themes
  # this takes advantage of the feature in Docker that a new anonymous
  # volume (which is what we're creating here) will be initialized with the
  # existing content of the image at the same location
  - /var/www/html/sites

Is there a way to associate an anonymous volume with a path on the host machine after the container is running? If not, what is the point of having anonymous volumes?

Full docker-compose.yml example:

version: '3.1'

services:

  drupal:
    image: drupal:8.2-apache
    ports:
      - 8080:80
    volumes:
      - /var/www/html/modules
      - /var/www/html/profiles
      - /var/www/html/themes
      # this takes advantage of the feature in Docker that a new anonymous
      # volume (which is what we're creating here) will be initialized with the
      # existing content of the image at the same location
      - /var/www/html/sites
    restart: always

  postgres:
    image: postgres:9.6
    environment:
      POSTGRES_PASSWORD: example
    restart: always


问:
C++ unwanted pause in do-while loop
I've been brushing off my c++ with a college class, and I came across an odd issue which I am having trouble diagnosing.

The code compiles and runs ok with the desired result, but after getting a valid entry, the program seems to hang for [ENTER] before continuing

The program receives input which it uses to create a file under that name.

```<code>#include<iostream>
#include<string>
#include<fstream>

using namespace std;

void createFile(string filename);//create userFile
void validateUserName(string &name);//validate user name

//main function
int main()
{

    ifstream file;
    string filename;

    cout<< "Enter your name and press <ENTER>";
    getline(cin, filename);

    validateUserName(filename);
    printf("validation passed\n");
    createFile(filename);

}

void createFile(string filename)
{
    ofstream file;
    file.open(filename.c_str());
    file.close();
}

void validateUserName(string &name){
    int errCount = 0;
    int i=0;
    do
    {
        errCount = 0;
        i=0;
        while (name[i])
            {
            if ( !isalpha(name[i]) )
            errCount++;
            i++;
            }

        if (errCount > 0)
        cout << "Invalid entry, try again" << endl;
        getline(cin, name);

    }
    while (errCount > 0);
    printf("validating\n");
}
</code>```

How can I avoid having the program hang waiting for [ENTER]?

答:
You have to put your validation into a scoped block:</p>

```<code>if (errCount > 0)
{ // <<<<<<<<<<<<<
     cout << "Invalid entry, try again" << endl;
     getline(cin, name);
} // <<<<<<<<<<<<<
</code>```

Title: C++ unwanted pause in do-while loop

Body:
I've been brushing off my c++ with a college class, and I came across an odd issue which I am having trouble diagnosing.

The code compiles and runs ok with the desired result, but after getting a valid entry, the program seems to hang for [ENTER] before continuing

The program receives input which it uses to create a file under that name.

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

void createFile(string filename);//create userFile
void validateUserName(string &name);//validate user name

//main function
int main()
{

    ifstream file;
    string filename;

    cout<< "Enter your name and press <ENTER>";
    getline(cin, filename);

    validateUserName(filename);
    printf("validation passed\n");
    createFile(filename);

}

void createFile(string filename)
{
    ofstream file;
    file.open(filename.c_str());
    file.close();
}

void validateUserName(string &name){
    int errCount = 0;
    int i=0;
    do
    {
        errCount = 0;
        i=0;
        while (name[i])
            {
            if ( !isalpha(name[i]) )
            errCount++;
            i++;
            }

        if (errCount > 0)
        cout << "Invalid entry, try again" << endl;
        getline(cin, name);

    }
    while (errCount > 0);
    printf("validating\n");
}

How can I avoid having the program hang waiting for [ENTER]?

Body:
You have to put your validation into a scoped block:

if (errCount > 0)
{ // <<<<<<<<<<<<<
     cout << "Invalid entry, try again" << endl;
     getline(cin, name);
} // <<<<<<<<<<<<<


问:
Python: Only using part of a shapefile
I am using Python 3.6 to create a map that shows precipitation data in North America. The code I have so far extracts my data inside of a shapefile and then plots it on a map.

My problem is that the shapefile I have downloaded contains the shapes of all of the continents. I was wondering is there a way I could only read in the North American continent from my shapefile?

If this isn't a possibility then does anyone know where I could download a shapefile that only has North America? Thank you!

This is the part of my code that reads the shapefile:

```<code>import shapefile
sf=shapefile.Reader('continents')
</code>```

This is the link for the shapefile.

答:
Taking a look at the shapefile you mentioned we can see that it has one attribute in its Attribute Table (which is "CONTINENT"). Therefore, we need to search for all the shapes and select those that match the continent you desire (North America), like this:

```<code>import shapefile

#read the shapefile
sf=shapefile.Reader('continent.shp')

#obtain shapes and its records
#the shapes are the actual coordinate points
#the record contains all attributes related to each shape
shape_records = sf.shapeRecords()

#search for the ones with desired records
#this shapefile has only one attribute calles CONTINENT
desired_shapes = []
for s in shape_records:
    if s.record[0] == 'North America':
        desired_shapes.append(s.shape)
        #or do whatever you want with that element s.shape is the actual shape
</code>```

If you want take a look at this page that describes the usage of shapefile. It is useful to use a tool (like QGis) to see what attributes your data has so you can then proceed to detect them programmatically.

Title: Python: Only using part of a shapefile

Body:
I am using Python 3.6 to create a map that shows precipitation data in North America. The code I have so far extracts my data inside of a shapefile and then plots it on a map.

My problem is that the shapefile I have downloaded contains the shapes of all of the continents. I was wondering is there a way I could only read in the North American continent from my shapefile?

If this isn't a possibility then does anyone know where I could download a shapefile that only has North America? Thank you!

This is the part of my code that reads the shapefile:

import shapefile
sf=shapefile.Reader('continents')

This is the link for the shapefile.

Body:
Taking a look at the shapefile you mentioned we can see that it has one attribute in its Attribute Table (which is "CONTINENT"). Therefore, we need to search for all the shapes and select those that match the continent you desire (North America), like this:

import shapefile

#read the shapefile
sf=shapefile.Reader('continent.shp')

#obtain shapes and its records
#the shapes are the actual coordinate points
#the record contains all attributes related to each shape
shape_records = sf.shapeRecords()

#search for the ones with desired records
#this shapefile has only one attribute calles CONTINENT
desired_shapes = []
for s in shape_records:
    if s.record[0] == 'North America':
        desired_shapes.append(s.shape)
        #or do whatever you want with that element s.shape is the actual shape

If you want take a look at this page that describes the usage of shapefile. It is useful to use a tool (like QGis) to see what attributes your data has so you can then proceed to detect them programmatically.


问:
Translate MYSQL query to HQL using multiple JOINS
everyone.

I am using grails 3.3.0.M2 framework with mysql as data-source the following sql query is working as expected

```<code>SELECT
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END) 'open',
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END) 'in progress',
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END) 'closed'
FROM
    tickets t
        INNER JOIN
    users u ON t.user_id = u.id
        INNER JOIN
    user_coordinations uc ON uc.user_id = u.id
        INNER JOIN
    coordinations c ON c.id = uc.coordination_id
GROUP BY 1
</code>```

I translated to HQL using implicit JOIN but I am getting the wrong results, here is the hql query:

```<code>SELECT
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END)
FROM
    Ticket t, User u, UserCoordination uc, Coordination c
WHERE
    MONTH(t.dateCreated) = :month
GROUP BY 1
</code>```

In order to get the right results stack overflow users help me to understand that the query needs to use explicit JOINS, here the question: Group by a field that does not belongs to the consulted table

Right now I am trying with the following query:

```<code>SELECT
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END)
FROM
    Ticket t
        INNER JOIN
    User u
        INNER JOIN
    UserCoordination uc
        INNER JOIN
    Coordination c
WHERE
    MONTH(t.dateCreated) = :month
GROUP BY 1
</code>```

But i am getting a com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException with the caused message You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inner join user_coordinations usercoordi2_ on inner join coordinations coordinat' at line 1

Thanks for your help and time

答:
```<code>SELECT new map(
    c.name as name,
(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END) as open,
(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END) as pending,
(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END) as closed,
    SUM(open) as openSum,
    SUM(pending) as pendingSum,
    SUM(closed) as closedSum
)
FROM
    Ticket t
        left join t.user u left join u.userCoordination uc left join uc.coordination c
WHERE
    MONTH(t.dateCreated) = :month
</code>```

//GROUP BY 1

What you had had lots missing above is more like what you need, you need
select new map(i.item as item... if you compare the basics of this with what you had and what i tried to do you can see why you had errors.

unsure about your group by it should be group by something. Wasn't sure by inner join if you just meant a join if that was the case leave out all the left join since left join attempts to connect and get any null hasMany relations etc.

Body:
everyone.

I am using grails 3.3.0.M2 framework with mysql as data-source the following sql query is working as expected

SELECT
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END) 'open',
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END) 'in progress',
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END) 'closed'
FROM
    tickets t
        INNER JOIN
    users u ON t.user_id = u.id
        INNER JOIN
    user_coordinations uc ON uc.user_id = u.id
        INNER JOIN
    coordinations c ON c.id = uc.coordination_id
GROUP BY 1

I translated to HQL using implicit JOIN but I am getting the wrong results, here is the hql query:

SELECT
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END)
FROM
    Ticket t, User u, UserCoordination uc, Coordination c
WHERE
    MONTH(t.dateCreated) = :month
GROUP BY 1

In order to get the right results stack overflow users help me to understand that the query needs to use explicit JOINS, here the question: Group by a field that does not belongs to the consulted table

Right now I am trying with the following query:

SELECT
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END)
FROM
    Ticket t
        INNER JOIN
    User u
        INNER JOIN
    UserCoordination uc
        INNER JOIN
    Coordination c
WHERE
    MONTH(t.dateCreated) = :month
GROUP BY 1

But i am getting a com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException with the caused message You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inner join user_coordinations usercoordi2_ on inner join coordinations coordinat' at line 1

Thanks for your help and time

Body:
SELECT new map(
    c.name as name,
(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END) as open,
(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END) as pending,
(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END) as closed,
    SUM(open) as openSum,
    SUM(pending) as pendingSum,
    SUM(closed) as closedSum
)
FROM
    Ticket t
        left join t.user u left join u.userCoordination uc left join uc.coordination c
WHERE
    MONTH(t.dateCreated) = :month

//GROUP BY 1

What you had had lots missing above is more like what you need, you need
select new map(i.item as item... if you compare the basics of this with what you had and what i tried to do you can see why you had errors.

unsure about your group by it should be group by something. Wasn't sure by inner join if you just meant a join if that was the case leave out all the left join since left join attempts to connect and get any null hasMany relations etc.


问:
Apollo Client React container add created element to paginated list of elements without refetching
This title is quite confusing, but I will try to explain the best that I can.  I have a situation where I am collecting and displaying a list of data elements from the server in React Native.  It uses a query that sends a GraphQL parameter to the server to limit the initial request to the first 15 elements.

```<code>query GetElements ($count: Int) {
    elements (count: $count) {
            id
            name
            tye
    }
}
</code>```

As previously stated, this will query the main list with an initial count of 15 elements.

I have another page of the app that a user can create a new element on the backend using a different GraphQL query.

My question is: Is there a way to easily update the main list of elements to include the newly created element without performing any addition network requests?  In other words, I want to be able to simply add the new element to the main list of elements whenever the create command is successful.

The problem is: Apollo's readQuery command on the update proxy will not return to me the appropriate data set to update unless I know the variables that were send with the initial query; this includes the pagination count variable.

答:
You can now define the key for the queries cache store like this:</p>

```<code> query AllItems($cursor: String, $limit: Int, $query: String) {
  items(cursor: $cursor, limit: $limit, query: $query) @connection(key: "AllItemsQuery") {
    count
    cursor
    has_next
    has_prior
    data{
      ...CoreItem
    }
  }
}
</code>```

Body:
This title is quite confusing, but I will try to explain the best that I can.  I have a situation where I am collecting and displaying a list of data elements from the server in React Native.  It uses a query that sends a GraphQL parameter to the server to limit the initial request to the first 15 elements.

query GetElements ($count: Int) {
    elements (count: $count) {
            id
            name
            tye
    }
}

As previously stated, this will query the main list with an initial count of 15 elements.

I have another page of the app that a user can create a new element on the backend using a different GraphQL query.

My question is: Is there a way to easily update the main list of elements to include the newly created element without performing any addition network requests?  In other words, I want to be able to simply add the new element to the main list of elements whenever the create command is successful.

The problem is: Apollo's readQuery command on the update proxy will not return to me the appropriate data set to update unless I know the variables that were send with the initial query; this includes the pagination count variable.

Body:
You can now define the key for the queries cache store like this:

 query AllItems($cursor: String, $limit: Int, $query: String) {
  items(cursor: $cursor, limit: $limit, query: $query) @connection(key: "AllItemsQuery") {
    count
    cursor
    has_next
    has_prior
    data{
      ...CoreItem
    }
  }
}


问:
How to query json data in angular 2
I want to query JSON data based on some conditions using angular2

My json is:

```<code>{
"logsArray":[
    {
        "Id": "1",
        "ProjectName": "Project01",
        "ModuleName": "Module01",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "2",
        "ProjectName": "Project02",
        "ModuleName": "Module01",
        "MethodName": "Method03",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "3",
        "ProjectName": "Project03",
        "ModuleName": "Module05",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "4",
        "ProjectName": "Project01",
        "ModuleName": "Module07",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "5",
        "ProjectName": "Project03",
        "ModuleName": "Module01",
        "MethodName": "Method10",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "6",
        "ProjectName": "Project06",
        "ModuleName": "Module01",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "7",
        "ProjectName": "Project03",
        "ModuleName": "Module03",
        "MethodName": "Method07",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "8",
        "ProjectName": "Project04",
        "ModuleName": "Module03",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    }
]
}
</code>```

I want to get the particular property based on some conditions like

Distinct ProjectNames where PojectName = Project03

Distincts ModuleNames where ModuleName = Module02 && MethodName = Method01

Distinct Method Names ProjectName = Project01

答:
You mean like this?

```<code>var nameSpace = angular.module("GuitarApp", []);

nameSpace.controller("GuitarFunction", ['$scope','$http', function($scope, $http)
        {
            $http.get('js/data.json').success (function(data){ // json call
                $scope.guitarVariable = data;
        });

    }]
);
</code>```

Source: https://blog.hfarazm.com/angularjs-service/

Title: How to query json data in angular 2

Body:
I want to query JSON data based on some conditions using angular2

My json is:

{
"logsArray":[
    {
        "Id": "1",
        "ProjectName": "Project01",
        "ModuleName": "Module01",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "2",
        "ProjectName": "Project02",
        "ModuleName": "Module01",
        "MethodName": "Method03",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "3",
        "ProjectName": "Project03",
        "ModuleName": "Module05",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "4",
        "ProjectName": "Project01",
        "ModuleName": "Module07",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "5",
        "ProjectName": "Project03",
        "ModuleName": "Module01",
        "MethodName": "Method10",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "6",
        "ProjectName": "Project06",
        "ModuleName": "Module01",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "7",
        "ProjectName": "Project03",
        "ModuleName": "Module03",
        "MethodName": "Method07",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "8",
        "ProjectName": "Project04",
        "ModuleName": "Module03",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    }
]
}

I want to get the particular property based on some conditions like

Distinct ProjectNames where PojectName = Project03

Distincts ModuleNames where ModuleName = Module02 && MethodName = Method01

Distinct Method Names ProjectName = Project01

Body:
You mean like this?

var nameSpace = angular.module("GuitarApp", []);

nameSpace.controller("GuitarFunction", ['$scope','$http', function($scope, $http)
        {
            $http.get('js/data.json').success (function(data){ // json call
                $scope.guitarVariable = data;
        });

    }]
);

Source: https://blog.hfarazm.com/angularjs-service/


问:
WebView download opens browser window for a short moment before returning to WebView
My Problem is that when I hit the pdf link in the webview, the browser opens for a short moment (I guess to download the linked file), the pdf file starts to download and the app returns back to the webview. Is there a way to stop the browser window opening to start the download?

I have used WebViewClient to shouldOverrideUrlLoading so that clicked urls are kept in the webview:

```<code>private class LinkWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
</code>```

And I have a download listener so I can download files  (for my needs these are pdf's):

```<code>webView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype,
                long contentLength) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);

        }
    });
</code>```

答: Add the MIME type to your Intent you use with startActivity() in your download listener.

Body:
My Problem is that when I hit the pdf link in the webview, the browser opens for a short moment (I guess to download the linked file), the pdf file starts to download and the app returns back to the webview. Is there a way to stop the browser window opening to start the download?

I have used WebViewClient to shouldOverrideUrlLoading so that clicked urls are kept in the webview:

private class LinkWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

And I have a download listener so I can download files  (for my needs these are pdf's):

webView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype,
                long contentLength) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);

        }
    });


答:
Your getting tripped up by your indentation.  validateUserName should actually look like:

```<code>void validateUserName(string &name){
    int errCount = 0;
    int i=0;
    do
    {
        errCount = 0;
        i=0;
        while (name[i])
        {
            if ( !isalpha(name[i]) )
            errCount++;
            i++;
        }

        if (errCount > 0)
            cout << "Invalid entry, try again" << endl;
        getline(cin, name);

    }
    while (errCount > 0);
    printf("validating\n");
}
</code>```

And what we really want to concentrate on is the part of the do while loop

```<code>do
{
    //...
    if (errCount > 0)
        cout << "Invalid entry, try again" << endl;
    getline(cin, name);

}
while (errCount > 0);
</code>```

Now you can see that if you don't have any errors in your input your still requesting input as getline(cin, name); is not inside the if.  We can fix that pretty easily by adding braces like

```<code>do
{
    //...
    if (errCount > 0)
    {
        cout << "Invalid entry, try again" << endl;
        getline(cin, name);
    }
}
while (errCount > 0);
</code>```

Title: C++ unwanted pause in do-while loop

Body:
Your getting tripped up by your indentation.  validateUserName should actually look like:

void validateUserName(string &name){
    int errCount = 0;
    int i=0;
    do
    {
        errCount = 0;
        i=0;
        while (name[i])
        {
            if ( !isalpha(name[i]) )
            errCount++;
            i++;
        }

        if (errCount > 0)
            cout << "Invalid entry, try again" << endl;
        getline(cin, name);

    }
    while (errCount > 0);
    printf("validating\n");
}

And what we really want to concentrate on is the part of the do while loop

do
{
    //...
    if (errCount > 0)
        cout << "Invalid entry, try again" << endl;
    getline(cin, name);

}
while (errCount > 0);

Now you can see that if you don't have any errors in your input your still requesting input as getline(cin, name); is not inside the if.  We can fix that pretty easily by adding braces like

do
{
    //...
    if (errCount > 0)
    {
        cout << "Invalid entry, try again" << endl;
        getline(cin, name);
    }
}
while (errCount > 0);


问:
How to deep copy an object in Realm containing a RealmList as a property and not have the RealmList objects referencing the same object
I have 3 Realm Objects

```<code>public class Portfolio extends RealmObject {
    @PrimaryKey
    public long id;
    public RealmList<PortfolioCoin> portfolioCoins = new RealmList<>();
}

public class PortfolioCoin extends RealmObject {
    public Coin coin;
    public RealmList<Holdings> holdings = new RealmList<>();
    public int color;
}

public class Holdings extends RealmObject {
    @PrimaryKey
    public long id;
    public double amount;
    public double price;
}
</code>```

Now i would like my users to be able to duplicate their portfolios.
If i create a new portfolio and do this

```<code>portfolio.portfolioCoins.addAll(activePortfolio2.portfolioCoins);
</code>```

Both portfolios are basically referencing the same objects. How do i do a deep copy of the items in the list, remembering that its nested twice. Holdings is nested in PortfolioCoin, and PortfolioCoin is nested in Portfolio.

Do i really have to write nested loops to do this? and itereate over each item and then iterate over each item within each item?

答:
You can try following trick</p>

```<code>portfolio.portfolioCoins.addAll(realm.copyToRealmOrUpdate(realm.copyFromRealm(activePortfolio2.portfolioCoins, 2))); // maybe 3?
</code>```

Body:
I have 3 Realm Objects

public class Portfolio extends RealmObject {
    @PrimaryKey
    public long id;
    public RealmList<PortfolioCoin> portfolioCoins = new RealmList<>();
}

public class PortfolioCoin extends RealmObject {
    public Coin coin;
    public RealmList<Holdings> holdings = new RealmList<>();
    public int color;
}

public class Holdings extends RealmObject {
    @PrimaryKey
    public long id;
    public double amount;
    public double price;
}

Now i would like my users to be able to duplicate their portfolios.
If i create a new portfolio and do this

portfolio.portfolioCoins.addAll(activePortfolio2.portfolioCoins);

Both portfolios are basically referencing the same objects. How do i do a deep copy of the items in the list, remembering that its nested twice. Holdings is nested in PortfolioCoin, and PortfolioCoin is nested in Portfolio.

Do i really have to write nested loops to do this? and itereate over each item and then iterate over each item within each item?

Body:
You can try following trick

portfolio.portfolioCoins.addAll(realm.copyToRealmOrUpdate(realm.copyFromRealm(activePortfolio2.portfolioCoins, 2))); // maybe 3?


问:
How To Run PHP From Windows Command Line in WAMPServer
I'm new to php and wanted to run php from command line. I have installed WAMP and set the "System Variables" to my php folder ( which is C:\wamp\bin\php\php5.4.3).

When i go to Run -> CMD -> Type php -a and hit enter, it says interactive mode enabled. But when I write echo 'Hi'; it shows nothing.

I even don't see anything like 'php >" when i type php -a and hit enter.

答:
The following solution is specifically for wamp environments:

This foxed me for a little while, tried all the other suggestions, $PATH etc even searched the windows registry looking for clues:

The GUI (wampmanager) indicates I have version 7 selected and yes if I phpinfo() in a page in the browser it will tell me its version 7.x.x yet php -v in the command prompt reports a 5.x.x

If you right click on the wampmanager head to icon->tools->delete unused versions and remove the old version, let it restart the services then the command prompt will return a 7.x.x

This solution means you no longer have the old version if you want to switch between php versions but there is a configuration file in C:\wamp64\wampmanager.conf which appears to specify the version to use with CLI (the parameter is called phpCliVersion). I changed it, restarted the server ... thought I had solved it but no effect perhaps I was a little impatient so I have a feeling there may be some mileage in that.

Hope that helps someone


问:
Angular 2/4, "ngStyle". Apply different style depeding its father element active o inactive
I need to apply a style to an element when it parent element is actived. I'm using routerLinkActive to apply CSS Class and works fine, but deppending if the father element is actite apply one inline style (display: block), in other cases apply another (display: none).

If parent element is active:

```<code><li class="active">
   <ul class="sub-menu" style="display: block;">
</li>
<li>
   <ul class="sub-menu" style="display: none;">
</li>
</code>```

When I choose another element:

```<code><li>
   <ul class="sub-menu" style="display: none;">
</li>
<li class="active">
   <ul class="sub-menu" style="display: block;">
</li>
</code>```

I have an extended list of items with their respectives Links. Each "sub-menu" has its own list of elements.

答:
This can be achieved with CSS only:

```<code>.sub-menu {
  display: none;
}

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

Check out this live demo to see how it works.

Body:
I need to apply a style to an element when it parent element is actived. I'm using routerLinkActive to apply CSS Class and works fine, but deppending if the father element is actite apply one inline style (display: block), in other cases apply another (display: none).

If parent element is active:

When I choose another element:

I have an extended list of items with their respectives Links. Each "sub-menu" has its own list of elements.

Body:
This can be achieved with CSS only:

.sub-menu {
  display: none;
}

.active .sub-menu {
  display: block;
}

Check out this live demo to see how it works.


问:
Thymeleaf + Spring Boot: Object creation with related object (Form & Return)
I'm developing an application using Spring Boot and Thymeleaf, in which I have a Package class and a User class.

Package Class:

```<code>@Entity
@Table(name = "table_package")
public class Package {

    @Id
    @GenericGenerator(name = "gen_id", strategy = "increment")
    @GeneratedValue(generator = "gen_id")
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "userid")
    @JsonBackReference
    private User package_owner;
//    private Integer userid;

    private String package_name;

    @OneToMany(mappedBy = "pkg")
    @JsonBackReference
    private Set<Article> articles;

    @ManyToOne
    @JoinColumn(name = "package_statusid")
    @JsonBackReference
    private PackageStatus packageStatus;
//    private Integer package_statusid;

    private String notes;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public User getPackage_owner() {
        return package_owner;
    }

    public void setPackage_owner(User package_owner) {
        this.package_owner = package_owner;
    }

//    public Integer getUserid() {
//        return userid;
//    }
//
//    public void setUserid(Integer userid) {
//        this.userid = userid;
//    }

    public String getPackage_name() {
        return package_name;
    }

    public void setPackage_name(String package_name) {
        this.package_name = package_name;
    }

    public Set<Article> getArticles() {
        return articles;
    }

    public void setArticles(Set<Article> articles) {
        this.articles = articles;
    }

    public PackageStatus getPackageStatus() {
        return packageStatus;
    }

    public void setPackageStatus(PackageStatus packageStatus) {
        this.packageStatus = packageStatus;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    @Override
    public String toString() {
        return "Package{" +
                "id=" + id +
                ", package_owner=" + package_owner +
                ", package_name='" + package_name + '\'' +
                ", articles=" + articles +
                ", packageStatus=" + packageStatus +
                ", notes='" + notes + '\'' +
                '}';
    }
}
</code>```

User Class:

```<code>@Entity
@Table(name = "table_user")
public class User {

    @Id
    @GenericGenerator(name="gen_id" , strategy="increment")
    @GeneratedValue(generator="gen_id")
    private Integer id;

    @OneToMany(mappedBy = "package_owner")
    @JsonBackReference
    private Set<Package> packages = new HashSet<Package>();

}
</code>```

I'm coding a screen for the package insert

Package Add/Insert:

```<code><form action="#" th:action="@{/packages/add}" th:object="${Package}" method="post">
    <table class="table stripped-table" id="article-table">
        <tr>
            <th>
                User:
            </th>
            <td>
                <input type="text" id="user-search"/>
                <input type="text" th:value="*{user.id}" hidden="hidden" th:required="required"/>
            </td>
        </tr>
        <tr>
            <th>
                Package:
            </th>
            <td>
                <input type="text" th:field="*{package_name}" th:required="required"/>
            </td>
        </tr>
    </table>
    <input type="submit" id="submit" value="Add" />
</form>
</code>```

Before I related the objects between them I was using JavaScript's autocomplete to write the name on the 'user-search', insert the value to the user_id input and just pass that to my controller.

But now that I've created the relation between both objects every time I try to load the template I get this error:

Invalid property 'user' of bean class [com.app.model.Package]: Bean property 'user' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

I've been looking at the getter and setter but can't find an issue. I'm also curious as of how the return should be handled on my controller, but that I assume would be inserting the whole object before the save function on the DB. Any ideas?

Thanks in advance.

EDIT Sorry for the delay, I was on a business trip.

Here's the controller:

```<code>@RequestMapping(value = "add", method = RequestMethod.GET)
public ModelAndView addPackageForm(Model model){

    List<PackageStatus> packageStatuses = packageStatusRepository.findAll();

    model.addAttribute("Package", new Package());
    model.addAttribute("PackageStatus", packageStatuses);
    ModelAndView mav = new ModelAndView("packages/add");
    mav.addObject("page_title", "Test: Add Package");
    mav.addObject("template_primary", "packages");
    mav.addObject("template_secondary", "add");
    return mav;
}
</code>```

答: You need to use the proper field name of your class, so switch user for package_owner or as you did in your comment, you can do the opposite.

Body:
I'm developing an application using Spring Boot and Thymeleaf, in which I have a Package class and a User class.

Package Class:

@Entity
@Table(name = "table_package")
public class Package {

    @Id
    @GenericGenerator(name = "gen_id", strategy = "increment")
    @GeneratedValue(generator = "gen_id")
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "userid")
    @JsonBackReference
    private User package_owner;
//    private Integer userid;

    private String package_name;

    @OneToMany(mappedBy = "pkg")
    @JsonBackReference
    private Set
 articles;

    @ManyToOne
    @JoinColumn(name = "package_statusid")
    @JsonBackReference
    private PackageStatus packageStatus;
//    private Integer package_statusid;

    private String notes;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public User getPackage_owner() {
        return package_owner;
    }

    public void setPackage_owner(User package_owner) {
        this.package_owner = package_owner;
    }

//    public Integer getUserid() {
//        return userid;
//    }
//
//    public void setUserid(Integer userid) {
//        this.userid = userid;
//    }

    public String getPackage_name() {
        return package_name;
    }

    public void setPackage_name(String package_name) {
        this.package_name = package_name;
    }

    public Set
 getArticles() {
        return articles;
    }

    public void setArticles(Set
 articles) {
        this.articles = articles;
    }

    public PackageStatus getPackageStatus() {
        return packageStatus;
    }

    public void setPackageStatus(PackageStatus packageStatus) {
        this.packageStatus = packageStatus;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    @Override
    public String toString() {
        return "Package{" +
                "id=" + id +
                ", package_owner=" + package_owner +
                ", package_name='" + package_name + '\'' +
                ", articles=" + articles +
                ", packageStatus=" + packageStatus +
                ", notes='" + notes + '\'' +
                '}';
    }
}

User Class:

@Entity
@Table(name = "table_user")
public class User {

    @Id
    @GenericGenerator(name="gen_id" , strategy="increment")
    @GeneratedValue(generator="gen_id")
    private Integer id;

    @OneToMany(mappedBy = "package_owner")
    @JsonBackReference
    private Set<Package> packages = new HashSet<Package>();

}

I'm coding a screen for the package insert

Package Add/Insert:

<form action="#" th:action="@{/packages/add}" th:object="${Package}" method="post">

                User:

                <input type="text" id="user-search"/>
                <input type="text" th:value="*{user.id}" hidden="hidden" th:required="required"/>

                Package:

                <input type="text" th:field="*{package_name}" th:required="required"/>

    <input type="submit" id="submit" value="Add" />
</form>

Before I related the objects between them I was using JavaScript's autocomplete to write the name on the 'user-search', insert the value to the user_id input and just pass that to my controller.

But now that I've created the relation between both objects every time I try to load the template I get this error:

Invalid property 'user' of bean class [com.app.model.Package]: Bean property 'user' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

I've been looking at the getter and setter but can't find an issue. I'm also curious as of how the return should be handled on my controller, but that I assume would be inserting the whole object before the save function on the DB. Any ideas?

Thanks in advance.

EDIT Sorry for the delay, I was on a business trip.

Here's the controller:

@RequestMapping(value = "add", method = RequestMethod.GET)
public ModelAndView addPackageForm(Model model){

    List<PackageStatus> packageStatuses = packageStatusRepository.findAll();

    model.addAttribute("Package", new Package());
    model.addAttribute("PackageStatus", packageStatuses);
    ModelAndView mav = new ModelAndView("packages/add");
    mav.addObject("page_title", "Test: Add Package");
    mav.addObject("template_primary", "packages");
    mav.addObject("template_secondary", "add");
    return mav;
}