问:
why xpath derived from chrome does not work
I am trying to scrap data from web of science

And here is the specific page I am going to work with.

Below is the code I use for extract the abstract:

```<code>import lxml
import requests

url = 'https://apps.webofknowledge.com/full_record.do?product=WOS&search_mode=GeneralSearch&qid=2&SID=Q1yAnqE4al4KxALF7RM&page=1&doc=3&cacheurlFromRightClick=no'
s = requests.Session()
d = s.get(url)
soup1 = etree.HTML(d.text)
</code>```

And here is the xpath I got  through the copy xpath in Chrome:

```<code>//*[@id="records_form"]/div/div/div/div[1]/div/div[4]/p/text()
</code>```

So I tried to get the abstract like this

```<code>path = '//*[@id="records_form"]/div/div/div/div[1]/div/div[4]/p/text()'
print(soup1.xpath(path))
</code>```

However, I just hot an empty list! Then I tried another way to test the xpath.

Firstly, I save the specific page as a local html file.

```<code>with open('1.html','w',encoding='UTF=8') as f:
    f.write(d.text)
f.close()
</code>```

Then, open the file

```<code>s.mount('file://',FileAdapter())
d = s.get('file:///K:/single_paper.html')
soup2 = etree.HTML(d.text)
soup2.xpath('//*[@id="records_form"]/div/div/div/div[1]/div/div[4]/p/text()')
</code>```

And it gives me the abstract I want! Could anyone tell me why that happens?

Weired when I try to do the steps with another page in the saving local file way, it returns an empty list again!

I checked that the xpath given by Chrome is the same for these two pages.

So could anyone tell me what's wrong with my code and how to fix it?

答:
Browser given full Xpaths are usually unhelpful and you should use relative and clever ones based on attributes (such as id, class, etc) or any identifying features like contains(@href, 'image').

You could try more specific xpath expression: (//div[@class="block-record-info"])[2]/p/text() and rewrite your code like this:

```<code>import requests
from lxml import html

url = 'https://apps.webofknowledge.com/full_record.do?product=WOS&search_mode=GeneralSearch&qid=2&SID=Q1yAnqE4al4KxALF7RM&page=1&doc=3&cacheurlFromRightClick=no'
s = requests.Session()
r = s.get(url)
tree = html.fromstring(r.content)
element = tree.xpath('(//div[@class="block-record-info"])[2]/p/text()')
print(element)
</code>```

Output:

Body:
I am trying to scrap data from web of science

And here is the specific page I am going to work with.

Below is the code I use for extract the abstract:

import lxml
import requests

url = 'https://apps.webofknowledge.com/full_record.do?product=WOS&search_mode=GeneralSearch&qid=2&SID=Q1yAnqE4al4KxALF7RM&page=1&doc=3&cacheurlFromRightClick=no'
s = requests.Session()
d = s.get(url)
soup1 = etree.HTML(d.text)

And here is the xpath I got  through the copy xpath in Chrome:

//*[@id="records_form"]/div/div/div/div[1]/div/div[4]/p/text()

So I tried to get the abstract like this

path = '//*[@id="records_form"]/div/div/div/div[1]/div/div[4]/p/text()'
print(soup1.xpath(path))

However, I just hot an empty list! Then I tried another way to test the xpath.

Firstly, I save the specific page as a local html file.

with open('1.html','w',encoding='UTF=8') as f:
    f.write(d.text)
f.close()

Then, open the file

s.mount('file://',FileAdapter())
d = s.get('file:///K:/single_paper.html')
soup2 = etree.HTML(d.text)
soup2.xpath('//*[@id="records_form"]/div/div/div/div[1]/div/div[4]/p/text()')

And it gives me the abstract I want! Could anyone tell me why that happens?

Weired when I try to do the steps with another page in the saving local file way, it returns an empty list again!

I checked that the xpath given by Chrome is the same for these two pages.

So could anyone tell me what's wrong with my code and how to fix it?

Body:
Browser given full Xpaths are usually unhelpful and you should use relative and clever ones based on attributes (such as id, class, etc) or any identifying features like contains(@href, 'image').

You could try more specific xpath expression: (//div[@class="block-record-info"])[2]/p/text() and rewrite your code like this:

import requests
from lxml import html

url = 'https://apps.webofknowledge.com/full_record.do?product=WOS&search_mode=GeneralSearch&qid=2&SID=Q1yAnqE4al4KxALF7RM&page=1&doc=3&cacheurlFromRightClick=no'
s = requests.Session()
r = s.get(url)
tree = html.fromstring(r.content)
element = tree.xpath('(//div[@class="block-record-info"])[2]/p/text()')
print(element)

Output:


来源: stackexchange

问:
C# m2mqtt to connect to AWS broker using Root CA, key, and certificate
I am trying to use M2MQtt library to connect to AWS MQTT broker using a root CA, client certificate and key. I am using the following C# client connection code

```<code>MqttClient client = new MqttClient(
    endPoint,
    MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
    true,
    new X509Certificate2(@"ca.pem"),
    new X509Certificate2(@"certificate.pem"),
    MqttSslProtocols.TLSv1_2
    );
client.Connect(Guid.NewGuid().ToString());
</code>```

however, this fails with a FormatException error. It's probably related to the fact that I don't know where to pass in the private key for this connection. This is something that I already have working, prototyped in Python using AWSIoTPythonSDK (see below)

```<code>from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

f = open('mqttEndpoint.txt', 'r')
awsHost = f.read()
f.close()

myAWSIoTMQTTClient = AWSIoTMQTTClient('foo')
myAWSIoTMQTTClient.configureEndpoint(awsHost, 8883)
myAWSIoTMQTTClient.configureCredentials('ca.pem', 'id_rsa', 'certificate.pem')
</code>```

Does anyone know how this is supposed to work?

答:
I figured out my problem. The clue was the fact that to properly authenticate against AWS, you need to provide both the certificate (a PEM in my case) as well as the private key, which I could not figure out how to pass into MqttClient() constructor, because it takes only one "certificate".

The solution is to use a PFX/P12 certificate, which includes inside it both a PEM and a private key (thank you, Microsoft, for being different). There are many resources that explain how to create a PFX from a PEM+key (i.e. here, here, here, here, etc). Then you have to use a X509Certificate2() class to pull in the PFX file (that '2' is

```<code>MqttClient client = new MqttClient(
    endPoint,
    MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
    true,
    rootCa,
    new X509Certificate2(@"certificate.pfx", @""); // My PFX was created with a blank password, hence empty string as 2nd arg
    MqttSslProtocols.TLSv1_2
    );
client.Connect(Guid.NewGuid().ToString());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use M2MQtt library to connect to AWS MQTT broker using a root CA, client certificate and key. I am using the following C# client connection code

MqttClient client = new MqttClient(
    endPoint,
    MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
    true,
    new X509Certificate2(@"ca.pem"),
    new X509Certificate2(@"certificate.pem"),
    MqttSslProtocols.TLSv1_2
    );
client.Connect(Guid.NewGuid().ToString());

however, this fails with a FormatException error. It's probably related to the fact that I don't know where to pass in the private key for this connection. This is something that I already have working, prototyped in Python using AWSIoTPythonSDK (see below)

from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

f = open('mqttEndpoint.txt', 'r')
awsHost = f.read()
f.close()

myAWSIoTMQTTClient = AWSIoTMQTTClient('foo')
myAWSIoTMQTTClient.configureEndpoint(awsHost, 8883)
myAWSIoTMQTTClient.configureCredentials('ca.pem', 'id_rsa', 'certificate.pem')

Does anyone know how this is supposed to work?

Body:
I figured out my problem. The clue was the fact that to properly authenticate against AWS, you need to provide both the certificate (a PEM in my case) as well as the private key, which I could not figure out how to pass into MqttClient() constructor, because it takes only one "certificate".

The solution is to use a PFX/P12 certificate, which includes inside it both a PEM and a private key (thank you, Microsoft, for being different). There are many resources that explain how to create a PFX from a PEM+key (i.e. here, here, here, here, etc). Then you have to use a X509Certificate2() class to pull in the PFX file (that '2' is

MqttClient client = new MqttClient(
    endPoint,
    MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
    true,
    rootCa,
    new X509Certificate2(@"certificate.pfx", @""); // My PFX was created with a blank password, hence empty string as 2nd arg
    MqttSslProtocols.TLSv1_2
    );
client.Connect(Guid.NewGuid().ToString());


问:
Tableau Map view Continent List
I have been trying to clean my data and have a column represent the various continents and ultimately have them represented on map view.

But it doesn't consider that column to be Geography and even when i forcefully make it, the same still does not show up in map view. Any suggestions?

Africa
Asia
Europe
North America
Oceania   (Tried without this too)
South America

答:
I don't think it is possible to have continent as geographic role in Tableau.
What you could do however is look for a list which maps countries to continents and then join with your original data source on continent.
This way all your data values get replicated for each country. When you then select the country column as geographic region you can get the effect you want.

List could be something like this.

Title: Tableau Map view Continent List


问:
How to load dicom from DCM4CHEE in cornerstone?
I am using cornerstone-wado-image-loader to display the dicom of the server using dcm4chee.

https://www.npmjs.com/package/cornerstone-wado-image-loader

I have followed and read the documentation to obtain the DCM4CHEE dicom
Here an example

```<code>Dicomweb: http: // localhost: 3333 / wado? RequestType = WADO & studyUID = 1.3.6.1.4.1.25403.166563008443.5076.20120418075541.1 & seriesUID = 1.3.6.1.4.1.25403.166563008443.5076.20120418075541.2 & objectUID = 1.3.6.1.4.1.25403.166563008443.5076.20120418075557. 1 & contentType = application% 2Fdicom & transferSyntax = 1.2.840.10008.1.2.1
</code>```

But I have doubt in how I am doing this is my code

```<code>Dicomweb: Http: // localhost: 8080 / dcm4chee-web3 / wado? RequestType = WADO & studyUID = 1.2.840.113619.2.134.1762680268.232 & seriesUID = 1.2.840.113619.2.134.1762680288.2032.1122564926.253 & objectUID = 1.2.840.113619.2.134.1762680288.2032.1122564926.265 & contentType = Application% 2Fdicom & transferSyntax = 1.2.840.10008.1.2.4.91
</code>```

I am using localhost: 8080 / dcm4chee / since that is the port that dcm4chee uses and the project I am doing uses port 3000, but I'm not sure if the url is correct, depending on the browser the url returns well with a status 200, but still I can not see the dicom, it is wrong the way the url is or I'm missing some configuration? please I need help

I'm sorry for my English

答:
Remove the dcm4chee-web3 from your address:

```<code>http://localhost:8080/wado?requestType=WADO&studyUID...
</code>```

You can check the format by viewing an image in DCM4CHEE, right-clicking on the image and selecting 'Copy Image Address,' and then pasting it into your browser location.

Body:
I am using cornerstone-wado-image-loader to display the dicom of the server using dcm4chee.

https://www.npmjs.com/package/cornerstone-wado-image-loader

I have followed and read the documentation to obtain the DCM4CHEE dicom
Here an example

Dicomweb: http: // localhost: 3333 / wado? RequestType = WADO & studyUID = 1.3.6.1.4.1.25403.166563008443.5076.20120418075541.1 & seriesUID = 1.3.6.1.4.1.25403.166563008443.5076.20120418075541.2 & objectUID = 1.3.6.1.4.1.25403.166563008443.5076.20120418075557. 1 & contentType = application% 2Fdicom & transferSyntax = 1.2.840.10008.1.2.1

But I have doubt in how I am doing this is my code

Dicomweb: Http: // localhost: 8080 / dcm4chee-web3 / wado? RequestType = WADO & studyUID = 1.2.840.113619.2.134.1762680268.232 & seriesUID = 1.2.840.113619.2.134.1762680288.2032.1122564926.253 & objectUID = 1.2.840.113619.2.134.1762680288.2032.1122564926.265 & contentType = Application% 2Fdicom & transferSyntax = 1.2.840.10008.1.2.4.91

I am using localhost: 8080 / dcm4chee / since that is the port that dcm4chee uses and the project I am doing uses port 3000, but I'm not sure if the url is correct, depending on the browser the url returns well with a status 200, but still I can not see the dicom, it is wrong the way the url is or I'm missing some configuration? please I need help

I'm sorry for my English

Body:
Remove the dcm4chee-web3 from your address:

http://localhost:8080/wado?requestType=WADO&studyUID...

You can check the format by viewing an image in DCM4CHEE, right-clicking on the image and selecting 'Copy Image Address,' and then pasting it into your browser location.


问:
HTTP used in location header instead of HTTPS
Setup:

Nginx as reverse proxy, terminates https

Apache at localhost:8080 delivers Mailman application (admin gui) to Nginx

When I enter the exact URL in the browser like
https://lists.staging.xxx.de/mailman/ it works perfectly.

When I enter either https://lists.staging.xxx.de/mailman (without trailing slash) or even only https://lists.staging.xxx.de/ an Apache RedirectMatch kicks in, and sends back the correct url via header location info - but with incorrect scheme, that is "Location: http://lists.staging.xxx.de/mailman/"

When I do a curl -L -v -s -o /dev/null localhost:8080 I get back: Location: http://localhost:8080/mailman/.

So I conclude:
Nginx correctly rewrites the host, but not the scheme.

So, either I have to change the configuration of Nginx, so it rewrites the header (ie scheme), or I have to make Apache aware, that - even https is terminated - header location statement should include a https.

Any help is appreciated!

Nginx config:

```<code>server {
listen xxx:443;

server_name lists.staging.xxx.de;

if ($host != lists.staging.xxx.de) {
       rewrite (.*) https://lists.staging.xxx.de$1 permanent;
}

ssl on;
ssl_certificate  /srv/s-bliss/deployment/work/nginxmailman/lists.staging.xxx.de.crt;
ssl_certificate_key  /srv/s-bliss/deployment/work/nginxmailman/lists.staging.xxx.de.key;

location / {
    proxy_pass              http://127.0.0.1:8080;
    proxy_set_header        Host $http_host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_redirect          off;
}
</code>```

}

Apache config:

```<code>Listen 127.0.0.1:8080
<VirtualHost 127.0.0.1:8080>
    ServerName lists.staging.xxx.de

    Alias /mailman/icons /usr/lib/mailman/icons
    <Directory "/usr/lib/mailman/icons/">
            AllowOverride None
            Require all granted
    </Directory>

    Alias /mailman/archives /var/lib/mailman/archives/public
    <Directory "/var/lib/mailman/archives/public/">
            AllowOverride None
            Options ExecCGI FollowSymLinks
            AddDefaultCharset off
            Require all granted
    </Directory>

    RedirectMatch ^/$ /mailman/
    RedirectMatch ^/mailman$ /mailman/
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/mailman/(archives|icons)
    RewriteRule ^/mailman/(.*) /usr/lib/mailman/cgi-bin/$1 [H=cgi-script]
    <Directory "/usr/lib/mailman/cgi-bin/">
            AllowOverride None
            Options ExecCGI
            DirectoryIndex listinfo
            Require all granted
    </Directory>
</code>```

答:
Our provider came up with following solution:

```<code>http://lists.staging.xxx.de/mailman/ https://lists.staging.xxx.de/mailman/;
</code>```

It works!

Update:
The header is now delivered correctly, but the payload (body) still contains a link to the http version.

Body:
Setup:

Nginx as reverse proxy, terminates https

Apache at localhost:8080 delivers Mailman application (admin gui) to Nginx

When I enter the exact URL in the browser like
https://lists.staging.xxx.de/mailman/ it works perfectly.

When I enter either https://lists.staging.xxx.de/mailman (without trailing slash) or even only https://lists.staging.xxx.de/ an Apache RedirectMatch kicks in, and sends back the correct url via header location info - but with incorrect scheme, that is "Location: http://lists.staging.xxx.de/mailman/"

When I do a curl -L -v -s -o /dev/null localhost:8080 I get back: Location: http://localhost:8080/mailman/.

So I conclude:
Nginx correctly rewrites the host, but not the scheme.

So, either I have to change the configuration of Nginx, so it rewrites the header (ie scheme), or I have to make Apache aware, that - even https is terminated - header location statement should include a https.

Any help is appreciated!

Nginx config:

server {
listen xxx:443;

server_name lists.staging.xxx.de;

if ($host != lists.staging.xxx.de) {
       rewrite (.*) https://lists.staging.xxx.de$1 permanent;
}

ssl on;
ssl_certificate  /srv/s-bliss/deployment/work/nginxmailman/lists.staging.xxx.de.crt;
ssl_certificate_key  /srv/s-bliss/deployment/work/nginxmailman/lists.staging.xxx.de.key;

location / {
    proxy_pass              http://127.0.0.1:8080;
    proxy_set_header        Host $http_host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_redirect          off;
}

}

Apache config:

Listen 127.0.0.1:8080
<VirtualHost 127.0.0.1:8080>
    ServerName lists.staging.xxx.de

    Alias /mailman/icons /usr/lib/mailman/icons
    <Directory "/usr/lib/mailman/icons/">
            AllowOverride None
            Require all granted
    </Directory>

    Alias /mailman/archives /var/lib/mailman/archives/public
    <Directory "/var/lib/mailman/archives/public/">
            AllowOverride None
            Options ExecCGI FollowSymLinks
            AddDefaultCharset off
            Require all granted
    </Directory>

    RedirectMatch ^/$ /mailman/
    RedirectMatch ^/mailman$ /mailman/
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/mailman/(archives|icons)
    RewriteRule ^/mailman/(.*) /usr/lib/mailman/cgi-bin/$1 [H=cgi-script]
    <Directory "/usr/lib/mailman/cgi-bin/">
            AllowOverride None
            Options ExecCGI
            DirectoryIndex listinfo
            Require all granted
    </Directory>

Body:
Our provider came up with following solution:

http://lists.staging.xxx.de/mailman/ https://lists.staging.xxx.de/mailman/;

It works!

Update:
The header is now delivered correctly, but the payload (body) still contains a link to the http version.


问:
How do you fetch a remote branch without "checking it out"
I am working on a branch "branch-A" and using the command git branch I can see that its the only branch locally.

If I use git branch -a I can see the remote copy of "remotes/origin/branch-B"

What I want to do is bring branch-B locally, but I don't want to actually check it out... I mean I could do that and then checkout my other branch to go back, but its slightly more painful since I am doing this to lots of repos.

I was thinking some sort of fetch? but I can't figure out how to phrase the command. Is it possible?

So I have:

```<code>user@pc> git branch
* branch-A
  master
</code>```

and

```<code>user@pc> git branch -a
* branch-A
  remotes/origin/branch-B
  remotes/origin/branch-A
  remotes/origin/master
</code>```

I want to be able to get:

```<code>user@pc> git branch
* branch-A
  branch-B
  master
</code>```

答: The command you're searching for is git fetch and use the option --all to fetch all remote branches.

Body:
I am working on a branch "branch-A" and using the command git branch I can see that its the only branch locally.

If I use git branch -a I can see the remote copy of "remotes/origin/branch-B"

What I want to do is bring branch-B locally, but I don't want to actually check it out... I mean I could do that and then checkout my other branch to go back, but its slightly more painful since I am doing this to lots of repos.

I was thinking some sort of fetch? but I can't figure out how to phrase the command. Is it possible?

So I have:

user@pc> git branch
* branch-A
  master

and

user@pc> git branch -a
* branch-A
  remotes/origin/branch-B
  remotes/origin/branch-A
  remotes/origin/master

I want to be able to get:

user@pc> git branch
* branch-A
  branch-B
  master


问:
Error Unorderable Types. Select rows where on hdf5 files
I work with python 3.5 and I have the next problem to import some datas from a hdf5 files.

I will show a very simple example which resume what happen. I have created a small dataframe and I have inserted it into a hdf5 files. Then I have tried to select from this hdf5 file the rows which have on the column "A" a value less that 1. So I get the error:

"Type error: unorderable types: str() < int()"

image

```<code>import pandas as pd
import numpy as np
import datetime
import time
import h5py
from pandas import DataFrame, HDFStore

def test_conected():
hdf_nombre_archivo ="1_Archivo.h5"
hdf = HDFStore(hdf_nombre_archivo)

np.random.seed(1234)
index = pd.date_range('1/1/2000', periods=3)
df = pd.DataFrame(np.random.randn(3, 4), index=index, columns=
['A', 'B','C','F'])
print(df)
with h5py.File(hdf_nombre_archivo) as f:
    df.to_hdf(hdf_nombre_archivo, 'df',format='table')

print("")

with h5py.File(hdf_nombre_archivo) as f:
    df_nuevo = pd.read_hdf(hdf_nombre_archivo, 'df',where= ['A' < 1])

print(df_nuevo )

def Fin():
print(" ")
print("FIN")

if __name__ == "__main__":
test_conected()
Fin()
print(time.strftime("%H:%M:%S"))
</code>```

I have been investigating but I dont get to solve this error. Some idea?

Thanks

Angel

答:
where= ['A' < 1]

in your condition statement 'A' is consider as string or char and 1 is int so first make them in same type by typecasting.
ex:
str(1)

Body:
I work with python 3.5 and I have the next problem to import some datas from a hdf5 files.

I will show a very simple example which resume what happen. I have created a small dataframe and I have inserted it into a hdf5 files. Then I have tried to select from this hdf5 file the rows which have on the column "A" a value less that 1. So I get the error:

"Type error: unorderable types: str() < int()"

image

import pandas as pd
import numpy as np
import datetime
import time
import h5py
from pandas import DataFrame, HDFStore

def test_conected():
hdf_nombre_archivo ="1_Archivo.h5"
hdf = HDFStore(hdf_nombre_archivo)

np.random.seed(1234)
index = pd.date_range('1/1/2000', periods=3)
df = pd.DataFrame(np.random.randn(3, 4), index=index, columns=
['A', 'B','C','F'])
print(df)
with h5py.File(hdf_nombre_archivo) as f:
    df.to_hdf(hdf_nombre_archivo, 'df',format='table')

print("")

with h5py.File(hdf_nombre_archivo) as f:
    df_nuevo = pd.read_hdf(hdf_nombre_archivo, 'df',where= ['A' < 1])

print(df_nuevo )

def Fin():
print(" ")
print("FIN")

if __name__ == "__main__":
test_conected()
Fin()
print(time.strftime("%H:%M:%S"))

I have been investigating but I dont get to solve this error. Some idea?

Thanks

Angel


问:
Get http request on server side works but not display on client side [Angular Universal(universal cli)]
I have request like this:

```<code>import {Component, OnInit} from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs';
import 'rxjs/add/operator/map';
import {isNode} from 'angular2-universal';

@Component({
    selector: 'app-todo',
    templateUrl: './todo.component.html',
    styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {

    constructor(private http: Http) {}
    private todo: any;

    ngOnInit() {
        if(isNode) {
            this.http
            .get('http://api.pushsc.com/api/v1/code/show/589ceab40a58d602a0b99d10')
            .map((response: Response) => response.json())
            .subscribe(data => {
                console.log(data);
                this.todo = data;
            })
            error => {
                console.log(error);
            };
        }

    }

}
</code>```

In console I get response from API which mean http from server works... But poroblem is on client even if I remove isNode content from http not render as it should... What can be a problem?

答: You need to install and enable preboot https://github.com/angular/preboot for run code on client side.</p>

Body:
I have request like this:

import {Component, OnInit} from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs';
import 'rxjs/add/operator/map';
import {isNode} from 'angular2-universal';

@Component({
    selector: 'app-todo',
    templateUrl: './todo.component.html',
    styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {

    constructor(private http: Http) {}
    private todo: any;

    ngOnInit() {
        if(isNode) {
            this.http
            .get('http://api.pushsc.com/api/v1/code/show/589ceab40a58d602a0b99d10')
            .map((response: Response) => response.json())
            .subscribe(data => {
                console.log(data);
                this.todo = data;
            })
            error => {
                console.log(error);
            };
        }

    }

}

In console I get response from API which mean http from server works... But poroblem is on client even if I remove isNode content from http not render as it should... What can be a problem?


问:
Django migrations not detecting all changes
I have the following models.
BaseClass1 and BaseClass2 are abstract models used by models.

In this case, the model AdBreak is used by a viewset and a serializer.
When I run python manage.py makemigrations, the changes on AdBreak model is detected. The model AdBreakStatus is not getting created.

Since, AdBreakStatus is linked to AdBreak, I am expecting a migration for AdBreakStatus also. Is my understanding wrong?

Edit

In the initial state, there was only AdBreak and BaseClass1 model. The new state, AdBreakStatus and BaseClass2 models were added. Some of the fields from AdBreak were moved to AdBreakStatus.

Thanks in advance for the help.

```<code>class BaseClass1(models.Model):
    class Meta:
        abstract=True
    timestamp = models.DateTimeField(auto_now_add=True)

class BaseClass2(models.Model):
    class Meta:
        abstract=True
    other_field = models.IntegerField()

class AdBreak(BaseClass1):
    class Meta:
        db_table = "ad_break"
    ad_break_id = models.AutoField(primary_key=True)
    ... # Other fields

class AdBreakStatus(BaseClass2):
    class Meta:
        db_table = "ad_break_status"
    ad_break = models.ForeignKey(AdBreak)
    ... # Other Fields
</code>```

答:
Do this first:

```<code>python manage.py makemigrations 'your-app'
python manage.py migrate
</code>```

If the above fails to detect changes, remove migration folder, open your database and open table django_migrations. You will see migrations listed associated to your app, delete the records and now execute makemigrations and migrate.

Body:
I have the following models.
BaseClass1 and BaseClass2 are abstract models used by models.

In this case, the model AdBreak is used by a viewset and a serializer.
When I run python manage.py makemigrations, the changes on AdBreak model is detected. The model AdBreakStatus is not getting created.

Since, AdBreakStatus is linked to AdBreak, I am expecting a migration for AdBreakStatus also. Is my understanding wrong?

Edit

In the initial state, there was only AdBreak and BaseClass1 model. The new state, AdBreakStatus and BaseClass2 models were added. Some of the fields from AdBreak were moved to AdBreakStatus.

Thanks in advance for the help.

class BaseClass1(models.Model):
    class Meta:
        abstract=True
    timestamp = models.DateTimeField(auto_now_add=True)

class BaseClass2(models.Model):
    class Meta:
        abstract=True
    other_field = models.IntegerField()

class AdBreak(BaseClass1):
    class Meta:
        db_table = "ad_break"
    ad_break_id = models.AutoField(primary_key=True)
    ... # Other fields

class AdBreakStatus(BaseClass2):
    class Meta:
        db_table = "ad_break_status"
    ad_break = models.ForeignKey(AdBreak)
    ... # Other Fields

Body:
Do this first:

python manage.py makemigrations 'your-app'
python manage.py migrate

If the above fails to detect changes, remove migration folder, open your database and open table django_migrations. You will see migrations listed associated to your app, delete the records and now execute makemigrations and migrate.


问:
Can not connect to elasticsearch container in docker
I'm trying to use the official elasticsearch image for docker and I followed this guide but when I'm trying to connect to elasticsearch cluster I had an exception NoNodeAvailableException[None of the configured nodes are available

my code

```<code>TransportClient client = new PreBuiltTransportClient(Settings.builder().put("cluster.name", "docker-cluster")
                .build())
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
</code>```

To run elasticsearch container I used this command

```<code>docker run -p 9200:9200 -p 9300:9300 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" docker.elastic.co/elasticsearch/elasticsearch:5.2.2
</code>```

and when I open the browser on localhost:9200 the browser shows this text

```<code>{
  "name" : "J5oojcO",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "SfkgAJmaT_Sb3erfYUl7sQ",
  "version" : {
    "number" : "5.2.2",
    "build_hash" : "f9d9b74",
    "build_date" : "2017-02-24T17:26:45.835Z",
    "build_snapshot" : false,
    "lucene_version" : "6.4.1"
  },
  "tagline" : "You Know, for Search"
}
</code>```

docker logs

```<code>[2017-03-28T23:57:47,804][INFO ][o.e.n.Node               ] [] initializing ...
[2017-03-28T23:57:48,214][INFO ][o.e.e.NodeEnvironment    ] [S5IAW08] using [1] data paths, mounts [[/ (overlay)]], net usable_space [54.8gb], net total_space [62.7gb], spins? [possibly], types [overlay]
[2017-03-28T23:57:48,216][INFO ][o.e.e.NodeEnvironment    ] [S5IAW08] heap size [1.9gb], compressed ordinary object pointers [true]
[2017-03-28T23:57:48,224][INFO ][o.e.n.Node               ] node name [S5IAW08] derived from node ID [S5IAW08lQvupW8s_e8btAQ]; set [node.name] to override
[2017-03-28T23:57:48,233][INFO ][o.e.n.Node               ] version[5.2.2], pid[1], build[f9d9b74/2017-02-24T17:26:45.835Z], OS[Linux/4.9.12-moby/amd64], JVM[Oracle Corporation/OpenJDK 64-Bit Server VM/1.8.0_92-internal/25.92-b14]
[2017-03-28T23:57:52,719][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [aggs-matrix-stats]
[2017-03-28T23:57:52,719][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [ingest-common]
[2017-03-28T23:57:52,720][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [lang-expression]
[2017-03-28T23:57:52,721][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [lang-groovy]
[2017-03-28T23:57:52,721][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [lang-mustache]
[2017-03-28T23:57:52,722][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [lang-painless]
[2017-03-28T23:57:52,722][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [percolator]
[2017-03-28T23:57:52,723][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [reindex]
[2017-03-28T23:57:52,723][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [transport-netty3]
[2017-03-28T23:57:52,724][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [transport-netty4]
[2017-03-28T23:57:52,727][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded plugin [x-pack]
[2017-03-28T23:57:54,117][WARN ][o.e.d.s.g.GroovyScriptEngineService] [groovy] scripts are deprecated, use [painless] scripts instead
[2017-03-28T23:58:00,388][INFO ][o.e.n.Node               ] initialized
[2017-03-28T23:58:00,389][INFO ][o.e.n.Node               ] [S5IAW08] starting ...
[2017-03-28T23:58:00,920][WARN ][i.n.u.i.MacAddressUtil   ] Failed to find a usable hardware address from the network interfaces; using random bytes: 53:a4:67:2d:77:c8:57:b6
[2017-03-28T23:58:01,073][INFO ][o.e.t.TransportService   ] [S5IAW08] publish_address {127.0.0.1:9300}, bound_addresses {127.0.0.1:9300}
[2017-03-28T23:58:04,224][INFO ][o.e.c.s.ClusterService   ] [S5IAW08] new_master {S5IAW08}{S5IAW08lQvupW8s_e8btAQ}{4xwcEYRxTmi7-bRwYXHbYA}{127.0.0.1}{127.0.0.1:9300}, reason: zen-disco-elected-as-master ([0] nodes joined)
[2017-03-28T23:58:04,293][INFO ][o.e.h.HttpServer         ] [S5IAW08] publish_address {172.17.0.2:9200}, bound_addresses {[::]:9200}
[2017-03-28T23:58:04,295][INFO ][o.e.n.Node               ] [S5IAW08] started
[2017-03-28T23:58:04,444][INFO ][o.e.g.GatewayService     ] [S5IAW08] recovered [0] indices into cluster_state
[2017-03-28T23:58:05,622][INFO ][o.e.l.LicenseService     ] [S5IAW08] license [c0268fbc-15ce-418c-aacc-5b9d7c3cbaf7] mode [trial] - valid
[2017-03-28T23:58:10,747][INFO ][o.e.c.m.MetaDataCreateIndexService] [S5IAW08] [.monitoring-data-2] creating index, cause [auto(bulk api)], templates [.monitoring-data-2], shards [1]/[1], mappings [node, _default_, logstash, cluster_info, kibana]
[2017-03-28T23:58:11,017][INFO ][o.e.c.m.MetaDataCreateIndexService] [S5IAW08] [.monitoring-es-2-2017.03.28] creating index, cause [auto(bulk api)], templates [.monitoring-es-2], shards [1]/[1], mappings [shards, _default_, node, index_stats, index_recovery, cluster_state, cluster_stats, indices_stats, node_stats]
[2017-03-28T23:58:11,598][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [cluster_stats]
[2017-03-28T23:58:11,852][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [node_stats]
[2017-03-28T23:58:22,105][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [cluster_stats]
[2017-03-28T23:58:22,192][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [indices_stats]
[2017-03-28T23:58:22,264][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [index_stats]
[2017-03-28T23:58:44,237][INFO ][o.e.m.j.JvmGcMonitorService] [S5IAW08] [gc][43] overhead, spent [668ms] collecting in the last [1.5s]
[2017-03-28T23:59:14,284][INFO ][o.e.m.j.JvmGcMonitorService] [S5IAW08] [gc][73] overhead, spent [306ms] collecting in the last [1s]
[2017-03-29T00:00:03,456][INFO ][o.e.c.m.MetaDataCreateIndexService] [S5IAW08] [.monitoring-es-2-2017.03.29] creating index, cause [auto(bulk api)], templates [.monitoring-es-2], shards [1]/[1], mappings [shards, _default_, node, index_stats, index_recovery, cluster_state, cluster_stats, indices_stats, node_stats]
[2017-03-29T00:00:03,685][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.29/FulovogFThmVCpL0RS99Hg] update_mapping [cluster_stats]
[2017-03-29T00:00:03,774][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.29/FulovogFThmVCpL0RS99Hg] update_mapping [node_stats]
[2017-03-29T00:00:03,856][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.29/FulovogFThmVCpL0RS99Hg] update_mapping [indices_stats]
[2017-03-29T00:00:03,909][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.29/FulovogFThmVCpL0RS99Hg] update_mapping [index_stats]
</code>```

health link

```<code>1490745899 00:04:59 docker-cluster yellow 1 1 3 3 0 0 3 0 - 50.0%
</code>```

Thanks in advance.

UPDATE

The official guide says that the image is built with X-Pack, so I tried to disable xpack security, and I succeeded to connect to elastic seacrh container using 127.0.0.1:9300

Thanks.

答:
I don't know why the docs instruct to do that, but when you pass 127.0.0.1 as the transport host the binding is made only to that address, and therefore is not accessible outside the container.

Try to define the transport.host as 0.0.0.0 too, so it binds also to the container IP.

Body:
I'm trying to use the official elasticsearch image for docker and I followed this guide but when I'm trying to connect to elasticsearch cluster I had an exception NoNodeAvailableException[None of the configured nodes are available

my code

TransportClient client = new PreBuiltTransportClient(Settings.builder().put("cluster.name", "docker-cluster")
                .build())
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

To run elasticsearch container I used this command

docker run -p 9200:9200 -p 9300:9300 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" docker.elastic.co/elasticsearch/elasticsearch:5.2.2

and when I open the browser on localhost:9200 the browser shows this text

{
  "name" : "J5oojcO",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "SfkgAJmaT_Sb3erfYUl7sQ",
  "version" : {
    "number" : "5.2.2",
    "build_hash" : "f9d9b74",
    "build_date" : "2017-02-24T17:26:45.835Z",
    "build_snapshot" : false,
    "lucene_version" : "6.4.1"
  },
  "tagline" : "You Know, for Search"
}

docker logs

[2017-03-28T23:57:47,804][INFO ][o.e.n.Node               ] [] initializing ...
[2017-03-28T23:57:48,214][INFO ][o.e.e.NodeEnvironment    ] [S5IAW08] using [1] data paths, mounts [[/ (overlay)]], net usable_space [54.8gb], net total_space [62.7gb], spins? [possibly], types [overlay]
[2017-03-28T23:57:48,216][INFO ][o.e.e.NodeEnvironment    ] [S5IAW08] heap size [1.9gb], compressed ordinary object pointers [true]
[2017-03-28T23:57:48,224][INFO ][o.e.n.Node               ] node name [S5IAW08] derived from node ID [S5IAW08lQvupW8s_e8btAQ]; set [node.name] to override
[2017-03-28T23:57:48,233][INFO ][o.e.n.Node               ] version[5.2.2], pid[1], build[f9d9b74/2017-02-24T17:26:45.835Z], OS[Linux/4.9.12-moby/amd64], JVM[Oracle Corporation/OpenJDK 64-Bit Server VM/1.8.0_92-internal/25.92-b14]
[2017-03-28T23:57:52,719][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [aggs-matrix-stats]
[2017-03-28T23:57:52,719][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [ingest-common]
[2017-03-28T23:57:52,720][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [lang-expression]
[2017-03-28T23:57:52,721][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [lang-groovy]
[2017-03-28T23:57:52,721][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [lang-mustache]
[2017-03-28T23:57:52,722][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [lang-painless]
[2017-03-28T23:57:52,722][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [percolator]
[2017-03-28T23:57:52,723][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [reindex]
[2017-03-28T23:57:52,723][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [transport-netty3]
[2017-03-28T23:57:52,724][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded module [transport-netty4]
[2017-03-28T23:57:52,727][INFO ][o.e.p.PluginsService     ] [S5IAW08] loaded plugin [x-pack]
[2017-03-28T23:57:54,117][WARN ][o.e.d.s.g.GroovyScriptEngineService] [groovy] scripts are deprecated, use [painless] scripts instead
[2017-03-28T23:58:00,388][INFO ][o.e.n.Node               ] initialized
[2017-03-28T23:58:00,389][INFO ][o.e.n.Node               ] [S5IAW08] starting ...
[2017-03-28T23:58:00,920][WARN ][i.n.u.i.MacAddressUtil   ] Failed to find a usable hardware address from the network interfaces; using random bytes: 53:a4:67:2d:77:c8:57:b6
[2017-03-28T23:58:01,073][INFO ][o.e.t.TransportService   ] [S5IAW08] publish_address {127.0.0.1:9300}, bound_addresses {127.0.0.1:9300}
[2017-03-28T23:58:04,224][INFO ][o.e.c.s.ClusterService   ] [S5IAW08] new_master {S5IAW08}{S5IAW08lQvupW8s_e8btAQ}{4xwcEYRxTmi7-bRwYXHbYA}{127.0.0.1}{127.0.0.1:9300}, reason: zen-disco-elected-as-master ([0] nodes joined)
[2017-03-28T23:58:04,293][INFO ][o.e.h.HttpServer         ] [S5IAW08] publish_address {172.17.0.2:9200}, bound_addresses {[::]:9200}
[2017-03-28T23:58:04,295][INFO ][o.e.n.Node               ] [S5IAW08] started
[2017-03-28T23:58:04,444][INFO ][o.e.g.GatewayService     ] [S5IAW08] recovered [0] indices into cluster_state
[2017-03-28T23:58:05,622][INFO ][o.e.l.LicenseService     ] [S5IAW08] license [c0268fbc-15ce-418c-aacc-5b9d7c3cbaf7] mode [trial] - valid
[2017-03-28T23:58:10,747][INFO ][o.e.c.m.MetaDataCreateIndexService] [S5IAW08] [.monitoring-data-2] creating index, cause [auto(bulk api)], templates [.monitoring-data-2], shards [1]/[1], mappings [node, _default_, logstash, cluster_info, kibana]
[2017-03-28T23:58:11,017][INFO ][o.e.c.m.MetaDataCreateIndexService] [S5IAW08] [.monitoring-es-2-2017.03.28] creating index, cause [auto(bulk api)], templates [.monitoring-es-2], shards [1]/[1], mappings [shards, _default_, node, index_stats, index_recovery, cluster_state, cluster_stats, indices_stats, node_stats]
[2017-03-28T23:58:11,598][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [cluster_stats]
[2017-03-28T23:58:11,852][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [node_stats]
[2017-03-28T23:58:22,105][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [cluster_stats]
[2017-03-28T23:58:22,192][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [indices_stats]
[2017-03-28T23:58:22,264][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.28/KmXIrx3-R-G_ngo8rfIcZA] update_mapping [index_stats]
[2017-03-28T23:58:44,237][INFO ][o.e.m.j.JvmGcMonitorService] [S5IAW08] [gc][43] overhead, spent [668ms] collecting in the last [1.5s]
[2017-03-28T23:59:14,284][INFO ][o.e.m.j.JvmGcMonitorService] [S5IAW08] [gc][73] overhead, spent [306ms] collecting in the last [1s]
[2017-03-29T00:00:03,456][INFO ][o.e.c.m.MetaDataCreateIndexService] [S5IAW08] [.monitoring-es-2-2017.03.29] creating index, cause [auto(bulk api)], templates [.monitoring-es-2], shards [1]/[1], mappings [shards, _default_, node, index_stats, index_recovery, cluster_state, cluster_stats, indices_stats, node_stats]
[2017-03-29T00:00:03,685][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.29/FulovogFThmVCpL0RS99Hg] update_mapping [cluster_stats]
[2017-03-29T00:00:03,774][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.29/FulovogFThmVCpL0RS99Hg] update_mapping [node_stats]
[2017-03-29T00:00:03,856][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.29/FulovogFThmVCpL0RS99Hg] update_mapping [indices_stats]
[2017-03-29T00:00:03,909][INFO ][o.e.c.m.MetaDataMappingService] [S5IAW08] [.monitoring-es-2-2017.03.29/FulovogFThmVCpL0RS99Hg] update_mapping [index_stats]

health link

1490745899 00:04:59 docker-cluster yellow 1 1 3 3 0 0 3 0 - 50.0%

Thanks in advance.

UPDATE

The official guide says that the image is built with X-Pack, so I tried to disable xpack security, and I succeeded to connect to elastic seacrh container using 127.0.0.1:9300

Thanks.


问:
LINQ ICollection of a Model to a string with Name and Surname from within another model
I have a field which is a collection of a model ICollection "Parties", which is in another model "Matter". I want to extract the Name and Surname of each party and separate with a "/" using LINQ. I am putting these into a field called Investors, the second last item.

This is my query:

```<code>    var matterQuery = (from matter in context.Matters
  select new
  {
      matter.ID,
      matter.AttorneyRef,
      matter.Status,
      matter.ProductType,
      matter.IsDiscarded,
      matter.Base_CreatedDate,
      matter.Base_CreatedBy,
      matter.BranchID,
      matter.InstitutionID,
      matter.InvestmentTypeID,

      StatusName = matter.MatterStatu != null ? matter.MatterStatu.Name : string.Empty,
      ProductTypeName = matter.ProductType1 != null ? matter.ProductType1.Name : string.Empty,
      AccountNumber = matter.Account != null ? matter.Account.AccountNumber : string.Empty,
      CreatedBy = matter.Paralegal != null ? matter.Paralegal
      : matter.AspNetUser != null ? matter.AspNetUser.FirstName + " " + matter.AspNetUser.LastName
      : matter.User != null ? matter.User.Firstname + " " + matter.User.Surname
      : string.Empty,
      IntermediaryName = matter.IntermediaryBranch != null ? matter.IntermediaryBranch.Intermediary.Name
      : matter.Attorney != null ? matter.Attorney.AttorneyName
      : string.Empty,
      CloseRequested = matter.CloseAccounts.Where(x => x.Status == (int)CloseAccountStatusEnum.Authorised).Count() > 0,
      StatementRequested = matter.Account != null ? matter.Account.StatementRequested : false,
      RequestedDate = matter.RequestedDate.HasValue ? matter.RequestedDate.Value : matter.Base_CreatedDate,
      Investors = matter.Parties.Select(x => x.Name.ToString()).Concat(matter.Parties.Select(x => x.Surname.ToString())),
      SoftLock = matter.SoftLock,
  })
   .AsQueryable();
</code>```

I need this in 1 long string as I am doing a search on the results for a filter and the following line:

```<code>(x.Investors != null && x.Investors.ToLower().Contains(search))
</code>```

requires it be in a string format. I want to display the results as "Name1 Surname1 / Name2 Surname2 / ..."

How can I do this?

EDIT:

I have tried Join and Aggregate but I get the errors:

base {System.SystemException} = {System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
   at System.Da...

and...

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Aggregate[String](System.Collections.Generic.IEnumerable1[System.String], System.Func3[System.String,System.String,System.String])'

答:
If i did understand your problem right, you have two options:

Bring all results from database and do the join locally

Call a sp to do that

Check this Is there a "for xml path" equivalent in LINQ to SQL?

Body:
I have a field which is a collection of a model ICollection "Parties", which is in another model "Matter". I want to extract the Name and Surname of each party and separate with a "/" using LINQ. I am putting these into a field called Investors, the second last item.

This is my query:

    var matterQuery = (from matter in context.Matters
  select new
  {
      matter.ID,
      matter.AttorneyRef,
      matter.Status,
      matter.ProductType,
      matter.IsDiscarded,
      matter.Base_CreatedDate,
      matter.Base_CreatedBy,
      matter.BranchID,
      matter.InstitutionID,
      matter.InvestmentTypeID,

      StatusName = matter.MatterStatu != null ? matter.MatterStatu.Name : string.Empty,
      ProductTypeName = matter.ProductType1 != null ? matter.ProductType1.Name : string.Empty,
      AccountNumber = matter.Account != null ? matter.Account.AccountNumber : string.Empty,
      CreatedBy = matter.Paralegal != null ? matter.Paralegal
      : matter.AspNetUser != null ? matter.AspNetUser.FirstName + " " + matter.AspNetUser.LastName
      : matter.User != null ? matter.User.Firstname + " " + matter.User.Surname
      : string.Empty,
      IntermediaryName = matter.IntermediaryBranch != null ? matter.IntermediaryBranch.Intermediary.Name
      : matter.Attorney != null ? matter.Attorney.AttorneyName
      : string.Empty,
      CloseRequested = matter.CloseAccounts.Where(x => x.Status == (int)CloseAccountStatusEnum.Authorised).Count() > 0,
      StatementRequested = matter.Account != null ? matter.Account.StatementRequested : false,
      RequestedDate = matter.RequestedDate.HasValue ? matter.RequestedDate.Value : matter.Base_CreatedDate,
      Investors = matter.Parties.Select(x => x.Name.ToString()).Concat(matter.Parties.Select(x => x.Surname.ToString())),
      SoftLock = matter.SoftLock,
  })
   .AsQueryable();

I need this in 1 long string as I am doing a search on the results for a filter and the following line:

(x.Investors != null && x.Investors.ToLower().Contains(search))

requires it be in a string format. I want to display the results as "Name1 Surname1 / Name2 Surname2 / ..."

How can I do this?

EDIT:

I have tried Join and Aggregate but I get the errors:

base {System.SystemException} = {System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
   at System.Da...

and...

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Aggregate[String](System.Collections.Generic.IEnumerable1[System.String], System.Func3[System.String,System.String,System.String])'


问:
Data in Relay not fetched when using it with react-navigation in React Native
I'm trying to setup my app with Relay and react-navigation, following the hints that were discussed in this GitHub issue. Also note that I used create-react-native-app to create the project.

This is what my setup looks like:

App.js

```<code>Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('https://api.graph.cool/relay/v1/ciyeih9590fhl0162e5zh1z4h', {
    headers: {
    },
  })
)

const RootNavigationStack = StackNavigator({
  PokemonList: {
    screen: PokemonList
  }
})

export default class App extends React.Component {
  render() {
    return <RootNavigationStack />
  }
}
</code>```

PokemonList.js

```<code>class IndexRoute extends Route {
  static queries = {
    viewer: () => Relay.QL`query { viewer }`
  }
  static routeName = 'IndexRoute'
}

export default class PokemonList extends React.Component {

  render() {
    return (
      <Relay.RootContainer
        Component={PokemonListRelayContainer}
        route={new IndexRoute()}
        renderFetched={(data) => {
          console.log('PokemonList - renderFetched', data)
          return <Text>Test</Text>
        }}
      />
    )
  }

}

const PokemonListRelayContainer = Relay.createContainer(PokemonList, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        id
        allPokemons(first: 10) {
          edges {
            node {
              id
              name
            }
          }
        }
      }
    `
  }
})
</code>```

The logging statement in renderFetched is being executed, but for some reason the datais empty:

```<code>PokemonList - renderFetched {"viewer":{"__dataID__":"viewer-fixed","__fragments__":{"0::client":[{}]}}}
</code>```

Any idea what I'm missing in this setup?

答:
I solved the issue myself, so apparently the PokemonList, being my root component, didn't get access to the data that was requested - though I assume it actually was loaded, but due to Relay's data masking wasn't visible to the component.

The solution I came up with to wrap PokemonList in another component that would render the Relay.RootContainer and then go from there with my conventional Relay setup.

This is what it now looks likes:

PokemonListWrapper.js

```<code>class PokemonListWrapper extends React.Component {
  render() {
    return (
      <Relay.RootContainer
        Component={PokemonList}
        route={new IndexRoute()}
        renderFetched={data => <PokemonList {...this.props} {...data}/>}
      />
    )
  }
}
</code>```

PokemonList.js

```<code>class PokemonList extends React.Component {

  render() {
    return (
      <ScrollView>
        {this.props.viewer.allPokemons.edges.map(pokemonEdge => (
          <Text key={pokemonEdge.node.id}>{pokemonEdge.node.name}</Text>
        ))}
      </ScrollView>
    )
  }

}

export default Relay.createContainer(PokemonList, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        id
        allPokemons(first: 10) {
          edges {
            node {
              id
              name
            }
          }
        }
      }
    `
  }
})
</code>```

App.js

```<code>Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('https://api.graph.cool/relay/v1/ciyeih9590fhl0162e5zh1z4h')
)

export class IndexRoute extends Route {
  static queries = {
    viewer: () => Relay.QL`query { viewer }`
  }
  static routeName = 'IndexRoute'
}

const RootNavigationStack = StackNavigator({
  PokemonList: {
    screen: PokemonListWrapper
  }
})

export default class App extends React.Component {
  render() {
    return (
      <RootNavigationStack />
    )
  }
}
</code>```

Body:
I'm trying to setup my app with Relay and react-navigation, following the hints that were discussed in this GitHub issue. Also note that I used create-react-native-app to create the project.

This is what my setup looks like:

App.js

Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('https://api.graph.cool/relay/v1/ciyeih9590fhl0162e5zh1z4h', {
    headers: {
    },
  })
)

const RootNavigationStack = StackNavigator({
  PokemonList: {
    screen: PokemonList
  }
})

export default class App extends React.Component {
  render() {
    return <RootNavigationStack />
  }
}

PokemonList.js

class IndexRoute extends Route {
  static queries = {
    viewer: () => Relay.QL`query { viewer }`
  }
  static routeName = 'IndexRoute'
}

export default class PokemonList extends React.Component {

  render() {
    return (
      <Relay.RootContainer
        Component={PokemonListRelayContainer}
        route={new IndexRoute()}
        renderFetched={(data) => {
          console.log('PokemonList - renderFetched', data)
          return <Text>Test</Text>
        }}
      />
    )
  }

}

const PokemonListRelayContainer = Relay.createContainer(PokemonList, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        id
        allPokemons(first: 10) {
          edges {
            node {
              id
              name
            }
          }
        }
      }
    `
  }
})

The logging statement in renderFetched is being executed, but for some reason the datais empty:

PokemonList - renderFetched {"viewer":{"__dataID__":"viewer-fixed","__fragments__":{"0::client":[{}]}}}

Any idea what I'm missing in this setup?

Body:
I solved the issue myself, so apparently the PokemonList, being my root component, didn't get access to the data that was requested - though I assume it actually was loaded, but due to Relay's data masking wasn't visible to the component.

The solution I came up with to wrap PokemonList in another component that would render the Relay.RootContainer and then go from there with my conventional Relay setup.

This is what it now looks likes:

PokemonListWrapper.js

class PokemonListWrapper extends React.Component {
  render() {
    return (
      <Relay.RootContainer
        Component={PokemonList}
        route={new IndexRoute()}
        renderFetched={data => <PokemonList {...this.props} {...data}/>}
      />
    )
  }
}

PokemonList.js

class PokemonList extends React.Component {

  render() {
    return (
      <ScrollView>
        {this.props.viewer.allPokemons.edges.map(pokemonEdge => (
          <Text key={pokemonEdge.node.id}>{pokemonEdge.node.name}</Text>
        ))}
      </ScrollView>
    )
  }

}

export default Relay.createContainer(PokemonList, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        id
        allPokemons(first: 10) {
          edges {
            node {
              id
              name
            }
          }
        }
      }
    `
  }
})

App.js

Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('https://api.graph.cool/relay/v1/ciyeih9590fhl0162e5zh1z4h')
)

export class IndexRoute extends Route {
  static queries = {
    viewer: () => Relay.QL`query { viewer }`
  }
  static routeName = 'IndexRoute'
}

const RootNavigationStack = StackNavigator({
  PokemonList: {
    screen: PokemonListWrapper
  }
})

export default class App extends React.Component {
  render() {
    return (
      <RootNavigationStack />
    )
  }
}


问:
Complex mathematical horizontal parallax easing function
I'm currently diving into parallax effects on the web.

Parallax scrolling is a technique in computer graphics and web design, where background images move by the camera slower than foreground images, creating an illusion of depth in a 2D scene and adding to the immersion.
  ~ Wikipedia

I want to create a little container (could be an image, or any block level element) and move it across the screen horizontally as the user scrolls.

The effect should be scalable across all viewports. Meaning that the hight and the width of the element that the element is moving across should not matter.

When the user has scrolled half of the height of the screen the "moving element" should be in the exact center. Since the user will have scrolled half of the screen the element will be vertically already. We're only worried about horizontally right now.

I've thought about this question for a while and came up with a pretty good idea of how.

Take the hight and the width of the element you want the "moving element" to move across. For example a screen that is 1000px tall and 600px wide.

Divide the width by the height. For example (600px / 1000px = 3/5 = 0.6)

Take the amount of pixels the user scrolled and multiply it by the number we just created. For example (500px * 0.6 = 300px). As you can see this is the exact center.

Move the element across the screen by the amount of pixels just calculated.

This calculation works fine even for every screen size, however it's linear. Meaning that the element will move at the same speed across the screen all the time. Let me show you what I mean.

Let's draw out a screen size. (Let's say 1000 * 500)

Calculate two points for this graph ->

screen factor: (500 / 1000) = 0.5
  1. The first point is going to be easy. Let's say we scrolled exactly 0px -> (0.5 * 0) = 0
  The "Moving element" will not have moved at all.
  2. For the second element we'll take the center. Just for convenience.

The vertical center is at 500px -> (0.5 * 500) = 250 px (Exactly the horizontal center)

Put the results in a graph and draw a line through the points.

In the graph above you can see that whenever the user scrolls down the "moving element" will follow the line (the values on the x-axis).

My question

I really hope I described all that well enough to understand. Now on to my question.

What I want to create is a moving element that would go faster on the edge of the screen and slow down a bit in the middle. If we were to draw that out in the same way we just did. (Creating a graph where we can take the amount of pixels scrolled and see where the element should be positioned horizontally) it would look like this:

Sorry for the poor quality of the image but this is the part I'm having problems with.

As you can see in this graph the "moving element" wouldn't be moving all that much in the middle of the graph. (I over did it a bit in my drawing but you get the general idea.)

What I need is a mathematical function that takes three parameters (Screen height, width and the amount of pixels scrolled) and returns the horizontal position of the "moving element".

My idea:

My idea was to position the element in the dead center of the page and then to move it left and right (translations using CSS and JavaScript) based on how far there has been scrolled.

The graph would look something like this:

The (Hand drawn) graph above would be true for a screen that's 1000x600px since the "moving element" translates -300px when no scrolling has been done and 300px when 100% has been scrolled.

However I have no idea on how to create a mathematical function that would be true for every screen size.

To be clear I need a function that "always" starts at Y= (-screen-width/2) and X = 0. It should always cross the point (sreen-height; (screen-width//2)) and the function should be in a form of x^3 (To get the right easing)

I really hope I explained myself well enough and I really hope somebody can help me out here.

答:
Answer from math.stackexchange

Besides asking my question here I also went ahead and posted this question on math.stackexchange.com. Stackoverflow's mathematical sister site. Somebody there helped me find an answer to my question.

The function had to be a function that would output the moving-element it's horizontal position in pixels relative to the horizontal center of the page based on the amount of pixels scrolled since the element was first visible. The function would have to be "steeper" on the edges and ease into a short stop in the middle and be usable across every possible screen size. Meaning that the mathematical function would have to be positioned based on two variables, screen height and -width.

The answer they came up with on math.stackexchange:

In this example s-width is the width of the screen in pixels. s-height is the height of the screen in pixels. px-scrolled is the amount of pixels scrolled since the element was first visible.

The output pos is the moving elements horizontal position in pixels relative to the center of the screen.

If you put all this math into JavaScript you get the following:

```<code>var pos = ((4*win_width)/(Math.pow(win_height, 3))) * Math.pow(px_since_visible - (win_height/2),3)
</code>```

There is a working example available on codepen. You can find it here.

Body:
Answer from math.stackexchange

Besides asking my question here I also went ahead and posted this question on math.stackexchange.com. Stackoverflow's mathematical sister site. Somebody there helped me find an answer to my question.

The function had to be a function that would output the moving-element it's horizontal position in pixels relative to the horizontal center of the page based on the amount of pixels scrolled since the element was first visible. The function would have to be "steeper" on the edges and ease into a short stop in the middle and be usable across every possible screen size. Meaning that the mathematical function would have to be positioned based on two variables, screen height and -width.

The answer they came up with on math.stackexchange:

In this example s-width is the width of the screen in pixels. s-height is the height of the screen in pixels. px-scrolled is the amount of pixels scrolled since the element was first visible.

The output pos is the moving elements horizontal position in pixels relative to the center of the screen.

If you put all this math into JavaScript you get the following:

var pos = ((4*win_width)/(Math.pow(win_height, 3))) * Math.pow(px_since_visible - (win_height/2),3)

There is a working example available on codepen. You can find it here.


问:
SignalR unavailable reasons
I'm developing a real time application using SignalR. Where SigalR will be hosted in an ASP.NET (VB.NET v.2010)

I have the following questions regarding SignalR availability:

What are the cases on which a client could not connect to the signalR?

Is SignalR is trusted to support Real Time Applications?

To have a static (shared) array in the hub, will it affect the performance if the array is too big?

Since the user of the client app will connect to the ASP.NET app via web-service, then is there a cases where the client app can consume the web-service and can not connect to the SignalR?

Can SignalR keep alive for long time, since my app will be working 24/7?´

答:
What are the cases on which a client could not connect to the signalR?

Network failure will do it. SignalR will attempt to reconnect due to a transient failure. Or your app being down. :-)

Is SignalR is trusted to support Real Time Applications?

Yep. I'm currently working on an app that has around 3K continuously active users and we never have any widespread connectivity problems. In fact, I don't even recall seeing a support ticket related to SignalR connectivity.

To have a static (shared) array in the hub, will it affect the performance if the array is too big?

Well, pursuant to available memory, you should be fine. Be careful with threading. If you are locking to access an array that is frequently updated, watch out for lock contention.

Since the user of the client app will connect to the ASP.NET app via web-service, then is there a cases where the client app can consume the web-service and can not connect to the SignalR?

I can't envision a scenario. A proper SignalR implementation would be available if network connectivity is available.

Can SignalR keep alive for long time, since my app will be working
  24/7?

Yep. SignalR will attempt to reconnect due to transient network interruptions. You can also handle events on the client for disconnect to attempt to reconnect after SignalR gives up.

Title: SignalR unavailable reasons


问:
SQL-Server - Microsoft Access (linked server)
I am trying to import tables and data from a Microsoft Access database into SQL server, but I have a problem:

At the company where I work, they use an Access Application to store data in an Access database. I would like to automatically import the data from this database in SQL Server without reprogramming the Access application. (I didn't build it).

I think there are a few ways to do this, but neither one of them really worked:

Creating linked tables using the Microsoft Migration Assistant disables me to edit or add new tables or columns (without rerunning the Assistant each time I made an adjustment.

Create a data import and schedule this is not working, because SQL Server keeps saying that I have to upgrade to SQL Server standard, developer etc version. (I also think that this is not the right way to do this.)

Create a linked server to my Access database, but in this situation I can't figure out which ODBC driver, bit version and rights I have to use. (I keep getting errormessages)

I think the linked server option is the best option, but maybe you guys have some other ideas? Or maybe does someone has experience importing Access db data? Please let me know!

Tom Smits

答:
The SQL Server Migration Assistant (SSMA) is the recommended tool.

You'll find a link for download of the Access version at that page.

It's a comprehensive tool, so you don't face a 15 minutes task, but it will handle everything you can imagine.


问:
Remove an array depending its values
I have this array :

```<code>Array
(
[0] => Array
    (
        [complet_title] => test1
        [have_background] => 0
        [condition_type] => 1
        [state] => 1
    )

[1] => Array
    (
        [complet_title] => test2
        [have_background] => 1
        [condition_type] => 1
        [state] => 0
    )
)
</code>```

My php code :

```<code>foreach($a_sliders as $k => $slider){
        switch($slider['condition_type']){
            case 1:
                if($slider['state'] == 1){
                    if(Test::check($id, $server)){
                        unset($a_sliders[$k]);
                    }else{

                    }
                }
        }
    }
</code>```

In the else I want to delete the sub-array with the condition_type = 1 and state = 0. It's possible to do that whitout a suplimentaire foreach ? Can you help me please ? Thx in advance and sorry for my english

答:
```<code>array_filter($array, function($v){return  ($v['condition_type'] != 1) || ($v['state'] != 0);})
</code>```

Title: Remove an array depending its values

Body:
I have this array :

Array
(
[0] => Array
    (
        [complet_title] => test1
        [have_background] => 0
        [condition_type] => 1
        [state] => 1
    )

[1] => Array
    (
        [complet_title] => test2
        [have_background] => 1
        [condition_type] => 1
        [state] => 0
    )
)

My php code :

foreach($a_sliders as $k => $slider){
        switch($slider['condition_type']){
            case 1:
                if($slider['state'] == 1){
                    if(Test::check($id, $server)){
                        unset($a_sliders[$k]);
                    }else{

                    }
                }
        }
    }

In the else I want to delete the sub-array with the condition_type = 1 and state = 0. It's possible to do that whitout a suplimentaire foreach ? Can you help me please ? Thx in advance and sorry for my english


问:
Creating an APK using MSBuild command line error (PackageForAndroid or SignAndroidPackage)
So I have been trying to create an APK in Release mode using the MSBuild command line executable.

Here is the contents of my batch file which I created:

```<code>ECHO Building DsdMobile Solution... >CON
cd "C:\Ross\DEVELOPMENT\HANDHELD\Android\Dsd Mobile MaterialDesign"

"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe" DsdMobile.sln /P:Configuration=Release /v:quiet /t:Clean /nologo

"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe" DsdMobile.sln /P:Configuration=Release /v:quiet /t:Rebuild,PackageForAndroid /nologo
</code>```

The first line I change the directory to my solution location.
Next, I do a Clean

Last, I do a Rebuild and PackageForAndroid (which I am expecting a ...apk file in my bin release folder. An apk is never created and I get an error.

The build is successful, but I get an error:

```<code>"C:Ross\Development\Handheld\Android\Dsd Mobile MaterialDesign\DsdMobile.sln.metaproj : error MSB4057: The target "PackageForAndroid" does not exists in the project. [C:\Ross\DEVELOPMENT\HANDHELD\Android\Dsd Mobile MaterialDesign\DsdMobile.sln]
</code>```

I have also tried to use SignAndroidPackage's :t/ parameter, but this also fails with the same error:

```<code>"C:Ross\Development\Handheld\Android\Dsd Mobile MaterialDesign\DsdMobile.sln.metaproj : error MSB4057: The target "SignAndroidPackage" does not exists in the project. [C:\Ross\DEVELOPMENT\HANDHELD\Android\Dsd Mobile MaterialDesign\DsdMobile.sln]
</code>```

The resource I have been using was from a PowerShell script:

https://gist.github.com/postb99/8319234

答: Try building the Android csproj file instead of the solution file.</p>

ContentLicense: CC BY-SA 4.0

Body:
So I have been trying to create an APK in Release mode using the MSBuild command line executable.

Here is the contents of my batch file which I created:

ECHO Building DsdMobile Solution... >CON
cd "C:\Ross\DEVELOPMENT\HANDHELD\Android\Dsd Mobile MaterialDesign"

"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe" DsdMobile.sln /P:Configuration=Release /v:quiet /t:Clean /nologo

"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe" DsdMobile.sln /P:Configuration=Release /v:quiet /t:Rebuild,PackageForAndroid /nologo

The first line I change the directory to my solution location.
Next, I do a Clean

Last, I do a Rebuild and PackageForAndroid (which I am expecting a ...apk file in my bin release folder. An apk is never created and I get an error.

The build is successful, but I get an error:

"C:Ross\Development\Handheld\Android\Dsd Mobile MaterialDesign\DsdMobile.sln.metaproj : error MSB4057: The target "PackageForAndroid" does not exists in the project. [C:\Ross\DEVELOPMENT\HANDHELD\Android\Dsd Mobile MaterialDesign\DsdMobile.sln]

I have also tried to use SignAndroidPackage's :t/ parameter, but this also fails with the same error:

"C:Ross\Development\Handheld\Android\Dsd Mobile MaterialDesign\DsdMobile.sln.metaproj : error MSB4057: The target "SignAndroidPackage" does not exists in the project. [C:\Ross\DEVELOPMENT\HANDHELD\Android\Dsd Mobile MaterialDesign\DsdMobile.sln]

The resource I have been using was from a PowerShell script:

https://gist.github.com/postb99/8319234


问:
Pointers and write access violation
So I got an assignment in school that includes 3 strix (int ***)
I need to write some int values into "pointers", but I get an error when I attempt to do so.  Here's my code:

```<code>void main()
{
    unsigned int size, i;
    int arr[SIZE];
    int ** pointers;
    int ascend_flag;

    printf("Please enter the number of items:\n");
    scanf("%u", &size);
    for (i = 0; i < size; i++)
        scanf("%d", &arr[i]);
    scanf("%d", &ascend_flag);

    pointerSort(arr, size, (char)ascend_flag, &pointers);
    printf("The sorted array:\n"); //Print the sorted array
    printPointers(pointers, size);
    free(pointers);
}

void pointerSort(int* arr, unsigned int size, char ascend_flag,
        int *** pointers)
{
    int i, j;

    pointers = (int ***) malloc(size * sizeof(int **));
    for (i = 0; i < size; i++)
    {
        ***(pointers+i) = *&arr[i];
    }

    mergeSort(*pointers, size);

    if (ascend_flag == 0)
    {
        for (i = 0, j = size - 1; i < (size / 2); i++, j--)
        {
            swapInArr(**(pointers + i), **(pointers + j));
        }
    }
}
</code>```

The debugger shows that that the error occurs in this loop:

```<code> for (i = 0; i < size; i++)
 {
     ***(pointers+i) = *&arr[i];
 }
</code>```

Specifically, I keep getting this error:

Exception thrown at 0x0127192A in Project3.exe: 0xC0000005: Access
  violation reading location 0xCDCDCDCD.

If there is a handler for this exception, the program may be safely
  continued

I acknowledge that the program is incomplete, and it may be flawed in ways unrelated to the error I'm getting.  Please focus on issues related to the access violation error.

答:
```<code>pointers = (int***)malloc(size * sizeof(int**));
</code>```

The above statement is allocating a block of memory and assigning it to pointers which can be used like an array like pointers[0] or like pointers+0.

***(pointers+i) = *&arr[i]; is the same as **(pointers[i]) = *&arr[i];

The problem here is that pointers[i] is an int ** and not yet pointing at any location in memory so you can't dereference it once, let alone twice.

If what you're trying to do is create an array of pointers to members of arr then your code should look more like this.

```<code>(*pointers) = (int**)malloc(size * sizeof(int*));
for (i = 0; i < size; i++)
{
    (*pointers)[i] = &(arr[i]);
}
</code>```

And because you want to return pointers to the calling function you pass it in as a pointer and have to de-reference it.

Title: Pointers and write access violation

Body:
So I got an assignment in school that includes 3 strix (int ***)
I need to write some int values into "pointers", but I get an error when I attempt to do so.  Here's my code:

void main()
{
    unsigned int size, i;
    int arr[SIZE];
    int ** pointers;
    int ascend_flag;

    printf("Please enter the number of items:\n");
    scanf("%u", &size);
    for (i = 0; i < size; i++)
        scanf("%d", &arr[i]);
    scanf("%d", &ascend_flag);

    pointerSort(arr, size, (char)ascend_flag, &pointers);
    printf("The sorted array:\n"); //Print the sorted array
    printPointers(pointers, size);
    free(pointers);
}

void pointerSort(int* arr, unsigned int size, char ascend_flag,
        int *** pointers)
{
    int i, j;

    pointers = (int ***) malloc(size * sizeof(int **));
    for (i = 0; i < size; i++)
    {
        ***(pointers+i) = *&arr[i];
    }

    mergeSort(*pointers, size);

    if (ascend_flag == 0)
    {
        for (i = 0, j = size - 1; i < (size / 2); i++, j--)
        {
            swapInArr(**(pointers + i), **(pointers + j));
        }
    }
}

The debugger shows that that the error occurs in this loop:

 for (i = 0; i < size; i++)
 {
     ***(pointers+i) = *&arr[i];
 }

Specifically, I keep getting this error:

Exception thrown at 0x0127192A in Project3.exe: 0xC0000005: Access
  violation reading location 0xCDCDCDCD.

If there is a handler for this exception, the program may be safely
  continued

I acknowledge that the program is incomplete, and it may be flawed in ways unrelated to the error I'm getting.  Please focus on issues related to the access violation error.

Body:
pointers = (int***)malloc(size * sizeof(int**));

The above statement is allocating a block of memory and assigning it to pointers which can be used like an array like pointers[0] or like pointers+0.

***(pointers+i) = *&arr[i]; is the same as **(pointers[i]) = *&arr[i];

The problem here is that pointers[i] is an int ** and not yet pointing at any location in memory so you can't dereference it once, let alone twice.

If what you're trying to do is create an array of pointers to members of arr then your code should look more like this.

(*pointers) = (int**)malloc(size * sizeof(int*));
for (i = 0; i < size; i++)
{
    (*pointers)[i] = &(arr[i]);
}

And because you want to return pointers to the calling function you pass it in as a pointer and have to de-reference it.


问:
Update progress bar from Task.Run async
I have a method to generate software activation key from User Information:

```<code>private async void GenerateAsync()
        {
            await Task.Run(() =>
            {
                var secretstring = "CustomerName >> " + txtFullname.Text + " >> " + txtproducid.Text;
                keymng = new KeyManager(secretstring);
                var dateexp = numExpdate.Value;
                if (dateexp == 0)
                {
                    dateexp = 730000;
                }

                if (cbLicenseType.SelectedIndex == 0)
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.FULL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };

                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
                else
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.TRIAL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };
                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
            });

        }
</code>```

and I have progressbar. I want to run this method async and update progress to progressbar. How to update UI with async-await method. BackgroundWorker is  alternative???

答:
I use this method in Winforms:</p>

```<code>progressBar1.Invoke((Action)(() => progressBar1.Value=50))
</code>```

Title: Update progress bar from Task.Run async

Body:
I have a method to generate software activation key from User Information:

private async void GenerateAsync()
        {
            await Task.Run(() =>
            {
                var secretstring = "CustomerName >> " + txtFullname.Text + " >> " + txtproducid.Text;
                keymng = new KeyManager(secretstring);
                var dateexp = numExpdate.Value;
                if (dateexp == 0)
                {
                    dateexp = 730000;
                }

                if (cbLicenseType.SelectedIndex == 0)
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.FULL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };

                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
                else
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.TRIAL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };
                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
            });

        }

and I have progressbar. I want to run this method async and update progress to progressbar. How to update UI with async-await method. BackgroundWorker is  alternative???

Body:
I use this method in Winforms:

progressBar1.Invoke((Action)(() => progressBar1.Value=50))


问:
How to get selected option value of all rows of table in JavaScript?
I have an HTML table created with dynamically generated data with each row having different IDs. Each row contains 3 columns where 2 are text input fields and 1 is select field.

What I want to do is to get all content of each row of table but I'm unable to get selected option's value. I'm using a for loop to iterate through each column value of every row.

I'm getting correct values for the first two input fields but the select field is giving undefined value.

How to get the selected option value for each select field?

function getData(){
  var table = document.getElementById("dataTable");
    for (var i = 1, row; row = table.rows[i]; i++) {
        var x = row.cells[0].childNodes[0].value;
        var y = row.cells[1].childNodes[0].value;
        var z = row.cells[2].childNodes[0].value; // select option field

    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td><input value="first" id="first1" name="first[]" /></td>
<td><input value="second" id="second1" name="second[]" /></td>
<td>
  <select name="third[]" id="third1">
    <option value="option1">One</option>
    <option value="option2">Two</option>
  </select>
</td></code>```

答:
The select field appears to be the second child of the table cell and hence is accessed by childNodes[1].

Demonstration of the first case:

function getData(){
  var table = document.getElementById("dataTable");
    var row;
    for (var i = 0,  row = table.rows[i]; i < table.rows.length ;i++) {
        console.log('here')
        var x = row.cells[0].childNodes[0].value;
        var y = row.cells[1].childNodes[0].value;
        var z = row.cells[2].childNodes[1].value; // select option field
        console.log(x,y,z)
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="dataTable">
<tr>
<td><input value="first" id="first1" name="first[]" /></td>
<td><input value="second" id="second1" name="second[]" /></td>
<td>
  <select name="third[]" id="third1">
    <option value="option1">One</option>
    <option value="option2">Two</option>
  </select>
</td>
</tr>
</table>
<button onclick="getData()">Click</button></code>```

The reason this happened was because you hadextra spaces between    <select>. Remove them and it can be accessed with childNodes[0]

function getData(){
  var table = document.getElementById("dataTable");

    var row;
    for (var i = 0,  row = table.rows[i]; i < table.rows.length ;i++) {
        var x = row.cells[0].childNodes[0].value;
        var y = row.cells[1].childNodes[0].value;
        var z = row.cells[2].childNodes[0].value; // select option field

    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="dataTable">
<tr>
<td><input value="first" id="first1" name="first[]" /></td>
<td><input value="second" id="second1" name="second[]" /></td>
<td><select name="third[]" id="third1">
    <option value="option1">One</option>
    <option value="option2">Two</option>
</select>
</td>
</tr>
</table>
<button onclick="getData()">Click</button></code>```

You also need to end you for loop and hence put a condition on number of rows

Body:
I have an HTML table created with dynamically generated data with each row having different IDs. Each row contains 3 columns where 2 are text input fields and 1 is select field.

What I want to do is to get all content of each row of table but I'm unable to get selected option's value. I'm using a for loop to iterate through each column value of every row.

I'm getting correct values for the first two input fields but the select field is giving undefined value.

How to get the selected option value for each select field?

function getData(){
  var table = document.getElementById("dataTable");
    for (var i = 1, row; row = table.rows[i]; i++) {
        var x = row.cells[0].childNodes[0].value;
        var y = row.cells[1].childNodes[0].value;
        var z = row.cells[2].childNodes[0].value; // select option field

    }
}

<input value="first" id="first1" name="first[]" />
<input value="second" id="second1" name="second[]" />

  <select name="third[]" id="third1">
    <option value="option1">One</option>
    <option value="option2">Two</option>
  </select>

Body:
The select field appears to be the second child of the table cell and hence is accessed by childNodes[1].

Demonstration of the first case:

function getData(){
  var table = document.getElementById("dataTable");
    var row;
    for (var i = 0,  row = table.rows[i]; i < table.rows.length ;i++) {
        console.log('here')
        var x = row.cells[0].childNodes[0].value;
        var y = row.cells[1].childNodes[0].value;
        var z = row.cells[2].childNodes[1].value; // select option field
        console.log(x,y,z)
    }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="dataTable">
<tr>
<td><input value="first" id="first1" name="first[]" /></td>
<td><input value="second" id="second1" name="second[]" /></td>
<td>
  <select name="third[]" id="third1">
    <option value="option1">One</option>
    <option value="option2">Two</option>
  </select>
</td>
</tr>
</table>
<button onclick="getData()">Click</button>

The reason this happened was because you hadextra spaces between <td>   <select>. Remove them and it can be accessed with childNodes[0]

function getData(){
  var table = document.getElementById("dataTable");

    var row;
    for (var i = 0,  row = table.rows[i]; i < table.rows.length ;i++) {
        var x = row.cells[0].childNodes[0].value;
        var y = row.cells[1].childNodes[0].value;
        var z = row.cells[2].childNodes[0].value; // select option field

    }
}

<table id="dataTable">
<tr>
<td><input value="first" id="first1" name="first[]" /></td>
<td><input value="second" id="second1" name="second[]" /></td>
<td><select name="third[]" id="third1">
    <option value="option1">One</option>
    <option value="option2">Two</option>
</select>
</td>
</tr>
</table>
<button onclick="getData()">Click</button>

You also need to end you for loop and hence put a condition on number of rows


问:
How can one determine the current region within an AWS Lambda function?
Regions.getCurrentRegion() returns null from within an AWS Lambda function.  It seems that Regions.getCurrentRegion() is not supported from within an AWS Lambda function.  Is there an alternative way to determine which region the lambda function is running in?

NOTE:  AWS Lambda function is written in Java.

答:
All Lambda containers has environment variables set $AWS_REGION

From Java Code in Lambda.You can access it as below

```<code>System.getenv("AWS_REGION")
</code>```

Body:
All Lambda containers has environment variables set $AWS_REGION

From Java Code in Lambda.You can access it as below

System.getenv("AWS_REGION")


问:
Sequence is not hitting in Oracle Application Apex After creating app
I am trying to create a app in oracle apex. I have installed it in my pc(Ubuntu).

I have created a table and a sequence through sql command in apex.
Like

create table test (
    test_id number primary key,
    test_name varchar2(20) not null
 );

and sequence like-

create sequence test_seq start with 1 increment by 1;

Now adding a single value in my table through sql-comand

insert into test values(test_seq.nextval, 'Test');

Okey runnig successfully.[1 row added]

But when i create a app using this table -
Please check it for details

Okey - Page creation successful but when i try to add data in it then it says -

ORA-01400: cannot insert NULL into ("WORKSPACE"."TEST"."TEST_ID")

Click here to See the attachment

So why this problem occurs?

答:
I think you have not associated sequence to primary column of your table. Alter your table and then try to add data using app.

```<code>ALTER TABLE TEST
MODIFY (TEST_ID DEFAULT TEST_SEQ.NEXTVAL );
</code>```

Ideally, you would create sequence first and then while creating table, you can define column default as follows,

```<code>CREATE TABLE TEST (
    TEST_ID NUMBER DEFAULT TEST_SEQ.NEXTVAL NOT NULL PRIMARY KEY,
    TEST_NAME VARCHAR2(20) NOT NULL
 );
</code>```

Body:
I think you have not associated sequence to primary column of your table. Alter your table and then try to add data using app.

ALTER TABLE TEST
MODIFY (TEST_ID DEFAULT TEST_SEQ.NEXTVAL );

Ideally, you would create sequence first and then while creating table, you can define column default as follows,

CREATE TABLE TEST (
    TEST_ID NUMBER DEFAULT TEST_SEQ.NEXTVAL NOT NULL PRIMARY KEY,
    TEST_NAME VARCHAR2(20) NOT NULL
 );


问:
javascript - How to add array to array position
I'm trying to create a specific structure of data but I'm having troubles with that.

I want to do this:

Parts

u_order

u_familia

u_part

u_type

articles (i want to add an array of articles here)

First, create the array parts:

```<code>parts.push(request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92'"));
</code>```

Next I will iterate this array and for each part I get the articles of this part and I want to add them to parts array:

```<code>return Promise.all([Promise.all(parts)]).then(function(listOfResults)
    {
      var articles = [];
      for(var i=0; i<listOfResults[0][0].length; i++)
      {
        articles.push(request.query("SELECT ststamp, ref, design FROM st WHERE u_posic = '"+listOfResults[0][0][i].u_order+"'"));
      }

      Promise.all([Promise.all(articles)]).then(function(listOfArticles)
      {
        console.log("ARTICLES:");
        for(var j=0; j<listOfArticles[0][0].length; j++)
        {
          HERE I WANT TO ADD THE ARTICLE ARRAY TO PART
          I TRY USE SPLICE BUT DOESN'T WORK.
        }
      });

    }).catch(function(err)
    {
        console.log(err);
    });
</code>```

How can I do that?

Thank you

答:
I would use Parts object rather than a parts array.  Make an array of Parts objects containing the named keys including a key for articles:

```<code>var part = request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92'");
var article = request.query("SELECT ststamp, ref, design FROM st WHERE u_posic = '"+listOfResults[0][0][i].u_order+"'");

parts.push({
  u_order: part[0],
  u_familia: part[1],
  u_part: part[2],
  u_type: part[3],
  articles: article
});
</code>```

Body:
I'm trying to create a specific structure of data but I'm having troubles with that.

I want to do this:

Parts

u_order

u_familia

u_part

u_type

articles (i want to add an array of articles here)

First, create the array parts:

parts.push(request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92'"));

Next I will iterate this array and for each part I get the articles of this part and I want to add them to parts array:

return Promise.all([Promise.all(parts)]).then(function(listOfResults)
    {
      var articles = [];
      for(var i=0; i<listOfResults[0][0].length; i++)
      {
        articles.push(request.query("SELECT ststamp, ref, design FROM st WHERE u_posic = '"+listOfResults[0][0][i].u_order+"'"));
      }

      Promise.all([Promise.all(articles)]).then(function(listOfArticles)
      {
        console.log("ARTICLES:");
        for(var j=0; j<listOfArticles[0][0].length; j++)
        {
          HERE I WANT TO ADD THE ARTICLE ARRAY TO PART
          I TRY USE SPLICE BUT DOESN'T WORK.
        }
      });

    }).catch(function(err)
    {
        console.log(err);
    });

How can I do that?

Thank you

Body:
I would use Parts object rather than a parts array.  Make an array of Parts objects containing the named keys including a key for articles:

var part = request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92'");
var article = request.query("SELECT ststamp, ref, design FROM st WHERE u_posic = '"+listOfResults[0][0][i].u_order+"'");

parts.push({
  u_order: part[0],
  u_familia: part[1],
  u_part: part[2],
  u_type: part[3],
  articles: article
});


答:
```<code>function remove($arr, $key1, $val1, $key2, $val2){
        $foundKey = '';
        foreach($arr as $k=>$a){
            if($a[$key1] == $val1 && $a[$key2] == $val2){
                $foundKey = $k;
            }
        }
        if(isset($arr[$foundkey])){
        unset($arr[$foundkey]);
    }

return $arr;
}
</code>```

Now call remove function:

```<code>remove($arr, 'state', '0', 'condition_type', '1');
</code>```

Title: Remove an array depending its values

Body:
function remove($arr, $key1, $val1, $key2, $val2){
        $foundKey = '';
        foreach($arr as $k=>$a){
            if($a[$key1] == $val1 && $a[$key2] == $val2){
                $foundKey = $k;
            }
        }
        if(isset($arr[$foundkey])){
        unset($arr[$foundkey]);
    }

return $arr;
}

Now call remove function:

remove($arr, 'state', '0', 'condition_type', '1');


问:
Eclipse plugin for Apache Axis2 to create webservice
please give me the link to download plugins for apache axis, i tried in some sites but the link was not current so i was not able to download.

thanks in advance,
Mahesh

答: I think the most comprehensive plugin is MyEclipse. But it's a commercial one. (not free)</p>

OwnerDisplayName: mahesh

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: LiorH


问:
What does error_already_set in Boost.python do and how to handle exceptions similarly in Python C API
I have been working on a project where I want to remove the boost dependencies and replace it with the Python C API.

I spent some time understanding the Python C API and I saw this
catch (error_already_set const &)

I read the boost docs but it explains where it is used. But I want to know why it is needed and how can I achieve the same functionality using the native Python C api.

答:
Boost throws error_already_set when a Python error has occurred.  So if you see code like this:

```<code>try {
    bp::exec(bp::str("garbage code is garbage"));
} catch (const bp::error_already_set&) {
    // your code here to examine Python traceback etc.
}
</code>```

you'll replace it with:

```<code>your_ptr<PyObject> res = PyRun_String("garbage code is garbage");
if (!res) {
    // your code here to examine Python traceback etc.
}
</code>```

In other words, wherever you see catch(error_already_set), there you will likely want to do some error handling using whatever PyObject* or other value is involved to recognize when an error has occurred (and therefore you can examine the traceback, or convert it into a C++ exception).

Body:
Boost throws error_already_set when a Python error has occurred.  So if you see code like this:

try {
    bp::exec(bp::str("garbage code is garbage"));
} catch (const bp::error_already_set&) {
    // your code here to examine Python traceback etc.
}

you'll replace it with:

your_ptr<PyObject> res = PyRun_String("garbage code is garbage");
if (!res) {
    // your code here to examine Python traceback etc.
}

In other words, wherever you see catch(error_already_set), there you will likely want to do some error handling using whatever PyObject* or other value is involved to recognize when an error has occurred (and therefore you can examine the traceback, or convert it into a C++ exception).