问:
Pandas: Calculating value of difference between current column value and the closest column value depending if it meets criteria at a different column
This question is an extension of this one: Pandas: Calculating value of difference between current column value and next column value depending if it meets criteria at a different column

Initially I wanted to know the difference between each position and the next position that has the opposite value in the foobar column.

Here is a dataframe:

```<code>pd.DataFrame.from_items([('A', [10, 'foo']), ('B', [440, 'foo']), ('C', [790, 'bar']), ('D', [800, 'bar']), ('E', [7000, 'foo']), ('F', [14000, 'bar']), ('G', [27000, 'bar'])], orient='index', columns=['position', 'foobar'])
</code>```

Which looks like this:

```<code>    position foobar
A   10       foo
B   440      foo
C   790      bar
D   800      bar
E   7000     foo
F   14000    bar
G   27000    bar
</code>```

Jezrael provided an excellent answer to finding the difference between each position and the next position that has the opposite value in the foobar column, producing the output:

```<code>    position foobar length
A   10       foo     780
B   440      foo     350
C   790      bar     6210
D   800      bar     6200
E   7000     foo     7000
F   14000    bar     NaN
G   27000    bar     NaN
</code>```

However what I would now like to do is look both forward and backwards. So  foo and should look for the bar which is the nearest based on position, rather than just the nearest looking forward (down the column). So the output should actually look like:

```<code>    position foobar length
A   10       foo     780
B   440      foo     350
C   790      bar     350
D   800      bar     360
E   7000     foo     6200
F   14000    bar     7000
G   27000    bar     20000
</code>```

As you can see several of the lengths are now changed as we are looking both up and down the foobar column. I confess to having no idea how to go about doing this.

答:
One way would be to apply the previous answer to the reverse-ordered dataframe and then combine the results.</p>

```<code># do solution from previous answer
print(df)

    position    foobar  difference
A   10          foo     780.0
B   440         foo     350.0
C   790         bar     6210.0
D   800         bar     6200.0
E   7000        foo     7000.0
F   14000       bar     NaN
G   27000       bar     NaN

# do the same thing on the reverse sorted df
df2 = df.sort_values(by=['position'], ascending=False)
a2 = df2['foobar'].ne(df2['foobar'].shift()).cumsum()
b2 = df2.groupby(a2)['position'].first()
df2['difference'] = a2.add(1).map(b2) - df2['position']
df2['difference'] *= -1
df2 = df2.sort_values(by='position')

print(df2)

   position foobar  difference
A        10    foo         NaN
B       440    foo         NaN
C       790    bar       350.0
D       800    bar       360.0
E      7000    foo      6200.0
F     14000    bar      7000.0
G     27000    bar     20000.0

# combine the two results
df['difference'] = pd.concat([df['difference'], df2['difference']], axis=1).min(1)

print(df)

   position foobar  difference
A        10    foo       780.0
B       440    foo       350.0
C       790    bar       350.0
D       800    bar       360.0
E      7000    foo      6200.0
F     14000    bar      7000.0
G     27000    bar     20000.0
</code>```

Body:
This question is an extension of this one: Pandas: Calculating value of difference between current column value and next column value depending if it meets criteria at a different column

Initially I wanted to know the difference between each position and the next position that has the opposite value in the foobar column.

Here is a dataframe:

pd.DataFrame.from_items([('A', [10, 'foo']), ('B', [440, 'foo']), ('C', [790, 'bar']), ('D', [800, 'bar']), ('E', [7000, 'foo']), ('F', [14000, 'bar']), ('G', [27000, 'bar'])], orient='index', columns=['position', 'foobar'])

Which looks like this:

    position foobar
A   10       foo
B   440      foo
C   790      bar
D   800      bar
E   7000     foo
F   14000    bar
G   27000    bar

Jezrael provided an excellent answer to finding the difference between each position and the next position that has the opposite value in the foobar column, producing the output:

    position foobar length
A   10       foo     780
B   440      foo     350
C   790      bar     6210
D   800      bar     6200
E   7000     foo     7000
F   14000    bar     NaN
G   27000    bar     NaN

However what I would now like to do is look both forward and backwards. So  foo and should look for the bar which is the nearest based on position, rather than just the nearest looking forward (down the column). So the output should actually look like:

    position foobar length
A   10       foo     780
B   440      foo     350
C   790      bar     350
D   800      bar     360
E   7000     foo     6200
F   14000    bar     7000
G   27000    bar     20000

As you can see several of the lengths are now changed as we are looking both up and down the foobar column. I confess to having no idea how to go about doing this.

Body:
One way would be to apply the previous answer to the reverse-ordered dataframe and then combine the results.

# do solution from previous answer
print(df)

    position    foobar  difference
A   10          foo     780.0
B   440         foo     350.0
C   790         bar     6210.0
D   800         bar     6200.0
E   7000        foo     7000.0
F   14000       bar     NaN
G   27000       bar     NaN

# do the same thing on the reverse sorted df
df2 = df.sort_values(by=['position'], ascending=False)
a2 = df2['foobar'].ne(df2['foobar'].shift()).cumsum()
b2 = df2.groupby(a2)['position'].first()
df2['difference'] = a2.add(1).map(b2) - df2['position']
df2['difference'] *= -1
df2 = df2.sort_values(by='position')

print(df2)

   position foobar  difference
A        10    foo         NaN
B       440    foo         NaN
C       790    bar       350.0
D       800    bar       360.0
E      7000    foo      6200.0
F     14000    bar      7000.0
G     27000    bar     20000.0

# combine the two results
df['difference'] = pd.concat([df['difference'], df2['difference']], axis=1).min(1)

print(df)

   position foobar  difference
A        10    foo       780.0
B       440    foo       350.0
C       790    bar       350.0
D       800    bar       360.0
E      7000    foo      6200.0
F     14000    bar      7000.0
G     27000    bar     20000.0


来源: stackexchange

问:
how to copy all the code of a URL with python
I want to copy all the code of an URL (http://modelseed.org/biochem/reactions/rxn00001) using Python 3.6, but I can only copy part of the code, and I don't know why.

So far, I tried with "requests" module

```<code>import requests
page = requests.get("http://modelseed.org/biochem/reactions/rxn00001")
print(page.content)
</code>```

and "urllib"

```<code>import urllib.request
site = urllib.request.urlopen("http://modelseed.org/biochem/reactions/rxn00001")
print(site.read())
</code>```

The part of the code with information of the "Reaction Details", like "Name", "ID" and "Abbreviation" are missing, but they are visible if I inspect the code on the  developer bar of Chrome.

The code I'm able to download using the two codes above is:

```<code><!DOCTYPE html>
<html lang="en" ng-app="ModelSEED">
 <head>
  <base href="/"/>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
  <meta content="IE=edge" http-equiv="X-UA-Compatible"/>
  <meta content="initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
   <meta content="The ModelSEED is a resource for the reconstruction, exploration, comparison, and analysis of metabolic models." name="description"/>
   <link href="/img/ModelSEED-favicon.png?v=2.0" rel="shortcut icon"/>
   <meta content="nconrad" name="author"/>
   <title>
    ModelSEED
   </title>
   <link href="components/angular-material/angular-material.css" rel="stylesheet"/>
   <link href="components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
   <!-- to be removed -->
   <link href="components/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
   <link href="icomoon/style.css" rel="stylesheet"/>
   <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
   <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"/>
   <link href="build/style.css" rel="stylesheet"/>
   <!--<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>-->
   <script src="build/site.js">
   </script>
   <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
   <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
   <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </meta>
 </head>
 <body>
  <div style="height: 100%;" ui-view="">
  </div>
  <script>
   (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-67412611-1', 'auto');
      ga('send', 'pageview');
  </script>
 </body>
</html>
</code>```

Anyone has any hint why the code between
 and  (just after  and before < script >) is not downloaded?

Thank you.

答:
It's being inserted by a javascript script, therefore, either requests nor urllib would find it, you would need to use a browser for this, you should try with selenium or PhantomJS

something like:

```<code>from selenium import webdriver

driver = webdriver.Chrome('./chromedriver')
driver.get(url)
driver.page_source
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to copy all the code of an URL (http://modelseed.org/biochem/reactions/rxn00001) using Python 3.6, but I can only copy part of the code, and I don't know why.

So far, I tried with "requests" module

import requests
page = requests.get("http://modelseed.org/biochem/reactions/rxn00001")
print(page.content)

and "urllib"

import urllib.request
site = urllib.request.urlopen("http://modelseed.org/biochem/reactions/rxn00001")
print(site.read())

The part of the code with information of the "Reaction Details", like "Name", "ID" and "Abbreviation" are missing, but they are visible if I inspect the code on the  developer bar of Chrome.

The code I'm able to download using the two codes above is:

<!DOCTYPE html>

  <base href="/"/>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
  <meta content="IE=edge" http-equiv="X-UA-Compatible"/>
  <meta content="initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
   <meta content="The ModelSEED is a resource for the reconstruction, exploration, comparison, and analysis of metabolic models." name="description"/>
   <link href="/img/ModelSEED-favicon.png?v=2.0" rel="shortcut icon"/>
   <meta content="nconrad" name="author"/>
   <title>
    ModelSEED
   </title>
   <link href="components/angular-material/angular-material.css" rel="stylesheet"/>
   <link href="components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>

   <link href="components/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
   <link href="icomoon/style.css" rel="stylesheet"/>
   <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
   <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"/>
   <link href="build/style.css" rel="stylesheet"/>

  </meta>

Anyone has any hint why the code between
 and  (just after  and before < script >) is not downloaded?

Thank you.

Body:
It's being inserted by a javascript script, therefore, either requests nor urllib would find it, you would need to use a browser for this, you should try with selenium or PhantomJS

something like:

from selenium import webdriver

driver = webdriver.Chrome('./chromedriver')
driver.get(url)
driver.page_source


问:
Read unknown data from yml configuration file
I'm writing a bukkit plugin which should read data from a yml configuration file made by users like shown in the example below.
I've searched for that before with no result, in fact I don't really know what I should search for.

Example config:

```<code>maps:
  01:
    name: world
    displayname: Plains
    icon: 2
    size: 1000
    info:
    - 'Some information'
    - 'Another information string'
  02:
    name: world_nether
    displayname: Nether
    icon: 87
    size: 500
    info:
    - 'Information'
    - 'More information'
    - 'As many lines as needed...'
</code>```

The number of maps is unknown, the user can create as many as he wants, so there are not only 01 and 02, the content (name, icon, info,...) is always the same.

How can I read out the number of maps (01, 02,...) and what is a good way to save the different types of content (strings, integers, lists) in Java?

答:
You can use an Argument /[yourcommand] [Number] [...].
If you don´t want a command you can save a Line like: Worlds: 1 When you create a new arena you can get the Number from Worlds and override it.

Body:
I'm writing a bukkit plugin which should read data from a yml configuration file made by users like shown in the example below.
I've searched for that before with no result, in fact I don't really know what I should search for.

Example config:

maps:
  01:
    name: world
    displayname: Plains
    icon: 2
    size: 1000
    info:
    - 'Some information'
    - 'Another information string'
  02:
    name: world_nether
    displayname: Nether
    icon: 87
    size: 500
    info:
    - 'Information'
    - 'More information'
    - 'As many lines as needed...'

The number of maps is unknown, the user can create as many as he wants, so there are not only 01 and 02, the content (name, icon, info,...) is always the same.

How can I read out the number of maps (01, 02,...) and what is a good way to save the different types of content (strings, integers, lists) in Java?


问:
Why nullable int (int?) doesn't increase the value via "+=" if the value is NULL?
I have a page counter type of int?:

```<code>spot.ViewCount += 1;
</code>```

It works ONLY if the value of ViewCount property is NOT NULL (any int).

Why the compiler do so?

I would be grateful for any solutions.

答:
You can use these extension methods:

```<code>public static int? Add(this int? num1, int? num2)
{
    return num1.GetValueOrDefault() + num2.GetValueOrDefault();
}
</code>```

Usage:

```<code>spot.ViewCount = spot.ViewCount.Add(1);
</code>```

Or even:

```<code>int? num2 = 2; // or null
spot.ViewCount = spot.ViewCount.Add(num2);
</code>```

Body:
I have a page counter type of int?:

spot.ViewCount += 1;

It works ONLY if the value of ViewCount property is NOT NULL (any int).

Why the compiler do so?

I would be grateful for any solutions.

Body:
You can use these extension methods:

public static int? Add(this int? num1, int? num2)
{
    return num1.GetValueOrDefault() + num2.GetValueOrDefault();
}

Usage:

spot.ViewCount = spot.ViewCount.Add(1);

Or even:

int? num2 = 2; // or null
spot.ViewCount = spot.ViewCount.Add(num2);


问:
Best Scheduler for .NET Application?
I'm trying to determine what would be a good Process Scheduler for .NET applications, so far I have only looked into Quartz.NET. Are there any viable alternatives and what are the tradeoffs when using them?</p>

答: You can consider Windows Task Scheduler, there are couple of limitations such as Windows XP Home Edition but other than it should do fine for basic tasks.</p>

ContentLicense: CC BY-SA 2.5

Title: Best Scheduler for .NET Application?


问:
How to calculate dimensions of a 2d array?
I am looking for the dimensions of a 2d array. Not the fixed values assigned to the array, but the values containing integers. Example:

```<code>int a[][] = new int[4][5];
a[1][1] = 1;
a[1][2] = 2;
a[1][3] = -2;
a[1][4] = 0;
a[2][1] = -3;
a[2][2] = 4;
a[2][3] = 7;
a[2][4] = 2;
a[3][1] = 6;
a[3][2] = 0;
a[3][3] = 3;
a[3][4] = 1;
</code>```

Only 3 variables are used out of 4, and 4 variables used out of 5. How can you tell what is actually there versus what is assigned to be there?

```<code>array.length;
array[0].length;
</code>```

The previous code will only give you the fixed variable assigned to the array. But what if your not using all the variables? In other words I am looking for an output of 3 for columns and 4 for rows.

答:
```<code>    // using Integer instead of int, which is a nullable object
    Integer a[][] =  new Integer[4][5];
    int cnt1 = 0;
    for(int i = 0; i < a.length; i++) {
        for(int j = 0; j < a[i].length; j++) {
            if(a[i][j] != null) {
                cnt1++;
            }
        }
    }
    System.out.println(cnt1 + " array indices are non-null.");

    // using int
    int b[][] =  new int[4][5];
    for(int i = 0; i < b.length; i++) {
        for(int j = 0; j < b[i].length; j++) {
            b[i][j] = -9999;
        }
    }

    int cnt2 = 0;
    for(int i = 0; i < b.length; i++) {
        for(int j = 0; j < b[i].length; j++) {
            // pick a value that will never be assigned
            if(b[i][j] != -9999) {
                cnt2++;
            }
        }
    }
    System.out.println(cnt2 + " array indices are not -9999.");
</code>```

Body:
I am looking for the dimensions of a 2d array. Not the fixed values assigned to the array, but the values containing integers. Example:

int a[][] = new int[4][5];
a[1][1] = 1;
a[1][2] = 2;
a[1][3] = -2;
a[1][4] = 0;
a[2][1] = -3;
a[2][2] = 4;
a[2][3] = 7;
a[2][4] = 2;
a[3][1] = 6;
a[3][2] = 0;
a[3][3] = 3;
a[3][4] = 1;

Only 3 variables are used out of 4, and 4 variables used out of 5. How can you tell what is actually there versus what is assigned to be there?

array.length;
array[0].length;

The previous code will only give you the fixed variable assigned to the array. But what if your not using all the variables? In other words I am looking for an output of 3 for columns and 4 for rows.


问:
Compile file with two separate libraries in Cython
I wrote a library in Cython that has two different "modes":

If rendering, I compile using GLFW.

If not rendering, I compile using EGL, which is faster, but I have not figured out how to render with it.

What is the recommended way to handle this situation?

Right now, I have the following directory structure:

```<code>mujoco
├── __init__.py
├── simEgl.pyx
├── simGlfw.pyx
├── sim.pxd
└── sim.pyx
</code>```

simEgl.pyx contains EGL code and simGlfw.pyx contains GLFW code. setup.py uses an environment variable to choose one or the other for the build.

This works ok, except that I need to recompile the code every time I want to switch between modes. There must be a better way.

Update

I agree that the best approach is to simultaneously compile two different libraries and use a toggle to choose which one to import. I already do have a base class in sim.pyx with shared functionality. However this base class must itself be compiled with the separate libraries. Specifically, sim.pyx depends on libmujoco.so which depends on either GLFW or EGL.

Here is my exhaustive search of possible approaches:

If I do not compile an extension for sim.pyx, I get ImportError: No module named 'mujoco.sim'

If I compile an extension for sim.pyx without including graphics libraries in the extension, I get ImportError: /home/ethanbro/.mujoco/mjpro150/bin/libmujoco150.so: undefined symbol: __glewBlitFramebuffer

If I compile an extension for sim.pyx and choose one set of graphics libraries (GLFW), then when I try to use the other set of graphics libraries (EGL) this does not work either unsurprisingly:
ERROR: GLEW initalization error: Missing GL version

If I compile two different versions of the sim.pyx library, one with one set of libraries, one with the other, I get: TypeError: unorderable types: dict() < dict() which is not a very helpful error message, but appears to result from trying to share a source file between two different extensions.

Something like option 4 should be possible. In fact, if I were working in raw C, I would simply build two shared objects side by side using the different libraries. Any advice on how to get around this Cython limitation would be very welcome.

答:
(This answer is just a summary of the comments with a bit more explanation.)

My initial suggestion was to create two extension modules defining a common interface. That way you pick which to import in Python but be able to use them in the same way once imported:

```<code>if rendering:
   import simGlfw as s
else:
   import simEgl as s
s.do_something() # doesn't matter which you imported
</code>```

It appears from the comments that the two modules also share a large chunk of their code and its really just the library that they're linked with that defines how they behave. Trying to re-use the same sources with

```<code>Extension(name='sim1', sources=["sim.pyx",...)
Extension(name='sim2', sources=["sim.pyx",...)
</code>```

fails. This is because Cython assumes that the module name will be the same as the filename, and so creates a function PyInit_sim (on Python 3 - Python 2 is named slightly differently but the idea is the same). However, when you import sim1.so it looks for the function PyInit_sim1, fails to find it, and gives an error.

An easy way round it is to put the common code in "sim.pxi" and use Cython's largely obsolete include mechanism to textually include that code in sim1.pyx and sim2.pyx

```<code>include "sim.pxi"
</code>```

Although include is generally no longer recommended and cimport is preferred since it provides more "Python-like" behaviour, include is a simple solution to this particular problem.

Body:
I wrote a library in Cython that has two different "modes":

If rendering, I compile using GLFW.

If not rendering, I compile using EGL, which is faster, but I have not figured out how to render with it.

What is the recommended way to handle this situation?

Right now, I have the following directory structure:

mujoco
├── __init__.py
├── simEgl.pyx
├── simGlfw.pyx
├── sim.pxd
└── sim.pyx

simEgl.pyx contains EGL code and simGlfw.pyx contains GLFW code. setup.py uses an environment variable to choose one or the other for the build.

This works ok, except that I need to recompile the code every time I want to switch between modes. There must be a better way.

Update

I agree that the best approach is to simultaneously compile two different libraries and use a toggle to choose which one to import. I already do have a base class in sim.pyx with shared functionality. However this base class must itself be compiled with the separate libraries. Specifically, sim.pyx depends on libmujoco.so which depends on either GLFW or EGL.

Here is my exhaustive search of possible approaches:

If I do not compile an extension for sim.pyx, I get ImportError: No module named 'mujoco.sim'

If I compile an extension for sim.pyx without including graphics libraries in the extension, I get ImportError: /home/ethanbro/.mujoco/mjpro150/bin/libmujoco150.so: undefined symbol: __glewBlitFramebuffer

If I compile an extension for sim.pyx and choose one set of graphics libraries (GLFW), then when I try to use the other set of graphics libraries (EGL) this does not work either unsurprisingly:
ERROR: GLEW initalization error: Missing GL version

If I compile two different versions of the sim.pyx library, one with one set of libraries, one with the other, I get: TypeError: unorderable types: dict() < dict() which is not a very helpful error message, but appears to result from trying to share a source file between two different extensions.

Something like option 4 should be possible. In fact, if I were working in raw C, I would simply build two shared objects side by side using the different libraries. Any advice on how to get around this Cython limitation would be very welcome.

Body:
(This answer is just a summary of the comments with a bit more explanation.)

My initial suggestion was to create two extension modules defining a common interface. That way you pick which to import in Python but be able to use them in the same way once imported:

if rendering:
   import simGlfw as s
else:
   import simEgl as s
s.do_something() # doesn't matter which you imported

It appears from the comments that the two modules also share a large chunk of their code and its really just the library that they're linked with that defines how they behave. Trying to re-use the same sources with

Extension(name='sim1', sources=["sim.pyx",...)
Extension(name='sim2', sources=["sim.pyx",...)

fails. This is because Cython assumes that the module name will be the same as the filename, and so creates a function PyInit_sim (on Python 3 - Python 2 is named slightly differently but the idea is the same). However, when you import sim1.so it looks for the function PyInit_sim1, fails to find it, and gives an error.

An easy way round it is to put the common code in "sim.pxi" and use Cython's largely obsolete include mechanism to textually include that code in sim1.pyx and sim2.pyx

include "sim.pxi"

Although include is generally no longer recommended and cimport is preferred since it provides more "Python-like" behaviour, include is a simple solution to this particular problem.


问:
Python requests library how to pass Authorization header with single token
I have a request URI and a token. If I use:

```<code>curl -s "<MY_URI>" -H "Authorization: TOK:<MY_TOKEN>"
</code>```

etc., I get a 200 and view the corresponding JSON data.
So, I installed requests and when I attempt to access this resource I get a 403 probably because I do not know the correct syntax to pass that token. Can anyone help me figure it out?
This is what I have:

```<code>import sys,socket
import requests

r = requests.get('<MY_URI>','<MY_TOKEN>')
r. status_code
</code>```

I already tried:

```<code>r = requests.get('<MY_URI>',auth=('<MY_TOKEN>'))
r = requests.get('<MY_URI>',auth=('TOK','<MY_TOKEN>'))
r = requests.get('<MY_URI>',headers=('Authorization: TOK:<MY_TOKEN>'))
</code>```

But none of these work.

答:
This worked for me:</p>

```<code>access_token = #yourAccessTokenHere#

result = requests.post(url,
      headers={'Content-Type':'application/json',
               'Authorization': 'Bearer {}'.format(access_token)})
</code>```

Body:
I have a request URI and a token. If I use:

curl -s "<MY_URI>" -H "Authorization: TOK:<MY_TOKEN>"

etc., I get a 200 and view the corresponding JSON data.
So, I installed requests and when I attempt to access this resource I get a 403 probably because I do not know the correct syntax to pass that token. Can anyone help me figure it out?
This is what I have:

import sys,socket
import requests

r = requests.get('<MY_URI>','<MY_TOKEN>')
r. status_code

I already tried:

r = requests.get('<MY_URI>',auth=('<MY_TOKEN>'))
r = requests.get('<MY_URI>',auth=('TOK','<MY_TOKEN>'))
r = requests.get('<MY_URI>',headers=('Authorization: TOK:<MY_TOKEN>'))

But none of these work.

Body:
This worked for me:

access_token = #yourAccessTokenHere#

result = requests.post(url,
      headers={'Content-Type':'application/json',
               'Authorization': 'Bearer {}'.format(access_token)})

ContentLicense: CC BY-SA 4.0


问:
Where in the NetBeans 6.9.1 source code is the code for scanning Java files and finding all the methods, variables, imports etc
I'm looking for a sample or possibly even code I can use which scans Java files and tells me key pieces of information about each class, which i can then use much like the NetBeans refactoring and go to source features do.</p>

答:
If you are looking for reusing Netbeans code which parses Java file, I don't know.

If you are looking for how to parse a Java file, you can try ANTLR. ANTLR is a parser generator. There exists Java grammar which you can use right away. Once, you generate a Java parser, you can use the parser to parse your Java file. You will have to learn how to use ANTLR.


问:
Difference between Prim's and Dijkstra's algorithms?
What  is the exact difference between Dijkstra's and Prim's algorithms? I know Prim's will give a MST but the tree generated by Dijkstra will also be a MST. Then what is the exact difference?</p>

答:
Dijkstras algorithm is used only to find shortest path.

In Minimum Spanning tree(Prim's or Kruskal's algorithm) you get minimum egdes with minimum edge value.

For example:- Consider a situation where you wan't to create a huge network for which u will be requiring a large number of wires so these counting of wire can be done using Minimum Spanning Tree(Prim's or Kruskal's algorithm) (i.e it will give you minimum number of wires to create huge wired network connection with minimum cost).

Whereas "Dijkstras algorithm" will be used to get the shortest path between two nodes while connecting any nodes with each other.


问:
How do I retrieve a value from a PHP array?
How do I retrieve an integer value from a PHP array so that I can use it in another function to fetch the details based on that integer value(primary key)?

This is what I get when I print the array:

```<code>print_r($myarray);
</code>```

result:

```<code>Array
(
  [0] => Array
   (
     [id] => 21785
     [customer_id] => 12456 //this is my primary key
     [date] => 12-06-2017
   )
)

//I am trying to retrieve the ID using something like the code below:

$cust_id = var_dump($myarray[0]['customer_id']);

 return cust_id;
 or
 myfunc(cust_id);
</code>```

My problem is that it's not returning the customer_id integer into $cust_id.

答:
The var_dump function doesn't return anything.  It prints to the output, but that doesn't matter to the variable.

What you want is to simply access the value directly and store it in the variable.  No function required:

```<code>$cust_id = $myarray[0]['customer_id'];
</code>```

Body:
How do I retrieve an integer value from a PHP array so that I can use it in another function to fetch the details based on that integer value(primary key)?

This is what I get when I print the array:

print_r($myarray);

result:

Array
(
  [0] => Array
   (
     [id] => 21785
     [customer_id] => 12456 //this is my primary key
     [date] => 12-06-2017
   )
)

//I am trying to retrieve the ID using something like the code below:

$cust_id = var_dump($myarray[0]['customer_id']);

 return cust_id;
 or
 myfunc(cust_id);

My problem is that it's not returning the customer_id integer into $cust_id.

Body:
The var_dump function doesn't return anything.  It prints to the output, but that doesn't matter to the variable.

What you want is to simply access the value directly and store it in the variable.  No function required:

$cust_id = $myarray[0]['customer_id'];


答:
You can't do it dynamically. Once you've initiated your matrix like that (new int[4][5]) you have and matrix of 0.

You must initiate the matrix ant set an invalid value to all posistions, something like -1 or whatever you wan't and iterate over it to discover the result

Title: How to calculate dimensions of a 2d array?


问:
How to break line in JavaScript?
Please let me know how to break line in JavaScript.

```<code><input type='submit' name='Submit' value='Submit'
onClick="parent.location='mailto:er.saurav123@gmail.com?subject=Thanks for writing to me &body=I will get back to you soon. Thanks and Regards Saurav Kumar'">
</code>```

I want a break line in Subject. The output I need is:

```<code>I will get back to you soon
Thanks and Regards
Saurav Kumar
</code>```

答:
Add %0D%0A to any place you want to encode a line break on the URL.

%0D is a carriage return character

%0A is a line break character

This is the new line sequence on windows machines, though not the same on linux and macs, should work in both.

If you want a linebreak in actual javascript, use the \n escape sequence.

```<code>onClick="parent.location='mailto:er.saurav123@gmail.com?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'
</code>```

Title: How to break line in JavaScript?

Body:
Please let me know how to break line in JavaScript.

<input type='submit' name='Submit' value='Submit'
onClick="parent.location='mailto:er.saurav123@gmail.com?subject=Thanks for writing to me &body=I will get back to you soon. Thanks and Regards Saurav Kumar'">

I want a break line in Subject. The output I need is:

I will get back to you soon
Thanks and Regards
Saurav Kumar

Body:
Add %0D%0A to any place you want to encode a line break on the URL.

%0D is a carriage return character

%0A is a line break character

This is the new line sequence on windows machines, though not the same on linux and macs, should work in both.

If you want a linebreak in actual javascript, use the \n escape sequence.

onClick="parent.location='mailto:er.saurav123@gmail.com?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'


问:
Layout doesn't show first item of View
I download pictures and names from a parse database and create a cardstack. Every view has a name and a picture, but I don't see the first picture of my view (position 0) until I use my swipe left or swipe right button (then I see it swiping away), the nameAgeLabel works fine.

Do you have any ideas how I can fix it? Nothing should overlap it, I checked again and again, but maybe i overlooked something special regarding position 0 in my adapter. The data should also be fine, otherwise the nameAgeLabel wouldn't work.

I can delete some of the Layouts in my content.xml, but that won't help either.

Edit: I now get an information in my log ONLY for my first view:

```<code>W/View: requestLayout()
improperly called by android.support.v7.widget.AppCompatTextView....app:id/nameAgeLabel} during
layout: running second layout pass
</code>```

SwipeDeckAdapter:

```<code>public class SwipeDeckAdapter extends BaseAdapter {

private LinkedList<String> data;
private Context context;
private LinkedList<String> userIds;
private Hashtable<String,String> userNames;
private Hashtable<String,String> userHashtags;
private Hashtable<String,Bitmap> userImages;
private Hashtable<String,ArrayList<String>> userAccepted;
private TextView nameAgeLabel;

public SwipeDeckAdapter(LinkedList<String> data, Context context, LinkedList<String> userIds, Hashtable<String,String> userNames, Hashtable<String,String> userHashtags, Hashtable<String,Bitmap> userImages, Hashtable<String,ArrayList<String>> userAccepted, TextView nameAgeLabel) {
    this.data = data;
    this.context = context;
    this.userIds = userIds;
    this.userNames = userNames;
    this.userHashtags = userHashtags;
    this.userImages = userImages;
    this.userAccepted = userAccepted;
    this.nameAgeLabel = nameAgeLabel;

}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return data.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View View, ViewGroup parent) {

    Log.d("position:", String.valueOf(position));
    Log.d("laenge user id", String.valueOf(userIds.size()));

    final String currentUserId = userIds.get(position);

    View v = View;
    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.content_single_mode_vc, parent, false);
    }

    ImageView imageView = (ImageView) v.findViewById(R.id.offer_image);
    Bitmap image;
    try {
        image = userImages.get(currentUserId);
        imageView.setImageBitmap(image);

    } catch (IOError error) {
        error.printStackTrace();
    }

    Log.d("info", userNames.toString());
    Log.d("info", userNames.get(currentUserId));
    nameAgeLabel.setText(userNames.get(userIds.get(position)));
    return v;
}
</code>```

I invoke it in another class like this:

```<code>//next line in my onCreate
cardStack = (SwipeDeck) findViewById(R.id.swipe_deck);

//back in my method
adapter= new SwipeDeckAdapter(data, getApplicationContext(), userIds, userNames, userHashtags, userImages, userAccepted,nameAgeLabel);
                            // e.printStackTrace();
                            if(cardStack != null){
                                cardStack.setAdapter(adapter);
                            }
</code>```

content_single_mode_vc.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="8dp"
card_view:cardElevation="8dp"
card_view:cardUseCompatPadding="true"
android:layout_margin="8dp"
android:gravity="center_horizontal"
android:padding="25dp">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/offer_image"
        android:layout_width="match_parent"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:layout_height="200dp" />

</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</code>```

activity_single_mode_vc.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<com.daprlabs.aaron.swipedeck.layouts.SwipeFrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipedeck="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/swipeLayout"
android:orientation="vertical"
android:background="@color/white">

<com.daprlabs.aaron.swipedeck.SwipeDeck
    android:id="@+id/swipe_deck"
    android:layout_width="match_parent"
    android:layout_height="700dp"
    android:padding="20dp"
    android:layout_marginTop="60dp"
    swipedeck:max_visible="1"
    swipedeck:card_spacing="15dp"
    swipedeck:swipe_enabled="true"
    swipedeck:render_above="true">

</com.daprlabs.aaron.swipedeck.SwipeDeck>

<Button
    android:id="@+id/close"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginBottom="50dp"
    android:layout_marginLeft="20dp"
    android:layout_gravity="bottom"
    android:elevation="1dp"
    android:background="@drawable/close"
    android:backgroundTint="@color/light" />

<Button
    android:id="@+id/check"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginBottom="50dp"
    android:layout_marginRight="20dp"
    android:layout_gravity="bottom|right"
    android:background="@drawable/check"
    android:backgroundTint="@color/light" />

<TextView
    android:layout_width="wrap_content"
    android:padding="20dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="350dp"
    android:id="@+id/nameAgeLabel"
    android:background="@color/separator"
   />
 </com.daprlabs.aaron.swipedeck.layouts.SwipeFrameLayout>
</code>```

答:
You are using swipedeck:max_visible="1" in the layout of the DeckSwipe that's why it is a bug in the library. Try to increase the max_visible to 2 or 3 and it will work fine for you.

If you need to show only one card you can modify the SwipeDeck.java in the library and replace the setAdapter function as below:

```<code>public void setAdapter(final Adapter adapter)
{
        if (adapter == null)
            return;

        if (this.mAdapter != null) {
            this.mAdapter.unregisterDataSetObserver(observer);
        }
        mHasStableIds = adapter.hasStableIds();
        mAdapter = adapter;
        .
        .
        .
        adapter.registerDataSetObserver(observer);
        if (deck.size() > 0)
            addNextView();
        removeAllViewsInLayout();
        requestLayout();
    }
</code>```

Title: Layout doesn't show first item of View

Body:
I download pictures and names from a parse database and create a cardstack. Every view has a name and a picture, but I don't see the first picture of my view (position 0) until I use my swipe left or swipe right button (then I see it swiping away), the nameAgeLabel works fine.

Do you have any ideas how I can fix it? Nothing should overlap it, I checked again and again, but maybe i overlooked something special regarding position 0 in my adapter. The data should also be fine, otherwise the nameAgeLabel wouldn't work.

I can delete some of the Layouts in my content.xml, but that won't help either.

Edit: I now get an information in my log ONLY for my first view:

W/View: requestLayout()
improperly called by android.support.v7.widget.AppCompatTextView....app:id/nameAgeLabel} during
layout: running second layout pass

SwipeDeckAdapter:

public class SwipeDeckAdapter extends BaseAdapter {

private LinkedList<String> data;
private Context context;
private LinkedList<String> userIds;
private Hashtable<String,String> userNames;
private Hashtable<String,String> userHashtags;
private Hashtable<String,Bitmap> userImages;
private Hashtable<String,ArrayList<String>> userAccepted;
private TextView nameAgeLabel;

public SwipeDeckAdapter(LinkedList<String> data, Context context, LinkedList<String> userIds, Hashtable<String,String> userNames, Hashtable<String,String> userHashtags, Hashtable<String,Bitmap> userImages, Hashtable<String,ArrayList<String>> userAccepted, TextView nameAgeLabel) {
    this.data = data;
    this.context = context;
    this.userIds = userIds;
    this.userNames = userNames;
    this.userHashtags = userHashtags;
    this.userImages = userImages;
    this.userAccepted = userAccepted;
    this.nameAgeLabel = nameAgeLabel;

}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return data.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View View, ViewGroup parent) {

    Log.d("position:", String.valueOf(position));
    Log.d("laenge user id", String.valueOf(userIds.size()));

    final String currentUserId = userIds.get(position);

    View v = View;
    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.content_single_mode_vc, parent, false);
    }

    ImageView imageView = (ImageView) v.findViewById(R.id.offer_image);
    Bitmap image;
    try {
        image = userImages.get(currentUserId);
        imageView.setImageBitmap(image);

    } catch (IOError error) {
        error.printStackTrace();
    }

    Log.d("info", userNames.toString());
    Log.d("info", userNames.get(currentUserId));
    nameAgeLabel.setText(userNames.get(userIds.get(position)));
    return v;
}

I invoke it in another class like this:

//next line in my onCreate
cardStack = (SwipeDeck) findViewById(R.id.swipe_deck);

//back in my method
adapter= new SwipeDeckAdapter(data, getApplicationContext(), userIds, userNames, userHashtags, userImages, userAccepted,nameAgeLabel);
                            // e.printStackTrace();
                            if(cardStack != null){
                                cardStack.setAdapter(adapter);
                            }

content_single_mode_vc.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="8dp"
card_view:cardElevation="8dp"
card_view:cardUseCompatPadding="true"
android:layout_margin="8dp"
android:gravity="center_horizontal"
android:padding="25dp">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/offer_image"
        android:layout_width="match_parent"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:layout_height="200dp" />

</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>

activity_single_mode_vc.xml

<?xml version="1.0" encoding="utf-8"?>
<com.daprlabs.aaron.swipedeck.layouts.SwipeFrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipedeck="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/swipeLayout"
android:orientation="vertical"
android:background="@color/white">

<com.daprlabs.aaron.swipedeck.SwipeDeck
    android:id="@+id/swipe_deck"
    android:layout_width="match_parent"
    android:layout_height="700dp"
    android:padding="20dp"
    android:layout_marginTop="60dp"
    swipedeck:max_visible="1"
    swipedeck:card_spacing="15dp"
    swipedeck:swipe_enabled="true"
    swipedeck:render_above="true">

</com.daprlabs.aaron.swipedeck.SwipeDeck>

<Button
    android:id="@+id/close"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginBottom="50dp"
    android:layout_marginLeft="20dp"
    android:layout_gravity="bottom"
    android:elevation="1dp"
    android:background="@drawable/close"
    android:backgroundTint="@color/light" />

<Button
    android:id="@+id/check"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginBottom="50dp"
    android:layout_marginRight="20dp"
    android:layout_gravity="bottom|right"
    android:background="@drawable/check"
    android:backgroundTint="@color/light" />

<TextView
    android:layout_width="wrap_content"
    android:padding="20dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="350dp"
    android:id="@+id/nameAgeLabel"
    android:background="@color/separator"
   />
 </com.daprlabs.aaron.swipedeck.layouts.SwipeFrameLayout>

Body:
You are using swipedeck:max_visible="1" in the layout of the DeckSwipe that's why it is a bug in the library. Try to increase the max_visible to 2 or 3 and it will work fine for you.

If you need to show only one card you can modify the SwipeDeck.java in the library and replace the setAdapter function as below:

public void setAdapter(final Adapter adapter)
{
        if (adapter == null)
            return;

        if (this.mAdapter != null) {
            this.mAdapter.unregisterDataSetObserver(observer);
        }
        mHasStableIds = adapter.hasStableIds();
        mAdapter = adapter;
        .
        .
        .
        adapter.registerDataSetObserver(observer);
        if (deck.size() > 0)
            addNextView();
        removeAllViewsInLayout();
        requestLayout();
    }


问:
Convert String to Double - JAVA
```<code>private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        //9

        txtTot.setText(jComboBox1.getSelectedItem().toString());
        tot= Double.parseDouble(txtTot.getText());
        CMB= (Double)jComboBox1.getSelectedItem();
        Total2=tot+CMB;
        txtTot.setText(Double.toString(Total2));

    }
</code>```

From the ComboBox I'm setting the jtextfield and the second line I'm taking the string from the textfield and trying to convert it into a double.

Error below:

```<code>Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at test.Test.jComboBox1ActionPerformed(Test.java:392)
    at test.Test.access$600(Test.java:18)
    at test.Test$7.actionPerformed(Test.java:134)
    at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
    at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
    at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)
</code>```

答:
To me it seems like you are selecting a value from a combobox then trying to add them together to create a grand total, with the total being updated every time you select a new value from the combobox.

This seems to be working for me, Note I've taken the first line away because it interfered with the existing total.

```<code>tot= Double.parseDouble(txtTot.getText());
CMB = Double.parseDouble((String) jComboBox1.getSelectedItem());
Total2=tot+CMB;
txtTot.setText(Double.toString(Total2));
</code>```

Title: Convert String to Double - JAVA

Body:
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        //9

        txtTot.setText(jComboBox1.getSelectedItem().toString());
        tot= Double.parseDouble(txtTot.getText());
        CMB= (Double)jComboBox1.getSelectedItem();
        Total2=tot+CMB;
        txtTot.setText(Double.toString(Total2));

    }

From the ComboBox I'm setting the jtextfield and the second line I'm taking the string from the textfield and trying to convert it into a double.

Error below:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at test.Test.jComboBox1ActionPerformed(Test.java:392)
    at test.Test.access$600(Test.java:18)
    at test.Test$7.actionPerformed(Test.java:134)
    at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
    at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
    at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)

Body:
To me it seems like you are selecting a value from a combobox then trying to add them together to create a grand total, with the total being updated every time you select a new value from the combobox.

This seems to be working for me, Note I've taken the first line away because it interfered with the existing total.

tot= Double.parseDouble(txtTot.getText());
CMB = Double.parseDouble((String) jComboBox1.getSelectedItem());
Total2=tot+CMB;
txtTot.setText(Double.toString(Total2));


问:
Android Things I2C Driver PioException: I/O error
Hello dear pioneers of Android things!

I am calling for your help as I have been triying for the last couple of months to build an android things driver for the Adafruit SI7021 Themperature and humidity sensor.
Here is the link to the github repository hosting the project.
Connecting and Getting the chip id with readRegByte work fine.
But, I get a PioException: I/O error while trying to retrieve Temperature or humidity data using readRegBuffer.

```<code>int address = 0xE5; // from datasheet
byte[] buffer = new byte[3];

device.readRegBuffer(address, buffer, 3); // throws PioException
</code>```

I don't know what other clue I can give you to get a clear idea of the problem so do not hesitate to ask any question.

Please don't make me buy an arduino and start all over again ;)

Thank you so mutch!

PS: Use simple words I am a beginner in IoT and Android.

答:
The readRegBuffer does not do what I believe you expect. From [the API documentation](https://developer.android.com/things/reference/com/google/android/things/pio/I2cDevice.html#readRegBuffer(int, byte[], int)):

Read multiple bytes from a given register.

This method would be used if the register you wanted to read was 3 bytes long (24 bits). Looking at the part's datasheet (p21), register 0xE5 for relative humidity appears to be a 2-bit word.

Expecting 3 bytes will create a problem as your device will be expecting 3 bytes to be returned. However, if only two bytes come back there will be an inconsistency in the actual result.

Body:
Hello dear pioneers of Android things!

I am calling for your help as I have been triying for the last couple of months to build an android things driver for the Adafruit SI7021 Themperature and humidity sensor.
Here is the link to the github repository hosting the project.
Connecting and Getting the chip id with readRegByte work fine.
But, I get a PioException: I/O error while trying to retrieve Temperature or humidity data using readRegBuffer.

int address = 0xE5; // from datasheet
byte[] buffer = new byte[3];

device.readRegBuffer(address, buffer, 3); // throws PioException

I don't know what other clue I can give you to get a clear idea of the problem so do not hesitate to ask any question.

Please don't make me buy an arduino and start all over again ;)

Thank you so mutch!

PS: Use simple words I am a beginner in IoT and Android.


问:
No route registered for '/api/continuouswebjobs/WebJobsName/run'
Main Issue:

"No route registered for
  '/api/continuouswebjobs/WebJobName/run'"  or /stop or
  /start  but that is what is offered on the Azure portal under the
  webhook copy to clip board button if you are under a webjob menu under
  your webjob app container.

Additionally if I try: /api/site/wwwroot/app_data/jobs/continuous/WebJobName/run it gives the same error.

So in short:  How do I force a register of the route?

Secondary Issue:
BTW:  Not sure if you are aware but "Publish as Azure Webjob" in VS2015 AND VS2017 doesnt work anymore. I have to zip up the bin directory and push a manual zip upload from the App Service Container for my WebJob. Very time consuming!

HALP! Any 411 would be much appreciated.

Thanks,
-Vandy

答:
I've received the same error in the Azure Portal.

As a work-around navigating to the WebJob using the Server Explorer in Visual Studio (2015), right clicking on the job and selecting run, it ran as expected with all logs working correctly.


问:
Visual Studio: can't add ATL class to ATL project?
So, I'm creating an ATL project in visual studio 2008 using the wizard (recommended here - How to create ActiveX DLL in Visual C++ - and elsewhere)

But I can't add any classes to my project.  VS returns the following error:

```<code>atl classes can only be added to mfc exe and mfc regular dll projects or projects with full atl support
</code>```

...the latter of which you'd think an atl project would have, right?

Can anyone offer a fix?

(I've tried both ticking and unticking 'Support COM+ 1.0' when creating the project - I'm not quite sure what to do with this option).

答: Add "new item..." instead of Add "class...". Then you can select one of the ATL options.</p>

Body:
So, I'm creating an ATL project in visual studio 2008 using the wizard (recommended here - How to create ActiveX DLL in Visual C++ - and elsewhere)

But I can't add any classes to my project.  VS returns the following error:

atl classes can only be added to mfc exe and mfc regular dll projects or projects with full atl support

...the latter of which you'd think an atl project would have, right?

Can anyone offer a fix?

(I've tried both ticking and unticking 'Support COM+ 1.0' when creating the project - I'm not quite sure what to do with this option).


问:
"[unixODBC][Driver Manager]Data source name not found, and no default driver specified" despite /etc/odbc.ini having the DSN
Getting the "[unixODBC][Driver Manager]Data source name not found, and no default driver specified" despite /etc/odbc.ini having the DSN referenced in the connection string. Why would this be happening and what can be done?

Trying to set up pyodbc for connecting to MSSQLServer using the docs (centos 7). Yet, when trying to actually connect to the database,

```<code>import pyodbc

# setup db connection
server = 'myserver'
database = 'mydb'
username = 'myusername'
password = 'mypassword'
cnxn_str = 'DSN=MyMSSQLServer;DATABASE='+database+'UID='+username+'PWD='+password+'MultipleActiveResultSets=True;'
cnxn = pyodbc.connect(cnxn_str)
</code>```

getting error "[unixODBC][Driver Manager]Data source name not found, and no default driver specified", even though when running:

```<code>[mapr@mnode01 ~]$ cat /etc/odbc.ini
[MyMSSQLServer] Driver=ODBC Driver 13 for SQL Server
Description=My MS SQL Server
Trace=No
Server=<now using my sql server ip>
</code>```

I can see that the DSN that I referenced in the python code is recorded in the /etc/odbc.ini file. Does anyone know what could be going on here? Thanks.

Note: I initially ran the pyodbc setup exactly as specified in the docs, but later re-did this step to use the ip address of the sql server I wanted to connect to:

```<code>vi /home/user/odbcadd.txt

[MyMSSQLServer] Driver = ODBC Driver 13 for SQL Server

Description = My MS SQL Server

Trace = No

Server = <my sql server ip>
</code>```

and just re-ran the write to odbc.ini:

```<code>sudo odbcinst -i -s -f /home/user/odbcadd.txt -l
</code>```

答:
The solution commented by user Gord Thompson solved my problem. The ~/odbcadd.txt file that I was using to fill the /etc/odbc.ini file needed to have the 'Driver=' line on a separate line from the DSN to look like:

```<code>[mapr@mnode01 ~]$ cat /etc/odbc.ini
[MyMSSQLServer]
Driver=ODBC Driver 13 for SQL Server
Description=My MS SQL Server
Trace=No
Server=172.18.4.38
</code>```

Body:
Getting the "[unixODBC][Driver Manager]Data source name not found, and no default driver specified" despite /etc/odbc.ini having the DSN referenced in the connection string. Why would this be happening and what can be done?

Trying to set up pyodbc for connecting to MSSQLServer using the docs (centos 7). Yet, when trying to actually connect to the database,

import pyodbc

# setup db connection
server = 'myserver'
database = 'mydb'
username = 'myusername'
password = 'mypassword'
cnxn_str = 'DSN=MyMSSQLServer;DATABASE='+database+'UID='+username+'PWD='+password+'MultipleActiveResultSets=True;'
cnxn = pyodbc.connect(cnxn_str)

getting error "[unixODBC][Driver Manager]Data source name not found, and no default driver specified", even though when running:

[mapr@mnode01 ~]$ cat /etc/odbc.ini
[MyMSSQLServer] Driver=ODBC Driver 13 for SQL Server
Description=My MS SQL Server
Trace=No
Server=<now using my sql server ip>

I can see that the DSN that I referenced in the python code is recorded in the /etc/odbc.ini file. Does anyone know what could be going on here? Thanks.

Note: I initially ran the pyodbc setup exactly as specified in the docs, but later re-did this step to use the ip address of the sql server I wanted to connect to:

vi /home/user/odbcadd.txt

[MyMSSQLServer] Driver = ODBC Driver 13 for SQL Server

Description = My MS SQL Server

Trace = No

Server = <my sql server ip>

and just re-ran the write to odbc.ini:

sudo odbcinst -i -s -f /home/user/odbcadd.txt -l

Body:
The solution commented by user Gord Thompson solved my problem. The ~/odbcadd.txt file that I was using to fill the /etc/odbc.ini file needed to have the 'Driver=' line on a separate line from the DSN to look like:

[mapr@mnode01 ~]$ cat /etc/odbc.ini
[MyMSSQLServer]
Driver=ODBC Driver 13 for SQL Server
Description=My MS SQL Server
Trace=No
Server=172.18.4.38


问:
Looking up values within a range of cells

Suppose I have the following data table in Excel

```<code>Company Amount  Text
Oracle  $3,400  330 Richard ERP
Walmart $750    348 Mary ERP
Amazon  $6,880  xxxx Loretta ERP
Rexel   $865    0000 Mike ERP
Toyota  $11,048 330 Richard ERP
</code>```

I want to go through each item in the "Text" column, search the item against the following range of names:

```<code>Mary
Mike
Janine
Susan
Richard
Jerry
Loretta
</code>```

and return the name in the "Person" column, if found. For example:

```<code>Company Amount  Text    Person
Oracle  $3,400  330 Richard ERP Richard
Walmart $750    348 Mary ERP    Mary
Amazon  $6,880  xxxx Loretta ERP    Loretta
Rexel   $865    0000 Mike ERP   Mike
Toyota  $11,048 330 Richard ERP Richard
</code>```

I've tried the following in Excel which works:

```<code>=IF(N2="","",
IF(ISNUMBER(SEARCH(Sheet2!$A$1,N2)),Sheet2!$A$1,
IF(ISNUMBER(SEARCH(Sheet2!$A$2,N2)),Sheet2!$A$2,
IF(ISNUMBER(SEARCH(Sheet2!$A$3,N2)),Sheet2!$A$3,
....
</code>```

Where $A$1:$A$133 is my range and N2 is the "Text" column values; however, that is a lot of nested code and apparently Excel has a limit on the number of nested IF statements you can have.

Is there a simpler solution (arrays? VBA?)

Thanks!

答:
Use the following formula:

```<code>=IFERROR(INDEX(Sheet2!A:A,AGGREGATE(15,6,ROW(Sheet2!$A$1:INDEX(Sheet2!A:A,MATCH("zzz",Sheet2!A:A)))/(ISNUMBER(SEARCH(Sheet2!$A$1:INDEX(Sheet2!A:A,MATCH("zzz",Sheet2!A:A)),N2))),1)),"")
</code>```

Body:
Suppose I have the following data table in Excel

Company Amount  Text
Oracle  $3,400  330 Richard ERP
Walmart $750    348 Mary ERP
Amazon  $6,880  xxxx Loretta ERP
Rexel   $865    0000 Mike ERP
Toyota  $11,048 330 Richard ERP

I want to go through each item in the "Text" column, search the item against the following range of names:

Mary
Mike
Janine
Susan
Richard
Jerry
Loretta

and return the name in the "Person" column, if found. For example:

Company Amount  Text    Person
Oracle  $3,400  330 Richard ERP Richard
Walmart $750    348 Mary ERP    Mary
Amazon  $6,880  xxxx Loretta ERP    Loretta
Rexel   $865    0000 Mike ERP   Mike
Toyota  $11,048 330 Richard ERP Richard

I've tried the following in Excel which works:

=IF(N2="","",
IF(ISNUMBER(SEARCH(Sheet2!$A$1,N2)),Sheet2!$A$1,
IF(ISNUMBER(SEARCH(Sheet2!$A$2,N2)),Sheet2!$A$2,
IF(ISNUMBER(SEARCH(Sheet2!$A$3,N2)),Sheet2!$A$3,
....

Where $A$1:$A$133 is my range and N2 is the "Text" column values; however, that is a lot of nested code and apparently Excel has a limit on the number of nested IF statements you can have.

Is there a simpler solution (arrays? VBA?)

Thanks!

Body:
Use the following formula:

=IFERROR(INDEX(Sheet2!A:A,AGGREGATE(15,6,ROW(Sheet2!$A$1:INDEX(Sheet2!A:A,MATCH("zzz",Sheet2!A:A)))/(ISNUMBER(SEARCH(Sheet2!$A$1:INDEX(Sheet2!A:A,MATCH("zzz",Sheet2!A:A)),N2))),1)),"")


问:
Trying to count words in different lists
I'm trying for sentiment analysis to score many comments in a data frame. I have a negative word corpora, and a positive one. I want to add 1 for every positive word, and remove 1 for every negative word in the comment. My code:

```<code>     text['counts'] = 0
     for i in text.Reviews:
         if i in p:
             text['counts'] += 1
         elif i in n:
             text['counts'] +=-1
</code>```

I want the new column, text.counts to give the comment's score for every comment, but so far I've only managed to get the total count appear on every row (as if my dataframe was one big comment.)

Thank you!

答:
Here, instead of a global count, you have a specific count for each comment. :)
I duplicated the if-statement because I assumed you wouldn't want to check at each iteration, but instead check on something less occurrent, and so, more memory efficient. :d</p>

```<code>text['commentsCount'] = {}
for i in text.Reviews:
    #   If review is positive
    if i in p:
        #   If comment_id key hasn't been added yet...
        if comment_id in text['commentsCount']:
            text['commentsCount'][comment_id] = 0
        text['commentsCount'][comment_id] += 1
    elif i in n:
        #   if comment_id key hasn't been added yet...
        if comment_id in text['commentsCount']:
            text['commentsCount'][comment_id] = 0
        text['commentsCount'][comment_id] -= 1
</code>```

Body:
I'm trying for sentiment analysis to score many comments in a data frame. I have a negative word corpora, and a positive one. I want to add 1 for every positive word, and remove 1 for every negative word in the comment. My code:

     text['counts'] = 0
     for i in text.Reviews:
         if i in p:
             text['counts'] += 1
         elif i in n:
             text['counts'] +=-1

I want the new column, text.counts to give the comment's score for every comment, but so far I've only managed to get the total count appear on every row (as if my dataframe was one big comment.)

Thank you!

Body:
Here, instead of a global count, you have a specific count for each comment. :)
I duplicated the if-statement because I assumed you wouldn't want to check at each iteration, but instead check on something less occurrent, and so, more memory efficient. :d

text['commentsCount'] = {}
for i in text.Reviews:
    #   If review is positive
    if i in p:
        #   If comment_id key hasn't been added yet...
        if comment_id in text['commentsCount']:
            text['commentsCount'][comment_id] = 0
        text['commentsCount'][comment_id] += 1
    elif i in n:
        #   if comment_id key hasn't been added yet...
        if comment_id in text['commentsCount']:
            text['commentsCount'][comment_id] = 0
        text['commentsCount'][comment_id] -= 1


问:
Javascript Why isn't "this" defined in subclass until after super() is called
I have found that keyword "this" is "undefined" until super() is called, and I'm wondering where this behavior documented.  I'm asking only to learn where I can lookup these answers myself (in the future).

Code that shows this behavior is given below:

class BaseClass {
    constructor(){
        this.baseVar = 1;
    }
}

class SubClass extends BaseClass {
    constructor(...args){
        try {
            console.log('this BEFORE calling super.  this:', this);
        } catch(ex) {
            console.log('this BEFORE calling super. this: caused exception!');
        }
        super(...args);
        this.subVar = 2;
        console.log('this AFTER calling super.  this:', this);
    }
}

var base = new BaseClass();
var subclass = new SubClass();```
</div>
</div>
</p>

<p>The output from this is shown below:</p>

```this BEFORE calling super. this: caused exception!
this AFTER calling super.  this: SubClass { baseVar: 1, subVar: 2 }
```

答:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

When used in a constructor, the super keyword appears alone and must
  be used before the this keyword is used. The super keyword can also be
  used to call functions on a parent object.

The example provided in the page showcases the behaviour you mentioned:

```<code>class Square extends Polygon {
  constructor(length) {
    this.height; // ReferenceError, super needs to be called first!

    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);

    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.height = this.width = Math.sqrt(value);
  }
}
</code>```

Body:
I have found that keyword "this" is "undefined" until super() is called, and I'm wondering where this behavior documented.  I'm asking only to learn where I can lookup these answers myself (in the future).

Code that shows this behavior is given below:

class BaseClass {
    constructor(){
        this.baseVar = 1;
    }
}

class SubClass extends BaseClass {
    constructor(...args){
        try {
            console.log('this BEFORE calling super.  this:', this);
        } catch(ex) {
            console.log('this BEFORE calling super. this: caused exception!');
        }
        super(...args);
        this.subVar = 2;
        console.log('this AFTER calling super.  this:', this);
    }
}

var base = new BaseClass();
var subclass = new SubClass();

The output from this is shown below:

this BEFORE calling super. this: caused exception!
this AFTER calling super.  this: SubClass { baseVar: 1, subVar: 2 }

Body:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

When used in a constructor, the super keyword appears alone and must
  be used before the this keyword is used. The super keyword can also be
  used to call functions on a parent object.

The example provided in the page showcases the behaviour you mentioned:

class Square extends Polygon {
  constructor(length) {
    this.height; // ReferenceError, super needs to be called first!

    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);

    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.height = this.width = Math.sqrt(value);
  }
}


问:
Symfony 3.4 + Propel + Authentication Error
I have setup Symfony 3.4 with propel and it's working fine. I have create one login script and get error.

```<code>public function loginAction(Request $request)
    {
        $session = $request->getSession();

        $authUtils = $this->get('security.authentication_utils');
        $error = $authUtils->getLastAuthenticationError();
        $lastUsername = $authUtils->getLastUsername();

        return $this->render('SecurityPersonBundle:Default:login.html.twig', array(
            'last_username' => $lastUsername,
            'error' => $error,
        ));
    }
</code>```

I have created above method for loginAction and for check login i have created below method.

```<code>public function logincheckAction(Request $request)
    {
       $email = $request->request->get('_username');
       $password = $request->request->get('_password');

       $person = PersonQuery::create()->filterByEmail($email)->findOne();

       if (!$person)
       {
           $this->get('session')->getFlashBag()->add('error',$email.' email id not found..!');
           return $this->redirect($this->generateUrl('person_login'));
       }

       $salt = $person->getSalt();

       if(sha1($salt.$password) == $person->getPassword())
       {
           $this->get('session')->set('personId',$person->getPersonId());

           $token = new UsernamePasswordToken($person->getFirstName(), null, 'main', array('ROLE_ADMIN'));

           $this->get('security.context')->setToken($token);

           return $this->redirect($this->generateUrl('help_releasenote_list'));
       }
       else
       {
         $this->get('session')->getFlashBag()->add('error','Email id or Password not match..!');
         return $this->redirect($this->generateUrl('person_login'));
       }
    }
</code>```

Error:

Attempted to load class "UsernamePasswordToken" from namespace
  "Security\PersonBundle\Controller".

Please help for fixed this issue.

答:
Add

```<code>use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
</code>```

to the top of your Security\PersonBundle\Controller class.

Body:
I have setup Symfony 3.4 with propel and it's working fine. I have create one login script and get error.

public function loginAction(Request $request)
    {
        $session = $request->getSession();

        $authUtils = $this->get('security.authentication_utils');
        $error = $authUtils->getLastAuthenticationError();
        $lastUsername = $authUtils->getLastUsername();

        return $this->render('SecurityPersonBundle:Default:login.html.twig', array(
            'last_username' => $lastUsername,
            'error' => $error,
        ));
    }

I have created above method for loginAction and for check login i have created below method.

public function logincheckAction(Request $request)
    {
       $email = $request->request->get('_username');
       $password = $request->request->get('_password');

       $person = PersonQuery::create()->filterByEmail($email)->findOne();

       if (!$person)
       {
           $this->get('session')->getFlashBag()->add('error',$email.' email id not found..!');
           return $this->redirect($this->generateUrl('person_login'));
       }

       $salt = $person->getSalt();

       if(sha1($salt.$password) == $person->getPassword())
       {
           $this->get('session')->set('personId',$person->getPersonId());

           $token = new UsernamePasswordToken($person->getFirstName(), null, 'main', array('ROLE_ADMIN'));

           $this->get('security.context')->setToken($token);

           return $this->redirect($this->generateUrl('help_releasenote_list'));
       }
       else
       {
         $this->get('session')->getFlashBag()->add('error','Email id or Password not match..!');
         return $this->redirect($this->generateUrl('person_login'));
       }
    }

Error:

Attempted to load class "UsernamePasswordToken" from namespace
  "Security\PersonBundle\Controller".

Please help for fixed this issue.

Body:
Add

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

to the top of your Security\PersonBundle\Controller class.


问:
Remap values in pandas column with a dict, preserve NaNs
I have a dictionary which looks like this: di = {1: "A", 2: "B"}

I would like to apply it to the col1 column of a dataframe similar to:

     col1   col2
0       w      a
1       1      2
2       2    NaN
```
<p>to get:</p>
<pre class="lang-none prettyprint-override"><code>     col1   col2
0       w      a
1       A      2
2       B    NaN
</code>```

How can I best do this?

答:
Adding to this question if you ever have more than one columns to remap in a data dataframe:

```<code>def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data
</code>```

Hope it can be useful to someone.

Cheers

Body:
I have a dictionary which looks like this: di = {1: "A", 2: "B"}

I would like to apply it to the col1 column of a dataframe similar to:

     col1   col2
0       w      a
1       1      2
2       2    NaN

to get:

     col1   col2
0       w      a
1       A      2
2       B    NaN

How can I best do this?

Body:
Adding to this question if you ever have more than one columns to remap in a data dataframe:

def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data

Hope it can be useful to someone.

Cheers


问:
how to copy all the code of a URL with python
I want to copy all the code of an URL (http://modelseed.org/biochem/reactions/rxn00001) using Python 3.6, but I can only copy part of the code, and I don't know why.

So far, I tried with "requests" module

```<code>import requests
page = requests.get("http://modelseed.org/biochem/reactions/rxn00001")
print(page.content)
</code>```

and "urllib"

```<code>import urllib.request
site = urllib.request.urlopen("http://modelseed.org/biochem/reactions/rxn00001")
print(site.read())
</code>```

The part of the code with information of the "Reaction Details", like "Name", "ID" and "Abbreviation" are missing, but they are visible if I inspect the code on the  developer bar of Chrome.

The code I'm able to download using the two codes above is:

```<code><!DOCTYPE html>
<html lang="en" ng-app="ModelSEED">
 <head>
  <base href="/"/>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
  <meta content="IE=edge" http-equiv="X-UA-Compatible"/>
  <meta content="initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
   <meta content="The ModelSEED is a resource for the reconstruction, exploration, comparison, and analysis of metabolic models." name="description"/>
   <link href="/img/ModelSEED-favicon.png?v=2.0" rel="shortcut icon"/>
   <meta content="nconrad" name="author"/>
   <title>
    ModelSEED
   </title>
   <link href="components/angular-material/angular-material.css" rel="stylesheet"/>
   <link href="components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
   <!-- to be removed -->
   <link href="components/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
   <link href="icomoon/style.css" rel="stylesheet"/>
   <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
   <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"/>
   <link href="build/style.css" rel="stylesheet"/>
   <!--<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>-->
   <script src="build/site.js">
   </script>
   <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
   <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
   <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </meta>
 </head>
 <body>
  <div style="height: 100%;" ui-view="">
  </div>
  <script>
   (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-67412611-1', 'auto');
      ga('send', 'pageview');
  </script>
 </body>
</html>
</code>```

Anyone has any hint why the code between
 and  (just after  and before < script >) is not downloaded?

Thank you.

答: Try getting this url instead: https://www.patricbrc.org/api/model_reaction/?http_accept=application/json&eq(id,rxn00001)</p>

Body:
I want to copy all the code of an URL (http://modelseed.org/biochem/reactions/rxn00001) using Python 3.6, but I can only copy part of the code, and I don't know why.

So far, I tried with "requests" module

import requests
page = requests.get("http://modelseed.org/biochem/reactions/rxn00001")
print(page.content)

and "urllib"

import urllib.request
site = urllib.request.urlopen("http://modelseed.org/biochem/reactions/rxn00001")
print(site.read())

The part of the code with information of the "Reaction Details", like "Name", "ID" and "Abbreviation" are missing, but they are visible if I inspect the code on the  developer bar of Chrome.

The code I'm able to download using the two codes above is:

<!DOCTYPE html>

  <base href="/"/>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
  <meta content="IE=edge" http-equiv="X-UA-Compatible"/>
  <meta content="initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
   <meta content="The ModelSEED is a resource for the reconstruction, exploration, comparison, and analysis of metabolic models." name="description"/>
   <link href="/img/ModelSEED-favicon.png?v=2.0" rel="shortcut icon"/>
   <meta content="nconrad" name="author"/>
   <title>
    ModelSEED
   </title>
   <link href="components/angular-material/angular-material.css" rel="stylesheet"/>
   <link href="components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>

   <link href="components/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
   <link href="icomoon/style.css" rel="stylesheet"/>
   <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
   <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"/>
   <link href="build/style.css" rel="stylesheet"/>

  </meta>

Anyone has any hint why the code between
 and  (just after  and before < script >) is not downloaded?

Thank you.


问:
Difference between dates in JavaScript
How to find the difference between two dates?</p>

答:
```<code>var DateDiff = function(type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    var returns = -1;

    switch(type){
        case 'm': case 'mm': case 'month': case 'months':
            returns = ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
            break;
        case 'y': case 'yy': case 'year': case 'years':
            returns = years;
            break;
        case 'd': case 'dd': case 'day': case 'days':
            returns = ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
            break;
    }

    return returns;

}
</code>```

Usage

var qtMonths = DateDiff('mm', new Date('2015-05-05'), new Date());

var qtYears = DateDiff('yy', new Date('2015-05-05'), new Date());

var qtDays = DateDiff('dd', new Date('2015-05-05'), new Date());

OR

var qtMonths = DateDiff('m', new Date('2015-05-05'), new Date()); // m || y || d

var qtMonths = DateDiff('month', new Date('2015-05-05'), new Date()); // month || year || day

var qtMonths = DateDiff('months', new Date('2015-05-05'), new Date()); // months || years || days

...

```<code>var DateDiff = function (type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
        return ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
    else if(['y', 'yy', 'year', 'years'].includes(type))
        return years;
    else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
        return ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
    else
        return -1;

}
</code>```

Title: Difference between dates in JavaScript

Body:
var DateDiff = function(type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    var returns = -1;

    switch(type){
        case 'm': case 'mm': case 'month': case 'months':
            returns = ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
            break;
        case 'y': case 'yy': case 'year': case 'years':
            returns = years;
            break;
        case 'd': case 'dd': case 'day': case 'days':
            returns = ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
            break;
    }

    return returns;

}

Usage

var qtMonths = DateDiff('mm', new Date('2015-05-05'), new Date());

var qtYears = DateDiff('yy', new Date('2015-05-05'), new Date());

var qtDays = DateDiff('dd', new Date('2015-05-05'), new Date());

OR

var qtMonths = DateDiff('m', new Date('2015-05-05'), new Date()); // m || y || d

var qtMonths = DateDiff('month', new Date('2015-05-05'), new Date()); // month || year || day

var qtMonths = DateDiff('months', new Date('2015-05-05'), new Date()); // months || years || days

...

var DateDiff = function (type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
        return ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
    else if(['y', 'yy', 'year', 'years'].includes(type))
        return years;
    else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
        return ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
    else
        return -1;

}


问:
Calling Directory.CreateDirectory() from within a lock()
Would it be a bad practice to call Directory.CreateDirectory() from within a lock()? Would it lead to any threading issues?</p>

答:
One does not need a lock as that is additional overhead.  However, appropriate exception handling is needed.

Please refer to this question for further details.

Is CreateDirectory() in C# thread-safe?


问:
Automatic new line and indentation in vim when inside braces?
For example, if I'm coding jQuery in vim, and I have this in insert mode ("|" is the current cursor position):

```<code>$('#something').click(function(){|})
</code>```

...and I hit enter, I would like to get this:

```<code>$('#something').click(function(){
    |
})
</code>```

...while currently, I'm getting this:

```<code>$('#something').click(function(){
|})
</code>```

The same thing happens with function definitions in PHP. Is there a way to automatically insert the extra new line and indent the cursor position when hitting enter inside braces like that?

(Apologies if this has been asked before - it seems like a common request but I searched for awhile and couldn't find it.)

答:
I use javascript.vim which (almost) does what you want for JavaScript code.

There's also a php.vim, but I didn't test it.

Body:
For example, if I'm coding jQuery in vim, and I have this in insert mode ("|" is the current cursor position):

$('#something').click(function(){|})

...and I hit enter, I would like to get this:

$('#something').click(function(){
    |
})

...while currently, I'm getting this:

$('#something').click(function(){
|})

The same thing happens with function definitions in PHP. Is there a way to automatically insert the extra new line and indent the cursor position when hitting enter inside braces like that?

(Apologies if this has been asked before - it seems like a common request but I searched for awhile and couldn't find it.)


问:
java | Return a reversed array by FOR loop
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

```<code>    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

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

But it is throwing out three exact same numbers.

答:
I am new to Java development and sorry if this question will be too
  silly, but it seems like I am stuck with the exercise which tells me
  to create a reversed array from the given one.

After some thinking I made such code:

```<code>    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

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

But it is throwing out three exact same numbers. Could I please count
  on some help? Thank you

Use one loop only. If you want to use 2 arrays(wich i do not see the point.) this will work:

```<code>    int j = 0;

    for(int i = nums.length -1; i >= 0; i--){
         nums2[j] = nums[i];
         j++;
     }
</code>```

But if you want to use only one array, you can do this:

```<code>for (int i = 0; i < nums.length/2; i++) {
    int aux = nums[i];
    nums[i] = nums[nums.length-i-1];
    nums[nums.length-i-1] = aux;
}
</code>```

Body:
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }
  }
  return nums2;
}

But it is throwing out three exact same numbers.

Body:
I am new to Java development and sorry if this question will be too
  silly, but it seems like I am stuck with the exercise which tells me
  to create a reversed array from the given one.

After some thinking I made such code:

    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }   }   return nums2; }

But it is throwing out three exact same numbers. Could I please count
  on some help? Thank you

Use one loop only. If you want to use 2 arrays(wich i do not see the point.) this will work:

    int j = 0;

    for(int i = nums.length -1; i >= 0; i--){
         nums2[j] = nums[i];
         j++;
     }

But if you want to use only one array, you can do this:

for (int i = 0; i < nums.length/2; i++) {
    int aux = nums[i];
    nums[i] = nums[nums.length-i-1];
    nums[nums.length-i-1] = aux;
}


问:
(PHP) Getting Blank Page with Curl (Mytischtennis)
I´m new to php and trying to program a few things.

In the first step I want to show the following page: "https://www.mytischtennis.de/public/home" on my website. I am using Curl to grab the page. But every time I want to output the page I am getting a blank page.

My code looks like this:

```<code><?php

function grab_page($site){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17');
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($ch, CURLOPT_URL, $site);

    ob_start();
    return curl_exec($ch);
    ob_end_clean();
    curl_close($ch);
}

echo grab_page("https://www.mytischtennis.de/public/home");
echo "hallo";
?>
</code>```

With other pages this code works. Only for "https://www.mytischtennis.de/public/home" it wont work for me?
Can someone help me why i get only with this site a blank page?

Thank you :)

答:
You need to set two more options in your curl request:

```<code>// Add some more headers here if you need to
$headers = [
    "Accept-Encoding: gzip, deflate, br"
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Decode the response automatically when needed
curl_setopt($ch, CURLOPT_ENCODING, '');
</code>```

After this you will get the page you want.

Body:
I´m new to php and trying to program a few things.

In the first step I want to show the following page: "https://www.mytischtennis.de/public/home" on my website. I am using Curl to grab the page. But every time I want to output the page I am getting a blank page.

My code looks like this:

<?php

function grab_page($site){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17');
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($ch, CURLOPT_URL, $site);

    ob_start();
    return curl_exec($ch);
    ob_end_clean();
    curl_close($ch);
}

echo grab_page("https://www.mytischtennis.de/public/home");
echo "hallo";
?>

With other pages this code works. Only for "https://www.mytischtennis.de/public/home" it wont work for me?
Can someone help me why i get only with this site a blank page?

Thank you :)

Body:
You need to set two more options in your curl request:

// Add some more headers here if you need to
$headers = [
    "Accept-Encoding: gzip, deflate, br"
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Decode the response automatically when needed
curl_setopt($ch, CURLOPT_ENCODING, '');

After this you will get the page you want.


问:
Decrypt bytes in asp.net
Following is my Java applet code

```<code>KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] privKeyBytes = loadPriavteKeyFromFile(fileName, new String(txtPassword.getPassword()));
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.ENCRYPT_MODE, privKey);
byte[] ciphertext = null;
ciphertext = rsaCipher.doFinal(xmlToSign.getBytes());
String urlString = "http://localhost:3290/SignApplet.aspx";
String senddata  = Base64.encodeBase64String(ciphertext);
doHttpUrlConnectionAction(urlString,senddata.getBytes());
JOptionPane.showMessageDialog(this, "XML successfully signed and sent to server.");
</code>```

on the server side i am trying too decrypt the byte using the public key

```<code>byte[] b;
b = Request.BinaryRead(178);
string encodedbytes = new System.Text.UTF8Encoding().GetString(b);
b = Convert.FromBase64String(encodedbytes);
Debug.WriteLine("decrypted bytes:" + new System.Text.UTF8Encoding().GetString(b));
// The path to the certificate.
string Certificate = @"c:\certs\lafa801114sd3.cer";

//// Load the certificate into an X509Certificate object.
X509Certificate cert = new X509Certificate(Certificate);
RSACryptoServiceProvider publicprovider = (RSACryptoServiceProvider)CertUtil.GetCertPublicKey(cert);
byte[] decbytes = publicprovider.Decrypt(b, false);
Debug.WriteLine("decrypted bytes" + new System.Text.UTF8Encoding().GetString(decbytes));
</code>```

can any one help in following exception which i  am getting at byte[] decbytes = publicprovider.Decrypt(b, false); line

A first chance exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
  Key does not exist.

and the certificate is not installed in nay key store.Also i can successfully decrypt the data using Java servlet .

i am using asp.net vs2010 on windows 7
the public and private keys are stored in separate files

答:
Here are a few articles that might help you: Java RSA Encrypt - Decrypt .NET (which seems like what you are looking for)
and http://www.jensign.com/JavaScience/dotnet/RSAEncrypt/</p>

Title: Decrypt bytes in asp.net

Body:
Following is my Java applet code

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] privKeyBytes = loadPriavteKeyFromFile(fileName, new String(txtPassword.getPassword()));
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.ENCRYPT_MODE, privKey);
byte[] ciphertext = null;
ciphertext = rsaCipher.doFinal(xmlToSign.getBytes());
String urlString = "http://localhost:3290/SignApplet.aspx";
String senddata  = Base64.encodeBase64String(ciphertext);
doHttpUrlConnectionAction(urlString,senddata.getBytes());
JOptionPane.showMessageDialog(this, "XML successfully signed and sent to server.");

on the server side i am trying too decrypt the byte using the public key

byte[] b;
b = Request.BinaryRead(178);
string encodedbytes = new System.Text.UTF8Encoding().GetString(b);
b = Convert.FromBase64String(encodedbytes);
Debug.WriteLine("decrypted bytes:" + new System.Text.UTF8Encoding().GetString(b));
// The path to the certificate.
string Certificate = @"c:\certs\lafa801114sd3.cer";

//// Load the certificate into an X509Certificate object.
X509Certificate cert = new X509Certificate(Certificate);
RSACryptoServiceProvider publicprovider = (RSACryptoServiceProvider)CertUtil.GetCertPublicKey(cert);
byte[] decbytes = publicprovider.Decrypt(b, false);
Debug.WriteLine("decrypted bytes" + new System.Text.UTF8Encoding().GetString(decbytes));

can any one help in following exception which i  am getting at byte[] decbytes = publicprovider.Decrypt(b, false); line

A first chance exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
  Key does not exist.

and the certificate is not installed in nay key store.Also i can successfully decrypt the data using Java servlet .

i am using asp.net vs2010 on windows 7
the public and private keys are stored in separate files