问:
Scala Play + Slick: How to inject dependencies to Spec tests?
I'm using Scala Play 2.7.x (the project is available here Play-Silhouette-Seed) and would like to test my daos. I have put together this simple one first to check what's the "new pattern" for testing play + slick + guice in 2.7.x:

```<code>package models.daos

import java.util.UUID
import org.specs2.mock._
import org.specs2.mutable._
import utils.AwaitUtil
import javax.inject.Inject
import models.generated.Tables.LoginInfoRow

class LoginInfoDaoSpec @Inject() (loginInfoDao: LoginInfoDao) extends Specification with Mockito with AwaitUtil {

  "Creating a new LoginInfo" should {
    "save it in the empty database" in {
      loginInfoDao.create(LoginInfoRow(0, UUID.randomUUID().toString, UUID.randomUUID().toString))
      loginInfoDao.findAll.size should beEqualTo(1)
    }
  }
}
</code>```

Unfortunately, the guice dependency LoginInfoDao is not being provided to my test and then I get the error:

```<code>[play-silhouette-seed] $ testOnly models.daos.LoginInfoDaoSpec
[info] Done compiling.
[error] Can't find a suitable constructor with 0 or 1 parameter for class models.daos.LoginInfoDao
[info] ScalaTest
[info] Run completed in 1 second, 966 milliseconds.
[info] Total number of tests run: 0
[info] Suites: completed 0, aborted 0
[info] Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
[info] No tests were executed.
[error] Error: Total 1, Failed 0, Errors 1, Passed 0
</code>```

How do I get guice loading the needed modules for my test-cases?

A module is defined as:

```<code>class SilhouetteModule extends AbstractModule with ScalaModule {
  override def configure() {
    // ...
    bind[LoginInfoDao].to[LoginInfoDaoImpl]
    // ...
  }
}
</code>```

and I have an application.test.conf available defined as:

```<code>include "application.conf"

slick.dbs {
  default {
    profile="slick.jdbc.MySQLProfile$"
    db.driver="com.mysql.cj.jdbc.Driver"
    db.url="jdbc:mysql://localhost:3306/mytestdb?useUnicode=true&searchpath=public&serverTimezone=CET"
    db.user="dev"
    db.password="12345"
  }
}
</code>```

答:
You should use another database for testing, H2 is the common choice.

```<code>class Module extends AbstractModule with ScalaModule {
...
}
</code>```

With that name you need to let play know there is a Module to load, if you call it Module, it automatically know what to load and should work just fine (if you only need 1 module in testing)

If that doesn't work let me know

Body:
I'm using Scala Play 2.7.x (the project is available here Play-Silhouette-Seed) and would like to test my daos. I have put together this simple one first to check what's the "new pattern" for testing play + slick + guice in 2.7.x:

package models.daos

import java.util.UUID
import org.specs2.mock._
import org.specs2.mutable._
import utils.AwaitUtil
import javax.inject.Inject
import models.generated.Tables.LoginInfoRow

class LoginInfoDaoSpec @Inject() (loginInfoDao: LoginInfoDao) extends Specification with Mockito with AwaitUtil {

  "Creating a new LoginInfo" should {
    "save it in the empty database" in {
      loginInfoDao.create(LoginInfoRow(0, UUID.randomUUID().toString, UUID.randomUUID().toString))
      loginInfoDao.findAll.size should beEqualTo(1)
    }
  }
}

Unfortunately, the guice dependency LoginInfoDao is not being provided to my test and then I get the error:

[play-silhouette-seed] $ testOnly models.daos.LoginInfoDaoSpec
[info] Done compiling.
[error] Can't find a suitable constructor with 0 or 1 parameter for class models.daos.LoginInfoDao
[info] ScalaTest
[info] Run completed in 1 second, 966 milliseconds.
[info] Total number of tests run: 0
[info] Suites: completed 0, aborted 0
[info] Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
[info] No tests were executed.
[error] Error: Total 1, Failed 0, Errors 1, Passed 0

How do I get guice loading the needed modules for my test-cases?

A module is defined as:

class SilhouetteModule extends AbstractModule with ScalaModule {
  override def configure() {
    // ...
    bind[LoginInfoDao].to[LoginInfoDaoImpl]
    // ...
  }
}

and I have an application.test.conf available defined as:

include "application.conf"

slick.dbs {
  default {
    profile="slick.jdbc.MySQLProfile$"
    db.driver="com.mysql.cj.jdbc.Driver"
    db.url="jdbc:mysql://localhost:3306/mytestdb?useUnicode=true&searchpath=public&serverTimezone=CET"
    db.user="dev"
    db.password="12345"
  }
}

Body:
You should use another database for testing, H2 is the common choice.

class Module extends AbstractModule with ScalaModule {
...
}

With that name you need to let play know there is a Module to load, if you call it Module, it automatically know what to load and should work just fine (if you only need 1 module in testing)

If that doesn't work let me know


来源: stackexchange

问:
How to work around integer input within a while loop
Code is meant to run forever except for when index_input == "Q". My problem is because i convert to an integer on the next line, the code fails and recognises the 'Q' as an integer.

```<code>while True:
  index_input = input("Enter index to insert element to list (enter Q to quit): ")
  index_input_int = int(index_input)

  if (index_input == "Q"):
    print('Good bye!')

    break

  elif (index_input_int >= 6):
    print('Index is too high')

  elif (index_input_int <= -1Q):
    print('Index is too low')

</code>```

Expected result is that 'Q' will break the while loop.

答:
Just move the cast to int after the check for "Q" and put everything else in an else block:</p>

```<code>while True:
  index_input = input(
      "Enter index to insert element to list (enter Q to quit): ")

  if (index_input == "Q"):
    print('Good bye!')
    break

  else:

    index_input_int = int(index_input)
    if (index_input_int >= 6):
        print('Index is too high')

    elif (index_input_int <= -1Q):
        print('Index is too low')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Code is meant to run forever except for when index_input == "Q". My problem is because i convert to an integer on the next line, the code fails and recognises the 'Q' as an integer.

while True:
  index_input = input("Enter index to insert element to list (enter Q to quit): ")
  index_input_int = int(index_input)

  if (index_input == "Q"):
    print('Good bye!')

    break

  elif (index_input_int >= 6):
    print('Index is too high')

  elif (index_input_int <= -1Q):
    print('Index is too low')

Expected result is that 'Q' will break the while loop.

Body:
Just move the cast to int after the check for "Q" and put everything else in an else block:

while True:
  index_input = input(
      "Enter index to insert element to list (enter Q to quit): ")

  if (index_input == "Q"):
    print('Good bye!')
    break

  else:

    index_input_int = int(index_input)
    if (index_input_int >= 6):
        print('Index is too high')

    elif (index_input_int <= -1Q):
        print('Index is too low')


问:
v-if not reactive (or data not reactive)
I have following vue component (I have removed rest of the code just to point out this issue).

```<code><template>
    <span splitpanes-default="70">
      Details Pane
            <uploader v-if="isUpload" class="uploader-example">
                <uploader-unsupport></uploader-unsupport>
                <uploader-drop>
                    <p>Drop files here to upload or</p>
                    <uploader-btn>select files</uploader-btn>
                    <uploader-btn :directory="true">select folder</uploader-btn>
                </uploader-drop>
                <uploader-list></uploader-list>
            </uploader>
    </span>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import uploader from 'vue-simple-uploader';

Vue.use(uploader);

@Component()
export default class In extends Vue {

  public isUpload: boolean = false;

  public upload() {
      this.isUpload = true;
  }

 }
</script>
</code>```

when I call upload method (let's say on click of button), "isUpload" property is setting to true, but uploader is not showing back.

Seems like property is not reactive. what do I need to make it reactive.

答:
Turned down that it was issue with splitpanes (that outer part I didn't include in the question as I felt that wasn't relevant).

So splitepane with property "watch-slots" should be there to make inner content (fully) reactive.

Reference: https://antoniandre.github.io/splitpanes/#in-depth-reactivity

Body:
I have following vue component (I have removed rest of the code just to point out this issue).

<template>

      Details Pane
            <uploader v-if="isUpload" class="uploader-example">
                <uploader-unsupport></uploader-unsupport>
                <uploader-drop>

Drop files here to upload or

                    <uploader-btn>select files</uploader-btn>
                    <uploader-btn :directory="true">select folder</uploader-btn>
                </uploader-drop>
                <uploader-list></uploader-list>
            </uploader>

</template>

when I call upload method (let's say on click of button), "isUpload" property is setting to true, but uploader is not showing back.

Seems like property is not reactive. what do I need to make it reactive.


问:
How can I store an input value in web local storege using javascript or jquery?
I have an input like below.
I want to keep its value after the page is refreshed.
notice that I have the name attribute, not class or ID.

```<code><input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>
</code>```

```<code><script type="text/javascript">
var nameArr = ["name"];
nameArr.forEach(function(el){
  document.getElementsByName(el)[0].value = getSavedValue(el);
})

function saveValue(e) {
  var name = e.target.name;
  var val = e.target.value;
  localStorage.setItem(name, val);
}

function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
    return "";
  }
  return localStorage.getItem(v);
}
</script>
</code>```

it only works for 1 input.I want something that works on unlimited number of inputs.

答:
document.getElementsByName("name") returns an array.
if you are sure that there is only one element with the name 'name'
then use</p>

```<code>document.getElementsByName("name")[0].value = getSavedValue("name");
</code>```

Body:
I have an input like below.
I want to keep its value after the page is refreshed.
notice that I have the name attribute, not class or ID.

<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>

it only works for 1 input.I want something that works on unlimited number of inputs.

Body:
document.getElementsByName("name") returns an array.
if you are sure that there is only one element with the name 'name'
then use

document.getElementsByName("name")[0].value = getSavedValue("name");


问:
How to parse release number for branch name
Given a branch name like release-1.0 or release-0.4alpha or release-12.02, I want to parse out the version number using a python 3 regex expression.

What I have is:

```<code>#!/usr/bin/python3

import re;
import sys

arg = sys.argv[1]
regex = r'(?<=(^release-))\d+.\d+(alpha)?$'

match = re.match(regex, arg)

if match:
    print(match.group())
else:
    print('Branch "{}" is not valid release branch.'.format(arg))
    sys.exit(1)
</code>```

But this fails to match any of the attempted names:

```<code>$ ./scripts/bin/get-version-number-from-branch release-1.0
Branch "release-1.0" is not valid release branch.
$ ./scripts/bin/get-version-number-from-branch release-1.0alpha
Branch "release-1.0alpha" is not valid release branch.

</code>```

I originally built and tested this on https://pythex.org/ and https://regex101.com/.

Any ideas what I am missing?

答:
https://docs.python.org/3/howto/regex.html#match-versus-search

Use search instead of match as:

```<code>#!/usr/bin/python3

import re;
import sys

arg = sys.argv[1]
regex = r'(?<=(^release-))\d+.\d+(alpha)?$'

match = re.search(regex, arg)

if match:
    print(match.group())
else:
    print('Branch "{}" is not valid release branch.'.format(arg))
    sys.exit(1)
</code>```

Body:
Given a branch name like release-1.0 or release-0.4alpha or release-12.02, I want to parse out the version number using a python 3 regex expression.

What I have is:

#!/usr/bin/python3

import re;
import sys

arg = sys.argv[1]
regex = r'(?<=(^release-))\d+.\d+(alpha)?$'

match = re.match(regex, arg)

if match:
    print(match.group())
else:
    print('Branch "{}" is not valid release branch.'.format(arg))
    sys.exit(1)

But this fails to match any of the attempted names:

$ ./scripts/bin/get-version-number-from-branch release-1.0
Branch "release-1.0" is not valid release branch.
$ ./scripts/bin/get-version-number-from-branch release-1.0alpha
Branch "release-1.0alpha" is not valid release branch.

I originally built and tested this on https://pythex.org/ and https://regex101.com/.

Any ideas what I am missing?

Body:
https://docs.python.org/3/howto/regex.html#match-versus-search

Use search instead of match as:

#!/usr/bin/python3

import re;
import sys

arg = sys.argv[1]
regex = r'(?<=(^release-))\d+.\d+(alpha)?$'

match = re.search(regex, arg)

if match:
    print(match.group())
else:
    print('Branch "{}" is not valid release branch.'.format(arg))
    sys.exit(1)


问:
How to send emails without speed limit?
I got some errors about sending mails too quick in 15 minutes when sending mails.
It seems there is a speed limit of sending mails.
But how many mails can be sent in 15 minutes?
Is this a standard or private rule based on vendor?</p>

答: It depends on both your mail service provider, and also the target system. For example gmail will let you send 500/1000 (or more) emails per day, per account depending on your agreement with them.</p>

ContentLicense: CC BY-SA 3.0

Title: How to send emails without speed limit?


问:
check whether date exists in database
I want to check if the entered date is taken or not.

I tried to fix it but it always indicates that a date has been taken even if it hasn't.

This is the DAO

```<code>public static String getDate(String date) throws SQLException, ClassNotFoundException {
    Connection cnx;
    String datee;
    cnx = Connect.getConnection();

    String req = "select date from examen where date=?";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, date);
    ResultSet rs = st.executeQuery();
    if (rs.next()) {
        String laDate = rs.getString(date);

    }
    return date;

}
</code>```

and this is the servlet

```<code>String dd = ExamDAO.getDate(date);

if (dd != null) {
                        String datePrise = "la date est prise ";
                        request.getSession().setAttribute("datePrise", datePrise);
                        System.out.println("priiiiise ");
                        response.sendRedirect("examen.jsp");
                    } else {...}
</code>```

答:
I guess, your method is to be rewritten like below if examen.jsp path is for dates already taken. Notice the extra declaration - String laDate =null; & change in return statement.

Also, notice change in laDate = rs.getString("date"); , your need to extract by column name & not variable. Table column name is "date" while date is a variable carrying date values & not table column name.

Variable String datee; from your code is unused, you can remove that.

```<code>public static String getDate(String date) throws SQLException, ClassNotFoundException {
    Connection cnx;
    String laDate =null;
    String datee;
    cnx = Connect.getConnection();
    String req = "select date from examen where date=?";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, date);
    ResultSet rs = st.executeQuery();
    if (rs.next()) {
         laDate = rs.getString("date");

    }
    return laDate ;
}
</code>```

Title: check whether date exists in database

Body:
I want to check if the entered date is taken or not.

I tried to fix it but it always indicates that a date has been taken even if it hasn't.

This is the DAO

public static String getDate(String date) throws SQLException, ClassNotFoundException {
    Connection cnx;
    String datee;
    cnx = Connect.getConnection();

    String req = "select date from examen where date=?";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, date);
    ResultSet rs = st.executeQuery();
    if (rs.next()) {
        String laDate = rs.getString(date);

    }
    return date;

}

and this is the servlet

String dd = ExamDAO.getDate(date);

if (dd != null) {
                        String datePrise = "la date est prise ";
                        request.getSession().setAttribute("datePrise", datePrise);
                        System.out.println("priiiiise ");
                        response.sendRedirect("examen.jsp");
                    } else {...}

Body:
I guess, your method is to be rewritten like below if examen.jsp path is for dates already taken. Notice the extra declaration - String laDate =null; & change in return statement.

Also, notice change in laDate = rs.getString("date"); , your need to extract by column name & not variable. Table column name is "date" while date is a variable carrying date values & not table column name.

Variable String datee; from your code is unused, you can remove that.

public static String getDate(String date) throws SQLException, ClassNotFoundException {
    Connection cnx;
    String laDate =null;
    String datee;
    cnx = Connect.getConnection();
    String req = "select date from examen where date=?";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, date);
    ResultSet rs = st.executeQuery();
    if (rs.next()) {
         laDate = rs.getString("date");

    }
    return laDate ;
}


问:
How to pass two dimensional array of an unknown size to a function
I want to make class library, a function which its parameter is a matrix of unknown size, and the user will create his own matrix with his own size and pass it to this function to do some operations on his matrix like this, will be the function </p>

```<code>calculateDeterminantOfTheMatrix( int matrix[][])
{
   some Operations to do on matrix
}
</code>```

答:
The Best way to use 2D array in the function that I have found so far is to use Mapping Function. As in the example below , I have use the mapping function to print 2D array

```<code>void Print2D(int x[],int ROWS,int COLS)
{
    for(int i=0;i<ROWS;i++)
{
    for(int j=0;j<COLS;j++)
    cout << x[i*COLS+j] << ' ';
    cout << endl;

}
}
</code>```

Here it is how to use it in main

```<code>int main(){

    int x[3][3];
    Print2D(&x[0],3,3);

}
</code>```

Here &x[0] is the starting address of the First Row of 2D array or more precisely Starting address of 2D array

Body:
I want to make class library, a function which its parameter is a matrix of unknown size, and the user will create his own matrix with his own size and pass it to this function to do some operations on his matrix like this, will be the function

calculateDeterminantOfTheMatrix( int matrix[][])
{
   some Operations to do on matrix
}

Body:
The Best way to use 2D array in the function that I have found so far is to use Mapping Function. As in the example below , I have use the mapping function to print 2D array

void Print2D(int x[],int ROWS,int COLS)
{
    for(int i=0;i<ROWS;i++)
{
    for(int j=0;j<COLS;j++)
    cout << x[i*COLS+j] << ' ';
    cout << endl;

}
}

Here it is how to use it in main

int main(){

    int x[3][3];
    Print2D(&x[0],3,3);

}

Here &x[0] is the starting address of the First Row of 2D array or more precisely Starting address of 2D array


答:
If you try to convert the Q character or any other string to integer it will throw a ValueError. You can use try-except:

```<code>while True:
    index_input = input("Enter index to insert element to list (enter Q to quit): ")

    try:
        index_input_int = int(index_input)
    except ValueError:
        if index_input == "Q":
            print('Good bye!')
            break

    if index_input_int >= 6:
        print('Index is too high')
    elif index_input_int <= -1:
        print('Index is too low')
</code>```

Title: How to work around integer input within a while loop

Body:
If you try to convert the Q character or any other string to integer it will throw a ValueError. You can use try-except:

while True:
    index_input = input("Enter index to insert element to list (enter Q to quit): ")

    try:
        index_input_int = int(index_input)
    except ValueError:
        if index_input == "Q":
            print('Good bye!')
            break

    if index_input_int >= 6:
        print('Index is too high')
    elif index_input_int <= -1:
        print('Index is too low')


问:
How to delete \n form string scraped from website
This is a text scraped from website (itemHtml.text):

```<code> dolar amerykański 1 USD 3.8436
 euro 1 EUR 4.2989
 funt szterling 1 GBP 4.8768
</code>```

How to delete \n from this text? I tryed this:

```<code>import requests
import urllib.request
import time
from bs4 import BeautifulSoup

url = "https://www.nbp.pl/home.aspx?f=/kursy/kursya.html"
response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")
soup.findAll("tr")

for itemHtml in soup.select('.pad5 tr'):
    currency = ['amerykański', 'euro', 'szterling']
    if itemHtml.find('td'):
        if any (cur in itemHtml.text for cur in currency):
            dane_comma = itemHtml.text
            dane_dot = dane_comma.replace(',', '.')
            dane = dane_dot.replace('\n', ' ')
            print(dane)

</i>
</code>```

Thanks for help

答:
There are no newlines (\n) in that text.

What you are seeing is 3 print statements, which gives you 3 lines of output.

e.g.

```<code>import requests
from bs4 import BeautifulSoup

url = "https://www.nbp.pl/home.aspx?f=/kursy/kursya.html"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
soup.findAll("tr")
single_line = ""
cnt = 0

for itemHtml in soup.select('.pad5 tr'):
    currency = ['amerykański', 'euro', 'szterling']
    if itemHtml.find('td'):
        if any (cur in itemHtml.text for cur in currency):
            dane = itemHtml.text
            dane = dane.replace(',', '.')
            single_line += " "+dane
            cnt += 1
            print("Print count",cnt,dane)
print(single_line.strip())
</code>```

Gives:

```<code>Print count 1  dolar amerykański 1 USD 3.8436
Print count 2  euro 1 EUR 4.2989
Print count 3  funt szterling 1 GBP 4.8768
dolar amerykański 1 USD 3.8436   euro 1 EUR 4.2989   funt szterling 1 GBP 4.8768
</code>```

With no attempt, in the code, to remove new-line characters (single_line.strip() only being used to remove leading and any following spaces)

Body:
This is a text scraped from website (itemHtml.text):

 dolar amerykański 1 USD 3.8436
 euro 1 EUR 4.2989
 funt szterling 1 GBP 4.8768

How to delete \n from this text? I tryed this:

import requests
import urllib.request
import time
from bs4 import BeautifulSoup

url = "https://www.nbp.pl/home.aspx?f=/kursy/kursya.html"
response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")
soup.findAll("tr")

for itemHtml in soup.select('.pad5 tr'):
    currency = ['amerykański', 'euro', 'szterling']
    if itemHtml.find('td'):
        if any (cur in itemHtml.text for cur in currency):
            dane_comma = itemHtml.text
            dane_dot = dane_comma.replace(',', '.')
            dane = dane_dot.replace('\n', ' ')
            print(dane)

Thanks for help

Body:
There are no newlines (\n) in that text.

What you are seeing is 3 print statements, which gives you 3 lines of output.

e.g.

import requests
from bs4 import BeautifulSoup

url = "https://www.nbp.pl/home.aspx?f=/kursy/kursya.html"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
soup.findAll("tr")
single_line = ""
cnt = 0

for itemHtml in soup.select('.pad5 tr'):
    currency = ['amerykański', 'euro', 'szterling']
    if itemHtml.find('td'):
        if any (cur in itemHtml.text for cur in currency):
            dane = itemHtml.text
            dane = dane.replace(',', '.')
            single_line += " "+dane
            cnt += 1
            print("Print count",cnt,dane)
print(single_line.strip())

Gives:

Print count 1  dolar amerykański 1 USD 3.8436
Print count 2  euro 1 EUR 4.2989
Print count 3  funt szterling 1 GBP 4.8768
dolar amerykański 1 USD 3.8436   euro 1 EUR 4.2989   funt szterling 1 GBP 4.8768

With no attempt, in the code, to remove new-line characters (single_line.strip() only being used to remove leading and any following spaces)


问:
2D array on CUDA
I want to dynamically allocate global 2D array in CUDA. How can I achieve this?

In my main I am calling my Kernel in a loop. But before I call the kernel I need to allocate some memory on the GPU. After the kernel call a single integer is send from GPU to CPU to inform whether the problem is solved or not.

If the problem is not solved, I will not free the old memory , since there is a further need of it, and I should allocate new memory to the GPU and call the kernel again.

a sudocode is shown:

```<code>int n=0,i=0;
while(n==0)
{
    //allocate 2d memory for MEM[i++]
    //call kernel(MEM,i)
    // get n from kernel
}

__global__ void kernerl(Mem,int i)
{
    Mem[0][5]=1;
    Mem[1][0]=Mem[0][5]+23;//can use this when MEM[1] is allocated before kernel call
}
</code>```

Any suggestions? Thank you.

答:
EDITED:

I was trying to help you providing an example in which, flattening the array, you can achieve the same result, but mates told me it's not what you're asking for.

So there is another post here telling you how you can allocate 2d arrays in CUDA.

Title: 2D array on CUDA

Body:
I want to dynamically allocate global 2D array in CUDA. How can I achieve this?

In my main I am calling my Kernel in a loop. But before I call the kernel I need to allocate some memory on the GPU. After the kernel call a single integer is send from GPU to CPU to inform whether the problem is solved or not.

If the problem is not solved, I will not free the old memory , since there is a further need of it, and I should allocate new memory to the GPU and call the kernel again.

a sudocode is shown:

int n=0,i=0;
while(n==0)
{
    //allocate 2d memory for MEM[i++]
    //call kernel(MEM,i)
    // get n from kernel
}

__global__ void kernerl(Mem,int i)
{
    Mem[0][5]=1;
    Mem[1][0]=Mem[0][5]+23;//can use this when MEM[1] is allocated before kernel call
}

Any suggestions? Thank you.


问:
How to pass values to textarea of a form with jquery
I am trying to pass a value to a form textarea using jquery. I am able to pass a value to a hidden input area using the code below, but not able to use the same code to pass to a textarea

```<code> <html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.0.6/jquery.tinymce.min.js"></script>
<form>
<textarea class="tinymce" id="test"></textarea>
<button id="generate">Generate</button>
</form>

<script type="text/javascript">
    $(document).on('click','#generate',function() {

    tinyMCE.get('test').setContent('test content');
});
</script>

</html>
</code>```

I tried passing values using both val and attr, but they both do not work unless the input type is hidden, I expected the textarea to show the values generated by jquery.

答:
$(function() {
  $('#test').val('This is a test');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="test"></textarea></code>```

Body:
I am trying to pass a value to a form textarea using jquery. I am able to pass a value to a hidden input area using the code below, but not able to use the same code to pass to a textarea

<form>
<textarea class="tinymce" id="test"></textarea>
<button id="generate">Generate</button>
</form>

I tried passing values using both val and attr, but they both do not work unless the input type is hidden, I expected the textarea to show the values generated by jquery.

Body:
$(function() {
  $('#test').val('This is a test');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="test"></textarea>


问:
Why do I get StaleElementReferenceException when I "read" the text contents of a column?
The issue occurs only when I try to collect ("crawl") the contents of a table twice. The first time that I read the table's contents is successful but the second time always fails.

This happens only with the Chrome browser (Version 74 with a corresponding chromedriver) . I tried the same with FireFox and it never occurs. I found a certain workaround in Chrome, which doesn't make any sense but it does the job.

When I "go" to other screen than the one that includes the table and then return back then the table crawling succeeds.

The following is the function that I use in order to collect the table:

```<code>def Get_Faults_List(Port_Number=None, PSU=None, Retries=5):
    for attempt in range(Retries):
        try:
            if Port_Number:
                # Show the Faults view in the context of "Port_Number"
                Device_Panel_Frame.Click_Port(self, Port_Number)
            elif PSU:
                if not Device_Panel_Frame.Click_PSU(self, PSU):
                    return None
            Left_Panel_Frame.Click_Fault(self)

            self.driver.switch_to_default_content()
            Main_Body = self.driver.find_element_by_name('main_page')
            self.driver.switch_to.frame(Main_Body)
            alarms_tab = self.driver.find_element_by_id('tab_alarms')
            alarms_tab.click()
            Fault_Screen = self.driver.find_element_by_name('faults')
            self.driver.switch_to.frame(Fault_Screen)
            # the rows that the following variable collect are automatically
            # the relevant fault lines. The XPATH that was used omits the two
            # irrelevant lines
            faultTable_rows = WebDriverWait(self.driver, timeout=3, poll_frequency=0.5).until(
                EC.presence_of_all_elements_located((By.XPATH, "//table[@id='faultTab']//tr[not(@id or @style)]")))

            current_faults = []
            row_index = 0
            for row in faultTable_rows:  # Go through each of the rows
                current_faults.append([])
                # Collect all the column elements of a certain row into a list
                faultTable_row_cols = row.find_elements_by_tag_name("td")
                for col in faultTable_row_cols:
                    # Each row of the Faults table is separated into 5 columns each column holds a string
                    current_faults[row_index].append(col.text)
                row_index += 1

            break
        except:
            print(attempt + 1, 'attempt failed', Retries - (attempt + 1), 'to go')
            self.Refresh_Screen()
            sleep(5)
            continue
</code>```

I will succeed to collect the table's contents also if I will open a new browser. By the way, the failure always occurs at the first line (after the header) of the following table. The line is current_faults[row_index].append(col.text) and I don't see why. The exception doesn't make any sense.

Is there another way to efficiently crawl the table's contents ?

The table:

答:
See this answer for the reason you get the Stale Element Reference Exception.

A Stale Element Reference Exception occurs when an element:

Has been deleted

Is no longer attached to the DOM (as in your case)

Has changed

From the docs:

You should discard the current reference you hold and replace it, possibly by locating the element again once it is attached to the DOM.

i.e.: "Find" the element again.

My suggestion is to capture the HTML and loop over it:

You can use driver.page_source then BeautifulSoup as such:

```<code>html = driver.page_source
soup = BeautifulSoup(html, "lxml")
</code>```

This should be implemented after you switch frames.

Hope this helps you!

Body:
The issue occurs only when I try to collect ("crawl") the contents of a table twice. The first time that I read the table's contents is successful but the second time always fails.

This happens only with the Chrome browser (Version 74 with a corresponding chromedriver) . I tried the same with FireFox and it never occurs. I found a certain workaround in Chrome, which doesn't make any sense but it does the job.

When I "go" to other screen than the one that includes the table and then return back then the table crawling succeeds.

The following is the function that I use in order to collect the table:

def Get_Faults_List(Port_Number=None, PSU=None, Retries=5):
    for attempt in range(Retries):
        try:
            if Port_Number:
                # Show the Faults view in the context of "Port_Number"
                Device_Panel_Frame.Click_Port(self, Port_Number)
            elif PSU:
                if not Device_Panel_Frame.Click_PSU(self, PSU):
                    return None
            Left_Panel_Frame.Click_Fault(self)

            self.driver.switch_to_default_content()
            Main_Body = self.driver.find_element_by_name('main_page')
            self.driver.switch_to.frame(Main_Body)
            alarms_tab = self.driver.find_element_by_id('tab_alarms')
            alarms_tab.click()
            Fault_Screen = self.driver.find_element_by_name('faults')
            self.driver.switch_to.frame(Fault_Screen)
            # the rows that the following variable collect are automatically
            # the relevant fault lines. The XPATH that was used omits the two
            # irrelevant lines
            faultTable_rows = WebDriverWait(self.driver, timeout=3, poll_frequency=0.5).until(
                EC.presence_of_all_elements_located((By.XPATH, "//table[@id='faultTab']//tr[not(@id or @style)]")))

            current_faults = []
            row_index = 0
            for row in faultTable_rows:  # Go through each of the rows
                current_faults.append([])
                # Collect all the column elements of a certain row into a list
                faultTable_row_cols = row.find_elements_by_tag_name("td")
                for col in faultTable_row_cols:
                    # Each row of the Faults table is separated into 5 columns each column holds a string
                    current_faults[row_index].append(col.text)
                row_index += 1

            break
        except:
            print(attempt + 1, 'attempt failed', Retries - (attempt + 1), 'to go')
            self.Refresh_Screen()
            sleep(5)
            continue

I will succeed to collect the table's contents also if I will open a new browser. By the way, the failure always occurs at the first line (after the header) of the following table. The line is current_faults[row_index].append(col.text) and I don't see why. The exception doesn't make any sense.

Is there another way to efficiently crawl the table's contents ?

The table:

Body:
See this answer for the reason you get the Stale Element Reference Exception.

A Stale Element Reference Exception occurs when an element:

Has been deleted

Is no longer attached to the DOM (as in your case)

Has changed

From the docs:

You should discard the current reference you hold and replace it, possibly by locating the element again once it is attached to the DOM.

i.e.: "Find" the element again.

My suggestion is to capture the HTML and loop over it:

You can use driver.page_source then BeautifulSoup as such:

html = driver.page_source
soup = BeautifulSoup(html, "lxml")

This should be implemented after you switch frames.

Hope this helps you!


问:
How to get all unique paths between two nodes?
I'm using trek and mountaineering routing database and I try to find all possible routes between Darjeeling and Sandakphu.

That is not a problem - here is query for that:

```<code>MATCH allPaths=(town:town{name:'Darjeeling'})-[*]->(peak:peak{name:'Sandakphu'})
RETURN allPaths
</code>```

But this query returns same routes multiple times, for example:

```<code>╒══════════════════════════════════════════════════════════════════════╕
│"allPaths"                                                            │
╞══════════════════════════════════════════════════════════════════════╡
│[{"name":"Darjeeling"},{"name":"Darjeeling-Rimbik","winter":"true","di│
│stance":15,"summer":"true"},{"name":"Rimbik"},{"name":"Rimbik"},{"name│
│":"Rimbik-Sirikhola","winter":"true","distance":4,"summer":"true"},{"n│
│ame":"Sirikhola"},{"name":"Sirikhola"},{"name":"Sirikhola-Gurdum","win│
│ter":"true","distance":6,"summer":"true"},{"name":"Gurdum"},{"name":"G│
│urdum"},{"name":"Gurdum-Sandakphu","winter":"true","distance":12,"summ│
│er":"true"},{"name":"Sandakphu","altitude":"12400 ft"}]               │
├──────────────────────────────────────────────────────────────────────┤
│[{"name":"Darjeeling"},{"name":"Darjeeling-Rimbik","winter":"true","di│
│stance":15,"summer":"true"},{"name":"Rimbik"},{"name":"Rimbik"},{"name│
│":"Rimbik-Sirikhola","winter":"true","distance":4,"summer":"true"},{"n│
│ame":"Sirikhola"},{"name":"Sirikhola"},{"name":"Sirikhola-Gurdum","win│
│ter":"true","distance":6,"summer":"true"},{"name":"Gurdum"},{"name":"G│
│urdum"},{"name":"Gurdum-Sandakphu","winter":"true","distance":12,"summ│
│er":"true"},{"name":"Sandakphu","altitude":"12400 ft"}]               │
├──────────────────────────────────────────────────────────────────────┤
</code>```

I've tried to use DISTINCT on RETURN as it is mentioned in documentation

```<code>MATCH allPaths=(town:town{name:'Darjeeling'})-[*]->(peak:peak{name:'Sandakphu'})
RETURN DISTINCT allPaths
</code>```

but unfortunately it doesn't work.

答:
Have you tried aliasing the relationship, and then returning that (and only that) distinctly?

```<code>match (town:town{name:'Darjeeling'})-[r]->(peak:peak{name:'Sandakphu'})
return distinct r
</code>```

Also while it isn't enforced, the convention in Neo4J is to create labels in UpperCamelCase (Town rather than town, Peak rather than peak).

Body:
I'm using trek and mountaineering routing database and I try to find all possible routes between Darjeeling and Sandakphu.

That is not a problem - here is query for that:

MATCH allPaths=(town:town{name:'Darjeeling'})-[*]->(peak:peak{name:'Sandakphu'})
RETURN allPaths

But this query returns same routes multiple times, for example:

╒══════════════════════════════════════════════════════════════════════╕
│"allPaths"                                                            │
╞══════════════════════════════════════════════════════════════════════╡
│[{"name":"Darjeeling"},{"name":"Darjeeling-Rimbik","winter":"true","di│
│stance":15,"summer":"true"},{"name":"Rimbik"},{"name":"Rimbik"},{"name│
│":"Rimbik-Sirikhola","winter":"true","distance":4,"summer":"true"},{"n│
│ame":"Sirikhola"},{"name":"Sirikhola"},{"name":"Sirikhola-Gurdum","win│
│ter":"true","distance":6,"summer":"true"},{"name":"Gurdum"},{"name":"G│
│urdum"},{"name":"Gurdum-Sandakphu","winter":"true","distance":12,"summ│
│er":"true"},{"name":"Sandakphu","altitude":"12400 ft"}]               │
├──────────────────────────────────────────────────────────────────────┤
│[{"name":"Darjeeling"},{"name":"Darjeeling-Rimbik","winter":"true","di│
│stance":15,"summer":"true"},{"name":"Rimbik"},{"name":"Rimbik"},{"name│
│":"Rimbik-Sirikhola","winter":"true","distance":4,"summer":"true"},{"n│
│ame":"Sirikhola"},{"name":"Sirikhola"},{"name":"Sirikhola-Gurdum","win│
│ter":"true","distance":6,"summer":"true"},{"name":"Gurdum"},{"name":"G│
│urdum"},{"name":"Gurdum-Sandakphu","winter":"true","distance":12,"summ│
│er":"true"},{"name":"Sandakphu","altitude":"12400 ft"}]               │
├──────────────────────────────────────────────────────────────────────┤

I've tried to use DISTINCT on RETURN as it is mentioned in documentation

MATCH allPaths=(town:town{name:'Darjeeling'})-[*]->(peak:peak{name:'Sandakphu'})
RETURN DISTINCT allPaths

but unfortunately it doesn't work.

Body:
Have you tried aliasing the relationship, and then returning that (and only that) distinctly?

match (town:town{name:'Darjeeling'})-[r]->(peak:peak{name:'Sandakphu'})
return distinct r

Also while it isn't enforced, the convention in Neo4J is to create labels in UpperCamelCase (Town rather than town, Peak rather than peak).


问:
Traversing an array to find the second largest element in linear time
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.

Solution : Sort the array and take the second element but Sorting not allowed

Modification : By definition second largest element will be the one which is numerically smaller. Like if we have

Arr = {5,5,4,3,1}
Then second largest is 4

Addition
Lets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.

答:
Yep. You tagged this as C/C++ but you mentioned you could do it in Python. Anyway, here is the algorithm:

Create the array (obviously).

If the first item is greater than the second item, set first variable to the first item and second variable to second item. Otherwise, do vise-versa.

Loop through all the items (except the first two).

If the item from the array is greater than first variable, set second variable to first variable and first variable to the item. Else if the item is greater than second variable set second variable to the item.

The second variable is your answer.

```<code>list = [-1,6,9,2,0,2,8,10,8,-10]

if list[0] > list[1]:
        first = list[0]
        second = list[1]
else:
        first = list[1]
        second = list[0]

for i in range(2, len(list)):
        if list[i] > first:
                first, second = list[i], first
        elif list[i] > second:
                second = list[i]

print("First:", first)
print("Second:", second)
</code>```

Body:
Yep. You tagged this as C/C++ but you mentioned you could do it in Python. Anyway, here is the algorithm:

Create the array (obviously).

If the first item is greater than the second item, set first variable to the first item and second variable to second item. Otherwise, do vise-versa.

Loop through all the items (except the first two).

If the item from the array is greater than first variable, set second variable to first variable and first variable to the item. Else if the item is greater than second variable set second variable to the item.

The second variable is your answer.

list = [-1,6,9,2,0,2,8,10,8,-10]

if list[0] > list[1]:
        first = list[0]
        second = list[1]
else:
        first = list[1]
        second = list[0]

for i in range(2, len(list)):
        if list[i] > first:
                first, second = list[i], first
        elif list[i] > second:
                second = list[i]

print("First:", first)
print("Second:", second)


问:
How to add two numbers using only pointer variables such as int *a,*b,*add;
I am getting a problem with pointers in 32-bit architecture.I want to add two numbers using only pointer variables for ex: int *a,*b,*add; but in 32-bit based compiler such as codeblocks doesn't giving the ouptut.

But in case of 16-bit based compiler such as turbo c++ it is working properly.

This is the code that I've tried

```<code>int *a,*b,*add;
printf("Enter two no.");
scanf("%d%d",a,b);
*add=*a+*b;
</code>```

in code block it is returning nothing .
but in turbo c ++ it is working properly.

答:
You need to allocate the memory for variables at first. When you only call "int *a" you don't have the memory reserved. So you need to call malloc or calloc.

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

int main(void) {
  int *a, *b, *add;

  // allocate memory
  a = malloc(sizeof(int));
  b = malloc(sizeof(int));
  add = malloc(sizeof(int));

  // check if there was an error allocating the memory
  if (a == NULL) {perror("allocate pointer a");};
  if (b == NULL) {perror("allocate pointer b");};
  if (add == NULL) {perror("allocate pointer add");};

  // read numbers
  printf("Enter two numbers ");
  scanf("%d%d", a, b);

  printf("a: %d; b:  %d\n", *a, *b);

  // calculate the result and print it
  *add = *a + *b;
  printf("sum: %d\n", *add);

  // free the pointer
  free(a);
  free(b);
  free(add);

  return 0;
}
</code>```

You should also check if your pointer is null after allocating because then you have not enough space for the variable and you should exit the program. You could also malloc and check for error in one line this would look for example like: if ((a = malloc(sizeof(int))) == NULL) {perror("allocate pointer a");};

When you don't need you pointer you should free them or you will get memory leaks.

Body:
I am getting a problem with pointers in 32-bit architecture.I want to add two numbers using only pointer variables for ex: int *a,*b,*add; but in 32-bit based compiler such as codeblocks doesn't giving the ouptut.

But in case of 16-bit based compiler such as turbo c++ it is working properly.

This is the code that I've tried

int *a,*b,*add;
printf("Enter two no.");
scanf("%d%d",a,b);
*add=*a+*b;

in code block it is returning nothing .
but in turbo c ++ it is working properly.

Body:
You need to allocate the memory for variables at first. When you only call "int *a" you don't have the memory reserved. So you need to call malloc or calloc.

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

int main(void) {
  int *a, *b, *add;

  // allocate memory
  a = malloc(sizeof(int));
  b = malloc(sizeof(int));
  add = malloc(sizeof(int));

  // check if there was an error allocating the memory
  if (a == NULL) {perror("allocate pointer a");};
  if (b == NULL) {perror("allocate pointer b");};
  if (add == NULL) {perror("allocate pointer add");};

  // read numbers
  printf("Enter two numbers ");
  scanf("%d%d", a, b);

  printf("a: %d; b:  %d\n", *a, *b);

  // calculate the result and print it
  *add = *a + *b;
  printf("sum: %d\n", *add);

  // free the pointer
  free(a);
  free(b);
  free(add);

  return 0;
}

You should also check if your pointer is null after allocating because then you have not enough space for the variable and you should exit the program. You could also malloc and check for error in one line this would look for example like: if ((a = malloc(sizeof(int))) == NULL) {perror("allocate pointer a");};

When you don't need you pointer you should free them or you will get memory leaks.


问:
Failed to connect to XX.XX.XXX.XX port 9200: Connection refused on EC2
I've installed Elasticsearch on an EC2 Ubuntu 14 server.

I can see it's running:

```<code>elastic@ip-xxx-xx-xx-xxx:~$ curl -get localhost:9200
{
  "name" : "ip-xxx-xx-xx-xxx",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "V6axWUV9SoqABC8sX62XMQ",
  "version" : {
    "number" : "7.0.1",
    "build_flavor" : "default",
    "build_type" : "deb",
    "build_hash" : "e4efcb5",
    "build_date" : "2019-04-29T12:57:03.145736Z",
    "build_snapshot" : false,
    "lucene_version" : "8.0.0",
    "minimum_wire_compatibility_version" : "6.7.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
</code>```

I've added it to the security group:

But I can't connect from remote:

```<code>C:\>curl -get http://XX.XX.XXX.XX:9200/
curl: (7) Failed to connect to XX.XX.XXX.XX port 9200: Connection refused
</code>```

netstat -nlp |grep 9200:

```<code>tcp6       0      0 127.0.0.1:9200          :::*                    LISTEN      29467/java
tcp6       0      0 ::1:9200                :::*                    LISTEN      29467/java
</code>```

This is the content of elasticsearch.yml after removing all comments:

```<code>path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
</code>```

答:
please add the following line in elasticsearch.yml and restart elasticsearch service:

```<code>network.host: xxx.xxx.xxx.xxx
</code>```

xxx.xxx.xxx.xxx is your elasticsearch server's IP address

Body:
I've installed Elasticsearch on an EC2 Ubuntu 14 server.

I can see it's running:

elastic@ip-xxx-xx-xx-xxx:~$ curl -get localhost:9200
{
  "name" : "ip-xxx-xx-xx-xxx",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "V6axWUV9SoqABC8sX62XMQ",
  "version" : {
    "number" : "7.0.1",
    "build_flavor" : "default",
    "build_type" : "deb",
    "build_hash" : "e4efcb5",
    "build_date" : "2019-04-29T12:57:03.145736Z",
    "build_snapshot" : false,
    "lucene_version" : "8.0.0",
    "minimum_wire_compatibility_version" : "6.7.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

I've added it to the security group:

But I can't connect from remote:

C:\>curl -get http://XX.XX.XXX.XX:9200/
curl: (7) Failed to connect to XX.XX.XXX.XX port 9200: Connection refused

netstat -nlp |grep 9200:

tcp6       0      0 127.0.0.1:9200          :::*                    LISTEN      29467/java
tcp6       0      0 ::1:9200                :::*                    LISTEN      29467/java

This is the content of elasticsearch.yml after removing all comments:

path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch

Body:
please add the following line in elasticsearch.yml and restart elasticsearch service:

network.host: xxx.xxx.xxx.xxx

xxx.xxx.xxx.xxx is your elasticsearch server's IP address


问:
Should I reuse service for calendar API, or is it safe to create new ones on demand?
I've made a small web server that creates and updates calendar events. However, I'm a bit uncertain about how I'm supposed to use the calendar api library service. At the moment I'm creating a new one each time the web server accepts a request, like so:

```<code>ctx := context.Background()
srv, err := calendar.NewService(ctx,option.WithTokenSource(config.TokenSource(ctx)))
</code>```

I suspect I'm probably supposed to reuse this service, but I can't find any documentation about this. Is it safe to reuse? Does it get discarded automatically when no longer in use (i.e. garbage collection)?

答:
You probably want to use req.Context() (where req is your *http.Request) instead of context.Background(). In this case, you have to create a new service object each time, and they will be garbage collected as appropriate.

The only reason you would want to use context.Background() is if you're asynchronously issuing the calendar API requests (eg, in a separate goroutine) and they might not finish before the HTTP request finishes. In this case, you could use a single shared service object if you wanted.

Body:
I've made a small web server that creates and updates calendar events. However, I'm a bit uncertain about how I'm supposed to use the calendar api library service. At the moment I'm creating a new one each time the web server accepts a request, like so:

ctx := context.Background()
srv, err := calendar.NewService(ctx,option.WithTokenSource(config.TokenSource(ctx)))

I suspect I'm probably supposed to reuse this service, but I can't find any documentation about this. Is it safe to reuse? Does it get discarded automatically when no longer in use (i.e. garbage collection)?


问:
2 Errors when trying to compile the bcrypt project
I'm using bcrypt library and getting these errors:

Error    LNK2019    unresolved external symbol bcrypt_gensalt referenced in function "public: static class std::basic_string,class std::allocator > cdecl BCrypt::generateHash(class std::basic_string,class std::allocator > const &,int)" (?generateHash@BCrypt@@SA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AEBV23@H@Z)

Error    LNK2019    unresolved external symbol bcrypt_hashpw referenced in function "public: static class std::basic_string,class std::allocator > cdecl BCrypt::generateHash(class std::basic_string,class std::allocator > const &,int)" (?generateHash@BCrypt@@SA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AEBV23@H@Z)

Here's my test code:

```<code>#include <iostream>
#include "bcrypt/BCrypt.hpp"

BCrypt bcrypt;

using namespace std;

int main() {
    string password = "test";
    string hash = bcrypt.generateHash(password);
    cout << bcrypt.validatePassword(password, hash) << endl;
    cout << bcrypt.validatePassword("test1", hash) << endl;
}
</code>```

答:
I used this code</p>

```<code>#include <iostream>
#include "bcrypt/BCrypt.hpp"

BCrypt bcrypt;

using namespace std;

int main() {

    string password = "test";
    string hash = bcrypt.generateHash(password);
    cout << bcrypt.validatePassword(password, hash) << endl;
    cout << bcrypt.validatePassword("test1", hash) << endl;

}
</code>```

Body:
I'm using bcrypt library and getting these errors:

Error    LNK2019    unresolved external symbol bcrypt_gensalt referenced in function "public: static class std::basic_string,class std::allocator > cdecl BCrypt::generateHash(class std::basic_string,class std::allocator > const &,int)" (?generateHash@BCrypt@@SA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AEBV23@H@Z)

Error    LNK2019    unresolved external symbol bcrypt_hashpw referenced in function "public: static class std::basic_string,class std::allocator > cdecl BCrypt::generateHash(class std::basic_string,class std::allocator > const &,int)" (?generateHash@BCrypt@@SA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AEBV23@H@Z)

Here's my test code:

#include <iostream>
#include "bcrypt/BCrypt.hpp"

BCrypt bcrypt;

using namespace std;

int main() {
    string password = "test";
    string hash = bcrypt.generateHash(password);
    cout << bcrypt.validatePassword(password, hash) << endl;
    cout << bcrypt.validatePassword("test1", hash) << endl;
}

Body:
I used this code

#include <iostream>
#include "bcrypt/BCrypt.hpp"

BCrypt bcrypt;

using namespace std;

int main() {

    string password = "test";
    string hash = bcrypt.generateHash(password);
    cout << bcrypt.validatePassword(password, hash) << endl;
    cout << bcrypt.validatePassword("test1", hash) << endl;

}


问:
How can I achieve this kind of sea-wave progress in android (check this gif image)?

I want to add the progress wave like the above gif image. I've seen this kind of progress wave recently in many apps. I also searched for the 3rd party library but couldn't find one. Maybe there is one, but I'm not searching with correct keywords.

答:
For Loading list place holders, you can use Shimmering Animations. I am listing out some of the cool Third parties libraries which you can use.

https://github.com/facebook/shimmer-android

https://github.com/team-supercharge/ShimmerLayout

Here is one of the best tutorial link

https://www.androidhive.info/2018/01/android-content-placeholder-animation-like-facebook-using-shimmer/


问:
Android: Progressbar displayed
I want to display a progressbar, and during this time it's get items and when it's finished geting all the items, it will show the list. </p>

<p>How is this possible? </p>

答:
Create the ProgressDialog in your Activity:

```<code>private ProgressDialog progressDialog;
</code>```

Set the ProgressDialog in any action where you want to take some time:

```<code>progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");
</code>```

Use Thread to handle the progress bar:

```<code>new Thread()
{
    public void run()
    {
        try
        {
            sleep(1500);
            // do some task (whatever you want to do)
        }
        catch(Exception e)
        {
            Log.e("tag",e.getMessage());
        }
    }.start();
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Android: Progressbar displayed

Body:
I want to display a progressbar, and during this time it's get items and when it's finished geting all the items, it will show the list.

How is this possible?

Body:
Create the ProgressDialog in your Activity:

private ProgressDialog progressDialog;

Set the ProgressDialog in any action where you want to take some time:

progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");

Use Thread to handle the progress bar:

new Thread()
{
    public void run()
    {
        try
        {
            sleep(1500);
            // do some task (whatever you want to do)
        }
        catch(Exception e)
        {
            Log.e("tag",e.getMessage());
        }
    }.start();
}


问:
How to return a cached PyObject* value several times without memory leaking or double/triple frees?
On my last question How to improve Python C Extensions file line reading? was brought up some memory problems I had. Then, I wrote this simple and ridiculous usage of and Python C Extension, just with the purpose of trying to understanding better Python Borrowing and Owning References.

static void PyFastFile_dealloc(PyFastFile* self) {
    for( PyObject* pyobject : linecache ) {
        Py_XDECREF( pyobject );
    }
    Py_TYPE(self)->tp_free( (PyObject*) self );
}

static PyObject* PyFastFile_tp_iter(PyFastFile* self, PyObject* args) {
    counter = 10;
    std::string line{"sample line"}
    PyObject* obj = PyUnicode_DecodeUTF8( line.c_str(), line.size(), "replace" );
    linecache.push_back( obj );
}

static PyObject* PyFastFile_iternext(PyFastFile* self, PyObject* args) {
    --counter;

    if( !( counter ) ) {
        PyErr_SetNone( PyExc_StopIteration );
        return NULL;
    }

    PyObject* retval = linecache[0];
    Py_XINCREF( retval );
    return retval;
}

// create the module
PyMODINIT_FUNC PyInit_fastfilepackage(void) {
    PyFastFileType.tp_iter = (getiterfunc) PyFastFile_tp_iter;
    PyFastFileType.tp_iternext = (iternextfunc) PyFastFile_iternext;
    PyFastFileType.tp_dealloc = (destructor) PyFastFile_dealloc;
    ...
}
```

On this case,

Is the tp_next() returning an owned reference to linecache[0] because it is incrementing its Py_XINCREF?

Meaning, is my linecache[0] cache now a borrowed reference?

As tp_next() is being called more than once, and I am returning the same pointer several times incrementing its Py_XINCREF, is this going to lead to double/triple/several frees?

Has the tp_next() return object only one owned reference, which will lead to double/triple/several?

Related:

Py_INCREF/DECREF: When

答:
You basically need the reference count of an object to be equal to the number of PyObject* that refer to it.

Yes - you return a PyObject* to your Python code so you should increment the reference count.

No - when linecache[0] is created it has a refcount of 1 and this represents ownership by linecache. Multiple places can "own" a single Python object.

Yes you are returning the same pointer multiple times; no this will not result in multiple frees. The pointer is freed when the reference count reaches 0. This will be when you break all the references to the values you've returned from next, and when you lose the reference in linecache (when PyFastFile_dealloc is called).

I don't understand the last question, but the code here is basically correct.

The one issue I can see here is "what is linecache/who owns it". If it's a global variable then it may end up being shared between multiple PyFastFile objects which is probably wrong. The destruction of a single PyFastFile will lead to the entire linecache being freed, but you don't pop_back or NULL the pointers.

Body:
On my last question How to improve Python C Extensions file line reading? was brought up some memory problems I had. Then, I wrote this simple and ridiculous usage of and Python C Extension, just with the purpose of trying to understanding better Python Borrowing and Owning References.

static void PyFastFile_dealloc(PyFastFile* self) {
    for( PyObject* pyobject : linecache ) {
        Py_XDECREF( pyobject );
    }
    Py_TYPE(self)->tp_free( (PyObject*) self );
}

static PyObject* PyFastFile_tp_iter(PyFastFile* self, PyObject* args) {
    counter = 10;
    std::string line{"sample line"}
    PyObject* obj = PyUnicode_DecodeUTF8( line.c_str(), line.size(), "replace" );
    linecache.push_back( obj );
}

static PyObject* PyFastFile_iternext(PyFastFile* self, PyObject* args) {
    --counter;

    if( !( counter ) ) {
        PyErr_SetNone( PyExc_StopIteration );
        return NULL;
    }

    PyObject* retval = linecache[0];
    Py_XINCREF( retval );
    return retval;
}

// create the module
PyMODINIT_FUNC PyInit_fastfilepackage(void) {
    PyFastFileType.tp_iter = (getiterfunc) PyFastFile_tp_iter;
    PyFastFileType.tp_iternext = (iternextfunc) PyFastFile_iternext;
    PyFastFileType.tp_dealloc = (destructor) PyFastFile_dealloc;
    ...
}

On this case,

Is the tp_next() returning an owned reference to linecache[0] because it is incrementing its Py_XINCREF?

Meaning, is my linecache[0] cache now a borrowed reference?

As tp_next() is being called more than once, and I am returning the same pointer several times incrementing its Py_XINCREF, is this going to lead to double/triple/several frees?

Has the tp_next() return object only one owned reference, which will lead to double/triple/several?

Related:

Py_INCREF/DECREF: When


问:
How to find closest lower value in array angular 6?
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

```<code><button (click) ="getPrev()">Previous Value</button>
</code>```

app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}
</code>```

答:
If your ids can be negative numbers, you can go with this:

getClosestLowerIdElement(value: number, array: Array<{[key: string]: number}>) {
    const v = {id: value};
    return array.reduce((acc, a) => acc = (
        (acc.id === undefined || Math.abs(v.id - a.id) < Math.abs(v.id - acc.id) ||
            acc.id > v.id) && a.id < v.id) ? a : acc, {id: undefined});
  }
```

<p>And you can use it like this:</p>

<pre class="lang-js prettyprint-override"><code>idArray = [{id: 1}, {id: -30}, {id: -5}, {id: 7}, {id: 9}, {id: 11}, {id: 21}];

...

console.log(this.getClosestLowerIdElement(0, this.idArray)); // prints {id: -5}
</code>```

If there's no number lower than the value passed to the getClosestLowerIdElement method, you'll get {id: undefined}

See the demo on Stackblitz

Body:
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

<button (click) ="getPrev()">Previous Value</button>

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}

Body:
If your ids can be negative numbers, you can go with this:

getClosestLowerIdElement(value: number, array: Array<{[key: string]: number}>) {
    const v = {id: value};
    return array.reduce((acc, a) => acc = (
        (acc.id === undefined || Math.abs(v.id - a.id) < Math.abs(v.id - acc.id) ||
            acc.id > v.id) && a.id < v.id) ? a : acc, {id: undefined});
  }

And you can use it like this:

idArray = [{id: 1}, {id: -30}, {id: -5}, {id: 7}, {id: 9}, {id: 11}, {id: 21}];

...

console.log(this.getClosestLowerIdElement(0, this.idArray)); // prints {id: -5}

If there's no number lower than the value passed to the getClosestLowerIdElement method, you'll get {id: undefined}

See the demo on Stackblitz


问:
Not able to create notebook and transfer files in evernote
I am developing a web application and I need to create an EverNote notebook and transfer some files in it.

I am able to authenticate user from EverNote but not able to create notebook. I'm also confused how to transfer files in that notebook.

Here is the authentication code. API URL

For creating a notebook:

```<code>noteStore.createNotebook(access_token.token, "my_notebook")
</code>```

Error:

```<code>An error occurred: undefined method `write' for "my_notebook":String
</code>```

edit

following seth's lead

```<code>      notebook = Evernote::EDAM::Type::Notebook.new()
          notebook.name = "my_notebook3"
          x= noteStore.createNotebook(access_token.token, notebook)
         note = Evernote::EDAM::Type::Note.new()
         note.notebookGuid = x.guid
         note.title="my note"
         y=noteStore.createNote(access_token.token,note)
</code>```

working on file transfer in that note.

答:
The second parameter is a Notebook structure, not a string. You need to do something like:

```<code>notebook = Evernote::EDAM::Type::Notebook.new()
notebook.name = "my_notebook"
noteStore.createNotebook(access_token.token, notebook)
</code>```

Evernote notebooks contain only Notes, and Notes can have files attached to them. To attach a file to a new note, you need to create a Resource and include it in the note:

```<code>filename = # the file that you want to attach
image = File.open(filename, "rb") { |io| io.read }
hashFunc = Digest::MD5.new
hashHex = hashFunc.hexdigest(image)

data = Evernote::EDAM::Type::Data.new()
data.size = image.size
data.bodyHash = hashHex
data.body = image

resource = Evernote::EDAM::Type::Resource.new()
resource.mime = # the appropriate MIME type
resource.data = data
resource.attributes = Evernote::EDAM::Type::ResourceAttributes.new()
resource.attributes.fileName = filename

note = Evernote::EDAM::Type::Note.new()
note.title = "Title"
note.content = '<?xml version="1.0" encoding="UTF-8"?>' +
  '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' +
  '<en-note>' +
  '<en-media type="' + resource.mime + '" hash="' + hashHex + '"/>' +
  '</en-note>'
note.resources = [ resource ]

createdNote = noteStore.createNote(authToken, note)
</code>```

The sample code in the Evernote API ZIP file demonstrates this. You can download the ZIP from http://www.evernote.com/about/developer/api/.

Body:
I am developing a web application and I need to create an EverNote notebook and transfer some files in it.

I am able to authenticate user from EverNote but not able to create notebook. I'm also confused how to transfer files in that notebook.

Here is the authentication code. API URL

For creating a notebook:

noteStore.createNotebook(access_token.token, "my_notebook")

Error:

An error occurred: undefined method `write' for "my_notebook":String

edit

following seth's lead

      notebook = Evernote::EDAM::Type::Notebook.new()
          notebook.name = "my_notebook3"
          x= noteStore.createNotebook(access_token.token, notebook)
         note = Evernote::EDAM::Type::Note.new()
         note.notebookGuid = x.guid
         note.title="my note"
         y=noteStore.createNote(access_token.token,note)

working on file transfer in that note.

Body:
The second parameter is a Notebook structure, not a string. You need to do something like:

notebook = Evernote::EDAM::Type::Notebook.new()
notebook.name = "my_notebook"
noteStore.createNotebook(access_token.token, notebook)

Evernote notebooks contain only Notes, and Notes can have files attached to them. To attach a file to a new note, you need to create a Resource and include it in the note:

filename = # the file that you want to attach
image = File.open(filename, "rb") { |io| io.read }
hashFunc = Digest::MD5.new
hashHex = hashFunc.hexdigest(image)

data = Evernote::EDAM::Type::Data.new()
data.size = image.size
data.bodyHash = hashHex
data.body = image

resource = Evernote::EDAM::Type::Resource.new()
resource.mime = # the appropriate MIME type
resource.data = data
resource.attributes = Evernote::EDAM::Type::ResourceAttributes.new()
resource.attributes.fileName = filename

note = Evernote::EDAM::Type::Note.new()
note.title = "Title"
note.content = '<?xml version="1.0" encoding="UTF-8"?>' +
  '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' +
  '<en-note>' +
  '<en-media type="' + resource.mime + '" hash="' + hashHex + '"/>' +
  '</en-note>'
note.resources = [ resource ]

createdNote = noteStore.createNote(authToken, note)

The sample code in the Evernote API ZIP file demonstrates this. You can download the ZIP from http://www.evernote.com/about/developer/api/.


问:
How to correctly create a .gdns to instantiate it?
I have a gdnative library loaded in my godot. I can also call functions on it, that works. But I want to instantiate c++-Classes from it inside Godot.

I think I have to generate .gdns files for that to work, but i dont really find a example of that.

I created a .gdns script already with the New Script Dialogue. I named it exactly like the c++ class. And I set the Library in the scripts inspector and set ClassName to MyClass. But the following does not work as someClass is Null:

```<code>var someclass = load("res://MyClass.gdns").new();
someclass.method("myMethod");
</code>```

What did I do wrong?
I tried to follow this tutorial.

Im Using Godot 1.1 and compiled the gdnative-library with the appropriate Godot-cpp headers.

答:
I created a .gdns file with the New Resource Dialogue and it worked then (after setting the library and Class-name of the .gdns in the Inspector).

I'll add more here when I found out why it didn't work before.

Body:
I have a gdnative library loaded in my godot. I can also call functions on it, that works. But I want to instantiate c++-Classes from it inside Godot.

I think I have to generate .gdns files for that to work, but i dont really find a example of that.

I created a .gdns script already with the New Script Dialogue. I named it exactly like the c++ class. And I set the Library in the scripts inspector and set ClassName to MyClass. But the following does not work as someClass is Null:

var someclass = load("res://MyClass.gdns").new();
someclass.method("myMethod");

What did I do wrong?
I tried to follow this tutorial.

Im Using Godot 1.1 and compiled the gdnative-library with the appropriate Godot-cpp headers.


问:
Retrieving Jenkins Container Template pre-configured Environment Variables
I'm not able to get the value of the pre-configured container template environment variable in my application pipeline (Manage Jenkins => Jenkins Configuration => Kubernetes Pod Templates => Container Templates => EnvVar).

I'm using the latest version of Jenkins and Kubernetes Jenkins Plugin.

I tried the following and every time I end with null.

```<code>node('bunking-gibbon-jenkins-slave') {
    container('apidev-container-build'){
        stage("extraction"){
            echo("Chart Var is '${env.CHARTPATH}'")
        }
    }
}
</code>```

OR

```<code>node('bunking-gibbon-jenkins-slave') {
    container('apidev-container-build'){
        stage("extraction"){
            echo CHARTPATH
        }
    }
}
</code>```

答: from groovy, this should work: ${CHARTPATH}</p>

Body:
I'm not able to get the value of the pre-configured container template environment variable in my application pipeline (Manage Jenkins => Jenkins Configuration => Kubernetes Pod Templates => Container Templates => EnvVar).

I'm using the latest version of Jenkins and Kubernetes Jenkins Plugin.

I tried the following and every time I end with null.

node('bunking-gibbon-jenkins-slave') {
    container('apidev-container-build'){
        stage("extraction"){
            echo("Chart Var is '${env.CHARTPATH}'")
        }
    }
}

OR

node('bunking-gibbon-jenkins-slave') {
    container('apidev-container-build'){
        stage("extraction"){
            echo CHARTPATH
        }
    }
}


问:
Read Sub directory and specific files in Java
I need find all the java files in a directory

```<code>    private void search(File directory) {
        if (directory.isDirectory()) {
            File[] javaFilesLs = directory.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                  return name.toLowerCase().endsWith(".java");
//                return name.toLowerCase().endsWith(".java") || dir.isDirectory();
                }
            });
            if (directory.canRead()) {
                assert javaFilesLs != null;
                for (File temp : javaFilesLs) {
                    if (temp.isDirectory()) {
                        search(temp);
                    } else {
                        fileList.add(temp.getAbsolutePath());
                    }
                }
            }
        }
    }
</code>```

When I use the commented line it finds the subdirectory and all the files not only ".java" files.

答:
The reason why you get all paths using the commented line, is that dir.isDirectory() will return true for all files.
Take a look at the documentation of FilenameFilter. It specifies that dir is "the directory in which the file was found."

So instead of looking at dir, you must test if name represents a directory. There may be smarter methods, but it can be done like this:

```<code>new File(dir.toPath().toString(), name).isDirectory() // returns true for directories
</code>```

The whole snippet thus looks like this:

```<code>private void search(File directory) {
    if (directory.isDirectory()) {
        File[] javaFilesLs = directory.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".java") || new File(dir.toPath().toString(), name).isDirectory();
            }
        });
        if (directory.canRead()) {
            assert javaFilesLs != null;
            for (File temp : javaFilesLs) {
                if (temp.isDirectory()) {
                    search(temp);
                } else {
                    fileList.add(temp.getAbsolutePath());
                }
            }
        }
    }
}
</code>```

Alternatively, Java 8 adds Files.walk which implements the recursion for you as a Stream.

```<code>private void search(File directory) throws IOException {
    Files.walk(directory.toPath())
        .filter(f -> {
            return f.getFileName().toString().endsWith(".java");
        })
        .forEach(f -> fileList.add(f.toFile().getAbsolutePath()));
}
</code>```

Body:
I need find all the java files in a directory

    private void search(File directory) {
        if (directory.isDirectory()) {
            File[] javaFilesLs = directory.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                  return name.toLowerCase().endsWith(".java");
//                return name.toLowerCase().endsWith(".java") || dir.isDirectory();
                }
            });
            if (directory.canRead()) {
                assert javaFilesLs != null;
                for (File temp : javaFilesLs) {
                    if (temp.isDirectory()) {
                        search(temp);
                    } else {
                        fileList.add(temp.getAbsolutePath());
                    }
                }
            }
        }
    }

When I use the commented line it finds the subdirectory and all the files not only ".java" files.

Body:
The reason why you get all paths using the commented line, is that dir.isDirectory() will return true for all files.
Take a look at the documentation of FilenameFilter. It specifies that dir is "the directory in which the file was found."

So instead of looking at dir, you must test if name represents a directory. There may be smarter methods, but it can be done like this:

new File(dir.toPath().toString(), name).isDirectory() // returns true for directories

The whole snippet thus looks like this:

private void search(File directory) {
    if (directory.isDirectory()) {
        File[] javaFilesLs = directory.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".java") || new File(dir.toPath().toString(), name).isDirectory();
            }
        });
        if (directory.canRead()) {
            assert javaFilesLs != null;
            for (File temp : javaFilesLs) {
                if (temp.isDirectory()) {
                    search(temp);
                } else {
                    fileList.add(temp.getAbsolutePath());
                }
            }
        }
    }
}

Alternatively, Java 8 adds Files.walk which implements the recursion for you as a Stream.

private void search(File directory) throws IOException {
    Files.walk(directory.toPath())
        .filter(f -> {
            return f.getFileName().toString().endsWith(".java");
        })
        .forEach(f -> fileList.add(f.toFile().getAbsolutePath()));
}


问:
What exactly do quotation marks around the table name do?
I thought that the quotation mark (") was simply a type of grouping marker but I'm debugging some NHibernate code and notice that while

```<code>SELECT * FROM site WHERE site_id = 3;
</code>```

Works fine

```<code>SELECT * FROM "site" WHERE site_id = 3;
</code>```

fails with a table or view does not exist error.

What gives?

答:
Putting double-quotes around an identifier in Oracle causes Oracle to treat the identifier as case sensitive rather than using the default of case-insensitivity.  If you create a table (or a column) with double-quotes around the name, you must always refer to the identifier with double quotes and by correctly specifying the case (with the exception of all upper case identifiers, where double-quotes are meaningless).

Under the covers, Oracle is always doing case-sensitive identifier matching.  But it always casts identifiers that are not double-quoted to upper case before doing the matching.  If you put double-quotes around an identifier, Oracle skips the casting to upper case.

So if you do something like

```<code>CREATE TABLE my_table(
  col1 number,
  col2 number
)
</code>```

you can

```<code>SELECT * FROM my_table
SELECT * FROM MY_TABLE
SELECT * FROM My_Table
SELECT * FROM "MY_TABLE"
</code>```

but something like

```<code>SELECT * FROM "my_table"
</code>```

will fail.

On the other hand, if you do something like

```<code>CREATE TABLE "my_other_table"(
  col1 number,
  col2 number
)
</code>```

you cannot do

```<code>SELECT * FROM my_other_table
SELECT * FROM MY_OTHER_TABLE
SELECT * FROM My_Other_Table
SELECT * FROM "MY_OTHER_TABLE"
</code>```

but this

```<code>SELECT * FROM "my_other_table"
</code>```

will work

OwnerDisplayName: George Mauer

Body:
I thought that the quotation mark (") was simply a type of grouping marker but I'm debugging some NHibernate code and notice that while

SELECT * FROM site WHERE site_id = 3;

Works fine

SELECT * FROM "site" WHERE site_id = 3;

fails with a table or view does not exist error.

What gives?

LastEditorDisplayName: Joel Coehoorn

Body:
Putting double-quotes around an identifier in Oracle causes Oracle to treat the identifier as case sensitive rather than using the default of case-insensitivity.  If you create a table (or a column) with double-quotes around the name, you must always refer to the identifier with double quotes and by correctly specifying the case (with the exception of all upper case identifiers, where double-quotes are meaningless).

Under the covers, Oracle is always doing case-sensitive identifier matching.  But it always casts identifiers that are not double-quoted to upper case before doing the matching.  If you put double-quotes around an identifier, Oracle skips the casting to upper case.

So if you do something like

CREATE TABLE my_table(
  col1 number,
  col2 number
)

you can

SELECT * FROM my_table
SELECT * FROM MY_TABLE
SELECT * FROM My_Table
SELECT * FROM "MY_TABLE"

but something like

SELECT * FROM "my_table"

will fail.

On the other hand, if you do something like

CREATE TABLE "my_other_table"(
  col1 number,
  col2 number
)

you cannot do

SELECT * FROM my_other_table
SELECT * FROM MY_OTHER_TABLE
SELECT * FROM My_Other_Table
SELECT * FROM "MY_OTHER_TABLE"

but this

SELECT * FROM "my_other_table"

will work

OwnerDisplayName: Justin Cave


问:
2 different routes on one page?
Hi I'm pretty new with MVC2 or MVC in general. If it's one thing I get caught up with it's routes. Like now I got this scenario. Im going from the regular site to Admin. My navigation is the same partialview on both I just do a check which data to render something like this.

```<code><% if (!Request.RawUrl.Contains("Admin")){%>
<% foreach (var site in Model) { %>
<%= Html.MenuItem(site.BelongSite, "Sida", "Site", site.BelongSite) %> |
<%} %>
<%} else {%>
<%= Html.ActionLink("Konfig", "Konfigurera", "Admin") %>
<% } %>
</code>```

My route looks like this

```<code>routes.MapRoute(
                "Admin", // Route name
                "Admin/{action}/{name}", // URL with parameters
                new { controller = "Admin", action = "konfigurera", name = UrlParameter.Optional } // Parameter defaults
            );
</code>```

On my View called Konfigurera I got Edit sites and they use the route above and it works great. The navigation tho dont get no action assigned to it. It's just href='Admin/'>

The navigation is in the shared folder, and it is a strongly typed. Any Ideas? I been struggling with this for about a hour now

Thanks for any input

EDIT

this is just one of those omg I'm so stupid moments. Ofcause the the link gone be only href='Admin/' because it's the default link (as the default values of the route). I noticed this as I put more links to the Admin navigation and they was ok. Well hope this can help anybody in the same situation as I had.

I wonder how I should do if I come up with the solution myself?

答: Ofcause the the link gone be only href='Admin/' because it's the default link (as the default values of the route). So really no problem here Index always gone result in a "empty" link.

Title: 2 different routes on one page?

Body:
Hi I'm pretty new with MVC2 or MVC in general. If it's one thing I get caught up with it's routes. Like now I got this scenario. Im going from the regular site to Admin. My navigation is the same partialview on both I just do a check which data to render something like this.

<% if (!Request.RawUrl.Contains("Admin")){%>
<% foreach (var site in Model) { %>
<%= Html.MenuItem(site.BelongSite, "Sida", "Site", site.BelongSite) %> |
<%} %>
<%} else {%>
<%= Html.ActionLink("Konfig", "Konfigurera", "Admin") %>
<% } %>

My route looks like this

routes.MapRoute(
                "Admin", // Route name
                "Admin/{action}/{name}", // URL with parameters
                new { controller = "Admin", action = "konfigurera", name = UrlParameter.Optional } // Parameter defaults
            );

On my View called Konfigurera I got Edit sites and they use the route above and it works great. The navigation tho dont get no action assigned to it. It's just

The navigation is in the shared folder, and it is a strongly typed. Any Ideas? I been struggling with this for about a hour now

Thanks for any input

EDIT

this is just one of those omg I'm so stupid moments. Ofcause the the link gone be only <a href='Admin/' because it's the default link (as the default values of the route). I noticed this as I put more links to the Admin navigation and they was ok. Well hope this can help anybody in the same situation as I had.

I wonder how I should do if I come up with the solution myself?

Body: Ofcause the the link gone be only <a href='Admin/' because it's the default link (as the default values of the route). So really no problem here Index always gone result in a "empty" link.


问:
How to import a specific folder containing python codes in any directory using conda environment?
I have a folder containing many python codes. I want to use this folder at any directory. How can I do that? I use this command in the directory that it exists:

```<code>python -c "from myfolder import *"
</code>```

I'm using anaconda and python 2.7. Thanks in advance.

答:
I think that you should be able to fix it by adding your folder to the PYTHONPATH, so by doing:

import sys
sys.path.append("your folder")
```

you should be able to use the scripts of this folder at any directory.
Let me know if it helps :)

Body:
I have a folder containing many python codes. I want to use this folder at any directory. How can I do that? I use this command in the directory that it exists:

python -c "from myfolder import *"

I'm using anaconda and python 2.7. Thanks in advance.

Body:
I think that you should be able to fix it by adding your folder to the PYTHONPATH, so by doing:

import sys
sys.path.append("your folder")

you should be able to use the scripts of this folder at any directory.
Let me know if it helps :)


问:
Unable to solve the XOR problem with just two hidden neurons in Python
I have a small, 3 layer, neural network with two input neurons, two hidden neurons and one output neuron. I am trying to stick to the below format of using only 2 hidden neurons.

I am trying to show how this can be used to behave as the XOR logic gate, however with just two hidden neurons I get the following poor output after 1,000,000 iterations!

```<code>Input: 0 0   Output:  [0.01039096]
Input: 1 0   Output:  [0.93708829]
Input: 0 1   Output:  [0.93599738]
Input: 1 1   Output:  [0.51917667]
</code>```

If I use three hidden neurons I get a much better output with 100,000 iterations:

```<code>Input: 0 0   Output:  [0.01831612]
Input: 1 0   Output:  [0.98558057]
Input: 0 1   Output:  [0.98567602]
Input: 1 1   Output:  [0.02007876]
</code>```

I am getting a decent output with 3 neurons in the hidden layer but not with two neurons in the hidden layer. Why?

As per a comment below, this repo contains code of high to solve the XOR problem using two hidden neurons.

I can't figure out what I am doing wrong. Any suggestions are appreciated!
Attached is my code:

```<code>import numpy as np
import matplotlib
from matplotlib import pyplot as plt

# Sigmoid function
def sigmoid(x, deriv=False):
    if deriv:
        return x * (1 - x)
    return 1 / (1 + np.exp(-x))

alpha = [0.7]

# Input dataset
X = np.array([[0, 0],
              [0, 1],
              [1, 0],
              [1, 1]])

# Output dataset
y = np.array([[0, 1, 1, 0]]).T

# seed random numbers to make calculation deterministic
np.random.seed(1)

# initialise weights randomly with mean 0
syn0 = 2 * np.random.random((2, 3)) - 1  # 1st layer of weights synapse 0 connecting L0 to L1
syn1 = 2 * np.random.random((3, 1)) - 1  # 2nd layer of weights synapse 0 connecting L1 to L2

# Randomize inputs for stochastic gradient descent
data = np.hstack((X, y))    # append Input and output dataset
np.random.shuffle(data)     # shuffle
x, y = np.array_split(data, 2, 1)    # Split along vertical(1) axis

for iter in range(100000):
    for i in range(4):
        # forward prop
        layer0 = x[i]  # Input layer
        layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
        layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

        layer2_error = y[i] - layer2  # Compare how well layer2's guess was with input

        layer2_delta = layer2_error * sigmoid(layer2, deriv=True)  # Error weighted derivative step

        if iter % 10000 == 0:
            print("Error: ", str(np.mean(np.abs(layer2_error))))
            plt.plot(iter, layer2_error, 'ro')

        # Uses "confidence weighted error" from l2 to establish an error for l1
        layer1_error = layer2_delta.dot(syn1.T)

        layer1_delta = layer1_error * sigmoid(layer1, deriv=True)  # Error weighted derivative step

        # Since SGD we need to dot product two 1D arrays. This is how.
        syn1 += (alpha * np.dot(layer1[:, None], layer2_delta[None, :]))  # Update weights
        syn0 += (alpha * np.dot(layer0[:, None], layer1_delta[None, :]))

    # Training was done above, below we re run to test algorithm

    layer0 = X  # Input layer
    layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
    layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

plt.show()
print("output after training: \n")
print("Input: 0 0 \t Output: ", layer2[0])
print("Input: 1 0 \t Output: ", layer2[1])
print("Input: 0 1 \t Output: ", layer2[2])
print("Input: 1 1 \t Output: ", layer2[3])
</code>```

答:
This is due to the fact that you have not considered any bias for the neurons.
You have only used weights to try and fit the XOR model.

Incase of 2 neurons in the hidden layer, the network under-fits as it can't compensate for the bias.

When you use 3 neurons in the hidden layer, the extra neuron counters the effect caused due to the lack of bias.

This is an example of a network for XOR gate. You'll notice theta (bias) added to the hidden layers. This gives the network an additional parameter to tweak.

Additional resources

Body:
I have a small, 3 layer, neural network with two input neurons, two hidden neurons and one output neuron. I am trying to stick to the below format of using only 2 hidden neurons.

I am trying to show how this can be used to behave as the XOR logic gate, however with just two hidden neurons I get the following poor output after 1,000,000 iterations!

Input: 0 0   Output:  [0.01039096]
Input: 1 0   Output:  [0.93708829]
Input: 0 1   Output:  [0.93599738]
Input: 1 1   Output:  [0.51917667]

If I use three hidden neurons I get a much better output with 100,000 iterations:

Input: 0 0   Output:  [0.01831612]
Input: 1 0   Output:  [0.98558057]
Input: 0 1   Output:  [0.98567602]
Input: 1 1   Output:  [0.02007876]

I am getting a decent output with 3 neurons in the hidden layer but not with two neurons in the hidden layer. Why?

As per a comment below, this repo contains code of high to solve the XOR problem using two hidden neurons.

I can't figure out what I am doing wrong. Any suggestions are appreciated!
Attached is my code:

import numpy as np
import matplotlib
from matplotlib import pyplot as plt

# Sigmoid function
def sigmoid(x, deriv=False):
    if deriv:
        return x * (1 - x)
    return 1 / (1 + np.exp(-x))

alpha = [0.7]

# Input dataset
X = np.array([[0, 0],
              [0, 1],
              [1, 0],
              [1, 1]])

# Output dataset
y = np.array([[0, 1, 1, 0]]).T

# seed random numbers to make calculation deterministic
np.random.seed(1)

# initialise weights randomly with mean 0
syn0 = 2 * np.random.random((2, 3)) - 1  # 1st layer of weights synapse 0 connecting L0 to L1
syn1 = 2 * np.random.random((3, 1)) - 1  # 2nd layer of weights synapse 0 connecting L1 to L2

# Randomize inputs for stochastic gradient descent
data = np.hstack((X, y))    # append Input and output dataset
np.random.shuffle(data)     # shuffle
x, y = np.array_split(data, 2, 1)    # Split along vertical(1) axis

for iter in range(100000):
    for i in range(4):
        # forward prop
        layer0 = x[i]  # Input layer
        layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
        layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

        layer2_error = y[i] - layer2  # Compare how well layer2's guess was with input

        layer2_delta = layer2_error * sigmoid(layer2, deriv=True)  # Error weighted derivative step

        if iter % 10000 == 0:
            print("Error: ", str(np.mean(np.abs(layer2_error))))
            plt.plot(iter, layer2_error, 'ro')

        # Uses "confidence weighted error" from l2 to establish an error for l1
        layer1_error = layer2_delta.dot(syn1.T)

        layer1_delta = layer1_error * sigmoid(layer1, deriv=True)  # Error weighted derivative step

        # Since SGD we need to dot product two 1D arrays. This is how.
        syn1 += (alpha * np.dot(layer1[:, None], layer2_delta[None, :]))  # Update weights
        syn0 += (alpha * np.dot(layer0[:, None], layer1_delta[None, :]))

    # Training was done above, below we re run to test algorithm

    layer0 = X  # Input layer
    layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
    layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

plt.show()
print("output after training: \n")
print("Input: 0 0 \t Output: ", layer2[0])
print("Input: 1 0 \t Output: ", layer2[1])
print("Input: 0 1 \t Output: ", layer2[2])
print("Input: 1 1 \t Output: ", layer2[3])


问:
How to show alert box after successful or not data deletion in mssql
I want to show JavaScript alert after successful or not data deletion in MSSQL. How to do this? I have written this code but it shows only the message=success part alert everytime, even when the deletion dont work becasue of errors like "conflict with reference(foreign_key)" So when i click on this link.

```<code> echo "<a class='activater'  href='ma_QualiOverviewloeschen.php?TestaufstellungID=".$row['TestaufstellungID'] ."&QualiID=".$row['QualiID'] ."' title='Qualitest löschen' data-toggle='tooltip' onclick='confirm_delete()'>   <span class='glyphicon glyphicon-trash'></span></a>";
</code>```

It calls the following php Page, which handle the SQL Part:

```<code>$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");

$sth = $connection->prepare($QualiDelete);
$sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));

                if($sth)
                {
                    header("location: ma_QualiOverview.php?message=success");
                }
                else
                {
                    echo sqlsrv_errors();
                    header("location: ma_QualiOverview.php?message=failed");
                }
                $connection = null;
</code>```

Back to the main page where the link is clicked the following ifelseconsider on messageshould Show me the right alert.

```<code><?php
if($_GET['message']=='success'){
    echo '<script language="javascript">';
    echo 'alert("Erfolgreich gelöscht.");';
    echo '</script>';
} elseif($_GET['message']=='failed'){
    echo '<script language="javascript">';
    echo 'alert("Nicht gelöscht, da Quali "ongoing" ist.");';
    echo '</script>';
}
?>
</code>```

What do i miss?

答:
$sth will never be falsy, you have to check the return value of $sth->execute
Also, you should echo the errors after sending out the header.

Since $sth is always defined, you always get the success result
See the modified code here

```<code>$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");

$sth = $connection->prepare($QualiDelete);//Check the value returned instead of $sth
$result = $sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));

                if($result )
                {
                    header("location: ma_QualiOverview.php?message=success");
                }
                else
                {
                    header("location: ma_QualiOverview.php?message=failed");
                    echo sqlsrv_errors();//Echo must be after header

                }
                $connection = null;
</code>```

Body:
I want to show JavaScript alert after successful or not data deletion in MSSQL. How to do this? I have written this code but it shows only the message=success part alert everytime, even when the deletion dont work becasue of errors like "conflict with reference(foreign_key)" So when i click on this link.

 echo "   ";

It calls the following php Page, which handle the SQL Part:

$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");

$sth = $connection->prepare($QualiDelete);
$sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));

                if($sth)
                {
                    header("location: ma_QualiOverview.php?message=success");
                }
                else
                {
                    echo sqlsrv_errors();
                    header("location: ma_QualiOverview.php?message=failed");
                }
                $connection = null;

Back to the main page where the link is clicked the following ifelseconsider on messageshould Show me the right alert.

<?php
if($_GET['message']=='success'){
    echo '';
} elseif($_GET['message']=='failed'){
    echo '';
}
?>

What do i miss?

Body:
$sth will never be falsy, you have to check the return value of $sth->execute
Also, you should echo the errors after sending out the header.

Since $sth is always defined, you always get the success result
See the modified code here

$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");

$sth = $connection->prepare($QualiDelete);//Check the value returned instead of $sth
$result = $sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));

                if($result )
                {
                    header("location: ma_QualiOverview.php?message=success");
                }
                else
                {
                    header("location: ma_QualiOverview.php?message=failed");
                    echo sqlsrv_errors();//Echo must be after header

                }
                $connection = null;