问:
Issues with pyenv-virtualenv: Python and PIP not changed when activating / deactivating virtual environment
I installed pyenv-virtualenv using Linuxbrew (Homebrew 2.2.5) on my Ubuntu 16.04 VPS. The pyenv version is: 1.2.16. Now when I do a test like this:

```<code>pyenv install 3.8.1
pyenv virtualenv 3.8.1 test
cd /.pyenv/versions/3.8.1/envs/test
pyenv local 3.8.1
</code>```

Then entering / leaving the /.pyenv/versions/3.8.1/envs/test doesn't activate deactivate the virtual environment and I don't see (test) username:~ in my shell. I also created a /home/users/test directory and .python-version there but still entering / leaving directory does nothing.

Accordingn to the documentation:

If eval "$(pyenv virtualenv-init -)" is configured in your shell,
  pyenv-virtualenv will automatically activate/deactivate virtualenvs on
  entering/leaving directories which contain a .python-version file that
  contains the name of a valid virtual environment as shown in the
  output of pyenv virtualenvs (e.g., venv34 or 3.4.3/envs/venv34 in
  example above) . .python-version files are used by pyenv to denote
  local Python versions and can be created and deleted with the pyenv
  local command.

So first question is: Why this doesn't work? Why the virtual environment is not activated / deactivated automatically at entering / leaving a directory containing a .python-version file?

Also when I activate virtualenv by hand pyenv activate test and then check the Python version, it prints the system Python version and not the one from environment: Python 3.8.1:

```<code>python --version
Python 3.7.6
</code>```

I can get the right Python version only by directly referring to virtualenv shims Python like this:

```<code>which python
/home/andre/.pyenv/shims/python
/home/andre/.pyenv/shims/python --version
Python 3.8.1
</code>```

The behaviour is the same whenever the virtualenv "test" is activated or not.
I would expect that after activating "test" the command python --version returns Python 3.8.1

So second question: why pip and python are not switched when activating / deactivating the virtual environment ?

Are these pyenv bugs? Or am I doing something wrong?

答:
It turns out that in order to automatically activate / deactivate a venv when entering / leaving a directory the .python-version file in there must contain the venv name and not the Python version associated with that venv

So executing:
pyenv local 3.8.1
creates a .python-version file which only includes the Python version 3.8.1.
Then entering / leaving a directory containing .python-version file will set / unset the Python version specified in that file but will not activate / deactivate any venv.

To create a .python-version file that will do both: activate a virtual environment and set Python version the command should look like: pyenv local test where test is a venv created with:
pyenv virtualenv 3.8.1 test.

So changing 3.8.1 to test in the .python-version fixed the problem.
After I done this the venv was activated / deactivated when entering / leaving directory containing .python-version.

But still the Python version did not change to the one associated with the venv (in this case 3.8.1)

Then I found out that I had two lines in my .profile that was causing this problem:

alias python=/home/linuxbrew/.linuxbrew/bin/python3
alias pip=/home/linuxbrew/.linuxbrew/bin/pip3
```
<p>After removing these lines everything works as expected.</p>
<p>If still having any problems make sure you have these lines in your <code>.profile</code> or <code>.bash_profile</code>, whichever one you are using:</p>
```export PATH="$HOME/.pyenv/bin:$PATH"

eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

if command -v pyenv 1>/dev/null 2>&1; then
  export PYENV_ROOT="$HOME/.pyenv"
  export PATH="$PYENV_ROOT/bin:$PATH"
  eval "$(pyenv init --path)"
  eval "$(pyenv init -)"
fi

```

Body:
I installed pyenv-virtualenv using Linuxbrew (Homebrew 2.2.5) on my Ubuntu 16.04 VPS. The pyenv version is: 1.2.16. Now when I do a test like this:

pyenv install 3.8.1
pyenv virtualenv 3.8.1 test
cd /.pyenv/versions/3.8.1/envs/test
pyenv local 3.8.1

Then entering / leaving the /.pyenv/versions/3.8.1/envs/test doesn't activate deactivate the virtual environment and I don't see (test) username:~ in my shell. I also created a /home/users/test directory and .python-version there but still entering / leaving directory does nothing.

Accordingn to the documentation:

If eval "$(pyenv virtualenv-init -)" is configured in your shell,
  pyenv-virtualenv will automatically activate/deactivate virtualenvs on
  entering/leaving directories which contain a .python-version file that
  contains the name of a valid virtual environment as shown in the
  output of pyenv virtualenvs (e.g., venv34 or 3.4.3/envs/venv34 in
  example above) . .python-version files are used by pyenv to denote
  local Python versions and can be created and deleted with the pyenv
  local command.

So first question is: Why this doesn't work? Why the virtual environment is not activated / deactivated automatically at entering / leaving a directory containing a .python-version file?

Also when I activate virtualenv by hand pyenv activate test and then check the Python version, it prints the system Python version and not the one from environment: Python 3.8.1:

python --version
Python 3.7.6

I can get the right Python version only by directly referring to virtualenv shims Python like this:

which python
/home/andre/.pyenv/shims/python
/home/andre/.pyenv/shims/python --version
Python 3.8.1

The behaviour is the same whenever the virtualenv "test" is activated or not.
I would expect that after activating "test" the command python --version returns Python 3.8.1

So second question: why pip and python are not switched when activating / deactivating the virtual environment ?

Are these pyenv bugs? Or am I doing something wrong?

Body:
It turns out that in order to automatically activate / deactivate a venv when entering / leaving a directory the .python-version file in there must contain the venv name and not the Python version associated with that venv

So executing:
pyenv local 3.8.1
creates a .python-version file which only includes the Python version 3.8.1.
Then entering / leaving a directory containing .python-version file will set / unset the Python version specified in that file but will not activate / deactivate any venv.

To create a .python-version file that will do both: activate a virtual environment and set Python version the command should look like: pyenv local test where test is a venv created with:
pyenv virtualenv 3.8.1 test.

So changing 3.8.1 to test in the .python-version fixed the problem.
After I done this the venv was activated / deactivated when entering / leaving directory containing .python-version.

But still the Python version did not change to the one associated with the venv (in this case 3.8.1)

Then I found out that I had two lines in my .profile that was causing this problem:

alias python=/home/linuxbrew/.linuxbrew/bin/python3
alias pip=/home/linuxbrew/.linuxbrew/bin/pip3

After removing these lines everything works as expected.

If still having any problems make sure you have these lines in your .profile or .bash_profile, whichever one you are using:

export PATH="$HOME/.pyenv/bin:$PATH"

eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

if command -v pyenv 1>/dev/null 2>&1; then
  export PYENV_ROOT="$HOME/.pyenv"
  export PATH="$PYENV_ROOT/bin:$PATH"
  eval "$(pyenv init --path)"
  eval "$(pyenv init -)"
fi


来源: stackexchange

问:
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
I included these in the Build Path:

all Spring libs

Apache Tomcat 7.0 library

The project still fails during startup:

```<code>SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
Jun 2, 2011 11:07:38 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
Jun 2, 2011 11:07:38 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class com.sun.faces.config.ConfigureListener
java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
</code>```

In org.sprintframework.web-3.1.0.M1.jar, I can see the org.springframework.web.context.ContextLoaderListener.

Someone on Google says that spring.jar should be included but I don't see any spring.jar in 3.x distribution.

Eclipse 3.6.2

Tomcat 7

Edit: Someone on the Spring Forum (offline) said "Automatically update dependencies" should be checked in Project Properties but I don't see anything like that in project properties.

答: If you're using maven, perhaps the project aint built yet. First do a mvn clean package then try redeploying again.

ContentLicense: CC BY-SA 4.0

Body:
I included these in the Build Path:

all Spring libs

Apache Tomcat 7.0 library

The project still fails during startup:

SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
Jun 2, 2011 11:07:38 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
Jun 2, 2011 11:07:38 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class com.sun.faces.config.ConfigureListener
java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)

In org.sprintframework.web-3.1.0.M1.jar, I can see the org.springframework.web.context.ContextLoaderListener.

Someone on Google says that spring.jar should be included but I don't see any spring.jar in 3.x distribution.

Eclipse 3.6.2

Tomcat 7

Edit: Someone on the Spring Forum (offline) said "Automatically update dependencies" should be checked in Project Properties but I don't see anything like that in project properties.


问:
MSWord how to unlink/break first link to excel document, without breaking remaining set of hyperlinks
I want to set up a word template, which has a linked excel table via a field with following code:

{LINK Excel.SheetMacroEnabled.12 D:\calendar.xlsm calendar!namedR \f 4 \h \* MERGEFORMAT}

The table resides in excel and is updated daily. The excel has several columns and one of them has a set of hyperlinks to various websites in rows. When I try to break the link to the table, in order to create rest of the document and archive it via the following code, I always get all of the links (including hyperlinks to websites) in the linked table broken.
The funny thing is that when I do it manually and select the table in Word it breaks only the link to the excel table, leaving the hyperlinks in a table column intact. This is the desired programmatic outcome. I tried 2 following macros and none of them works. Is there a way to achieve it via VBA without breaking all the links in a linked table?

```<code>Sub ConvertTableLink()

    Dim myField As Field

   For Each myField In ActiveDocument.Fields
      If myField.Type = wdFieldLink Then
         myField.Unlink
      End If
   Next

End Sub

Sub ConvertTableLinkTake2()

   ActiveDocument.Fields(1).Update
   ActiveDocument.Fields(1).Unlink

End Sub

</code>```

答:
For example, assuming the linked object is the first field in the document:</p>

```<code>Sub Demo()
Dim Rng As Range, Hlnk As Hyperlink, i As Long
Dim StrDisp As String, StrLink As String, StrFont As String, StrSize As String
With ActiveDocument.Fields(1)
  Set Rng = .Result
  With Rng
    For Each Hlnk In .Hyperlinks
      StrDisp = StrDisp & "|" & Hlnk.TextToDisplay
      StrLink = StrLink & "|" & Hlnk.Address
      StrFont = StrFont & "|" & Hlnk.Range.Font.Name
      StrSize = StrSize & "|" & Hlnk.Range.Font.Size
    Next
  End With
  .Unlink
  With Rng
    For i = 1 To UBound(Split(StrDisp, "|"))
      With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Forward = True
        .Format = False
        .Text = Split(StrDisp, "|")(i)
        .Replacement.Text = ""
        .Wrap = wdFindStop
        .Execute
      End With
      Set Hlnk = .Hyperlinks.Add(Anchor:=.Duplicate, Address:=Split(StrLink, "|")(i), TextToDisplay:=Split(StrDisp, "|")(i))
      Hlnk.Range.Font.Name = Split(StrFont, "|")(i)
      Hlnk.Range.Font.Size = Split(StrSize, "|")(i)
    Next
  End With
End With
End Sub
</code>```

Body:
I want to set up a word template, which has a linked excel table via a field with following code:

{LINK Excel.SheetMacroEnabled.12 D:\calendar.xlsm calendar!namedR \f 4 \h \* MERGEFORMAT}

The table resides in excel and is updated daily. The excel has several columns and one of them has a set of hyperlinks to various websites in rows. When I try to break the link to the table, in order to create rest of the document and archive it via the following code, I always get all of the links (including hyperlinks to websites) in the linked table broken.
The funny thing is that when I do it manually and select the table in Word it breaks only the link to the excel table, leaving the hyperlinks in a table column intact. This is the desired programmatic outcome. I tried 2 following macros and none of them works. Is there a way to achieve it via VBA without breaking all the links in a linked table?

Sub ConvertTableLink()

    Dim myField As Field

   For Each myField In ActiveDocument.Fields
      If myField.Type = wdFieldLink Then
         myField.Unlink
      End If
   Next

End Sub

Sub ConvertTableLinkTake2()

   ActiveDocument.Fields(1).Update
   ActiveDocument.Fields(1).Unlink

End Sub

Body:
For example, assuming the linked object is the first field in the document:

Sub Demo()
Dim Rng As Range, Hlnk As Hyperlink, i As Long
Dim StrDisp As String, StrLink As String, StrFont As String, StrSize As String
With ActiveDocument.Fields(1)
  Set Rng = .Result
  With Rng
    For Each Hlnk In .Hyperlinks
      StrDisp = StrDisp & "|" & Hlnk.TextToDisplay
      StrLink = StrLink & "|" & Hlnk.Address
      StrFont = StrFont & "|" & Hlnk.Range.Font.Name
      StrSize = StrSize & "|" & Hlnk.Range.Font.Size
    Next
  End With
  .Unlink
  With Rng
    For i = 1 To UBound(Split(StrDisp, "|"))
      With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Forward = True
        .Format = False
        .Text = Split(StrDisp, "|")(i)
        .Replacement.Text = ""
        .Wrap = wdFindStop
        .Execute
      End With
      Set Hlnk = .Hyperlinks.Add(Anchor:=.Duplicate, Address:=Split(StrLink, "|")(i), TextToDisplay:=Split(StrDisp, "|")(i))
      Hlnk.Range.Font.Name = Split(StrFont, "|")(i)
      Hlnk.Range.Font.Size = Split(StrSize, "|")(i)
    Next
  End With
End With
End Sub


问:
How do I add a correctly formatted link (with a hash mark) to an email message using intent on Android?
I am creating an email intent and filling the message with a link that contains a hashmark:

```<code>emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://en.wikipedia.org/wiki/Android_(operating_system)#Software_development");
</code>```

Once I send this and reopen it on Android, the default mail client only makes the link to http://en.wikipedia.org/wiki/Android_(operating_system)

Is there a way to fix this problem?

答:
Try the following. I am unable to test my code because of problem in my IDE.

```<code>final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setType("text/html");
            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("http://en.wikipedia.org/wiki/Android_(operating_system)#Software_development"));
</code>```

Thanks
Deepak

ContentLicense: CC BY-SA 3.0

Body:
I am creating an email intent and filling the message with a link that contains a hashmark:

emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://en.wikipedia.org/wiki/Android_(operating_system)#Software_development");

Once I send this and reopen it on Android, the default mail client only makes the link to http://en.wikipedia.org/wiki/Android_(operating_system)

Is there a way to fix this problem?

Body:
Try the following. I am unable to test my code because of problem in my IDE.

final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setType("text/html");
            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("http://en.wikipedia.org/wiki/Android_(operating_system)#Software_development"));

Thanks
Deepak


问:
How can I make my conditionals working in this JavaScript piece of code?
I'm writing some JavaScript code as part of my homework to create a password generator app and I have decided to put all the questions that I should ask from the user inside a function. One of the criteria to generate a password is to choose the number of characters between 8 and 128. I wanted to be sure that the user enters the correct number otherwise the function restarts and won't let the user see the rest of the confirm boxes until he enters the desired number so I wrote it like this:

```<code>function askQuestions() {
  let numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
  console.log(numOfChracaters);
  if (numOfChracaters >= 8 || numOfChracaters <= 128) {
    let hasUppercase = confirm("Do you want your password to include uppercase letters?");
    let hasLowercase = confirm("Do you want your password to include lowercase letters?");
    let hasNumber = confirm("Do you want your password to include numbers?");
    let hasSpecialCharacters = confirm("Do you want your password to include special characters?");

    let prefrencesArray = [numOfChracaters, hasUppercase, hasLowercase, hasNumber, hasSpecialCharacters];
    return prefrencesArray;
  } else {
    askQuestions();
  }
}
</code>```

But for some reason it doesn't work and still allows user to enter whatever number they want. Any ideas what did I do wrong here?

答:
if (numOfChracaters >= 8 && numOfChracaters <= 128)

Since for your OR (||) operator, it was true for the condition numOfChracaters <= 128, thus according to you inputs
 (false || true)=> returns true. and (false && true)=> return false

Explaining your mistake so that next time you don't make such error.

Body:
I'm writing some JavaScript code as part of my homework to create a password generator app and I have decided to put all the questions that I should ask from the user inside a function. One of the criteria to generate a password is to choose the number of characters between 8 and 128. I wanted to be sure that the user enters the correct number otherwise the function restarts and won't let the user see the rest of the confirm boxes until he enters the desired number so I wrote it like this:

function askQuestions() {
  let numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
  console.log(numOfChracaters);
  if (numOfChracaters >= 8 || numOfChracaters <= 128) {
    let hasUppercase = confirm("Do you want your password to include uppercase letters?");
    let hasLowercase = confirm("Do you want your password to include lowercase letters?");
    let hasNumber = confirm("Do you want your password to include numbers?");
    let hasSpecialCharacters = confirm("Do you want your password to include special characters?");

    let prefrencesArray = [numOfChracaters, hasUppercase, hasLowercase, hasNumber, hasSpecialCharacters];
    return prefrencesArray;
  } else {
    askQuestions();
  }
}

But for some reason it doesn't work and still allows user to enter whatever number they want. Any ideas what did I do wrong here?


问:
Converting multiple oracle join to multiple ANSI join
Using this tool: http://107.170.101.241:8080/joinConverter/

I see that a simple Oracle join is converted from:

```<code> SELECT *
     FROM Table1 t1,
          Table2 t2
    WHERE t1.id = t2.id
</code>```

to ANSI join:

```<code>SELECT *
     FROM Table1 t1
inner join Table2 t2 on t1.id = t2.id
</code>```

However, it errors out for more complex queries like this one:

```<code>SELECT *
 FROM Table1 t1,
      Table2 t2,
      Table3 t3
WHERE t2.id = t3.id
  AND t1.account_id = 5
  AND t2.coord in (t1.w, t1.x, t1.y, t1.z)
  AND t3.num IS NOT NULL
</code>```

I get the error:

```<code>Error 1, Message: This table has no join condition: Table2
Error 2, Message: This table has no join condition: Table3
</code>```

How would I fix this? What would be the appropriate ANSI syntax to use?

答:
The syntax is:</p>

```<code>SELECT *
FROM Table1 t1 JOIN
     Table2 t2
     ON t2.coord IN (t1.w, t1.x, t1.y, t1.z) JOIN
     Table3 t3
     ON t2.id = t3.id
WHERE t1.account_id = 5
      t3.num IS NOT NULL
</code>```

Body:
Using this tool: http://107.170.101.241:8080/joinConverter/

I see that a simple Oracle join is converted from:

 SELECT *
     FROM Table1 t1,
          Table2 t2
    WHERE t1.id = t2.id

to ANSI join:

SELECT *
     FROM Table1 t1
inner join Table2 t2 on t1.id = t2.id

However, it errors out for more complex queries like this one:

SELECT *
 FROM Table1 t1,
      Table2 t2,
      Table3 t3
WHERE t2.id = t3.id
  AND t1.account_id = 5
  AND t2.coord in (t1.w, t1.x, t1.y, t1.z)
  AND t3.num IS NOT NULL

I get the error:

Error 1, Message: This table has no join condition: Table2
Error 2, Message: This table has no join condition: Table3

How would I fix this? What would be the appropriate ANSI syntax to use?

Body:
The syntax is:

SELECT *
FROM Table1 t1 JOIN
     Table2 t2
     ON t2.coord IN (t1.w, t1.x, t1.y, t1.z) JOIN
     Table3 t3
     ON t2.id = t3.id
WHERE t1.account_id = 5
      t3.num IS NOT NULL


问:
Get text string between first and 2nd comma
Let's say I have this text within a specific H1 called ".prop-address h1":

```<code><h1>31620 NE 129th St, Duvall, WA 98019</h1>
</code>```

How do I get the text "Duvall" (text between first & second comma) with Jquery/JS so I can use it for whatever purposes? I've looked up a bunch of stuff but can't seem to make it work. Thanks in advance!

Body:
Let's say I have this text within a specific H1 called ".prop-address h1":

31620 NE 129th St, Duvall, WA 98019

How do I get the text "Duvall" (text between first & second comma) with Jquery/JS so I can use it for whatever purposes? I've looked up a bunch of stuff but can't seem to make it work. Thanks in advance!

Body:
<h1 class='prop-address'>31620 NE 129th St, Duvall, WA 98019</h1>
<script>
  var text = document.querySelector("h1.prop-address").firstChild.nodeValue;
  var res = text.split(',')[1].trim();
  console.log(res)
</script>


问:
ArrayList keeps giving me null
I was successful in creating the file and the citizen classes but the ArrayList used to store the citizens is giving me errors. I checked if it was declared and appended properly but if I try to run a method  on the ArrayList data it gives me null in the command line</p>

```<code>import java.io.*;
import java.util.*;

public class SNIDApp
{

  private SNIDDb sNIDDb;
  private ArrayList<Citizen> data;

  public SNIDApp(String name, char delimiter) throws Exception
  {
    this.sNIDDb = new SNIDDb(name,delimiter);
    String[] cits;
    while(sNIDDb.hasNext())
    {
      try{
      String[] a=sNIDDb.getNext();
      System.out.println(Arrays.toString(a));
      char sex= a[0].charAt(0);
      int year=Integer.parseInt(a[1]);
      Citizen cit=new Citizen(sex,year,a[2],a[3],a[4]);
      System.out.println(cit.getName());
      data.add(cit);
      //System.out.println(data.isEmpty());
      }
      catch(Exception e){
        System.out.println(e.getMessage());
      }
    }
  }

  public ArrayList<Citizen> getData() throws Exception
  {
    return this.data;
  }
}
</code>```

答:
Seems like your ArrayList is never initialized.

Use

```<code>private ArrayList<Citizen> data = new ArrayList<>();
</code>```

Title: ArrayList keeps giving me null

Body:
I was successful in creating the file and the citizen classes but the ArrayList used to store the citizens is giving me errors. I checked if it was declared and appended properly but if I try to run a method  on the ArrayList data it gives me null in the command line

import java.io.*;
import java.util.*;

public class SNIDApp
{

  private SNIDDb sNIDDb;
  private ArrayList<Citizen> data;

  public SNIDApp(String name, char delimiter) throws Exception
  {
    this.sNIDDb = new SNIDDb(name,delimiter);
    String[] cits;
    while(sNIDDb.hasNext())
    {
      try{
      String[] a=sNIDDb.getNext();
      System.out.println(Arrays.toString(a));
      char sex= a[0].charAt(0);
      int year=Integer.parseInt(a[1]);
      Citizen cit=new Citizen(sex,year,a[2],a[3],a[4]);
      System.out.println(cit.getName());
      data.add(cit);
      //System.out.println(data.isEmpty());
      }
      catch(Exception e){
        System.out.println(e.getMessage());
      }
    }
  }

  public ArrayList<Citizen> getData() throws Exception
  {
    return this.data;
  }
}

Body:
Seems like your ArrayList is never initialized.

Use

private ArrayList<Citizen> data = new ArrayList<>();


问:
Adding a React Component within dangerouslySetInnerHtml or similar
I'm making a Gatsby site, and after running some GraphQL queries, I pass some HTML strings into React components. I've been able to render these with dangerouslySetInnerHtml, html-react-parser, etc. However, I'd like to also just write component tags within the original Markdown and render those as components.

A simple example of this would be

```<code>import React from "react";

export default function App() {
  const RedDiv = () => {
    return <div style={{ color: "red" }}>This is a red div</div>;
  };

  const StringRedDiv = "<div style={{color: 'red'}}>This is a red div</div>";

  return (
    <div className="App">
      <RedDiv />
      <div dangerouslySetInnerHTML={{ __html: StringRedDiv }} />
    </div>
  );
}
</code>```

CodeSandbox

Obviously, we don't need to use dangerouslySetInnerHtml here, but I'd like to achieve the desired effect (in this case having both divs have red text) using a method which takes an HTML string and transforms it into React.

答:
For that, you can use the react-html-parser like this:

import React from 'react';
import ReactHtmlParser from 'react-html-parser';

class HtmlComponent extends React.Component {
  render() {
    const html = "
This is a red div
";
    return
{ ReactHtmlParser(html) }
;
  }
}
```

<p>On a side note, in order for the <code>dangerouslySetInnerHTML</code> or alternatively the <code>ReactHtmlParser</code> to work, you must use valid HTML attributes.</p>

<p>For instance, the style attribute in your example:</p>

<pre class="lang-html prettyprint-override"><code><div style={{color: 'red'}}>This is a red div</div>
</code>```

should be changed to:

This is a red div

```

Body:
I'm making a Gatsby site, and after running some GraphQL queries, I pass some HTML strings into React components. I've been able to render these with dangerouslySetInnerHtml, html-react-parser, etc. However, I'd like to also just write component tags within the original Markdown and render those as components.

A simple example of this would be

import React from "react";

export default function App() {
  const RedDiv = () => {
    return
This is a red div
;
  };

  const StringRedDiv = "
This is a red div
";

  return (

      <RedDiv />

  );
}

CodeSandbox

Obviously, we don't need to use dangerouslySetInnerHtml here, but I'd like to achieve the desired effect (in this case having both divs have red text) using a method which takes an HTML string and transforms it into React.

Body:
For that, you can use the react-html-parser like this:

import React from 'react';
import ReactHtmlParser from 'react-html-parser';

class HtmlComponent extends React.Component {
  render() {
    const html = "<div style={{color: 'red'}}>This is a red div</div>";
    return <div>{ ReactHtmlParser(html) }</div>;
  }
}

On a side note, in order for the dangerouslySetInnerHTML or alternatively the ReactHtmlParser to work, you must use valid HTML attributes.

For instance, the style attribute in your example:

<div style={{color: 'red'}}>This is a red div</div>

should be changed to:

<div style="color: red;">This is a red div</div>


问:
Flutter: setState((){} fails to redraw DropdownButton value
I am new to flutter, and am trying to code mobile game. So far I have been able to manage through previous questions on forums, youtube tutorials and example apps. However I have hit a wall that I cannot solve.

Many of the features in my UI are supposed to change based on user behavior but do not update, I am using this DropdownButton as my example but it is a problem I am having elsewhere in the code as well. When the user makes a selection from the DropdownButton it should update the value of the button, but instead only the hint is displayed. I have been able to determine through print statements that the selection is registered.

Based on what I have learned so far I suspect that the issue entails my widget's statefulness or lack thereof. I found a few similar questions which suggested using a StatefulBuilder, however when I tried to implement it the code had errors or else duplicated my entire ListTile group. I also saw suggestions about creating a stateful widget instead but the instructions were too vague for me to follow and implement without errors. I am including snippets of the code below, I am hesitant to paste the whole thing because the app is nearly 2000 lines at this point. Please let me know if any further information or code is needed.
this is the problematic code, see below for the code in context.

```<code>        DropdownButton(
          value: skillChoice,
          items: listDrop,
          hint: Text("Choose Skill"),
          onChanged: (value) {
            setState(() {
              skillChoice = value;
            });
          },
        ),
</code>```
```<code>void main() => runApp(MyApp());
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hunters Guild',
      theme: ThemeData(
        primaryColor: Colors.grey,
      ),
      home: Main(),
    );
  }
}
final List<Combatant> _combatants = List<Combatant>();
//combatant is a class that holds stats like HP which may change during a battle
//they also have a Fighter and a Monster and one of those will be null and the other useful
//depending if faction = "good" or "evil
//I am aware that this may not be the most elegant implementation but that is a problem for another day.

class MainState extends State<Main> {
  final List<Fighter> _squad = List<Fighter>();
//Fighter is a class which stores info like HP, name, skills, etc for game character,
//this List is populated in the page previous to _fight
//where the user picks which characters they are using in a given battle
void _fight(Quest theQuest){
    for(Fighter guy in _squad){
      _combatants.add(Combatant("good", guy, null));
    }
    _combatants.add(Combatant("evil", null, theQuest.boss));
//quests are a class which store a boss Monster, later on I will add other things like rewards and prerequisites
final tiles = _combatants.map((Combatant comba){ //this structure is from the build your first app codelab
      List<DropdownMenuItem<String>> listDrop = [];
      String skillChoice = null;
      if (comba.faction == "good"){
        for (Skill skill in comba.guy.skills){
          listDrop.add((DropdownMenuItem(child: Text(skill.name), value: skill.name)));
        }
      }
      else if (comba.faction == "evil"){
        for (Skill skill in comba.boss.skills){
          listDrop.add((DropdownMenuItem(child: Text(skill.name), value: skill.name)));
        }
      }
//^this code populates each ListTile (one for each combatant) with a drop down button of all their combat skills
      return ListTile(

        leading: comba.port,
        title: Text(comba.info),
        onTap: () {
          if(comba.faction == "good"){
            _fighterFightInfo(comba.guy, theQuest.boss); //separate page with more detailed info, not finished
          }
          else{
            _monsterFightInfo(theQuest.boss); //same but for monsters
          }
        },
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [

            DropdownButton( //HERE IS WHERE THE ERROR LIES
              value: skillChoice,
              items: listDrop,
              hint: Text("Choose Skill"),
              onChanged: (value) {
                setState(() {
                  skillChoice = value;
                });
              },
            ),
            IconButton(icon: Icon(Icons.check), onPressed: (){
//eventually this button will be used to execute the user's skill choice
            })
          ],
        ),
        subtitle: Text(comba.hp.toString()),
      );
    },
    );
    Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) {
//I have tried moving most of the above code into here,
//and also implementing StatelessBuilders here and other places in the below code to no effect
          final divided = ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList();
          return Scaffold(
            appBar: AppBar(
              title: Text("Slay "+theQuest.boss.name+"  "+theQuest.boss.level.toString()+"  "+theQuest.boss.type.name, style: TextStyle(fontSize: 14),),
              leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: () {
                _squadSelect(theQuest);
              }),
            ),
            body: ListView(children: divided),
          );
        },
      ),
    );
  }
//there are a lot more methods here which I haven't included
 @override

  Widget build(BuildContext context) {
//I can show this if you need it but there's a lot of UI building on the main page
//Also might not be the most efficiently implemented
//what you need to know is that there are buttons which call _fight and go to that page
}
class Main extends StatefulWidget {
  @override
  MainState createState() => MainState();
}

</code>```

Thank you for any help or advice you can offer.

答:
The following question had information which helped me find the answer. Different question but the solution applies. Thanks user:4576996 Sven. Basically I need to reformat from doing my constructing in the void _fight to a new stateful page. This may be useful for anyone else who is using the beginning tutorial as a framework to build their app.

flutter delete item from listview

Body:
I am new to flutter, and am trying to code mobile game. So far I have been able to manage through previous questions on forums, youtube tutorials and example apps. However I have hit a wall that I cannot solve.

Many of the features in my UI are supposed to change based on user behavior but do not update, I am using this DropdownButton as my example but it is a problem I am having elsewhere in the code as well. When the user makes a selection from the DropdownButton it should update the value of the button, but instead only the hint is displayed. I have been able to determine through print statements that the selection is registered.

Based on what I have learned so far I suspect that the issue entails my widget's statefulness or lack thereof. I found a few similar questions which suggested using a StatefulBuilder, however when I tried to implement it the code had errors or else duplicated my entire ListTile group. I also saw suggestions about creating a stateful widget instead but the instructions were too vague for me to follow and implement without errors. I am including snippets of the code below, I am hesitant to paste the whole thing because the app is nearly 2000 lines at this point. Please let me know if any further information or code is needed.
this is the problematic code, see below for the code in context.

        DropdownButton(
          value: skillChoice,
          items: listDrop,
          hint: Text("Choose Skill"),
          onChanged: (value) {
            setState(() {
              skillChoice = value;
            });
          },
        ),

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hunters Guild',
      theme: ThemeData(
        primaryColor: Colors.grey,
      ),
      home: Main(),
    );
  }
}
final List<Combatant> _combatants = List<Combatant>();
//combatant is a class that holds stats like HP which may change during a battle
//they also have a Fighter and a Monster and one of those will be null and the other useful
//depending if faction = "good" or "evil
//I am aware that this may not be the most elegant implementation but that is a problem for another day.

class MainState extends State {
  final List<Fighter> _squad = List<Fighter>();
//Fighter is a class which stores info like HP, name, skills, etc for game character,
//this List is populated in the page previous to _fight
//where the user picks which characters they are using in a given battle
void _fight(Quest theQuest){
    for(Fighter guy in _squad){
      _combatants.add(Combatant("good", guy, null));
    }
    _combatants.add(Combatant("evil", null, theQuest.boss));
//quests are a class which store a boss Monster, later on I will add other things like rewards and prerequisites
final tiles = _combatants.map((Combatant comba){ //this structure is from the build your first app codelab
      List<DropdownMenuItem<String>> listDrop = [];
      String skillChoice = null;
      if (comba.faction == "good"){
        for (Skill skill in comba.guy.skills){
          listDrop.add((DropdownMenuItem(child: Text(skill.name), value: skill.name)));
        }
      }
      else if (comba.faction == "evil"){
        for (Skill skill in comba.boss.skills){
          listDrop.add((DropdownMenuItem(child: Text(skill.name), value: skill.name)));
        }
      }
//^this code populates each ListTile (one for each combatant) with a drop down button of all their combat skills
      return ListTile(

        leading: comba.port,
        title: Text(comba.info),
        onTap: () {
          if(comba.faction == "good"){
            _fighterFightInfo(comba.guy, theQuest.boss); //separate page with more detailed info, not finished
          }
          else{
            _monsterFightInfo(theQuest.boss); //same but for monsters
          }
        },
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [

            DropdownButton( //HERE IS WHERE THE ERROR LIES
              value: skillChoice,
              items: listDrop,
              hint: Text("Choose Skill"),
              onChanged: (value) {
                setState(() {
                  skillChoice = value;
                });
              },
            ),
            IconButton(icon: Icon(Icons.check), onPressed: (){
//eventually this button will be used to execute the user's skill choice
            })
          ],
        ),
        subtitle: Text(comba.hp.toString()),
      );
    },
    );
    Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) {
//I have tried moving most of the above code into here,
//and also implementing StatelessBuilders here and other places in the below code to no effect
          final divided = ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList();
          return Scaffold(
            appBar: AppBar(
              title: Text("Slay "+theQuest.boss.name+"  "+theQuest.boss.level.toString()+"  "+theQuest.boss.type.name, style: TextStyle(fontSize: 14),),
              leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: () {
                _squadSelect(theQuest);
              }),
            ),
            body: ListView(children: divided),
          );
        },
      ),
    );
  }
//there are a lot more methods here which I haven't included
 @override

  Widget build(BuildContext context) {
//I can show this if you need it but there's a lot of UI building on the main page
//Also might not be the most efficiently implemented
//what you need to know is that there are buttons which call _fight and go to that page
}
class Main extends StatefulWidget {
  @override
  MainState createState() => MainState();
}

Thank you for any help or advice you can offer.


问:
Make a database and tables via php
I want to create a database automatically, execute /tmp/tmp.sql that describes the template table, and register it in the newly created database.

```<code><?php
    //create db
    $uuid= "uniqueID";
    $dbname = $uuid.'_reservedb';

    //connectーーーーーーーーーーーーーーーー
    $dsn = 'mysql:;host=localhost';
    $user = 'root';

    try {
        $dbh = new PDO($dsn, $user);
        print_r("success\n");
    } catch (PDOException $e) {
        print_r('Error:'.$e->getMessage());
        die();
    }
    print_r($dbname."\n");

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = file_get_contents('/tmp/tmp.sql');
    $rtn=$dbh->exec($sql);
    if($rtn){
        print_r("OK\n");
    }else
        print_r("NG\n");;
    ?>
</code>```

It shows message "success" and "OK", but there is not new database named "success
uniqueID_reservedb" checked from SQL command "show databases;"
I confirmed with the SQL command "show databases", but there is no new database.

Of course, /tmp/tmp.sql is not running.

Please let me know what's wrong?

答:
exec returns number or rows affected or FALSE, so your test is incorrect as per the documentation.

Note: it says executes A SQL statement, not many.

Title: Make a database and tables via php

Body:
I want to create a database automatically, execute /tmp/tmp.sql that describes the template table, and register it in the newly created database.

<?php
    //create db
    $uuid= "uniqueID";
    $dbname = $uuid.'_reservedb';

    //connectーーーーーーーーーーーーーーーー
    $dsn = 'mysql:;host=localhost';
    $user = 'root';

    try {
        $dbh = new PDO($dsn, $user);
        print_r("success\n");
    } catch (PDOException $e) {
        print_r('Error:'.$e->getMessage());
        die();
    }
    print_r($dbname."\n");

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = file_get_contents('/tmp/tmp.sql');
    $rtn=$dbh->exec($sql);
    if($rtn){
        print_r("OK\n");
    }else
        print_r("NG\n");;
    ?>

It shows message "success" and "OK", but there is not new database named "success
uniqueID_reservedb" checked from SQL command "show databases;"
I confirmed with the SQL command "show databases", but there is no new database.

Of course, /tmp/tmp.sql is not running.

Please let me know what's wrong?


问:
How to separate or draw some independent legends in a linear plot?
I have been struggling to visually separate the legends. My data only has time vs amount of different growth values, but I need to separate the Raw Data (colored lines) from the geometric mean (black smooth curve).

Growth curves A

Growth Curves B

I have "successfully" plotted them, but I either get a plot with the 'geometric mean' without it appearing in the legend, or all four curves in the same legend.

I would love to separate them, so that the three lines have the title "Fluorescence excitation at" title, and the geometric mean of these lines, just the name "60 mM Mean". The reason I want that data to be separated is because I will be creating other graphs that will compare the mean fluorescence excitation at different concentrations (60, 30, 15, so on).

Data: Small file with the data frame (28 observations of 11 numerical variables)

Here is my code for A:

```<code>GraphChl60mM <- ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  #Geometric mean
  geom_smooth(aes(y=Mean.60.mM, colour= "60 mM"), method = "loess", alpha = 0.5) +
  #colour= "Black"
  theme_minimal() +
  #theme(legend.position="none") +
  labs(y = "Fluorescence intensity", x = "Time (days)", title = expression(paste("Growth curve of ",
   italic("Chlorella vulgaris "), "UTEX 2714 at 60 mM"))) +
#  guides(colour = guide_legend(override.aes = list(pch = c(16,17,18,21), fill = c('gray', 'grey', 'gray', "gray")))) +
#  guides(color=guide_legend("Mean excitation at")) +
    scale_color_manual(name =bquote(paste("Mean excitation at ", lambda)),
                       values = c( "335 nm" = "blue", "440 nm" = "red", "480 nm" = "orange", "60 mM" = "black"),
                       labels = c("335 nm", "440 nm", "480 nm", "Geometric mean values")) +
  coord_cartesian(ylim=c(0, 10000))
</code>```

And the code for graph B

```<code>
GraphChl60mM <- ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  #Promedio
  geom_smooth(aes(y= df_Comparative_Chlorella$`Mean.60.mM`, colour= "30 mM"), color= "Black", method = "loess") +

  theme_minimal() +
  #theme(legend.position="none") +
  labs(y = "Fluorescence intensity", x = "Time (h)", title = expression(paste(italic("C. vulgaris "), "UTEX 2714 at 60 mM"))) +
  coord_cartesian(ylim=c(0, 10000))

</code>```

答:
I'm not very skilled with ggplot2 but your question drew my interest, so I tried a few things with your second code based on this blog post.

ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  theme_minimal() +
  labs(y = "Fluorescence intensity", x = "Time (h)", title = expression(paste(italic("C. vulgaris "), "UTEX 2714 at 60 mM"))) +
  coord_cartesian(ylim=c(0, 10000)) +

  scale_color_hue(bquote(paste("Mean excitation at ", lambda))) +

  geom_smooth(aes(y=Mean.60.mM, colour= "30 mM", fill="Geom. Mean"), colour="Black", method = "loess")+

  scale_fill_manual("Geometric mean values", values=rep(1,4), guide=guide_legend(override.aes = list(colour=c("Black"))))
```

This yields

Perhaps you can use this answer to proceed further your desired result.

Body:
I have been struggling to visually separate the legends. My data only has time vs amount of different growth values, but I need to separate the Raw Data (colored lines) from the geometric mean (black smooth curve).

Growth curves A

Growth Curves B

I have "successfully" plotted them, but I either get a plot with the 'geometric mean' without it appearing in the legend, or all four curves in the same legend.

I would love to separate them, so that the three lines have the title "Fluorescence excitation at" title, and the geometric mean of these lines, just the name "60 mM Mean". The reason I want that data to be separated is because I will be creating other graphs that will compare the mean fluorescence excitation at different concentrations (60, 30, 15, so on).

Data: Small file with the data frame (28 observations of 11 numerical variables)

Here is my code for A:

GraphChl60mM <- ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  #Geometric mean
  geom_smooth(aes(y=Mean.60.mM, colour= "60 mM"), method = "loess", alpha = 0.5) +
  #colour= "Black"
  theme_minimal() +
  #theme(legend.position="none") +
  labs(y = "Fluorescence intensity", x = "Time (days)", title = expression(paste("Growth curve of ",
   italic("Chlorella vulgaris "), "UTEX 2714 at 60 mM"))) +
#  guides(colour = guide_legend(override.aes = list(pch = c(16,17,18,21), fill = c('gray', 'grey', 'gray', "gray")))) +
#  guides(color=guide_legend("Mean excitation at")) +
    scale_color_manual(name =bquote(paste("Mean excitation at ", lambda)),
                       values = c( "335 nm" = "blue", "440 nm" = "red", "480 nm" = "orange", "60 mM" = "black"),
                       labels = c("335 nm", "440 nm", "480 nm", "Geometric mean values")) +
  coord_cartesian(ylim=c(0, 10000))

And the code for graph B

GraphChl60mM <- ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  #Promedio
  geom_smooth(aes(y= df_Comparative_Chlorella$`Mean.60.mM`, colour= "30 mM"), color= "Black", method = "loess") +

  theme_minimal() +
  #theme(legend.position="none") +
  labs(y = "Fluorescence intensity", x = "Time (h)", title = expression(paste(italic("C. vulgaris "), "UTEX 2714 at 60 mM"))) +
  coord_cartesian(ylim=c(0, 10000))

Body:
I'm not very skilled with ggplot2 but your question drew my interest, so I tried a few things with your second code based on this blog post.

ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  theme_minimal() +
  labs(y = "Fluorescence intensity", x = "Time (h)", title = expression(paste(italic("C. vulgaris "), "UTEX 2714 at 60 mM"))) +
  coord_cartesian(ylim=c(0, 10000)) +

  scale_color_hue(bquote(paste("Mean excitation at ", lambda))) +

  geom_smooth(aes(y=Mean.60.mM, colour= "30 mM", fill="Geom. Mean"), colour="Black", method = "loess")+

  scale_fill_manual("Geometric mean values", values=rep(1,4), guide=guide_legend(override.aes = list(colour=c("Black"))))

This yields

Perhaps you can use this answer to proceed further your desired result.


问:
iPad - General Network->What is the UI control?
In the below image, what is the UI control used to create the "Other Network" dialog? We need to create a similar non-full-screen popup.

答:
I think what you're looking for is a UIModalPresentationFormSheet.

From Apple's UIViewController documentation reference

UIModalPresentationFormSheet
  The width and height of the presented view are smaller than those of the screen and the view is centered on the screen. If the device is in a landscape orientation and the keyboard is visible, the position of the view is adjusted upward so that the view remains visible. All uncovered areas are dimmed to prevent the user from interacting with them.
  Available in iOS 3.2 and later.
  Declared in UIViewController.h.

See this article for an example Display a view using modalPresentationStyle


问:
How to map images in reactjs
So in a Reactjs class component, I have an array in my state like this:

```<code>myArray: [
   { number: 1, title: 'Users', image: '../../../assets/images/website/homepage/users.png' },
   { number: 2, title: 'Clients', image: '../../../assets/images/website/homepage/clients.png' },
   { number: 3, title: 'Admin', image: '../../../assets/images/website/homepage/admins.png' },
]
</code>```

and I mapped the array this way:

```<code>{this.state.myArray.map((item, index) => (
   <Box key={index} className="col-sm-12">
      <img src={ item.image } className="img-fluid" alt={item.title} />
      <Typography variant="h4">{item.number}</Typography>
   </Box>
))}
</code>```

Now, everything works fine, except the image that doesn't display, I really don't understand where I'm getting it wrong.

Note that, if I copy one of the image links directly inside the src using require method, it works. Kindly help.

答:
I think you are missing require.

Like:

```<code><img src={require(item.image)} />
</code>```

Title: How to map images in reactjs

Body:
So in a Reactjs class component, I have an array in my state like this:

myArray: [
   { number: 1, title: 'Users', image: '../../../assets/images/website/homepage/users.png' },
   { number: 2, title: 'Clients', image: '../../../assets/images/website/homepage/clients.png' },
   { number: 3, title: 'Admin', image: '../../../assets/images/website/homepage/admins.png' },
]

and I mapped the array this way:

{this.state.myArray.map((item, index) => (
   <Box key={index} className="col-sm-12">

      <Typography variant="h4">{item.number}</Typography>
   </Box>
))}

Now, everything works fine, except the image that doesn't display, I really don't understand where I'm getting it wrong.

Note that, if I copy one of the image links directly inside the src using require method, it works. Kindly help.

Body:
I think you are missing require.

Like:

<img src={require(item.image)} />


问:
UITableView checkmark style remove highlight on select
I am trying to remove the highlight when selecting a table view cell, but want to keep the checkmark that appears.

When I try this in cellForRowAtIndexPath:

```<code>    cell.backgroundView = UIView()
    cell.backgroundView?.backgroundColor = UIColor.clearColor()
</code>```

It only removes the highlight underneath the checkmark, rather than the whole row (refer to image attached).

When I try this in cellForRowAtIndexPath:

```<code>    cell.selectionStyle = UITableViewCellSelectionStyle.None
</code>```

It no longer displays the checkmark.

UPDATE: tried this, does the same thing as cell.selectionStyle where it no longer does checkmark

```<code>func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return false
}
</code>```

What is a good way of doing this? I want it to still function like a checkbox but just don't want the blue highlighting to occur. TableView is dynamically generated:

```<code>    checkBoxView = UITableView()
    checkBoxView.frame = CGRect(x: qView.bounds.midX, y: qView.bounds.midY, width: qView.bounds.width - 100, height: qView.bounds.height/1.5)
    checkBoxView.center = CGPointMake(qView.bounds.midX, qView.bounds.midY)
    checkBoxView.delegate = self
    checkBoxView.dataSource = self
    checkBoxView.tag = 100
    checkBoxView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    checkBoxView.setEditing(true, animated: true)
    self.qView.addSubview(checkBoxView)
</code>```

Table View Functions:

```<code>func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.checkBoxContent.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell = checkBoxView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    cell.textLabel?.text = self.checkBoxContent[indexPath.row]
    cell.backgroundColor = UIColor.clearColor()
    cell.tintColor = UIColor.greenColor()
    return cell
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    return UITableViewCellEditingStyle(rawValue: 3)!
}
</code>```

答:
None of the suggestions above worked for me. In Swift 5, add this line to your cellForRowAtIndexPath function:</p>

```<code>cell.selectionStyle = UITableViewCell.SelectionStyle.none
</code>```

Body:
I am trying to remove the highlight when selecting a table view cell, but want to keep the checkmark that appears.

When I try this in cellForRowAtIndexPath:

    cell.backgroundView = UIView()
    cell.backgroundView?.backgroundColor = UIColor.clearColor()

It only removes the highlight underneath the checkmark, rather than the whole row (refer to image attached).

When I try this in cellForRowAtIndexPath:

    cell.selectionStyle = UITableViewCellSelectionStyle.None

It no longer displays the checkmark.

UPDATE: tried this, does the same thing as cell.selectionStyle where it no longer does checkmark

func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return false
}

What is a good way of doing this? I want it to still function like a checkbox but just don't want the blue highlighting to occur. TableView is dynamically generated:

    checkBoxView = UITableView()
    checkBoxView.frame = CGRect(x: qView.bounds.midX, y: qView.bounds.midY, width: qView.bounds.width - 100, height: qView.bounds.height/1.5)
    checkBoxView.center = CGPointMake(qView.bounds.midX, qView.bounds.midY)
    checkBoxView.delegate = self
    checkBoxView.dataSource = self
    checkBoxView.tag = 100
    checkBoxView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    checkBoxView.setEditing(true, animated: true)
    self.qView.addSubview(checkBoxView)

Table View Functions:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.checkBoxContent.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell = checkBoxView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    cell.textLabel?.text = self.checkBoxContent[indexPath.row]
    cell.backgroundColor = UIColor.clearColor()
    cell.tintColor = UIColor.greenColor()
    return cell
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    return UITableViewCellEditingStyle(rawValue: 3)!
}

Body:
None of the suggestions above worked for me. In Swift 5, add this line to your cellForRowAtIndexPath function:

cell.selectionStyle = UITableViewCell.SelectionStyle.none


问:
Replacing a letter within a string - why is function not working?
the following function is supposed to be replacing instances of 't' with 'a' in a given string input. Not sure why it's not working - suggestions? Cheers</p>

```<code>const replaceLetter = (str) => {

  let newString = str.split(' ')

  for (let i = 0; i < newString.length; i++) {
    for (let j = 0; j < newString[i].length; j++){
      if (newString[i][j] === 't') {
        newString[i][j] = 'a'
      }
    }
  }
  return newString.join(' ')
}
</code>```

答:
Isn't it better with a regular expression?

const regex = /a/gi;

document.getElementById('result').textContent = document.getElementById('test').textContent.replace(regex, 't')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test">tatatatatat</div>
<div id="result"></div></code>```

Body:
the following function is supposed to be replacing instances of 't' with 'a' in a given string input. Not sure why it's not working - suggestions? Cheers

const replaceLetter = (str) => {

  let newString = str.split(' ')

  for (let i = 0; i < newString.length; i++) {
    for (let j = 0; j < newString[i].length; j++){
      if (newString[i][j] === 't') {
        newString[i][j] = 'a'
      }
    }
  }
  return newString.join(' ')
}

Body:
Isn't it better with a regular expression?

const regex = /a/gi;

document.getElementById('result').textContent = document.getElementById('test').textContent.replace(regex, 't')

<div id="test">tatatatatat</div>
<div id="result"></div>


答:
Javascript provide a method to replace string

```<code>    const demo = "tttttaaaaabbbb"
    const regex = /t/gi
    const result = demo.replace(regex, "a")
    console.log(result)
</code>```

read more the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Title: Replacing a letter within a string - why is function not working?

Body:
Javascript provide a method to replace string

    const demo = "tttttaaaaabbbb"
    const regex = /t/gi
    const result = demo.replace(regex, "a")
    console.log(result)

read more the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace


问:
Dockerfile and docker compose with node alpine
this is my docker file:

```<code>#building code
FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

CMD node dist/src/index.js
</code>```

and this is my docker compose:

```<code>version: '3.7'
services:
  db:
    image: postgres:12
    restart: always
    container_name: 'db'
    ports:
      - '${DB_PORT}:5432'
    volumes:
      - db_data:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}

  api:
    image: ci-api
    restart: always
    depends_on:
      - db
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
volumes:
  db_data:
</code>```

and i create my image with docker build docker build -t ci-api .

but if I make any changes to my project and use my docker build again it is not updating in the container

答:
This issue has been documented in docker/compose#4337, and the proposed fix is to use the flag --renew-anon-volumes in docker-compose up. Here is the documentation for docker-compose up.

You might consider changing your docker-compose.yml file to reference the Dockerfile in your api service. Then docker-compose up will build the image if it has to, and you don't have to build it yourself.

```<code>api:
  build:
    dockerfile: Dockerfile
    context: .
...
</code>```

Body:
this is my docker file:

#building code
FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

CMD node dist/src/index.js

and this is my docker compose:

version: '3.7'
services:
  db:
    image: postgres:12
    restart: always
    container_name: 'db'
    ports:
      - '${DB_PORT}:5432'
    volumes:
      - db_data:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}

  api:
    image: ci-api
    restart: always
    depends_on:
      - db
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
volumes:
  db_data:

and i create my image with docker build docker build -t ci-api .

but if I make any changes to my project and use my docker build again it is not updating in the container

Body:
This issue has been documented in docker/compose#4337, and the proposed fix is to use the flag --renew-anon-volumes in docker-compose up. Here is the documentation for docker-compose up.

You might consider changing your docker-compose.yml file to reference the Dockerfile in your api service. Then docker-compose up will build the image if it has to, and you don't have to build it yourself.

api:
  build:
    dockerfile: Dockerfile
    context: .
...


问:
Hello, i have a text file that i want to write in UTF-16 unicode using python
for example i read from the file 1:

```<code>ch="Hello world, this a stackoverflow example"
</code>```

i write in file 2 the unicode UTF-16, the output must be like that:

```<code>output="\u0048\u0065\u006c\u006c\u006f \u0077\u006f\u0072\u006c\u0064\u002c \u0074\u0068\u0069\u0073 \u0061 \u0073\u0074\u0061\u0063\u006b\u006f\u0076\u0065\u0072 \u0066\u006c\u006f\u0077 \u0065\u0078\u0061\u006d\u0070\u006c\u0065"
</code>```

i found how to convert or read, but not how to transform

答:
Just pass encoding="utf-16" when you open your output file:

ch="Hello world, this a stackoverflow example"

with open("utf_16.txt", "w", encoding="utf-16") as f:
   f.write(ch)
```

<pre class="lang-none prettyprint-override"><code>$ file utf_16.txt
utf_16.txt: Little-endian UTF-16 Unicode text, with no line terminators

$ hexdump -Cv utf_16.txt
00000000  ff fe 48 00 65 00 6c 00  6c 00 6f 00 20 00 77 00  |..H.e.l.l.o. .w.|
00000010  6f 00 72 00 6c 00 64 00  2c 00 20 00 74 00 68 00  |o.r.l.d.,.
.t.h.|
...
</code>```

Note that utf-16 encoding includes a Byte-Order Mark (BOM). If you don't want this, include the endianness in the encoding name (e.g. utf-16le):

ch="Hello world, this a stackoverflow example"

with open("utf_16.txt", "w", encoding="utf-16le") as f:
   f.write(ch)
```

<pre class="lang-none prettyprint-override"><code>$ file utf_16.txt
utf_16.txt: data

$ hexdump -Cv utf_16.txt
00000000  48 00 65 00 6c 00 6c 00  6f 00 20 00 77 00 6f 00  |H.e.l.l.o. .w.o.|
00000010  72 00 6c 00 64 00 2c 00  20 00 74 00 68 00 69 00  |r.l.d.,. .t.h.i.|
...
</code>```

Body:
for example i read from the file 1:

ch="Hello world, this a stackoverflow example"

i write in file 2 the unicode UTF-16, the output must be like that:

output="\u0048\u0065\u006c\u006c\u006f \u0077\u006f\u0072\u006c\u0064\u002c \u0074\u0068\u0069\u0073 \u0061 \u0073\u0074\u0061\u0063\u006b\u006f\u0076\u0065\u0072 \u0066\u006c\u006f\u0077 \u0065\u0078\u0061\u006d\u0070\u006c\u0065"

i found how to convert or read, but not how to transform

Body:
Just pass encoding="utf-16" when you open your output file:

ch="Hello world, this a stackoverflow example"

with open("utf_16.txt", "w", encoding="utf-16") as f:
   f.write(ch)

$ file utf_16.txt
utf_16.txt: Little-endian UTF-16 Unicode text, with no line terminators

$ hexdump -Cv utf_16.txt
00000000  ff fe 48 00 65 00 6c 00  6c 00 6f 00 20 00 77 00  |..H.e.l.l.o. .w.|
00000010  6f 00 72 00 6c 00 64 00  2c 00 20 00 74 00 68 00  |o.r.l.d.,.
.t.h.|
...

Note that utf-16 encoding includes a Byte-Order Mark (BOM). If you don't want this, include the endianness in the encoding name (e.g. utf-16le):

ch="Hello world, this a stackoverflow example"

with open("utf_16.txt", "w", encoding="utf-16le") as f:
   f.write(ch)

$ file utf_16.txt
utf_16.txt: data

$ hexdump -Cv utf_16.txt
00000000  48 00 65 00 6c 00 6c 00  6f 00 20 00 77 00 6f 00  |H.e.l.l.o. .w.o.|
00000010  72 00 6c 00 64 00 2c 00  20 00 74 00 68 00 69 00  |r.l.d.,. .t.h.i.|
...


问:
How can I extend object by mapping name with specific id from another object?
I am thinking to use _.extend and _.map but I am not sure how exactly. I am new to Lodash.

```<code>const students = [
    {'studentId': 1, 'name': 'Beth'},
    {'studentId': 2, 'name': 'Tina'}
];

const marks = [
    {'studentId': 1, 'score': '123'},
    {'studentId': 1, 'score': '200'},
    {'studentId': 2, 'score': '99'}
];

I want output as:
[
    {'studentId': 1, 'name': 'Beth', 'testScore': '123'},
    {'studentId': 1, 'name': 'Beth', 'testScore': '200'},
    {'studentId': 2, 'name': 'Tina', 'testScore': '99'}
];
</code>```

How can I do this?

答:
create object map of studentId: name.
map over marks and add name.  rename score to testScore.

const stus= [
    {'studentId': 1, 'name': 'Beth'},
    {'studentId': 2, 'name': 'Tina'}
];

const marks = [
    {'studentId': 1, 'score': '123'},
    {'studentId': 1, 'score': '200'},
    {'studentId': 2, 'score': '99'}
];

const stumap = stus.reduce((a,x)=>(a[x.studentId]=x.name,a),{});

console.log(JSON.stringify(
marks.map(({studentId, score:testScore})=>({studentId, testScore, name: stumap[studentId]}))
))```

Body:
I am thinking to use _.extend and _.map but I am not sure how exactly. I am new to Lodash.

const students = [
    {'studentId': 1, 'name': 'Beth'},
    {'studentId': 2, 'name': 'Tina'}
];

const marks = [
    {'studentId': 1, 'score': '123'},
    {'studentId': 1, 'score': '200'},
    {'studentId': 2, 'score': '99'}
];

I want output as:
[
    {'studentId': 1, 'name': 'Beth', 'testScore': '123'},
    {'studentId': 1, 'name': 'Beth', 'testScore': '200'},
    {'studentId': 2, 'name': 'Tina', 'testScore': '99'}
];

How can I do this?


问:
lit-element: can't get an array of objects to render output in loop
Just starting with lit-element

in my render i have:

```<code>  return html`
   ${this.jobCreate}
   ${this.jobDetails}
  `;
</code>```

get jobCreate works fine

this is my get jobDetails:

```<code>  get jobDetails() {
    const jobs = [
      { name: "phoenix job", location: "phoenix", expires: "2020-10-01" },
      { name: "chicago job", location: "chicago", expires: "2020-10-01" },
      { name: "pittsburgh job", location: "pittsburgh", expires: "2020-10-01" },
    ];

    return html`<ul>
      ${jobs.forEach((job) => html`<li>${job.name}</li>`)}
    </ul>`;
  }
</code>```

inspecting the element i can see an empty
 set

if do a

${jobs[2].name}

 that works

if i console out job, i can see all the right job print 3 times in the loop

I can't understand why i can't get the
 to render in the loop

i used this for reference: https://lit-element.polymer-project.org/guide/templates#template-syntax-cheat-sheet

答:
You're using forEach instead of map for looping the jobs array. forEach returns undefined whereas map returns a new array with every value mapped according to the function given.

As an alternative way of thinking about it, if you took out the template literal tags and output a string 'undefined' when a value is undefined, forEach will output the following:

     undefined

```

<p>whereas <code>map</code> would output:</p>

<pre class="lang-html prettyprint-override"><code><ul>
    <li>phoenix job</li><li>chicago job</ul><ul>pittsburgh job</ul>
</ul>
</code>```

The following is likely what you're aiming for:

get jobDetails() {
    const jobs = [
        { name: "phoenix job", location: "phoenix", expires: "2020-10-01" },
        { name: "chicago job", location: "chicago", expires: "2020-10-01" },
        {
            name: "pittsburgh job",
            location: "pittsburgh",
            expires: "2020-10-01",
        },
    ];

    return html`

        ${jobs.map((job) => html`<li>${job.name}</li>`)}

`;
}

```

Further reading:

MDN on map

MDN on forEach

Body:
Just starting with lit-element

in my render i have:

  return html`
   ${this.jobCreate}
   ${this.jobDetails}
  `;

get jobCreate works fine

this is my get jobDetails:

  get jobDetails() {
    const jobs = [
      { name: "phoenix job", location: "phoenix", expires: "2020-10-01" },
      { name: "chicago job", location: "chicago", expires: "2020-10-01" },
      { name: "pittsburgh job", location: "pittsburgh", expires: "2020-10-01" },
    ];

    return html`

      ${jobs.forEach((job) => html`<li>${job.name}</li>`)}

`;
  }

inspecting the element i can see an empty
 set

if do a

${jobs[2].name}

 that works

if i console out job, i can see all the right job print 3 times in the loop

I can't understand why i can't get the
 to render in the loop

i used this for reference: https://lit-element.polymer-project.org/guide/templates#template-syntax-cheat-sheet

Body:
You're using forEach instead of map for looping the jobs array. forEach returns undefined whereas map returns a new array with every value mapped according to the function given.

As an alternative way of thinking about it, if you took out the template literal tags and output a string 'undefined' when a value is undefined, forEach will output the following:

<ul>
     undefined
</ul>

whereas map would output:

<ul>
    <li>phoenix job</li><li>chicago job</ul><ul>pittsburgh job</ul>
</ul>

The following is likely what you're aiming for:

get jobDetails() {
    const jobs = [
        { name: "phoenix job", location: "phoenix", expires: "2020-10-01" },
        { name: "chicago job", location: "chicago", expires: "2020-10-01" },
        {
            name: "pittsburgh job",
            location: "pittsburgh",
            expires: "2020-10-01",
        },
    ];

    return html`<ul>
        ${jobs.map((job) => html`<li>${job.name}</li>`)}
    </ul>`;
}

Further reading:

MDN on map

MDN on forEach


问:
Use OAuth Bearer tokens only for certain controllers
Using OAuth to allow access to an web api. I have something like this (from various tutorials for example: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/):

```<code>public void ConfigureOAuth(IAppBuilder app, System.Web.Mvc.IDependencyResolver kernel)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new SimpleAuthorizationServerProvider(),
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

}
</code>```

In Startup.cs. But this turns on authorization globally for all my controllers. Is there a way to turn it on just for a single controller (or a handful of controllers or methods)?  I have custom authorization for other parts of the website and I could go in to them and just check if the credentials passed is a bearer token and just reject it, but I'm wondering if there isn't a more elegant solution.

答:
Just use [AllowAnonymous] decorator at controller level or inside any web method. For me it was not necessary to configure web.config as suggested by @Marshall</p>

```<code>[AllowAnonymous]
public class MyController : ApiController
{

    [AllowAnonymous]
    [HttpGet]
    public async Task<IHttpActionResult> GetDetails(string name) {}
}
</code>```

Body:
Using OAuth to allow access to an web api. I have something like this (from various tutorials for example: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/):

public void ConfigureOAuth(IAppBuilder app, System.Web.Mvc.IDependencyResolver kernel)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new SimpleAuthorizationServerProvider(),
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

}

In Startup.cs. But this turns on authorization globally for all my controllers. Is there a way to turn it on just for a single controller (or a handful of controllers or methods)?  I have custom authorization for other parts of the website and I could go in to them and just check if the credentials passed is a bearer token and just reject it, but I'm wondering if there isn't a more elegant solution.

Body:
Just use [AllowAnonymous] decorator at controller level or inside any web method. For me it was not necessary to configure web.config as suggested by @Marshall

[AllowAnonymous]
public class MyController : ApiController
{

    [AllowAnonymous]
    [HttpGet]
    public async Task<IHttpActionResult> GetDetails(string name) {}
}


问:
TypeError: can only concatenate str (not "DeferredAttribute") to str
I am wondering anyone can help me in one of the thing I cannot get my around it and really bothering as I spent last two on it but couldnt make it.

Basically, I am building an App (Django Python) to restore the information regarding all the network device e.g hostname, IP Address, S/N, Rack info etc. but I also to enable few options like Add, Edit, Delete and Connect next to device entery. I was able to create all the options except Connect option where I am completely stuck, I am trying to query database to get the IP address information and then using Popen module to open a putty window with the ssh to that IP Address device related, I tried everything I could but nothing worked, thereofrore, asking your help if you have any idea about this ? or any other alternative method for a user when he click on connect the putty or similar app will open and he just put the login credentials and get into the device.

I am sharing my code here, let me know if I am doing something wrong.

on the show all device page, i have this code, show.html

```<code><td><a href="/connect/{{ i.ip_address }}">Connect</a></td>
<!--<td><a href="/connect/{{ i.id }}">Connect</a></td>-->
</code>```

I tried both ways, with id and ip address entry in the database

on view.py

```<code>def connect(request, ip_address):
hostlist_ip = HostList.ip_address
print(hostlist_ip)
Popen("putty.exe" + hostlist_ip)
return redirect('/show')
</code>```

and in the url.py

```<code>path('connect/<str:ip_address>', views.connect),
or
path('connect/<str:ip_address>', views.connect),
</code>```

Since I am also printing the the output on the terminal I notice that it is not returning the actually IP address but return this;

```<code><django.db.models.query_utils.DeferredAttribute object at 0x04B77C50>
</code>```

and on the web I receiving this error

```<code>TypeError at /connect/10.10.32.10
can only concatenate str (not "DeferredAttribute") to str
Request Method: GET
Request URL: http://localhost:8000/connect/10.10.32.10
Django Version: 2.2.3
Exception Type: TypeError
Exception Value:
can only concatenate str (not "DeferredAttribute") to str
</code>```

let me know if you can help.

Just a F.Y.I I already tested the Popen via python but since we not getting the actual IP address from the database I am seeing this and I am a complete newbie with html/css and Djano, however I have some basic knowledge of python, so please ignore my any stupid comments in the post.

Many thanks

答:
ahh I cannot believe I spend two day to troubleshoot this and just changed the name from ip_address to ip_add and it is working now :) i think as I mentioned above in the comment, it probably confusing with the built in module

here is simple solution:

views.py

```<code>def connect(request, ip_add):
    import os
    from subprocess import Popen
    Popen("powershell putty.exe " + ip_add)
    return redirect('/show')
</code>```

url.py

```<code>path('connect/<str:ip_add>', views.connect),
</code>```

I may have to find out a way if user is using the mac or linux, how I am going to change this powershell to something else. but anyhow it is working for windows

thanks all for the responses.

Body:
I am wondering anyone can help me in one of the thing I cannot get my around it and really bothering as I spent last two on it but couldnt make it.

Basically, I am building an App (Django Python) to restore the information regarding all the network device e.g hostname, IP Address, S/N, Rack info etc. but I also to enable few options like Add, Edit, Delete and Connect next to device entery. I was able to create all the options except Connect option where I am completely stuck, I am trying to query database to get the IP address information and then using Popen module to open a putty window with the ssh to that IP Address device related, I tried everything I could but nothing worked, thereofrore, asking your help if you have any idea about this ? or any other alternative method for a user when he click on connect the putty or similar app will open and he just put the login credentials and get into the device.

I am sharing my code here, let me know if I am doing something wrong.

on the show all device page, i have this code, show.html

Connect

I tried both ways, with id and ip address entry in the database

on view.py

def connect(request, ip_address):
hostlist_ip = HostList.ip_address
print(hostlist_ip)
Popen("putty.exe" + hostlist_ip)
return redirect('/show')

and in the url.py

path('connect/<str:ip_address>', views.connect),
or
path('connect/<str:ip_address>', views.connect),

Since I am also printing the the output on the terminal I notice that it is not returning the actually IP address but return this;

<django.db.models.query_utils.DeferredAttribute object at 0x04B77C50>

and on the web I receiving this error

TypeError at /connect/10.10.32.10
can only concatenate str (not "DeferredAttribute") to str
Request Method: GET
Request URL: http://localhost:8000/connect/10.10.32.10
Django Version: 2.2.3
Exception Type: TypeError
Exception Value:
can only concatenate str (not "DeferredAttribute") to str

let me know if you can help.

Just a F.Y.I I already tested the Popen via python but since we not getting the actual IP address from the database I am seeing this and I am a complete newbie with html/css and Djano, however I have some basic knowledge of python, so please ignore my any stupid comments in the post.

Many thanks

Body:
ahh I cannot believe I spend two day to troubleshoot this and just changed the name from ip_address to ip_add and it is working now :) i think as I mentioned above in the comment, it probably confusing with the built in module

here is simple solution:

views.py

def connect(request, ip_add):
    import os
    from subprocess import Popen
    Popen("powershell putty.exe " + ip_add)
    return redirect('/show')

url.py

path('connect/<str:ip_add>', views.connect),

I may have to find out a way if user is using the mac or linux, how I am going to change this powershell to something else. but anyhow it is working for windows

thanks all for the responses.


问:
not getting complete aws ec2 list
I have written a python-boto3 script to get all aws instances list from an account and region.
the script is running fine and getting output in csv format as expected(getting only one instance under one reservation number , so remaining instances are missing )
 problem is not getting all aws instances list correctly.
for example ,
 I have total 5 instances in aws account

             Instance-1 and Instance-2 are with  Reservation1 number
             Instance-3 and Instance-4 are with  Reservation2 number
             Instance-5 is with Reservation3 number
 I am getting only 3 instances list in csv format instead of 5 instances.
please look at the below script , please help me how can I get all aws instances list irrespective of reservation number.

```<code>output = "Prod.csv"
     ec = boto3.client('ec2', config=config, region_name=rg)

        def get_tags():
            tag_list = []
            resp =  ec.describe_instances()
            tag_result = [['Name','InstanceId','State','bt:product','bt:environment-type','bt:environment-name']]
            for ec2 in resp['Reservations']:
                tag_list = []
                try:
                    ecName = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'Name')['Value']
                    tag_list.append(ecName)
                except:
                    ecName = 'Null'
                    tag_list.append(ecName)
                insId = ec2['Instances'][0]['InstanceId']
                instanceID = str(insId)
                tag_list.append(instanceID)
                state = ec2['Instances'][0]['State']['Name']
                tag_list.append(state)
                try:
                    btprod = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'bt:product')['Value']
                    tag_list.append(btprod)
                except:
                    btprod = 'Null'
                    tag_list.append(btprod)
                try:
                    btenvtype = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'b1:environment-type')['Value']
                    tag_list.append(btenvtype)
                except:
                    btenvtype = 'Null'
                    tag_list.append(btenvtype)
                try:
                    btenvname = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'b1:environment-name')['Value']
                    tag_list.append(btenvname)
                except:
                    btenvname = 'Null'
                    tag_list.append(btenvname)
                tag_result.append(tag_list)
            return tag_result
        def main():

            tag = get_tags()
            with open(output,'w') as resultFile:
                wr = csv.writer(resultFile, dialect='excel')
                wr.writerows(tag)
                log = open(output, 'r').read()
</code>```

答:
Here is an updated version of the program based upon the answer I provided in your other question:

import boto3
import csv

output = "Prod.csv"
ec2_client = boto3.client('ec2')

def get_tag(instance, tag_name):

    # Find tag on instance
    if 'Tags' in instance:
        for tag in instance['Tags']:
            if tag['Key'] == tag_name:
                return tag['Value']

    # Not found
    return 'Null'

def get_all_tags():

    # Add header row
    tag_result = [['Name','InstanceId','State','bt:product','bt:environment-type','bt:environment-name']]

    response = ec2_client.describe_instances()

    for reservation in response['Reservations']:
        for instance in reservation['Instances']:

            tag_list = []
            tag_list.append(get_tag(instance, 'Name'))
            tag_list.append(instance['InstanceId'])
            tag_list.append(instance['State']['Name'])

            for tag in ['bt:product','bt:environment-type','bt:environment-name']:
                tag_list.append(get_tag(instance, tag))

            tag_result.append(tag_list)

    return tag_result

def main():

    all_tags = get_all_tags()
    with open('output.csv','w') as resultFile:
        wr = csv.writer(resultFile, dialect='excel')
        wr.writerows(all_tags)

main()
```

Title: not getting complete aws ec2 list

Body:
I have written a python-boto3 script to get all aws instances list from an account and region.
the script is running fine and getting output in csv format as expected(getting only one instance under one reservation number , so remaining instances are missing )
 problem is not getting all aws instances list correctly.
for example ,
 I have total 5 instances in aws account

             Instance-1 and Instance-2 are with  Reservation1 number
             Instance-3 and Instance-4 are with  Reservation2 number
             Instance-5 is with Reservation3 number
 I am getting only 3 instances list in csv format instead of 5 instances.
please look at the below script , please help me how can I get all aws instances list irrespective of reservation number.

output = "Prod.csv"
     ec = boto3.client('ec2', config=config, region_name=rg)

        def get_tags():
            tag_list = []
            resp =  ec.describe_instances()
            tag_result = [['Name','InstanceId','State','bt:product','bt:environment-type','bt:environment-name']]
            for ec2 in resp['Reservations']:
                tag_list = []
                try:
                    ecName = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'Name')['Value']
                    tag_list.append(ecName)
                except:
                    ecName = 'Null'
                    tag_list.append(ecName)
                insId = ec2['Instances'][0]['InstanceId']
                instanceID = str(insId)
                tag_list.append(instanceID)
                state = ec2['Instances'][0]['State']['Name']
                tag_list.append(state)
                try:
                    btprod = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'bt:product')['Value']
                    tag_list.append(btprod)
                except:
                    btprod = 'Null'
                    tag_list.append(btprod)
                try:
                    btenvtype = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'b1:environment-type')['Value']
                    tag_list.append(btenvtype)
                except:
                    btenvtype = 'Null'
                    tag_list.append(btenvtype)
                try:
                    btenvname = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'b1:environment-name')['Value']
                    tag_list.append(btenvname)
                except:
                    btenvname = 'Null'
                    tag_list.append(btenvname)
                tag_result.append(tag_list)
            return tag_result
        def main():

            tag = get_tags()
            with open(output,'w') as resultFile:
                wr = csv.writer(resultFile, dialect='excel')
                wr.writerows(tag)
                log = open(output, 'r').read()