问:
Error inserting file content in SQL Database using mssql php

I'm trying to upload files (pdf, images) into the database using PHP and MSSQL.

```<code><form role="form" action="kyc.php" method="post" enctype="multipart/form-data">
    <div class="form-body">

        <div class="row">
            <div class="col-md-offset-1">
                <div class="form-group">
                    <label for="aadhaar">Aadhaar Card</label>
                    <input type="file" name="aadhaar" id="aadhaar" accept="application/pdf,image/x-png,image/gif,image/jpeg" required>
                </div>
            </div>
        </div>

        <input type="hidden" value="<?php echo $client_id; ?>" name="clientCode">
    </div>
    <div class="form-actions">
        <button name="submit" type="submit" class="btn blue">Upload</button>
    </div>
</form>
</code>```

Here's the PHP code which is executed post form submission:

```<code>$clientCode = $_POST['clientCode'];
$fileName=$_FILES["aadhaar"]["name"];
$fileType = $_FILES['aadhaar']['type'];

//Get the content of the image and then add slashes to it
$fileTemp=addslashes(file_get_contents($_FILES['aadhaar']['tmp_name']));

//Insert the image name and image content in image_table
$query="INSERT INTO KYCSCANS (FIRMNUMBER, CLIENTCODE, FILENAME, FILETYPE, FILECONTENT, TIMESTAMP, CREATIONTIMESTAMP, ADDEDBY, FILERELATED) VALUES('Global','{$clientCode}', '{$fileName}', '{$fileType}', '{$fileTemp}', GETDATE(), GETDATE(), 'madWeb', 'temp')";

$insertQuery = sqlsrv_query($jarvisconnection, $query);

if(!$insertQuery) {
    die("Aadhaar Query Failed" . print_r(sqlsrv_errors(), true));
}
</code>```

Here's the table structure -

```<code>SRNO - int
FIRMNUMBER - nchar(10)
CLIENTCODE - nvarchar(50)
FILENAME- nvarchar(50)
FILETYPE - nvarchar(50)
FILECONTENT - varbinary(MAX)
TIMESTAMP - datetime
CREATIONTIMESTAMP - datetime
ADDEDBY - nchar(15)
FILERELATED - nvarchar(50)
</code>```

I tried a lot of things but I'm still getting the following error:

Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 0
  [code] => 0 [2] => [Microsoft][ODBC Driver 11 for SQL Server]Syntax
  error, permission violation, or other nonspecific error [message] =>
  [Microsoft][ODBC Driver 11 for SQL Server]Syntax error, permission
  violation, or other nonspecific error ) )

答:
It could be any number of things, but most likely culprit is binary content in the file. Use proper parameterization to ensure the data is sanitized, and to improve security. You should also have some checks on the data to ensure data is not too long for your database columns, and truncate or reject as needed.</p>

```<code><?php
$clientCode = $_POST["clientCode"];
$fileName   = $_FILES["aadhaar"]["name"];
$fileType   = $_FILES["aadhaar"]["type"];
$fileTemp   = file_get_contents($_FILES["aadhaar"]["tmp_name"]);
$parameters = array(
    $clientCode,
    $fileName,
    $fileType,
    array($fileTemp, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING, SQLSRV_SQLTYPE_BINARY)
);
$query      = <<<SQL
INSERT INTO KYCSCANS (
    FIRMNUMBER, CLIENTCODE, FILENAME, FILETYPE, FILECONTENT,
    TIMESTAMP, CREATIONTIMESTAMP, ADDEDBY, FILERELATED
)
VALUES (
    'Global', ?, ?, ?, ?, GETDATE(), GETDATE(), 'madWeb', 'temp'
)
SQL;

$insertQuery = sqlsrv_query($jarvisconnection, $query, $parameters);

if ($insertQuery === false) {
    die("Aadhaar Query Failed" . print_r(sqlsrv_errors(), true));
}
</code>```

Body:
I'm trying to upload files (pdf, images) into the database using PHP and MSSQL.

<form role="form" action="kyc.php" method="post" enctype="multipart/form-data">

                    Aadhaar Card
                    <input type="file" name="aadhaar" id="aadhaar" accept="application/pdf,image/x-png,image/gif,image/jpeg" required>

        <input type="hidden" value="<?php echo $client_id; ?>" name="clientCode">

        <button name="submit" type="submit" class="btn blue">Upload</button>

</form>

Here's the PHP code which is executed post form submission:

$clientCode = $_POST['clientCode'];
$fileName=$_FILES["aadhaar"]["name"];
$fileType = $_FILES['aadhaar']['type'];

//Get the content of the image and then add slashes to it
$fileTemp=addslashes(file_get_contents($_FILES['aadhaar']['tmp_name']));

//Insert the image name and image content in image_table
$query="INSERT INTO KYCSCANS (FIRMNUMBER, CLIENTCODE, FILENAME, FILETYPE, FILECONTENT, TIMESTAMP, CREATIONTIMESTAMP, ADDEDBY, FILERELATED) VALUES('Global','{$clientCode}', '{$fileName}', '{$fileType}', '{$fileTemp}', GETDATE(), GETDATE(), 'madWeb', 'temp')";

$insertQuery = sqlsrv_query($jarvisconnection, $query);

if(!$insertQuery) {
    die("Aadhaar Query Failed" . print_r(sqlsrv_errors(), true));
}

Here's the table structure -

SRNO - int
FIRMNUMBER - nchar(10)
CLIENTCODE - nvarchar(50)
FILENAME- nvarchar(50)
FILETYPE - nvarchar(50)
FILECONTENT - varbinary(MAX)
TIMESTAMP - datetime
CREATIONTIMESTAMP - datetime
ADDEDBY - nchar(15)
FILERELATED - nvarchar(50)

I tried a lot of things but I'm still getting the following error:

Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 0
  [code] => 0 [2] => [Microsoft][ODBC Driver 11 for SQL Server]Syntax
  error, permission violation, or other nonspecific error [message] =>
  [Microsoft][ODBC Driver 11 for SQL Server]Syntax error, permission
  violation, or other nonspecific error ) )

Body:
It could be any number of things, but most likely culprit is binary content in the file. Use proper parameterization to ensure the data is sanitized, and to improve security. You should also have some checks on the data to ensure data is not too long for your database columns, and truncate or reject as needed.

<?php
$clientCode = $_POST["clientCode"];
$fileName   = $_FILES["aadhaar"]["name"];
$fileType   = $_FILES["aadhaar"]["type"];
$fileTemp   = file_get_contents($_FILES["aadhaar"]["tmp_name"]);
$parameters = array(
    $clientCode,
    $fileName,
    $fileType,
    array($fileTemp, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING, SQLSRV_SQLTYPE_BINARY)
);
$query      = <<<SQL
INSERT INTO KYCSCANS (
    FIRMNUMBER, CLIENTCODE, FILENAME, FILETYPE, FILECONTENT,
    TIMESTAMP, CREATIONTIMESTAMP, ADDEDBY, FILERELATED
)
VALUES (
    'Global', ?, ?, ?, ?, GETDATE(), GETDATE(), 'madWeb', 'temp'
)
SQL;

$insertQuery = sqlsrv_query($jarvisconnection, $query, $parameters);

if ($insertQuery === false) {
    die("Aadhaar Query Failed" . print_r(sqlsrv_errors(), true));
}


来源: stackexchange

问:
Program not increasing variable in loop
For my program I am trying to find out the percentage of words in my data file that are 3 letters long. Though whenever I run the program I receive an error stating that you can not divide by 0. I increase my variable wordCount by 1 every time my loop runs, yet for some reason my program recognizes it as 0. Can anybody assist me as to how I am recieving this error?

```<code>int threeLetters=0;
        int wordCount=0;

        while(inFile.hasNextLine()){
            wordCount= wordCount +1;
            String line = inFile.nextLine();
            String[] word =line.split(" ");
            int wordLength = word.length;
            if (wordLength == 3){
                threeLetters= threeLetters+1;
            }

}
double percentage = wordCount/threeLetters;// error recieved here
</code>```

This is the text file the program is reading from

```<code>Good morning life and all
Things glad and beautiful
My pockets nothing hold
But he that owns the gold
The sun is my great friend
His spending has no end
Hail to the morning sky
Which bright clouds measure high
Hail to you birds whose throats
Would number leaves by notes
Hail to you shady bowers
And you green fields of flowers
Hail to you women fair
That make a show so rare
In cloth as white as milk
Be it calico or silk
Good morning life and all
Things glad and beautiful
</code>```

答:
You're not dividing by wordCount, you're dividing by threeLetters.  And it is indeed 0 because nothing ever incremented it.

The problem with your logic is here:

```<code>String[] word =line.split(" ");
int wordLength = word.length;
if (wordLength == 3){
    threeLetters= threeLetters+1;
}
</code>```

You're not counting how long the words are, you're counting how many words are on that line.  And since no line in that file has exactly three words, the if is never true and threeLetters is never increased.  So it remains 0.

What you need is another loop over that array.  Something like this:

```<code>String[] words = line.split(" ");
for (int i = 0; i < words.length; i++) {
    int wordLength = words[i].length();
    if (wordLength == 3){
        threeLetters = threeLetters + 1;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Program not increasing variable in loop

Body:
For my program I am trying to find out the percentage of words in my data file that are 3 letters long. Though whenever I run the program I receive an error stating that you can not divide by 0. I increase my variable wordCount by 1 every time my loop runs, yet for some reason my program recognizes it as 0. Can anybody assist me as to how I am recieving this error?

int threeLetters=0;
        int wordCount=0;

        while(inFile.hasNextLine()){
            wordCount= wordCount +1;
            String line = inFile.nextLine();
            String[] word =line.split(" ");
            int wordLength = word.length;
            if (wordLength == 3){
                threeLetters= threeLetters+1;
            }

}
double percentage = wordCount/threeLetters;// error recieved here

This is the text file the program is reading from

Good morning life and all
Things glad and beautiful
My pockets nothing hold
But he that owns the gold
The sun is my great friend
His spending has no end
Hail to the morning sky
Which bright clouds measure high
Hail to you birds whose throats
Would number leaves by notes
Hail to you shady bowers
And you green fields of flowers
Hail to you women fair
That make a show so rare
In cloth as white as milk
Be it calico or silk
Good morning life and all
Things glad and beautiful

Body:
You're not dividing by wordCount, you're dividing by threeLetters.  And it is indeed 0 because nothing ever incremented it.

The problem with your logic is here:

String[] word =line.split(" ");
int wordLength = word.length;
if (wordLength == 3){
    threeLetters= threeLetters+1;
}

You're not counting how long the words are, you're counting how many words are on that line.  And since no line in that file has exactly three words, the if is never true and threeLetters is never increased.  So it remains 0.

What you need is another loop over that array.  Something like this:

String[] words = line.split(" ");
for (int i = 0; i < words.length; i++) {
    int wordLength = words[i].length();
    if (wordLength == 3){
        threeLetters = threeLetters + 1;
    }
}


问:
what exactly does this do Class.forName("com.mysql.jdbc.Driver").newInstance();
While connecting to MySQL database I do following steps

```<code>Connection con = null;
Resultset rs = null;
Statement st = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","passwp");
</code>```

Actually I wanted to know what does Class.forName("com.mysql.jdbc.Driver").newInstance(); statement do.

Althogh this class is not in mysql.jar. Where is it present?

答:
It create a new instance of the com.mysql.jdbc.Driver class and Register the driver.

So then what happens is you call Class.forName("com.mysql.jdbc.Driver") without 'newInstance()' it returns com.mysql.jdbc.Driver class and register the driver only

Body:
While connecting to MySQL database I do following steps

Connection con = null;
Resultset rs = null;
Statement st = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","passwp");

Actually I wanted to know what does Class.forName("com.mysql.jdbc.Driver").newInstance(); statement do.

Althogh this class is not in mysql.jar. Where is it present?


问:
Using XMLBeans on Android
I was just wondering if anyone had any success in getting XMLBeans (or any other generator) to work on android. It would be very nice if I could use it because I have a very large schema that I would rather not write all the classes by hand.

I had asked about this on the android developers mailing list, but no one responded. This tells me that either they don't care, or no one feels like telling me its not possible.

If anyone knows of anything else like XMLBeans that works for android, please let me know. It would be very helpful.

Thanks,
Robbie

答:
You can use Castor . Just be sure, in Android 2.1, not to use default android SAXParser. You'll get namespace errors. You do this by defining the parser to be, for example, Xerces (and the you add the required JARS), in core.properties .
In android 2.2 it may be ok.
Note that if you create an xmlcontext for the unmarsheler with xerces, it still won't work, as the mapping itself would be parsed with android's SAX. It must be done at core (top level properties file) so that even the mapping is parsed by xerces.
finally - performance is as slow as you can expect... :(
Good luck
SM</p>

Title: Using XMLBeans on Android

ContentLicense: CC BY-SA 2.5


问:
QuickFix - parse string with microseconds to DateTime
I´m having the following error in my .Net application:

20170710-18:47:34.938 : Connection succeeded 20170710-18:47:34.940 :
  Initiated logon request 20170710-18:47:35.012 : Verify failed: Could
  not convert field: Could not convert string (20170710-18:47:34.979386)
  to DateTime: String was not recognized as a valid DateTime.

I want my application to support microseconds, currently I can send a LogOn msg but when I get the response, my App is not able to process the message.
Actually, the received message doesn't appear in my Log nor does it trigger any of my events (FromAdmin, FromApp)

I've tried changing my Dictionary but I could not pull it off.

答:
This was probably caused by a limitation in QuickFIXn which didn't used to support UTCTimeStamps with anything other than zero or three milliseconds.

This appears to have been fixed in March.  (Though it still isn't quite inline with the protocol.)

You should be able to fix this by updating your version of QuickFIX.


答:
You are not processing your words correctly: you are counting three-word sentences, of which you have zero, rather than three-letter words. You need another for loop here:

```<code>while(inFile.hasNextLine()){
    String line = inFile.nextLine();
    for (String word : line.split(" ")) {
        wordCount++;
        int wordLength = word.length();
        if (wordLength == 3){
            threeLetters++;
        }
    }
}
</code>```

In addition, you are not computing percentage correctly: threeLetters should be the numerator, not the denominator.

Finally, unless you'd like to truncate percentage to whole numbers, use double for your counters, or cast them before division:

```<code>double percentage = ((double)threeLetters)/wordCount;
</code>```

Demo.

Title: Program not increasing variable in loop

Body:
You are not processing your words correctly: you are counting three-word sentences, of which you have zero, rather than three-letter words. You need another for loop here:

while(inFile.hasNextLine()){
    String line = inFile.nextLine();
    for (String word : line.split(" ")) {
        wordCount++;
        int wordLength = word.length();
        if (wordLength == 3){
            threeLetters++;
        }
    }
}

In addition, you are not computing percentage correctly: threeLetters should be the numerator, not the denominator.

Finally, unless you'd like to truncate percentage to whole numbers, use double for your counters, or cast them before division:

double percentage = ((double)threeLetters)/wordCount;

Demo.


问:
get value referencing key with Marshal
The project is using Marshal.

And I have a JSON structure that looks like this:

```<code>{"Stuff":
   [
      {"Key": "SomeKey", "Value": "4056"},
      {"Key": "SomeOtherKey", "Value": "18"}
   ]
 }
</code>```

Now I want to get the content of the "Value" where the "Key" is "SomeKey" (In this case it would be "4056").

Does anyone know how to do it with this library?

答:
In case someone is having the same problem, this is the only way I found:

I created a class to unmarshal all those items:

```<code>extension KeyValue: Unmarshaling {
    internal init(object: MarshaledObject) throws {
        self.name = try object <| "Key"
        self.value = try object <| "Value"
    }
}
</code>```

and then filtered the one I needed:

```<code>let stuff: [KeyValue]
var someKey: String? {
   return stuff.first(where: { $0.name == "SomeKey" })?.value
}
</code>```

(I guess there is no easy way to do this with Marshal)

Title: get value referencing key with Marshal

Body:
The project is using Marshal.

And I have a JSON structure that looks like this:

{"Stuff":
   [
      {"Key": "SomeKey", "Value": "4056"},
      {"Key": "SomeOtherKey", "Value": "18"}
   ]
 }

Now I want to get the content of the "Value" where the "Key" is "SomeKey" (In this case it would be "4056").

Does anyone know how to do it with this library?

Body:
In case someone is having the same problem, this is the only way I found:

I created a class to unmarshal all those items:

extension KeyValue: Unmarshaling {
    internal init(object: MarshaledObject) throws {
        self.name = try object <| "Key"
        self.value = try object <| "Value"
    }
}

and then filtered the one I needed:

let stuff: [KeyValue]
var someKey: String? {
   return stuff.first(where: { $0.name == "SomeKey" })?.value
}

(I guess there is no easy way to do this with Marshal)


问:
Spring Boot - updated from 1.2.3.Release to 1.5.0.RELEASE
I updated following:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.3.RELEASE</version>
</parent>
</code>```

to

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.0.RELEASE</version>
</parent>
</code>```

and afterwards I started maven with:

```<code>mvn clean install -DskipTests
</code>```

and I got this trace in the console, which mentions a non parsable POM:

```<code>[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-parseable POM
C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-
dependencies\1.5.0.RELEASE\spring-boot-dependencies-1.5.0.RELEASE.pom: in
epilog non whitespace content is not allowed but got r (position: END_TAG
seen ...</build>\n</project>r... @2606:12)  @
C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-
dependencies\1.5.0.RELEASE\spring-boot-dependencies-1.5.0.RELEASE.pom, line
2606, column 12
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.smartinnotec.legalprojectmanagement:smartinnotec-
legalprojectmanagement-main:1.0.1-SNAPSHOT
(C:\Users\05906\Documents\workspace-sts-
survey\maven.1498452192342\smartinnotec-legalprojectmanagement-main\pom.xml)
has 1 error
[ERROR]     Non-parseable POM
C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-
dependencies\1.5.0.RELEASE\spring-boot-dependencies-1.5.0.RELEASE.pom: in
epilog non whitespace content is not allowed but got r (position: END_TAG
seen ...</build>\n</project>r... @2606:12)  @
C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-
dependencies\1.5.0.RELEASE\spring-boot-dependencies-1.5.0.RELEASE.pom, line
2606, column 12 -> [Help 2]
</code>```

Does anyone know what I am doing wrong, the content in

```<code>C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-starter-parent\1.5.0.RELEASE
</code>```

seems ok.

答:
Please check end of your pom.xml file (spring-boot-dependencies-1.5.0.RELEASE.pom) on line 2606. It should only contain a </project>, but seems to have something starting with an 'r' after it.

If it is corrupted, you can easily fix it, by just removing it from the .m2 folder and letting Maven redownload it on the next build.

Other ways this issue could occur is if you have an old Maven version, and there is some construct in the pom.xml it does not yet now, but this is not the case for you.

Body:
I updated following:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.3.RELEASE</version>
</parent>

to

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.0.RELEASE</version>
</parent>

and afterwards I started maven with:

mvn clean install -DskipTests

and I got this trace in the console, which mentions a non parsable POM:

[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-parseable POM
C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-
dependencies\1.5.0.RELEASE\spring-boot-dependencies-1.5.0.RELEASE.pom: in
epilog non whitespace content is not allowed but got r (position: END_TAG
seen ...</build>\n</project>r... @2606:12)  @
C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-
dependencies\1.5.0.RELEASE\spring-boot-dependencies-1.5.0.RELEASE.pom, line
2606, column 12
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.smartinnotec.legalprojectmanagement:smartinnotec-
legalprojectmanagement-main:1.0.1-SNAPSHOT
(C:\Users\05906\Documents\workspace-sts-
survey\maven.1498452192342\smartinnotec-legalprojectmanagement-main\pom.xml)
has 1 error
[ERROR]     Non-parseable POM
C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-
dependencies\1.5.0.RELEASE\spring-boot-dependencies-1.5.0.RELEASE.pom: in
epilog non whitespace content is not allowed but got r (position: END_TAG
seen ...</build>\n</project>r... @2606:12)  @
C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-
dependencies\1.5.0.RELEASE\spring-boot-dependencies-1.5.0.RELEASE.pom, line
2606, column 12 -> [Help 2]

Does anyone know what I am doing wrong, the content in

C:\Users\05906\.m2\repository\org\springframework\boot\spring-boot-starter-parent\1.5.0.RELEASE

seems ok.


问:
Using ws:// while on https:// (mixed content)
I have a html5 page with

```<code>var connection = new WebSocket('ws://foo.bar:8888');
</code>```

But I get an error

Mixed Content: The page at 'https://foo.bar/' was loaded over HTTPS,
  but attempted to connect to the insecure WebSocket endpoint
  'ws://foo.bar:8888/'. This request has been blocked; this endpoint
  must be available over WSS.

I understand that, but I can't serve a Secure Websocket.
Is there any way to make this work, except starting chrome with --allow-running-insecure-content or something like that, where the user has to do something?

Thanks!

答: So months later I can say: If you can serve the page via https somewhere on your server there are certificate and chain files, use these to serve a wss</p>

Body:
I have a html5 page with

var connection = new WebSocket('ws://foo.bar:8888');

But I get an error

Mixed Content: The page at 'https://foo.bar/' was loaded over HTTPS,
  but attempted to connect to the insecure WebSocket endpoint
  'ws://foo.bar:8888/'. This request has been blocked; this endpoint
  must be available over WSS.

I understand that, but I can't serve a Secure Websocket.
Is there any way to make this work, except starting chrome with --allow-running-insecure-content or something like that, where the user has to do something?

Thanks!


问:
Exception while Dropbox API tries to read a resource - might be multidex issue?
I have an Android app with Dropbox support. Lately I've started getting an exception for some users. I can not reproduce it. It affects just a few users. The exception happens when Dropbox tries to access /sdk-version.txt which is one of their resources. On Android Studio I can see the resource is there, here is a screenshot:

And like I said, it doesn't happen for me or for most of my users. If I use apktool on my apk, the sdk-version.txt file shows up on a folder called unknown. I see a lot of other files there but most have a package, this one doesn't. Not sure if that matters.

I also have this line on my gradle file multiDexKeepFile file('multidex-config.txt') and in there I have:

```<code>com.dropbox.core.DbxRequestUtil
com.dropbox.core.http.HttpRequestor
com.dropbox.core.DbxSdkVersion
</code>```

Those were all attempts at fixing this but it didn't help.

So far the exception has happened on Android 5 and 6 across multiple manufacturers. This is the exception:

```<code>Fatal Exception: java.lang.ExceptionInInitializerError
       at com.dropbox.core.DbxRequestUtil.buildUserAgentHeader(DbxRequestUtil.java:151)
       at com.dropbox.core.DbxRequestUtil.addUserAgentHeader(DbxRequestUtil.java:136)
       at com.dropbox.core.DbxRequestUtil.startPostRaw(DbxRequestUtil.java:233)
       at com.dropbox.core.v2.DbxRawClientV2$1.execute(DbxRawClientV2.java:107)
       at com.dropbox.core.v2.DbxRawClientV2.executeRetriable(DbxRawClientV2.java:284)
       at com.dropbox.core.v2.DbxRawClientV2.rpcStyle(DbxRawClientV2.java:102)
       at com.dropbox.core.v2.users.DbxUserUsersRequests.getCurrentAccount(DbxUserUsersRequests.java:120)
       at mypackage.UserDropbox.(UserDropbox.java)
       at mypackage.DropboxHelper$1.run(DropboxHelper.java)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:81smiling face with sunglasses
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'void java.util.jar.JarVerifier.removeMetaEntries()' on a null object reference
       at java.util.jar.JarFile.getInputStream(JarFile.java:381)
       at libcore.net.url.JarURLConnectionImpl.getInputStream(JarURLConnectionImpl.java:222)
       at java.net.URL.openStream(URL.java:470)
       at java.lang.ClassLoader.getResourceAsStream(ClassLoader.java:444)
       at java.lang.Class.getResourceAsStream(Class.java:1412)
       at com.dropbox.core.DbxSdkVersion.loadLineFromResource(DbxSdkVersion.java:34)
       at com.dropbox.core.DbxSdkVersion.loadVersion(DbxSdkVersion.java:56)
       at com.dropbox.core.DbxSdkVersion.(DbxSdkVersion.java)
       at com.dropbox.core.DbxRequestUtil.buildUserAgentHeader(DbxRequestUtil.java:151)
       at com.dropbox.core.DbxRequestUtil.addUserAgentHeader(DbxRequestUtil.java:136)
       at com.dropbox.core.DbxRequestUtil.startPostRaw(DbxRequestUtil.java:233)
       at com.dropbox.core.v2.DbxRawClientV2$1.execute(DbxRawClientV2.java:107)
       at com.dropbox.core.v2.DbxRawClientV2.executeRetriable(DbxRawClientV2.java:284)
       at com.dropbox.core.v2.DbxRawClientV2.rpcStyle(DbxRawClientV2.java:102)
       at com.dropbox.core.v2.users.DbxUserUsersRequests.getCurrentAccount(DbxUserUsersRequests.java:120)
       at mypackage.UserDropbox.(UserDropbox.java)
</code>```

答:
This isn't a direct solution.

You can integrate fabric clashlytics into your app to get a full report on the cause of the exception and information on the type and OS of devices experiencing the Exception.

Body:
I have an Android app with Dropbox support. Lately I've started getting an exception for some users. I can not reproduce it. It affects just a few users. The exception happens when Dropbox tries to access /sdk-version.txt which is one of their resources. On Android Studio I can see the resource is there, here is a screenshot:

And like I said, it doesn't happen for me or for most of my users. If I use apktool on my apk, the sdk-version.txt file shows up on a folder called unknown. I see a lot of other files there but most have a package, this one doesn't. Not sure if that matters.

I also have this line on my gradle file multiDexKeepFile file('multidex-config.txt') and in there I have:

com.dropbox.core.DbxRequestUtil
com.dropbox.core.http.HttpRequestor
com.dropbox.core.DbxSdkVersion

Those were all attempts at fixing this but it didn't help.

So far the exception has happened on Android 5 and 6 across multiple manufacturers. This is the exception:

Fatal Exception: java.lang.ExceptionInInitializerError
       at com.dropbox.core.DbxRequestUtil.buildUserAgentHeader(DbxRequestUtil.java:151)
       at com.dropbox.core.DbxRequestUtil.addUserAgentHeader(DbxRequestUtil.java:136)
       at com.dropbox.core.DbxRequestUtil.startPostRaw(DbxRequestUtil.java:233)
       at com.dropbox.core.v2.DbxRawClientV2$1.execute(DbxRawClientV2.java:107)
       at com.dropbox.core.v2.DbxRawClientV2.executeRetriable(DbxRawClientV2.java:284)
       at com.dropbox.core.v2.DbxRawClientV2.rpcStyle(DbxRawClientV2.java:102)
       at com.dropbox.core.v2.users.DbxUserUsersRequests.getCurrentAccount(DbxUserUsersRequests.java:120)
       at mypackage.UserDropbox.(UserDropbox.java)
       at mypackage.DropboxHelper$1.run(DropboxHelper.java)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:81smiling face with sunglasses
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'void java.util.jar.JarVerifier.removeMetaEntries()' on a null object reference
       at java.util.jar.JarFile.getInputStream(JarFile.java:381)
       at libcore.net.url.JarURLConnectionImpl.getInputStream(JarURLConnectionImpl.java:222)
       at java.net.URL.openStream(URL.java:470)
       at java.lang.ClassLoader.getResourceAsStream(ClassLoader.java:444)
       at java.lang.Class.getResourceAsStream(Class.java:1412)
       at com.dropbox.core.DbxSdkVersion.loadLineFromResource(DbxSdkVersion.java:34)
       at com.dropbox.core.DbxSdkVersion.loadVersion(DbxSdkVersion.java:56)
       at com.dropbox.core.DbxSdkVersion.(DbxSdkVersion.java)
       at com.dropbox.core.DbxRequestUtil.buildUserAgentHeader(DbxRequestUtil.java:151)
       at com.dropbox.core.DbxRequestUtil.addUserAgentHeader(DbxRequestUtil.java:136)
       at com.dropbox.core.DbxRequestUtil.startPostRaw(DbxRequestUtil.java:233)
       at com.dropbox.core.v2.DbxRawClientV2$1.execute(DbxRawClientV2.java:107)
       at com.dropbox.core.v2.DbxRawClientV2.executeRetriable(DbxRawClientV2.java:284)
       at com.dropbox.core.v2.DbxRawClientV2.rpcStyle(DbxRawClientV2.java:102)
       at com.dropbox.core.v2.users.DbxUserUsersRequests.getCurrentAccount(DbxUserUsersRequests.java:120)
       at mypackage.UserDropbox.(UserDropbox.java)


问:
Reading contents of different webpages and adding then together to put into another URL
I'm not advanced at python but its the best coding language I know. I'm doing this challenge that has 5 URLS which change contents every 10 seconds. They each contain part of a code. There is also a validation link which checks the urls I have clicked and checks if it the right code, if it is it will give me a code. So to solve this I'm writing a script that will get all the contents of the 5 URLs and concatenate them together and paste it in the URL of the validation link which will then give me a code which I need.

Here's my code

```<code>import urllib.request

fp1 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes1 = fp1.read()
fp1.close()

fp2 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes2 = fp2.read()
fp2.close()

fp3 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes3 = fp3.read()
fp3.close()

fp4 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes4 = fp4.read()
fp4.close()

fp5 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes5 = fp5.read()
fp5.close()

fp6 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/get-flag?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D&string=" + mybytes1 + mybytes2 + mybytes3 + mybytes4 + mybytes5)
mybytes6 = fp6.read()
fp6.close()

print(mybytes6)
</code>```

However I am getting an error which I don't understand.

```<code>Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1318, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1026, in _send_output
self.send(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 964, in send
self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1400, in connect
server_hostname=server_hostname)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 401, in wrap_socket
_context=self, _session=session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 808, in __init__
self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/sarvesh/Documents/scriptdis.py", line 3, in <module>
fp1 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 526, in open
response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 544, in _open
'_open', req)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1361, in https_open
context=self._context, check_hostname=self._check_hostname)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1320, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)>
</code>```

Can anyone help me understand what's wrong?

答:
urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

You are trying to open a website without a valid certificate. If you trust the website, then you need to create an uncertified context or urllib will throw the error you are seeing.

```<code>import ssl

# This restores the same behavior as before.
context = ssl._create_unverified_context()
fp1 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D", context=context)
</code>```

Body:
I'm not advanced at python but its the best coding language I know. I'm doing this challenge that has 5 URLS which change contents every 10 seconds. They each contain part of a code. There is also a validation link which checks the urls I have clicked and checks if it the right code, if it is it will give me a code. So to solve this I'm writing a script that will get all the contents of the 5 URLs and concatenate them together and paste it in the URL of the validation link which will then give me a code which I need.

Here's my code

import urllib.request

fp1 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes1 = fp1.read()
fp1.close()

fp2 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes2 = fp2.read()
fp2.close()

fp3 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes3 = fp3.read()
fp3.close()

fp4 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes4 = fp4.read()
fp4.close()

fp5 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
mybytes5 = fp5.read()
fp5.close()

fp6 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/get-flag?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D&string=" + mybytes1 + mybytes2 + mybytes3 + mybytes4 + mybytes5)
mybytes6 = fp6.read()
fp6.close()

print(mybytes6)

However I am getting an error which I don't understand.

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1318, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1026, in _send_output
self.send(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 964, in send
self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1400, in connect
server_hostname=server_hostname)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 401, in wrap_socket
_context=self, _session=session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 808, in __init__
self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/sarvesh/Documents/scriptdis.py", line 3, in <module>
fp1 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 526, in open
response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 544, in _open
'_open', req)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1361, in https_open
context=self._context, check_hostname=self._check_hostname)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1320, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)>

Can anyone help me understand what's wrong?

Body:
urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

You are trying to open a website without a valid certificate. If you trust the website, then you need to create an uncertified context or urllib will throw the error you are seeing.

import ssl

# This restores the same behavior as before.
context = ssl._create_unverified_context()
fp1 = urllib.request.urlopen("https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=Gl7fPRYxQvgBdbmhMo8vkA%3D%3D", context=context)


问:
Verify that a given string can be converted into a positive integer
I wrote method that checks if a given String input can be parsed as positive integer or not.

Is there a cleaner way to write this so I'm not repeating the code that rejects the value?

```<code>try {
  int num = Integer.parseInt(value);

  if (num <= 0) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
  }
} catch (NumberFormatException e) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}
</code>```

答:
One simple way:</p>

```<code>int num = 0;
try {
   num = Integer.parseInt(value);
 } catch (NumberFormatException e) {
    num = -1;
 }
 if (num <= 0) {
   errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
 }
</code>```

Body:
I wrote method that checks if a given String input can be parsed as positive integer or not.

Is there a cleaner way to write this so I'm not repeating the code that rejects the value?

try {
  int num = Integer.parseInt(value);

  if (num <= 0) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
  }
} catch (NumberFormatException e) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}

Body:
One simple way:

int num = 0;
try {
   num = Integer.parseInt(value);
 } catch (NumberFormatException e) {
    num = -1;
 }
 if (num <= 0) {
   errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
 }


问:
Any plans for "do"/Action LINQ operator?
Here's a simple method with a foreach loop:

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}
</code>```

Kind of ugly. If there were some operator in LINQ that mean "do something" (e.g. perform an Action for each selected in the LINQ statement), it would look nicer, more terse:

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}
</code>```

I realize that's subjective, and just my opinion. For a foreach loop that has one line that simply invokes a method, a "do" operator makes sense, in my opinion. But I'm wondering if anyone at MS has thought the same thing. Is such LINQ operator planned in any upcoming releases (e.g. alongside the C# 4.0 debut)?

Here's another example, with a predicate, where the fictitious do operator would really make the code look cleaner. This:

```<code>IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance).Where(predicate))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}
</code>```

vs. this:

```<code>IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    where predicate(field)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}
</code>```

答:
If you are simply looking at calling a function from within your linq statement then you can already do that, you can make a call out to a function in a Let assignment.</p>

```<code>var qry = from e in somelist
          let errorcode = DoSomeProcessing(e)
          select e;
</code>```

OwnerDisplayName: Chris

Body:
Here's a simple method with a foreach loop:

IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}

Kind of ugly. If there were some operator in LINQ that mean "do something" (e.g. perform an Action for each selected in the LINQ statement), it would look nicer, more terse:

IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}

I realize that's subjective, and just my opinion. For a foreach loop that has one line that simply invokes a method, a "do" operator makes sense, in my opinion. But I'm wondering if anyone at MS has thought the same thing. Is such LINQ operator planned in any upcoming releases (e.g. alongside the C# 4.0 debut)?

Here's another example, with a predicate, where the fictitious do operator would really make the code look cleaner. This:

IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance).Where(predicate))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}

vs. this:

IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    where predicate(field)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}

Body:
If you are simply looking at calling a function from within your linq statement then you can already do that, you can make a call out to a function in a Let assignment.

var qry = from e in somelist
          let errorcode = DoSomeProcessing(e)
          select e;

OwnerDisplayName: Tim J


问:
How to read integers elegantly using C++ stream?
I have a file full of lines in this format:

```<code>1 - 2: 3
</code>```

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

答:
I would recommend doing at least cursory sanity checks when reading this:

```<code>int a, b, c;
char dash, colon;

if (not (cin >> a >> dash >> b >> colon >> c) or dash != '-' or colon != ':')
    Failure. Do something.
</code>```

Body:
I have a file full of lines in this format:

1 - 2: 3

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

Body:
I would recommend doing at least cursory sanity checks when reading this:

int a, b, c;
char dash, colon;

if (not (cin >> a >> dash >> b >> colon >> c) or dash != '-' or colon != ':')
    Failure. Do something.


问:
JavaScript Advanced Object Keys
I'm making a Chrome app that requires advanced Object.keys() that I can't seem to find anywhere. Here's some of my code.

```<code>Dictionary = {
  C: {
    "calculation": {"definitions":["a process or result of calculating
    something.", "careful thought and planning that is done usually for
    selfish reasons.]}
  },

  Search: function(word) {
    var foundWordInfo = {Word:null, Definitions:[]};
    var allDictionaryKeys = Object.keys(Dictionary);
    var firstLetter = word.charAt(0).toUpperCase();
    var letterIndex = allDictionaryKeys.indexOf(firstLetter);

    var wordKeys = Object.keys(Dictionary[firstLetter]);
    for(i=0; i<wordKeys.length; i++) {
      if (wordKeys[i] == word) {
        foundWordInfo.Word = wordKeys[i];
        break;
      } else {}
    }

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

The way it works is you use

```<code>var search = Dictionary.Search("calculation");
</code>```

where the search variable is equal to the Dictionary.Search foundWordInfo object.

The search variable does return the word but the definitions always return as either undefined or null. I've tried things like

```<code>var definitions = wordKeys[i].Definitions;
</code>```

and

```<code>var definitions = Dictionary[letterIndex][wordKeys[i]].Definitions;
</code>```

but nothing I've used so far works. I'd prefer something like

```<code>var definitions = wordKeys[i].Definitions;
</code>```

but as of right now I'll use what I can get. Any help is appreciated. Thanks.

答:
You can access the word definitions using Dictionary[firstLetter][wordKeys[i]].definitions

var Dictionary = {
  C: {
    "calculation": {"definitions":["a process or result of calculating something.", "careful thought and planning that is done usually for selfish reasons."]}
  },

  Search: function(word) {
    var foundWordInfo = {Word:null, Definitions:[]};
    var allDictionaryKeys = Object.keys(Dictionary);
    var firstLetter = word.charAt(0).toUpperCase();
    var wordKeys = Object.keys(Dictionary[firstLetter]);
    for(i=0; i< wordKeys.length; i++) {
      if (wordKeys[i] == word) {
        foundWordInfo.Word = wordKeys[i];
        foundWordInfo.Definitions = Dictionary[firstLetter][wordKeys[i]].definitions;
        break;
      } else {}
    }
    return foundWordInfo;
}
}
var search = Dictionary.Search("calculation");
console.log(search);```
</div>
</div>
</p>

<p>Alternatively, you can do like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var Dictionary = {
  C: {
    "calculation": {"definitions":["a process or result of calculating something.", "careful thought and planning that is done usually for selfish reasons."]}
  },

  Search: function(word) {
    var foundWordInfo = {Word:null, Definitions:[]};
    var firstLetter = word.charAt(0).toUpperCase();
    foundWordInfo.Word = Object.keys(Dictionary[firstLetter]).find(function(key) {
      return key === word;
    }) || null;
    if(foundWordInfo.Word)
      foundWordInfo.Definitions = Dictionary[firstLetter][word].definitions;
    return foundWordInfo;
}
}
var search = Dictionary.Search("calculation");
console.log(search);</code>```

Title: JavaScript Advanced Object Keys

Body:
I'm making a Chrome app that requires advanced Object.keys() that I can't seem to find anywhere. Here's some of my code.

Dictionary = {
  C: {
    "calculation": {"definitions":["a process or result of calculating
    something.", "careful thought and planning that is done usually for
    selfish reasons.]}
  },

  Search: function(word) {
    var foundWordInfo = {Word:null, Definitions:[]};
    var allDictionaryKeys = Object.keys(Dictionary);
    var firstLetter = word.charAt(0).toUpperCase();
    var letterIndex = allDictionaryKeys.indexOf(firstLetter);

    var wordKeys = Object.keys(Dictionary[firstLetter]);
    for(i=0; i<wordKeys.length; i++) {
      if (wordKeys[i] == word) {
        foundWordInfo.Word = wordKeys[i];
        break;
      } else {}
    }

    return foundWordInfo;
};

The way it works is you use

var search = Dictionary.Search("calculation");

where the search variable is equal to the Dictionary.Search foundWordInfo object.

The search variable does return the word but the definitions always return as either undefined or null. I've tried things like

var definitions = wordKeys[i].Definitions;

and

var definitions = Dictionary[letterIndex][wordKeys[i]].Definitions;

but nothing I've used so far works. I'd prefer something like

var definitions = wordKeys[i].Definitions;

but as of right now I'll use what I can get. Any help is appreciated. Thanks.

Body:
You can access the word definitions using Dictionary[firstLetter][wordKeys[i]].definitions

var Dictionary = {
  C: {
    "calculation": {"definitions":["a process or result of calculating something.", "careful thought and planning that is done usually for selfish reasons."]}
  },

  Search: function(word) {
    var foundWordInfo = {Word:null, Definitions:[]};
    var allDictionaryKeys = Object.keys(Dictionary);
    var firstLetter = word.charAt(0).toUpperCase();
    var wordKeys = Object.keys(Dictionary[firstLetter]);
    for(i=0; i< wordKeys.length; i++) {
      if (wordKeys[i] == word) {
        foundWordInfo.Word = wordKeys[i];
        foundWordInfo.Definitions = Dictionary[firstLetter][wordKeys[i]].definitions;
        break;
      } else {}
    }
    return foundWordInfo;
}
}
var search = Dictionary.Search("calculation");
console.log(search);

Alternatively, you can do like this.

var Dictionary = {
  C: {
    "calculation": {"definitions":["a process or result of calculating something.", "careful thought and planning that is done usually for selfish reasons."]}
  },

  Search: function(word) {
    var foundWordInfo = {Word:null, Definitions:[]};
    var firstLetter = word.charAt(0).toUpperCase();
    foundWordInfo.Word = Object.keys(Dictionary[firstLetter]).find(function(key) {
      return key === word;
    }) || null;
    if(foundWordInfo.Word)
      foundWordInfo.Definitions = Dictionary[firstLetter][word].definitions;
    return foundWordInfo;
}
}
var search = Dictionary.Search("calculation");
console.log(search);


问:
Where do I put front-end code in my backend project and how/when to run it?
The question is, say I have written a backend REST service using Python, and then some other guy wrote some frontend code in Angular JS. Is the typical workflow putting them into two separate folders and run them separately? So the process will look like below

```<code>python manage.py runserver
</code>```

in Python colder and then probably

```<code># in the angular2 folder
npm start
</code>```

Or should I place all the JS code into some assets folder and when I start my server, all the JS code will run automatically with them? If so, how should I do it?

Another question related is, when is all the JS code sent to users’ browsers? If the app is a client-side rendering app, is the code sent to browser at the first time of server requesting? How does the server know it should package your JS code and ship it?

答:
Q)The question is, say I have written a backend REST service using Python, and then some other guy wrote some frontend code in Angular JS. Is the typical workflow putting them into two separate folders and run them separately?

Both Angular and Python can be run differently as well as together.
You could choose to place the Angular files (which qualify for all practical purposes as public files) in the public (or related folder) depending on which framework you're using - Django, Flask, Web2py or so on.

You can also choose to run them independently as standalone apps.

Depends on your requirement. Honestly, there are so many ways to answer this question.

Q)Or should I place all the JS code into some assets folder and when I start my server, all the JS code will run automatically with them? If so, how should I do it?
If you place everything in your assets folder, then as soon as the home route  or any other route is made a request for [from a browser] , the public folder passes on to the browser.
Although I'm not sure if it is the case with server side rendering.
If you're using Angular 1, I do not think it fits server side rendering although you could use some libraries out there.

Q)Another question related is, when is all the JS code sent to users’ browsers? If the app is a client-side rendering app, is the code sent to browser at the first time of server requesting? How does the server know it should package your JS code and ship it?
All the files in PUBLIC folder on the server are accessible by a browser.

All of your questions seem to essentially ask the same question.

Body:
The question is, say I have written a backend REST service using Python, and then some other guy wrote some frontend code in Angular JS. Is the typical workflow putting them into two separate folders and run them separately? So the process will look like below

python manage.py runserver

in Python colder and then probably

# in the angular2 folder
npm start

Or should I place all the JS code into some assets folder and when I start my server, all the JS code will run automatically with them? If so, how should I do it?

Another question related is, when is all the JS code sent to users’ browsers? If the app is a client-side rendering app, is the code sent to browser at the first time of server requesting? How does the server know it should package your JS code and ship it?


问:
Can't Sign Signature: error: Task failed with exit 1 signal 0 {
Getting error "Can't verify/Sign Signature: error: Task failed with exit 1 signal 0 {"

Xcode9.1
iOS 11.1
iPhone 6

I've googled and seen lot of this error asked, but none of the solutions work in my case (delete Derived Data & clean build folder).

When I try to make a build to my iPhone, I get this error (signed in on correct AppleID and so on). Build in simulator works fine. It did work by creating a new AppleID, and then verify it in 'profiles & device management', but I can't jump between the new AppleID and my main one.

Sorry if I got some expressions wrong, started with Xcode today. Thanks!

答:
This is an issue that I ran into while trying to build an app and simulating it on my phone.

Solution : When prompted to enter your password in keychain, press the 'always allow', not simply allow.

If you are currently in this process, restart your computer, then open Xcode, and simulate on a Generic device, then you should get prompted to re-enter your password again. Make sure to click always allow.

(if this didn't work, then make sure that all your sign in certificates are good to go and updated).

If that still doesn't work, try to upload the app to the iTunes Connect to testflight the app.

Hope this works. :)


问:
Wordpress blog doesn't show up online?
I have created a self-hosted wordpress blog and on my ftp server everything is under

```<code>     /public_html/wordpress/..
         then you have /wp-admin and /wp-content etc..
</code>```

but when I got to my website the theme doesn't show up, it only shows a white page with

```<code>    www.******.co.cc

    " index of
    /wordpress"
</code>```

I figured out the wordpress blog has installed its own directory so if I want to see my website I need to enter that directory first. So I tried to type

```<code>   www.*******.co.cc/wordpress/
</code>```

and it worked my website is all here.

BUT ! I don't wanna have people to type www.**.co.cc/wordpress/ since the site was originially known without adding /wordpress at the end.

If I move all my wordpress folders under the root

```<code>   /public_html .. will it work ??
</code>```

答:
This is because you have installed your wordpress script in the

public_html >> wordpress

Install your wordpress in the root i.e left the directory field empty

/

Title: Wordpress blog doesn't show up online?

Body:
I have created a self-hosted wordpress blog and on my ftp server everything is under

     /public_html/wordpress/..
         then you have /wp-admin and /wp-content etc..

but when I got to my website the theme doesn't show up, it only shows a white page with

    www.******.co.cc

    " index of
    /wordpress"

I figured out the wordpress blog has installed its own directory so if I want to see my website I need to enter that directory first. So I tried to type

   www.*******.co.cc/wordpress/

and it worked my website is all here.

BUT ! I don't wanna have people to type www.**.co.cc/wordpress/ since the site was originially known without adding /wordpress at the end.

If I move all my wordpress folders under the root

   /public_html .. will it work ??


问:
Cannot assign a value of type ViewController to a value of type UITextFieldDelegate?
Here's the error when I wrote the line self.MessageTextField.delegate = self:

/ChatApp/ViewController.swift:27:42: Cannot assign a value of type 'ViewController' to a value of type 'UITextFieldDelegate?'

Here's my Swift code (ViewerController.swift):

```<code>//
//  ViewController.swift
//  ChatApp
//
//  Created by David Chen on 15/4/12.
//  Copyright (c) 2015年 cwsoft. All rights reserved.
//

import UIKit
import Parse

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var messagesArray:[String] = [String]()

    @IBOutlet weak var MessageTableView: UITableView!
    @IBOutlet weak var ButtonSend: UIButton!
    @IBOutlet weak var DockViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var MessageTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        //
        self.MessageTableView.delegate = self
        self.MessageTableView.dataSource = self
        //Set delegate
        self.MessageTextField.delegate = self

        self.messagesArray.append("Test 1")
        self.messagesArray.append("Test 2")
        self.messagesArray.append("Test 3")
    }

    @IBAction func ButtonSendPressed(sender: UIButton) {
        self.view.layoutIfNeeded()
        UIView.animateWithDuration(0.5, animations: {
            self.DockViewHeightConstraint.constant = 400
            self.view.layoutIfNeeded()
            }, completion: nil)
    }

    //MARK : TextField Delegage Methods

    //MARK : Table View Delegate Methods

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.MessageTableView.dequeueReusableCellWithIdentifier("MessageCell") as! UITableViewCell
        cell.textLabel?.text = self.messagesArray[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messagesArray.count
    }
}
</code>```

答:
I had the same problem, but it was because of a different issue:

```<code>class CustomViewController: UIViewController {

    let customerCardTableView: UITableView = {
        let table = UITableView()
        table.translatesAutoresizingMaskIntoConstraints = false
        table.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
        table.delegate = self
        table.dataSource = self
        table.separatorStyle = .none
        table.separatorColor = UIColor(rgb:0xFFFFFF)
        table.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)

        return table
    }()

    ...other code
}
</code>```

and I did extend my CustomViewController to conform to the UITableViewDelegate, UITableViewDataSource protocols.

The reason was that self isn't accessible if you're using let. I had to lazy var customerCardTableView: UITableView i.e.:

```<code>lazy var customerCardTableView: UITableView = {
    let table = UITableView()
    table.translatesAutoresizingMaskIntoConstraints = false
    table.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
    table.delegate = self
    table.dataSource = self
    table.separatorStyle = .none
    table.separatorColor = UIColor(rgb:0xFFFFFF)
    table.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)

    return table
}()
</code>```

lets are required to happen during instantiation, but lazy vars can be delayed to a time after instantiation, hence they can access self...

ContentLicense: CC BY-SA 4.0

Body:
Here's the error when I wrote the line self.MessageTextField.delegate = self:

/ChatApp/ViewController.swift:27:42: Cannot assign a value of type 'ViewController' to a value of type 'UITextFieldDelegate?'

Here's my Swift code (ViewerController.swift):

//
//  ViewController.swift
//  ChatApp
//
//  Created by David Chen on 15/4/12.
//  Copyright (c) 2015年 cwsoft. All rights reserved.
//

import UIKit
import Parse

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var messagesArray:[String] = [String]()

    @IBOutlet weak var MessageTableView: UITableView!
    @IBOutlet weak var ButtonSend: UIButton!
    @IBOutlet weak var DockViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var MessageTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        //
        self.MessageTableView.delegate = self
        self.MessageTableView.dataSource = self
        //Set delegate
        self.MessageTextField.delegate = self

        self.messagesArray.append("Test 1")
        self.messagesArray.append("Test 2")
        self.messagesArray.append("Test 3")
    }

    @IBAction func ButtonSendPressed(sender: UIButton) {
        self.view.layoutIfNeeded()
        UIView.animateWithDuration(0.5, animations: {
            self.DockViewHeightConstraint.constant = 400
            self.view.layoutIfNeeded()
            }, completion: nil)
    }

    //MARK : TextField Delegage Methods

    //MARK : Table View Delegate Methods

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.MessageTableView.dequeueReusableCellWithIdentifier("MessageCell") as! UITableViewCell
        cell.textLabel?.text = self.messagesArray[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messagesArray.count
    }
}

Body:
I had the same problem, but it was because of a different issue:

class CustomViewController: UIViewController {

    let customerCardTableView: UITableView = {
        let table = UITableView()
        table.translatesAutoresizingMaskIntoConstraints = false
        table.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
        table.delegate = self
        table.dataSource = self
        table.separatorStyle = .none
        table.separatorColor = UIColor(rgb:0xFFFFFF)
        table.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)

        return table
    }()

    ...other code
}

and I did extend my CustomViewController to conform to the UITableViewDelegate, UITableViewDataSource protocols.

The reason was that self isn't accessible if you're using let. I had to lazy var customerCardTableView: UITableView i.e.:

lazy var customerCardTableView: UITableView = {
    let table = UITableView()
    table.translatesAutoresizingMaskIntoConstraints = false
    table.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
    table.delegate = self
    table.dataSource = self
    table.separatorStyle = .none
    table.separatorColor = UIColor(rgb:0xFFFFFF)
    table.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)

    return table
}()

lets are required to happen during instantiation, but lazy vars can be delayed to a time after instantiation, hence they can access self...


问:
How to map an object of getters to their value?
I have this function applyObject that I want to propertly type. The paramters to the function are of T and V where V is an object of functions:

```<code>type V = { [key: string]: <R>(t: T) => R };
</code>```

and T is the type I want to feed across all the functions of V when applied. Is there any way to do this?

I'm thinking it's possible with a mapped type but I'm unsure. I'm thinking like this:

```<code>function applyObject<T, V extends { [key: string]: (t: T) => any }>(t: T, v: V) {
  return Object.entries(v).reduce((applied, [_key, func]) => {
    const key = _key as keyof V;
    applied[key] = func(t);
    return applied;
  }, {} as {[P in keyof V]: Invoke<V[P]>}); // `Invoke` doesn't exist
}

const applied = applyObject(
  { one: 1, two: 'something' },
  { a: t => t.one, b: t => t.two }
);

applied.a; // should give intellisense as number
applied.b // should give intellisense as string
</code>```

答:
How about this:

```<code>type V<T, A> = {[K in keyof A]: (t: T) => A[K]};
function applyObject<T, A extends any>(t: T, v: V<T, A>): A {
  const ret = {} as A;
  for (const k in v) {
    ret[k] = v[k](t);
  }
  return ret;
}

const applied = applyObject(
  { one: 1, two: 'something' },
  { a: t => t.one, b: t => t.two }
); // inferred as {a: number, b: string}
</code>```

The idea is to express the V type in terms of the input object type T, and the type A of the intended return value of applyObject().  The keys of V<T,A> are the same as those of A, and the values are functions from T to the appropriate property type of A.  And this definition lets you use inference from mapped types to type applyObject().

(There's a little caveat here.  If you see, I defined the A parameter in applyObject() to be A extends any.  That shouldn't be necessary; every type extends any in TypeScript.  But without it, A gets inferred as {a: any, b: any} which isn't particularly useful.  I have no idea why A extends any fixes it, but it does.  Someone better acquainted with the nitty gritty of TypeScript type inference have any ideas?)

I also modified the implementation since it was easier for me to convince TypeScript that it was type-safe.  Feel free to use your own implementation, if you can make TypeScript happy or force it into silence.

Anyway, hope that helps. Good luck!

Body:
I have this function applyObject that I want to propertly type. The paramters to the function are of T and V where V is an object of functions:

type V = { [key: string]: <R>(t: T) => R };

and T is the type I want to feed across all the functions of V when applied. Is there any way to do this?

I'm thinking it's possible with a mapped type but I'm unsure. I'm thinking like this:

function applyObject<T, V extends { [key: string]: (t: T) => any }>(t: T, v: V) {
  return Object.entries(v).reduce((applied, [_key, func]) => {
    const key = _key as keyof V;
    applied[key] = func(t);
    return applied;
  }, {} as {[P in keyof V]: Invoke<V[P]>}); // `Invoke` doesn't exist
}

const applied = applyObject(
  { one: 1, two: 'something' },
  { a: t => t.one, b: t => t.two }
);

applied.a; // should give intellisense as number
applied.b // should give intellisense as string

Body:
How about this:

type V<T, A> = {[K in keyof A]: (t: T) => A[K]};
function applyObject<T, A extends any>(t: T, v: V<T, A>): A {
  const ret = {} as A;
  for (const k in v) {
    ret[k] = v[k](t);
  }
  return ret;
}

const applied = applyObject(
  { one: 1, two: 'something' },
  { a: t => t.one, b: t => t.two }
); // inferred as {a: number, b: string}

The idea is to express the V type in terms of the input object type T, and the type A of the intended return value of applyObject().  The keys of V<T,A> are the same as those of A, and the values are functions from T to the appropriate property type of A.  And this definition lets you use inference from mapped types to type applyObject().

(There's a little caveat here.  If you see, I defined the A parameter in applyObject() to be A extends any.  That shouldn't be necessary; every type extends any in TypeScript.  But without it, A gets inferred as {a: any, b: any} which isn't particularly useful.  I have no idea why A extends any fixes it, but it does.  Someone better acquainted with the nitty gritty of TypeScript type inference have any ideas?)

I also modified the implementation since it was easier for me to convince TypeScript that it was type-safe.  Feel free to use your own implementation, if you can make TypeScript happy or force it into silence.

Anyway, hope that helps. Good luck!


问:
How does event handlers with arrow functions achieve context binding
I know about the general theory of this binding (function call site what matters, implicit, explicit binding, etc...) and the methods to solving the problem of this binding in React so it always points to what I want this to be (binding in constructor, arrow functions, etc), but I am struggling to get the inner mechanisms.

Take a look at these two pieces of code:

```<code>class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={(e) => this.goToStore(e)}>test</button>
  }
}
</code>```

vs.

```<code>class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={this.goToStore}>test</button>
  }
}
</code>```

What I know is that:

in both versions we end up successfully in the goToStore method, because the this inside the render() method is automatically bound (by React) to the component instance

the first one succeeds because of that,

the second one fails, because class methods in es6 are not bound to the component instance, thus resolving this in the method to undefined

In theory in the first version as far as I understand, the following occurs:

the button click handler is an anonymous arrow function, so whenever I reference this inside of it, it picks up this from the environment (in this case from render())

then it calls the goToStore method, that is a regular function.

because the call seems to fit the rules of implicit binding (object.function()) object will be the context object and in such function calls it will be used as this

so, inside the goToStore method the lexically picked up this (used as a context object) will resolve to the component instance correctly

I feel 3. and 4. is not the case here, because then it would apply to the 2. case:

```<code><button onClick={this.goToStore}>test</button>
</code>```

Also with this the context object.

What is happening exactly in this particular case, step-by-step?

答:
As the MDN docs states

An arrow function does not have its own this; the this value of the
  enclosing execution context is used

So you would think of

```<code>onClick={(e) => this.goToStore(e)}
</code>```

as being an anonymous function which can be written as

```<code>    (e) => {
         return this.goToStore(e)
    }
</code>```

Now here in this anonymous function this refers to the lexical context of the render function which in turn refers to the React Class instance.

Now

Context is most often determined by how a function is invoked. When a function is called as a method of an object, this is set to the object the method is called on:

```<code>var obj = {
    foo: function() {
        return this;
    }
};

obj.foo() === obj; // true
</code>```

The same principle applies when invoking a function with the new operator to create an instance of an object. When invoked in this manner, the value of this within the scope of the function will be set to the newly created instance:

```<code>function foo() {
    alert(this);
}

foo() // window
new foo() // foo
</code>```

When called as an unbound function, this will default to the global context or window object in the browser.

So here since the function is called like this.goToStore()  this inside it will refer to the context of React component.

However when you write onClick={this.goToStore}, the function is not executed but a reference of it is assigned to the onClick function, which then later invokes it, causing this to be undefined inside the function as the function runs on the context of the  window object.

Now even though onClick={(e) => this.goToStore(e)} works, whenever render is called a new function instance is created. In your case its easy to avoid, just by created the function goToStore using arrow function syntax.

```<code>goToStore = (e) => {

}
</code>```

Check the docs for more details on this

Body:
I know about the general theory of this binding (function call site what matters, implicit, explicit binding, etc...) and the methods to solving the problem of this binding in React so it always points to what I want this to be (binding in constructor, arrow functions, etc), but I am struggling to get the inner mechanisms.

Take a look at these two pieces of code:

class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={(e) => this.goToStore(e)}>test</button>
  }
}

vs.

class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={this.goToStore}>test</button>
  }
}

What I know is that:

in both versions we end up successfully in the goToStore method, because the this inside the render() method is automatically bound (by React) to the component instance

the first one succeeds because of that,

the second one fails, because class methods in es6 are not bound to the component instance, thus resolving this in the method to undefined

In theory in the first version as far as I understand, the following occurs:

the button click handler is an anonymous arrow function, so whenever I reference this inside of it, it picks up this from the environment (in this case from render())

then it calls the goToStore method, that is a regular function.

because the call seems to fit the rules of implicit binding (object.function()) object will be the context object and in such function calls it will be used as this

so, inside the goToStore method the lexically picked up this (used as a context object) will resolve to the component instance correctly

I feel 3. and 4. is not the case here, because then it would apply to the 2. case:

<button onClick={this.goToStore}>test</button>

Also with this the context object.

What is happening exactly in this particular case, step-by-step?

Body:
As the MDN docs states

An arrow function does not have its own this; the this value of the
  enclosing execution context is used

So you would think of

onClick={(e) => this.goToStore(e)}

as being an anonymous function which can be written as

    (e) => {
         return this.goToStore(e)
    }

Now here in this anonymous function this refers to the lexical context of the render function which in turn refers to the React Class instance.

Now

Context is most often determined by how a function is invoked. When a function is called as a method of an object, this is set to the object the method is called on:

var obj = {
    foo: function() {
        return this;
    }
};

obj.foo() === obj; // true

The same principle applies when invoking a function with the new operator to create an instance of an object. When invoked in this manner, the value of this within the scope of the function will be set to the newly created instance:

function foo() {
    alert(this);
}

foo() // window
new foo() // foo

When called as an unbound function, this will default to the global context or window object in the browser.

So here since the function is called like this.goToStore()  this inside it will refer to the context of React component.

However when you write onClick={this.goToStore}, the function is not executed but a reference of it is assigned to the onClick function, which then later invokes it, causing this to be undefined inside the function as the function runs on the context of the  window object.

Now even though onClick={(e) => this.goToStore(e)} works, whenever render is called a new function instance is created. In your case its easy to avoid, just by created the function goToStore using arrow function syntax.

goToStore = (e) => {

}

Check the docs for more details on this


问:
VBA powerpoint Strikethrough of a single word
I have a powerpoint file with several sheets. On this sheets are text fields with texts. Some of the words are strikethrough. I would like to make a list of all the slides where a word exists which is strike through.
I tried to use the function:
If  objShape.TextFrame2.TextRange.Font.Strikethrough = True Then

Problem is that is only get true when the first word is strike through. So
Hallo jaja the function works.
Hallo jaja  function does not work
Does anybody have a solution for this?

答:
Since only SOME text within a text box may be underlined, you need to look at the .Runs collection for each shape that has text in order to extract just the struck-out text. Here's a start:</p>

```<code>Sub ListStrikeThroughText()
' This will list the struck-through text from Slide 1
' Adapt as needed to collect all of the text from all slides

Dim sTextList As String
Dim oShp As Shape
Dim oRng As TextRange2
Dim x As Long

With ActivePresentation.Slides(1)
    For Each oShp In .Shapes
        If oShp.HasTextFrame And oShp.TextFrame2.HasText Then
            With oShp.TextFrame2.TextRange
                For x = 1 To .Runs.Count
                    If .Runs(x).Font.Strikethrough Then
                        sTextList = sTextList & .Runs(x).Text & vbCrLf
                    End If
                Next
            End With

        End If
    Next
End With

MsgBox sTextList

End Sub
</code>```

Body:
Since only SOME text within a text box may be underlined, you need to look at the .Runs collection for each shape that has text in order to extract just the struck-out text. Here's a start:

Sub ListStrikeThroughText()
' This will list the struck-through text from Slide 1
' Adapt as needed to collect all of the text from all slides

Dim sTextList As String
Dim oShp As Shape
Dim oRng As TextRange2
Dim x As Long

With ActivePresentation.Slides(1)
    For Each oShp In .Shapes
        If oShp.HasTextFrame And oShp.TextFrame2.HasText Then
            With oShp.TextFrame2.TextRange
                For x = 1 To .Runs.Count
                    If .Runs(x).Font.Strikethrough Then
                        sTextList = sTextList & .Runs(x).Text & vbCrLf
                    End If
                Next
            End With

        End If
    Next
End With

MsgBox sTextList

End Sub


问:
Is there a shorter way to provide an Observable onComplete handler?

I'm working with an Observable chain and I'm not interested in the next or error values, only when the chain has fully complete.  It feels wrong to tap into the subscribe method and supply 2 noops for next and error just so I can provide an onComplete callback.

For Example:

```<code>let isRunning = true;

Observable.from([1000, 2000, 3000])
  .concatMap(value => Observable.timer(value)
  .subscribe(
    () => {},
    () => {},
    () => isRunning = false;
  );
</code>```

What I'd like is something that looks like this

```<code>let isRunning = true;

Observable.from([1000, 2000, 3000])
  .concatMap(value => Observable.timer(value)
  .onComplete(() => isRunning = false);
</code>```

答:
No, there's no shortcut. However, you can pass null instead of empty functions.

```<code>obs$.subscribe(null, null, () => this.isRunning = false);
</code>```

If you want some kind of trick you could also do

```<code>obs$.last().subscribe(() => this.isRunning = false);
</code>```

This would make sense if, for example, you need access to the last emitted value in the completion handler.

Body:
I'm working with an Observable chain and I'm not interested in the next or error values, only when the chain has fully complete.  It feels wrong to tap into the subscribe method and supply 2 noops for next and error just so I can provide an onComplete callback.

For Example:

let isRunning = true;

Observable.from([1000, 2000, 3000])
  .concatMap(value => Observable.timer(value)
  .subscribe(
    () => {},
    () => {},
    () => isRunning = false;
  );

What I'd like is something that looks like this

let isRunning = true;

Observable.from([1000, 2000, 3000])
  .concatMap(value => Observable.timer(value)
  .onComplete(() => isRunning = false);

Body:
No, there's no shortcut. However, you can pass null instead of empty functions.

obs$.subscribe(null, null, () => this.isRunning = false);

If you want some kind of trick you could also do

obs$.last().subscribe(() => this.isRunning = false);

This would make sense if, for example, you need access to the last emitted value in the completion handler.


问:
LINQ query multiple conditions
I need to have multiple conditions in my LINQ.

I have a database with id, Name, and pID. For instance, the data would be:

```<code>id=1 | Name='A1' | pID = 0
id=2 | Name='A2' | pID = 0
id=3 | Name='A3' | pID = 0
id=4 | Name='A2' | pID = 5
</code>```

In this case the pID=0 is the defaults data. However, when someone edit a specific Name, a new record is inserted for this name with a new pID. My problem is when I try to query this data. I need to get all the Names for a specific pID and the defaults, but I can't have the same names.
I want a query that return the ids 1, 4, and 3.

I tried it:

```<code>int id = 5;

var test= db.MyTable.Where(a => a.pID == id).ToList();
</code>```

It only returns the row with id=4

```<code>int id = 5;

var test= db.MyTable.Where(a => a.pID == id || a.pID == 0).ToList();
</code>```

It return everything.

Does anyone know how to query it using LINQ?

答:
Something like this should work for you</p>

```<code>var listOfIds = from x in db.MyTable
                     group x by x.Name
                  into groups
                     select groups.OrderByDescending(p => p.pID).First();
</code>```

Title: LINQ query multiple conditions

Body:
I need to have multiple conditions in my LINQ.

I have a database with id, Name, and pID. For instance, the data would be:

id=1 | Name='A1' | pID = 0
id=2 | Name='A2' | pID = 0
id=3 | Name='A3' | pID = 0
id=4 | Name='A2' | pID = 5

In this case the pID=0 is the defaults data. However, when someone edit a specific Name, a new record is inserted for this name with a new pID. My problem is when I try to query this data. I need to get all the Names for a specific pID and the defaults, but I can't have the same names.
I want a query that return the ids 1, 4, and 3.

I tried it:

int id = 5;

var test= db.MyTable.Where(a => a.pID == id).ToList();

It only returns the row with id=4

int id = 5;

var test= db.MyTable.Where(a => a.pID == id || a.pID == 0).ToList();

It return everything.

Does anyone know how to query it using LINQ?

Body:
Something like this should work for you

var listOfIds = from x in db.MyTable
                     group x by x.Name
                  into groups
                     select groups.OrderByDescending(p => p.pID).First();


问:
Adding products to a new sales quote through the Odoo API (Java)
I'm creating new sales quotes programatically through the Odoo API like so:

```<code>final Object orderLineItem = asList((Object[]) models.execute("execute_kw", asList(
    db, uid, password,
    "sale.order.line", "search",
    asList(asList()),
    new HashMap() {{
      put("limit", 10);
    }})
  )).get(0);

final Integer id = (Integer) models.execute("execute_kw", asList(
    db, uid, password,
    "sale.order", "create",
    asList(new HashMap() {{
      put("currency_id", resCurrency);
      put("date_order", dateTime);
      put("partner_id", resPartnerId);
      put("picking_policy", "");
      put("pricelist_id", productPricelistId);
      put("name", name);
      put("warehouse_id", stockWarehouseId);
      put("partner_invoice_id", resPartnerId);
      put("partner_shipping_id", resPartnerId);
      put("access_token", "");
      put("order_line", asList(
        asList(1, false, new HashMap<String, Object>() {{
          put("product_id", orderLineItem);
        }})));
    }})
  ));
</code>```

However, I'm unable to list products in the quotation's order_line section. Order_line has a one to many relation, but I'm not sure if thats a relationship to products that can be sold to a customer, or something entirely different.

I know the the sale.order.line resources contains all of my 'order_lines' or products, but I'm not sure how to add these products to a new sales quote.

Any help in Java or a python equivalent would be greatly appreciated.

答: Solved this by making orderLineItem a resource of product.prodcut</p>

Body:
I'm creating new sales quotes programatically through the Odoo API like so:

final Object orderLineItem = asList((Object[]) models.execute("execute_kw", asList(
    db, uid, password,
    "sale.order.line", "search",
    asList(asList()),
    new HashMap() {{
      put("limit", 10);
    }})
  )).get(0);

final Integer id = (Integer) models.execute("execute_kw", asList(
    db, uid, password,
    "sale.order", "create",
    asList(new HashMap() {{
      put("currency_id", resCurrency);
      put("date_order", dateTime);
      put("partner_id", resPartnerId);
      put("picking_policy", "");
      put("pricelist_id", productPricelistId);
      put("name", name);
      put("warehouse_id", stockWarehouseId);
      put("partner_invoice_id", resPartnerId);
      put("partner_shipping_id", resPartnerId);
      put("access_token", "");
      put("order_line", asList(
        asList(1, false, new HashMap<String, Object>() {{
          put("product_id", orderLineItem);
        }})));
    }})
  ));

However, I'm unable to list products in the quotation's order_line section. Order_line has a one to many relation, but I'm not sure if thats a relationship to products that can be sold to a customer, or something entirely different.

I know the the sale.order.line resources contains all of my 'order_lines' or products, but I'm not sure how to add these products to a new sales quote.

Any help in Java or a python equivalent would be greatly appreciated.


问:
Embedded Interop REGDB_E_CLASSNOTREG error on client machine
I've compiled my app as x86.
I'm using a VB6 COM Interop in my app.
I've set the reference to "Embed Interop type=Yes", "Isolated=No".

I don't need to install anything on the client machine, not even the "Interop.MyDLL.dll", it magically worked without installing anything.

I can test this easily on my test computer, it works just fine.

Now, on a client machine the error "System.TypeInitializationException, class not registered, HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)" is thrown when I try to access the DLL.

It occured after I recompiled the app and deployed it. Before that, it worked fine.

What might be the culprit here?

答:
There's not "magic" with COM, you must register the VB6 COM component (dll, ocx, etc.).

The interop .NET dll is not a COM component, it just contains metadata/binding from .NET to COM, so it doesn't need to be registered.

PS: in fact, you don't have to register, you just need to give clients a way to find you, so there's also the possibility to use Registration-Free Activation of COM Components: A Walkthrough, but it can be more work than simply register a bunch of dlls.


问:
How to reload the page while moving from tab bar in swift 3?
Here after running the application i had clicked on cart in tab bar at that time there was no items added in cart so it shown your shopping cart is empty but after adding items in cart then I clicked on cart icon on tab bar also it is showing like as in previous and the cart page was not reloading can anyone help me how to resolve this ?

I had used this code in my home view controller

```<code>func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let tabBarIndex = tabBarController.selectedIndex
        if tabBarIndex == 1 {
            let  navController = self.tabBarController?.viewControllers![1] as! UINavigationController
            let secondViewController = navController.viewControllers[0] as! AddToCartViewController
            secondViewController.firstTimeTableSkip = true
            self.tabBarController?.selectedIndex = 1
        }
    }
</code>```

in my cart view controller I used this code

```<code>override func viewWillAppear(_ animated: Bool) {
        if firstLoginCheck == true {
        checkOutButton.isHidden = false
        checkOutButton.layer.cornerRadius = 5
        if conditonCheck == true || conditonCheck == nil{
        checkOutButton.isHidden = true
        checkOutButton.layer.cornerRadius = 5
        tableDetails.isHidden = true
        emptyView.isHidden = true
        tableDetails.separatorInset = UIEdgeInsets.zero
        loginCheck = UserDefaults.standard.integer(forKey: "CustomerLogin")
        activityIndicator.startAnimating()
        emptyView.isHidden = true
        if loginCheck == 1 {
            let token = UserDefaults.standard.value(forKey: "CustomerLoginToken")
            self.customerKeyToken = token!
            print(self.customerKeyToken!)
            if itemCode != nil {
                self.customerAddToCartItemsDownloadJsonWithURl(cartApi: customerAddtoCartApi)
       customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
            else {
                customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
        }else if (loginCheck == 0) || (loginCheck == nil) {
            if let token = UserDefaults.standard.value(forKey: "user_token")  {
                self.key = token as? String
                let defaultValue = UserDefaults.standard.value(forKey: "MenuButton") as? String
                if (defaultValue == "Tab" && itemCode == nil) {
                    check = true
           cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                }
            } else {
                gettingKeyFromJsonWithURL(keyApi: keygettingApi)
            }
            if itemCode != nil && key != nil {
                self.PostingKeyFromJsonWithURL(PostingApi: postingKeyApi)
            }
            if key != nil {
                cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                emptyView.isHidden = true
            }
            }
        }
</code>```

答: Rather than using notification or delegate or relevant, viewWillApear() method will be more suitable for reloading views. Just put your code which you want to be reloaded into viewWillApear()

Body:
Here after running the application i had clicked on cart in tab bar at that time there was no items added in cart so it shown your shopping cart is empty but after adding items in cart then I clicked on cart icon on tab bar also it is showing like as in previous and the cart page was not reloading can anyone help me how to resolve this ?

I had used this code in my home view controller

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let tabBarIndex = tabBarController.selectedIndex
        if tabBarIndex == 1 {
            let  navController = self.tabBarController?.viewControllers![1] as! UINavigationController
            let secondViewController = navController.viewControllers[0] as! AddToCartViewController
            secondViewController.firstTimeTableSkip = true
            self.tabBarController?.selectedIndex = 1
        }
    }

in my cart view controller I used this code

override func viewWillAppear(_ animated: Bool) {
        if firstLoginCheck == true {
        checkOutButton.isHidden = false
        checkOutButton.layer.cornerRadius = 5
        if conditonCheck == true || conditonCheck == nil{
        checkOutButton.isHidden = true
        checkOutButton.layer.cornerRadius = 5
        tableDetails.isHidden = true
        emptyView.isHidden = true
        tableDetails.separatorInset = UIEdgeInsets.zero
        loginCheck = UserDefaults.standard.integer(forKey: "CustomerLogin")
        activityIndicator.startAnimating()
        emptyView.isHidden = true
        if loginCheck == 1 {
            let token = UserDefaults.standard.value(forKey: "CustomerLoginToken")
            self.customerKeyToken = token!
            print(self.customerKeyToken!)
            if itemCode != nil {
                self.customerAddToCartItemsDownloadJsonWithURl(cartApi: customerAddtoCartApi)
       customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
            else {
                customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
        }else if (loginCheck == 0) || (loginCheck == nil) {
            if let token = UserDefaults.standard.value(forKey: "user_token")  {
                self.key = token as? String
                let defaultValue = UserDefaults.standard.value(forKey: "MenuButton") as? String
                if (defaultValue == "Tab" && itemCode == nil) {
                    check = true
           cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                }
            } else {
                gettingKeyFromJsonWithURL(keyApi: keygettingApi)
            }
            if itemCode != nil && key != nil {
                self.PostingKeyFromJsonWithURL(PostingApi: postingKeyApi)
            }
            if key != nil {
                cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                emptyView.isHidden = true
            }
            }
        }