问:
Python FTP not sending full files
I have written this code that's suppose to  send files over FTP. The problem is that in 3/5 cases the files are not fully getting to the other side -- I understand you have to use retrieve. I am writing this code for work so ignore the obnoxious "REDACTED" parts of the code. Currently, the only files that are reaching the other side in full are the .bin file and the Image file. -- They are the two smallest files as the other ones are quite big (the biggest is 19000 kb.)
When the files are downloaded, they are very small compared to their original size. 35 kb compared to 10000 kb. 141 kb compared to 14000 kb. etc. </p>

```<code>ftp = FTP('REDACTED')
ftp.login('REDACTED', 'REDACTED')
print ("Opening FTP...\n")
   with open ('REDACTED.gz.uboot') as f:
    print ('writing file...REDACTED.gz.uboot')
    ftp.storbinary('STOR %s' % 'REDACTED.gz.uboot', f)

with open('REDACTED_Image', 'rb') as x:
    print ("writing file...REDACTED_Image")
    ftp.storbinary('STOR %s' % 'Image', f)

with open('REDACTED.rbf', 'rb') as f:
    ftp.storbinary('STOR %s' % 'huh.rbf', f)
    print ("writing file...m0_host_top.rbf")

with open ('REDACTED.tar.bz2') as f:
    print ('writing file...REDACTED')
    ftp.storbinary('STOR %s' % 'REDACTED', f)

with open ('REDACTED.bin') as f:
    print ('writing file...REDACTED.bin')
    ftp.storbinary('STOR %s' % 'REDACTED.bin', f)
</code>```

<p>Any help here would be greatly appreciated, I need to get the full files across.
Edit: I am presuming that there is an issue with the upload because each time the files are uploaded, they are of different sizes. </p>

答:
As you are sending all the file in binary mode, you should open all the files with 'rb' mode.

Default open() will use the text mode to open a file, which means treats all the content as text.However you have some binary file like REDACTED.tar.bz2 in the case above. Using text mode to read these files will make the file content different from the origin one.

This question may help you on open() : Difference between parsing a text file in r and rb mode:

Title: Python FTP not sending full files

Body:
I have written this code that's suppose to  send files over FTP. The problem is that in 3/5 cases the files are not fully getting to the other side -- I understand you have to use retrieve. I am writing this code for work so ignore the obnoxious "REDACTED" parts of the code. Currently, the only files that are reaching the other side in full are the .bin file and the Image file. -- They are the two smallest files as the other ones are quite big (the biggest is 19000 kb.)
When the files are downloaded, they are very small compared to their original size. 35 kb compared to 10000 kb. 141 kb compared to 14000 kb. etc.

ftp = FTP('REDACTED')
ftp.login('REDACTED', 'REDACTED')
print ("Opening FTP...\n")
   with open ('REDACTED.gz.uboot') as f:
    print ('writing file...REDACTED.gz.uboot')
    ftp.storbinary('STOR %s' % 'REDACTED.gz.uboot', f)

with open('REDACTED_Image', 'rb') as x:
    print ("writing file...REDACTED_Image")
    ftp.storbinary('STOR %s' % 'Image', f)

with open('REDACTED.rbf', 'rb') as f:
    ftp.storbinary('STOR %s' % 'huh.rbf', f)
    print ("writing file...m0_host_top.rbf")

with open ('REDACTED.tar.bz2') as f:
    print ('writing file...REDACTED')
    ftp.storbinary('STOR %s' % 'REDACTED', f)

with open ('REDACTED.bin') as f:
    print ('writing file...REDACTED.bin')
    ftp.storbinary('STOR %s' % 'REDACTED.bin', f)

Any help here would be greatly appreciated, I need to get the full files across.
Edit: I am presuming that there is an issue with the upload because each time the files are uploaded, they are of different sizes.


来源: stackexchange

问:
Granting write access for the Authenticated Users to S3 bucket
I want to give read access to all AWS authenticated users to a bucket. Note I don't want my bucket to be publicly available. Old amazon console seems to give that provision which I no longer see -

Old S3 bucket ACL -

New bucket Acl -

How can I achieve old behavior? Can I do it using bucket policies -

Again I don't want

```<code>{
  "Id": "Policy1510826508027",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1510826503866",
      "Action": [
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::athakur",
      "Principal": {
        "AWS": [
          "*"
        ]
      }
    }
  ]
}
</code>```

答:
We can give entire ACL string in the aws cli command as ExploringApple explained or just do -

```<code>aws s3api put-bucket-acl --bucket bucketname --grant-full-control uri=http://acs.amazonaws.com/groups/global/AuthenticatedUsers
</code>```

Docs - http://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-acl.html

ContentLicense: CC BY-SA 3.0

Body:
I want to give read access to all AWS authenticated users to a bucket. Note I don't want my bucket to be publicly available. Old amazon console seems to give that provision which I no longer see -

Old S3 bucket ACL -

New bucket Acl -

How can I achieve old behavior? Can I do it using bucket policies -

Again I don't want

{
  "Id": "Policy1510826508027",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1510826503866",
      "Action": [
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::athakur",
      "Principal": {
        "AWS": [
          "*"
        ]
      }
    }
  ]
}

Body:
We can give entire ACL string in the aws cli command as ExploringApple explained or just do -

aws s3api put-bucket-acl --bucket bucketname --grant-full-control uri=http://acs.amazonaws.com/groups/global/AuthenticatedUsers

Docs - http://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-acl.html


问:
Facebook-passport with JWT
I've been using Passport on my server for user authentication.
When a user is signing in locally (using a username and password), the server sends them a JWT which is stored in localstorage, and is sent back to server for every api call that requires user authentication.

Now I want to support Facebook and Google login as well. Since I began with Passport I thought it would be best to continue with Passport strategies, using passport-facebook and passport-google-oauth.

I'll refer to Facebook, but both strategies behave the same. They both require redirection to a server route ('/auth/facebook' and '/auth/facebook/callback' for that matter).
The process is successful to the point of saving users including their facebook\google ids and tokens on the DB.

When the user is created on the server, a JWT is created (without any reliance on the token received from facebook\google).

```<code>     ... // Passport facebook startegy
     var newUser = new User();
     newUser.facebook = {};
     newUser.facebook.id = profile.id;
     newUser.facebook.token = token; // token received from facebook
     newUser.facebook.name  = profile.displayName;
     newUser.save(function(err) {
          if (err)
               throw err;
          // if successful, return the new user
          newUser.jwtoken = newUser.generateJwt(); // JWT CREATION!
          return done(null, newUser);
     });
</code>```

The problem is that after its creation, I don't find a proper way to send the JWT to the client, since I should also redirect to my app.

```<code>app.get('/auth/facebook/callback',
    passport.authenticate('facebook', {
        session: false,
        successRedirect : '/',
        failureRedirect : '/'
    }), (req, res) => {
        var token = req.user.jwtoken;
        res.json({token: token});
    });
</code>```

The code above redirects me to my app main page, but I don't get the token.
If I remove the successRedirect, I do get the token, but I'm not redirected to my app.

Any solution for that? Is my approach wrong? Any suggestions will do.

答:
A proper solution would be to implement the redirection on the client side.

Simply use:

```<code>app.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    session: false,
    failureRedirect: '/login'
  }), (req, res) => {
    res.json({
      token: req.user.jwtoken
    })
  }
)
</code>```

If you're client side receives the token, then redirect from there to home page, and in the case the login wasn't successful, it would be redirected by the server directly.

Or you can go for the full client side management as I would:

```<code>app.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    session: false
  }), (req, res) => {
    if (req.user.jwtoken) {
      res.json({
        success: true,
        token: req.user.jwtoken
      })
    } else {
      res.json({
        success: false
      })
    }
  }
)
</code>```

If success === true, store JWT in LocalStorage, else redirect to login page.

Title: Facebook-passport with JWT

Body:
I've been using Passport on my server for user authentication.
When a user is signing in locally (using a username and password), the server sends them a JWT which is stored in localstorage, and is sent back to server for every api call that requires user authentication.

Now I want to support Facebook and Google login as well. Since I began with Passport I thought it would be best to continue with Passport strategies, using passport-facebook and passport-google-oauth.

I'll refer to Facebook, but both strategies behave the same. They both require redirection to a server route ('/auth/facebook' and '/auth/facebook/callback' for that matter).
The process is successful to the point of saving users including their facebook\google ids and tokens on the DB.

When the user is created on the server, a JWT is created (without any reliance on the token received from facebook\google).

     ... // Passport facebook startegy
     var newUser = new User();
     newUser.facebook = {};
     newUser.facebook.id = profile.id;
     newUser.facebook.token = token; // token received from facebook
     newUser.facebook.name  = profile.displayName;
     newUser.save(function(err) {
          if (err)
               throw err;
          // if successful, return the new user
          newUser.jwtoken = newUser.generateJwt(); // JWT CREATION!
          return done(null, newUser);
     });

The problem is that after its creation, I don't find a proper way to send the JWT to the client, since I should also redirect to my app.

app.get('/auth/facebook/callback',
    passport.authenticate('facebook', {
        session: false,
        successRedirect : '/',
        failureRedirect : '/'
    }), (req, res) => {
        var token = req.user.jwtoken;
        res.json({token: token});
    });

The code above redirects me to my app main page, but I don't get the token.
If I remove the successRedirect, I do get the token, but I'm not redirected to my app.

Any solution for that? Is my approach wrong? Any suggestions will do.

Body:
A proper solution would be to implement the redirection on the client side.

Simply use:

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    session: false,
    failureRedirect: '/login'
  }), (req, res) => {
    res.json({
      token: req.user.jwtoken
    })
  }
)

If you're client side receives the token, then redirect from there to home page, and in the case the login wasn't successful, it would be redirected by the server directly.

Or you can go for the full client side management as I would:

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    session: false
  }), (req, res) => {
    if (req.user.jwtoken) {
      res.json({
        success: true,
        token: req.user.jwtoken
      })
    } else {
      res.json({
        success: false
      })
    }
  }
)

If success === true, store JWT in LocalStorage, else redirect to login page.

ContentLicense: CC BY-SA 4.0


问:
Count vowels in a string with ruby
My objective is to return the number of vowels in a given string. I've tried this code:

```<code>def count_vowels(string)
  vowels = ['a', 'e', 'i', 'o', 'u']
  chars_ary = string.split(//)
  ary_with_vowels = chars_ary.take_while {|letter| vowels.include?(letter)}
  return ary_with_vowels.length
end
</code>```

and it doesn't pass the majority of test cases. I understand that there are multiple other ways to solve this problem, but I want to solve it using the code that I provided.

Can someone give me some insight as to why this isn't working?

答:
Try something like this, its looking at each character in the vowels array and comparing it to each character in the string and the p it if the condition is true.

```<code>def vowles(string)
arr = []
vowels = %w(a e i o u)
vowels.each do |x|
    if string.each_char { |letter| (arr << x) if x == letter }
    end
  end
  p "#{arr} has #{arr.count} vowels"
end
vowles("wwwweeeeeee")
</code>```

or the more efficient

```<code>def vowels(string)
  p string.scan(/[a e i o u]/).count
end
vowels("hello world")
</code>```

Title: Count vowels in a string with ruby

Body:
My objective is to return the number of vowels in a given string. I've tried this code:

def count_vowels(string)
  vowels = ['a', 'e', 'i', 'o', 'u']
  chars_ary = string.split(//)
  ary_with_vowels = chars_ary.take_while {|letter| vowels.include?(letter)}
  return ary_with_vowels.length
end

and it doesn't pass the majority of test cases. I understand that there are multiple other ways to solve this problem, but I want to solve it using the code that I provided.

Can someone give me some insight as to why this isn't working?

Body:
Try something like this, its looking at each character in the vowels array and comparing it to each character in the string and the p it if the condition is true.

def vowles(string)
arr = []
vowels = %w(a e i o u)
vowels.each do |x|
    if string.each_char { |letter| (arr << x) if x == letter }
    end
  end
  p "#{arr} has #{arr.count} vowels"
end
vowles("wwwweeeeeee")

or the more efficient

def vowels(string)
  p string.scan(/[a e i o u]/).count
end
vowels("hello world")


问:
How to sort XML elements in powershell
I have an XML:

```<code><project>
  <settings>
     <setting1 name="s1">foo</setting1>
     <setting2 name="s2">bar</setting2>
  </settings>
  <items>
     <item name="a">
        <property1>foo1</property1>
        <property2>bar2</property2>
     </item>
     <item name="c">
        <property1>foo3</property1>
        <property2>bar4</property2>
     </item>
     <item name="b">
        <property1>foo5</property1>
        <property2>bar6</property2>
     </item>
  </items>
</project>
</code>```

I need to sort the xml by attribute "name" of element "item".

I'm doing something like this:

```<code>[xml]$myXml = Get-Content -Encoding UTF8 $xmlPath

$myXml | Sort-Object {$_.project.items.item.name}

$myXml.Save($xmlPathSorted)
</code>```

Is it possible to do it that easy in PS?

答:
Try this

```<code># Get the items collection
$items = $myXml.project.items
# Sort the items and store in $orderedItems
$orderedItems = $items.item | Sort name
# Removed existing items from xml variable
$items.RemoveAll()
# Append sorted items
$orderedItems | foreach { $items.AppendChild($_) }
</code>```

After running the above test with

```<code>$myxml.InnerXml
</code>```

And you should see that the item elements have been sorted.

Title: How to sort XML elements in powershell

Body:
I have an XML:

<project>
  <settings>
     <setting1 name="s1">foo</setting1>
     <setting2 name="s2">bar</setting2>
  </settings>
  <items>
     <item name="a">
        <property1>foo1</property1>
        <property2>bar2</property2>
     </item>
     <item name="c">
        <property1>foo3</property1>
        <property2>bar4</property2>
     </item>
     <item name="b">
        <property1>foo5</property1>
        <property2>bar6</property2>
     </item>
  </items>
</project>

I need to sort the xml by attribute "name" of element "item".

I'm doing something like this:

[xml]$myXml = Get-Content -Encoding UTF8 $xmlPath

$myXml | Sort-Object {$_.project.items.item.name}

$myXml.Save($xmlPathSorted)

Is it possible to do it that easy in PS?

Body:
Try this

# Get the items collection
$items = $myXml.project.items
# Sort the items and store in $orderedItems
$orderedItems = $items.item | Sort name
# Removed existing items from xml variable
$items.RemoveAll()
# Append sorted items
$orderedItems | foreach { $items.AppendChild($_) }

After running the above test with

$myxml.InnerXml

And you should see that the item elements have been sorted.


问:
How can I create own Bluetooth RGB Controller app for android and ios using phonegap or ionic?
I'm currently doing home lighting system using Arduino and LED Strip and Android Phone. But I don't want to use other app from store. I want to create my own Android to make Bluetooth RGB Controller app using ionic or phonegap. I can't find the tutorial on googling. Please guide me and help me. Thanks you very much.</p>

答: It's the most easy way that u use ""APP Inventor2"" to build ur own app </p>


问:
Two anchor.hash properties differ, but js disagrees
In a html page I'm trying to compare the hash property of two anchor elements, but even when the strings are different, javascript still returns true.

HTML

  link0
  link1
  link2
  link3
  link4

<button onclick="myFunction()">Click</button>

```

<h2>JS</h2>

<pre class="lang-js prettyprint-override"><code>let currPg = 0;

function myFunction() {
  let currPg = 0;
  let pages = document.getElementById('navbar').getElementsByTagName('a');
  location.hash = 'link2';

  for (i = 0; i < pages.length; ++i) {
    if (location.hash == pages[i].hash); {
      //this always gets hit, even when they're different strings
      currPg = i;
    }
  }
  //just for the demo
  document.getElementById("demo").innerHTML = currPg;
}
</code>```

I've been fiddling with it, here: https://jsfiddle.net/danobdgz/1/

答:
Try wit this code there is an additional semicolan </p>

```<code>function myFunction() {
  let currPg = 0;
  let pages = document.getElementById('navbar').getElementsByTagName('a');
  location.hash = 'link2';

  for (i = 0; i < pages.length; ++i) {
    if (location.hash == pages[i].hash){
      //this always gets hit, even when they're different strings
      currPg = i;
    }
  }
  //just for the demo
  document.getElementById("demo").innerHTML = currPg;
}
</code>```

Body:
In a html page I'm trying to compare the hash property of two anchor elements, but even when the strings are different, javascript still returns true.

HTML

  link0
  link1
  link2
  link3
  link4

<button onclick="myFunction()">Click</button>

JS

let currPg = 0;

function myFunction() {
  let currPg = 0;
  let pages = document.getElementById('navbar').getElementsByTagName('a');
  location.hash = 'link2';

  for (i = 0; i < pages.length; ++i) {
    if (location.hash == pages[i].hash); {
      //this always gets hit, even when they're different strings
      currPg = i;
    }
  }
  //just for the demo
  document.getElementById("demo").innerHTML = currPg;
}

I've been fiddling with it, here: https://jsfiddle.net/danobdgz/1/

Body:
Try wit this code there is an additional semicolan

function myFunction() {
  let currPg = 0;
  let pages = document.getElementById('navbar').getElementsByTagName('a');
  location.hash = 'link2';

  for (i = 0; i < pages.length; ++i) {
    if (location.hash == pages[i].hash){
      //this always gets hit, even when they're different strings
      currPg = i;
    }
  }
  //just for the demo
  document.getElementById("demo").innerHTML = currPg;
}


问:
Error when trying with Azure Government endpoint with Azure Storage Java Library
I am trying to use the Azure Storage Java library with the Azure Government endpoints. My code is as follows.

```<code>CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
</code>```

connectionString has the suffix of Azure Gov cloud. For some reason the values for the blob.storage URI are still marked as blob.core.windows.net and I receive the following error. I am unable to run any blob operations.

```<code>com.microsoft.azure.storage.StorageException: The server encountered an unknown failure: at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:178)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:214)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:749)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:736)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:710)
at com.scalegrid.cloudconnector.azure.AzureStorageClient.createContainerIfItDoesntExist(AzureStorageClient.java:369)

java.net.UnknownHostException: XXXX.core.usgovcloudapi.net
ERROR ~ s failed.
Code:12207
</code>```

Is there any way I can get this to work ?

Update

I was using an earlier version of the Azure storage Java. Storage endpoints have not been added at this point. Updating to the newer version fixed it.

答:
The only modification you need from the Code Sample in the azure-storage-java README.md is to add EndpointSuffix in your connection string for the Azure Government endpoints.

Here's the modified sample Java code:

import java.io.*;

import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.blob.*;

public class BlobSample {
    public static final String storageConnectionString =
        "DefaultEndpointsProtocol=http;"
        + "AccountName=your_account_name;"
        + "AccountKey=your_account_key"
        + "EndpointSuffix=core.usgovcloudapi.net";

    public static void main(String[] args) {
        try {
            CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
            CloudBlobClient serviceClient = account.createCloudBlobClient();

            // Container name must be lower case.
            CloudBlobContainer container = serviceClient.getContainerReference("myimages");
            container.createIfNotExists();

            // Upload an image file.
            CloudBlockBlob blob = container.getBlockBlobReference("image1.jpg");
            File sourceFile = new File("c:\\myimages\\image1.jpg");
            blob.upload(new FileInputStream(sourceFile), sourceFile.length());

            // Download the image file.
            File destinationFile = new File(sourceFile.getParentFile(), "image1Download.tmp");
            blob.downloadToFile(destinationFile.getAbsolutePath());
        }
        catch (FileNotFoundException fileNotFoundException) {
            System.out.print("FileNotFoundException encountered: ");
            System.out.println(fileNotFoundException.getMessage());
            System.exit(-1);
        }
        catch (StorageException storageException) {
            System.out.print("StorageException encountered: ");
            System.out.println(storageException.getMessage());
            System.exit(-1);
        }
        catch (Exception e) {
            System.out.print("Exception encountered: ");
            System.out.println(e.getMessage());
            System.exit(-1);
        }
    }
}
```

Body:
I am trying to use the Azure Storage Java library with the Azure Government endpoints. My code is as follows.

CloudStorageAccount account = CloudStorageAccount.parse(connectionString);

connectionString has the suffix of Azure Gov cloud. For some reason the values for the blob.storage URI are still marked as blob.core.windows.net and I receive the following error. I am unable to run any blob operations.

com.microsoft.azure.storage.StorageException: The server encountered an unknown failure: at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:178)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:214)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:749)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:736)
at com.microsoft.azure.storage.blob.CloudBlobContainer.exists(CloudBlobContainer.java:710)
at com.scalegrid.cloudconnector.azure.AzureStorageClient.createContainerIfItDoesntExist(AzureStorageClient.java:369)

java.net.UnknownHostException: XXXX.core.usgovcloudapi.net
ERROR ~ s failed.
Code:12207

Is there any way I can get this to work ?

Update

I was using an earlier version of the Azure storage Java. Storage endpoints have not been added at this point. Updating to the newer version fixed it.


问:
on rotate mobile webview refresh hide menu
i have a problem i am create an app web view to get and website on play store.

the problem is that it have a dropdown Menu html5+jquery+css3. when i rotate the smartphone, the web are refreshed.

this my code Android Studio 3.0:

Activity xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.icarosnet.icarosnetsa.IcarosWeb">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/wv"
    />

</android.support.constraint.ConstraintLayout>
</code>```

Main.Java

```<code>package com.icarosnet.icarosnetsa;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class IcarosWeb extends AppCompatActivity {
    WebView wv ;

    @Override
    public void onBackPressed(){
        if(wv.canGoBack()){
            wv.goBack();
        }else{
            super.onBackPressed();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icaros_web);
        wv= (WebView) findViewById(R.id.wv);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setFocusable(true);
        wv.setFocusableInTouchMode(true);
        wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setDatabaseEnabled(true);
        wv.getSettings().setAppCacheEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        wv.loadUrl("https://icarosnet.com");
        wv.setWebViewClient(new WebViewClient());
    }
    @Override
    protected void onSaveInstanceState(Bundle outState ){
        super.onSaveInstanceState(outState);
        wv= (WebView) findViewById(R.id.wv);
        wv.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        wv= (WebView) findViewById(R.id.wv);
        wv.restoreState(savedInstanceState);
    }

}
</code>```

Xml Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.icarosnet.icarosnetsa">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".IcarosWeb">
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

does not respect the content that was loaded by ajax.

how can i prevent refresh and resize the view; or how can i show it only portrait and block the view.

答:
Try this:
It saves state onPause for WebView.

```<code>@Override
public void onPause() {
    super.onPause();
    webViewBundle = new Bundle();
    wv.saveState(webViewBundle);
  }
</code>```

Add in OnCreate:

```<code>if (webViewBundle == null) {
wv.getSettings().setJavaScriptEnabled(true);
wv.setFocusable(true);
wv.setFocusableInTouchMode(true);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wv.getSettings().setDomStorageEnabled(true);
wv.getSettings().setDatabaseEnabled(true);
wv.getSettings().setAppCacheEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl("https://icarosnet.com");
} else {
wv.restoreState(webViewBundle);
}
</code>```

*Assuming wv would be declared for the class

Body:
i have a problem i am create an app web view to get and website on play store.

the problem is that it have a dropdown Menu html5+jquery+css3. when i rotate the smartphone, the web are refreshed.

this my code Android Studio 3.0:

Activity xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.icarosnet.icarosnetsa.IcarosWeb">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/wv"
    />

</android.support.constraint.ConstraintLayout>

Main.Java

package com.icarosnet.icarosnetsa;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class IcarosWeb extends AppCompatActivity {
    WebView wv ;

    @Override
    public void onBackPressed(){
        if(wv.canGoBack()){
            wv.goBack();
        }else{
            super.onBackPressed();
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icaros_web);
        wv= (WebView) findViewById(R.id.wv);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setFocusable(true);
        wv.setFocusableInTouchMode(true);
        wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setDatabaseEnabled(true);
        wv.getSettings().setAppCacheEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        wv.loadUrl("https://icarosnet.com");
        wv.setWebViewClient(new WebViewClient());
    }
    @Override
    protected void onSaveInstanceState(Bundle outState ){
        super.onSaveInstanceState(outState);
        wv= (WebView) findViewById(R.id.wv);
        wv.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        wv= (WebView) findViewById(R.id.wv);
        wv.restoreState(savedInstanceState);
    }

}

Xml Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.icarosnet.icarosnetsa">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".IcarosWeb">
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

does not respect the content that was loaded by ajax.

how can i prevent refresh and resize the view; or how can i show it only portrait and block the view.

Body:
Try this:
It saves state onPause for WebView.

@Override
public void onPause() {
    super.onPause();
    webViewBundle = new Bundle();
    wv.saveState(webViewBundle);
  }

Add in OnCreate:

if (webViewBundle == null) {
wv.getSettings().setJavaScriptEnabled(true);
wv.setFocusable(true);
wv.setFocusableInTouchMode(true);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wv.getSettings().setDomStorageEnabled(true);
wv.getSettings().setDatabaseEnabled(true);
wv.getSettings().setAppCacheEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl("https://icarosnet.com");
} else {
wv.restoreState(webViewBundle);
}

*Assuming wv would be declared for the class


问:
Python - how to append an item to a list created on the same line from some element?
I've got a very simple question regarding creation of lists and appending items on the same line.  I have been writing a Python Program for a school project (implementing an AI to play Blackjack) and would like to be able to do something like this:

hands = [[2,3]].append([4,5])

I need to be able to create new hands and add them to the AI players attributes for if it chooses to split, and I thought this would work but results in hands being None.  I can certainly split it into two lines, but I feel like it would be more pythonic to do it within one line.  I do not see why this doesn't work, if anyone can explain why it doesn't that would be great.  What I read it as is that hands will be set to list [[2,3]] with element [4,5] appended to it.

答:
append mutates the list that it is called on, but returns None. So assigning the return value to a variable makes little sense. One option is:

```<code>hands = [[2, 3]]
hands.append([4, 5])
</code>```

or in one line (you seem to know the lists beforehand):

```<code>hands = [[2, 3], [4, 5]]
# Or
# hands = [[2, 3]] + [[4, 5]]
</code>```

Body:
append mutates the list that it is called on, but returns None. So assigning the return value to a variable makes little sense. One option is:

hands = [[2, 3]]
hands.append([4, 5])

or in one line (you seem to know the lists beforehand):

hands = [[2, 3], [4, 5]]
# Or
# hands = [[2, 3]] + [[4, 5]]


问:
How do I get a list of locked users in an Oracle database?
I want to be able to list all of the users in a given database along with an icon that determines whether they are locked or not. The problem I'm having is querying the "locked" status for a given user, I though it might have been on all_users but it isn't. Can anyone point me in the right direction?

答:
This suits the requirement:

```<code>select username, account_status, EXPIRY_DATE from dba_users where
username='<username>';
</code>```

Output:

```<code>USERNAME        ACCOUNT_STATUS                   EXPIRY_DA
--------------------------------------------------------------------------------
SYSTEM          EXPIRED                          13-NOV-17
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This suits the requirement:

select username, account_status, EXPIRY_DATE from dba_users where
username='<username>';

Output:

USERNAME        ACCOUNT_STATUS                   EXPIRY_DA
--------------------------------------------------------------------------------
SYSTEM          EXPIRED                          13-NOV-17


问:
Google wants to verify my adress because of AdMob
Google wants to verify my adress because of AdMob. They want to send a PIN number in a traditional letter on adress which I have set. The problem is that account adress is false. I have a question: Will they send that letter even if I did not clicked the "Send me PIN" button? And if they will send that letter will it contain my account password? Please help:)</p>

答:
AdMob send your PIN by standard mail several days after your account balance reaches the verification threshold.

The letter contains only PIN that can only used by your AdMob account.

If you haven’t received your first PIN? You can request additional PINs.

Before requesting a new PIN, correct your payment address.


问:
node promises.all() doesnt work as expected
I'm trying to run a list of functions synchronously after a loop using promise.all() but my code doesn't work as expected.

Does someone know what I did wrong?

my code is :

```<code>var Promise = require('promise');
var promises = [];

for (var i = 0; i < 3; i++) {
    console.log('push promise ' + i);
    promises.push(foo(i));
}

Promise.all(promises)
        .then(function (data) {
            console.log("done");
        });

function foo(i) {
    return new Promise(function (resolve, reject) {
        console.log('---> foo i ' + i);
        resolve('done foo ' + i);

    });
}
</code>```

but the output is

```<code>push promise 0
---> foo i 0
push promise 1
---> foo i 1
push promise 2
---> foo i 2
done
</code>```

where I expect

```<code>push promise 0
push promise 1
push promise 2
---> foo i 0
---> foo i 1
---> foo i 2
done
</code>```

Thank you in advance.

答:
I'm trying to run a list of functions synchronously after a loop using promise.all() but my code doesn't work as expected.

I think you want run a list of functions synchronously. If so, I recommend to use Bluebird Promise.each().

```<code>var Promise = require('bluebird');
var promises = [];

for (var i = 0; i < 3; i++) {
    console.log('push promise ' + i);
    promises.push(foo(i));
}

Promise.each(promises, function(result) {
    console.log(result);
});

function foo(i) {
    return new Promise(function (resolve, reject) {
        resolve('done foo ' + i);
    });
}
</code>```

Results:

```<code>push promise 0
push promise 1
push promise 2
done foo 0
done foo 1
done foo 2
</code>```

Body:
I'm trying to run a list of functions synchronously after a loop using promise.all() but my code doesn't work as expected.

Does someone know what I did wrong?

my code is :

var Promise = require('promise');
var promises = [];

for (var i = 0; i < 3; i++) {
    console.log('push promise ' + i);
    promises.push(foo(i));
}

Promise.all(promises)
        .then(function (data) {
            console.log("done");
        });

function foo(i) {
    return new Promise(function (resolve, reject) {
        console.log('---> foo i ' + i);
        resolve('done foo ' + i);

    });
}

but the output is

push promise 0
---> foo i 0
push promise 1
---> foo i 1
push promise 2
---> foo i 2
done

where I expect

push promise 0
push promise 1
push promise 2
---> foo i 0
---> foo i 1
---> foo i 2
done

Thank you in advance.

Body:
I'm trying to run a list of functions synchronously after a loop using promise.all() but my code doesn't work as expected.

I think you want run a list of functions synchronously. If so, I recommend to use Bluebird Promise.each().

var Promise = require('bluebird');
var promises = [];

for (var i = 0; i < 3; i++) {
    console.log('push promise ' + i);
    promises.push(foo(i));
}

Promise.each(promises, function(result) {
    console.log(result);
});

function foo(i) {
    return new Promise(function (resolve, reject) {
        resolve('done foo ' + i);
    });
}

Results:

push promise 0
push promise 1
push promise 2
done foo 0
done foo 1
done foo 2


问:
Reload Webview when onMessage callback setting state
I am using React native Webview to load my web app. I am posting message from my web app using window.postMessage and I have implemented onMessage callback

```<code>render(){
   return <View>
     <Text>{this.state.messageFromWebview}</Text>
     <WebView onMessage={this.onWebViewMessage} source={{uri: webAppUri}} />
   </View>;
}
</code>```

In onWebViewMessage function, in doing

```<code>onWebViewMessage=(event)=>{
   this.setState({
    messageFromWebview: event.nativeEvent.data
   })
}
</code>```

Above code is going into infinite loop. While setting state, Webview rerendering and calling the post message that triggering the setState.

Is there any alternative or am I missing anything here. Is it possible to set the <Text/> to the message from the webview without rerendering the Webview.

答:
I think the infinite loop is because of calling the event without const request. All you need to do is add const variable before setState. The following code works for me.</p>

```<code>onWebViewMessage = (event) => {
  // set const data
  const WishData = event.nativeEvent.data;
  // then excuting setState the constant data here
  this.setState({
    messageFromWebview: WishData
  });
}
</code>```

Body:
I am using React native Webview to load my web app. I am posting message from my web app using window.postMessage and I have implemented onMessage callback

render(){
   return <View>
     <Text>{this.state.messageFromWebview}</Text>
     <WebView onMessage={this.onWebViewMessage} source={{uri: webAppUri}} />
   </View>;
}

In onWebViewMessage function, in doing

onWebViewMessage=(event)=>{
   this.setState({
    messageFromWebview: event.nativeEvent.data
   })
}

Above code is going into infinite loop. While setting state, Webview rerendering and calling the post message that triggering the setState.

Is there any alternative or am I missing anything here. Is it possible to set the <Text/> to the message from the webview without rerendering the Webview.

Body:
I think the infinite loop is because of calling the event without const request. All you need to do is add const variable before setState. The following code works for me.

onWebViewMessage = (event) => {
  // set const data
  const WishData = event.nativeEvent.data;
  // then excuting setState the constant data here
  this.setState({
    messageFromWebview: WishData
  });
}


问:
NHibernate in C sharp
If possible to use NHibernate  in c#.net?How can use NHibernate  in c#?</p>

答:
If possible to use NHibernate in c#.net?

Yes.

How can use NHibernate in c#?

http://nhibernate.info/doc/tutorials/first-nh-app/your-first-nhibernate-based-application.html

Title: NHibernate in C sharp


问:
How to ensure a user has a valid Paypal account to accept payments with?
I ask my users to provide a Paypal account on which they will receive automatic payments (through Paypal PHP SDK) and I want to be sure such account is valid ( active and ready to accept payments) before the first payment occurs (e.g. when they sign-up. Of course I'm aware the account status may change in the meanwhile). Does Paypal provide a better way (or is there a smarter flow) to achieve this  without a classic 0.01$ transaction?

答:
It is better to implement "Login with Paypal" using Paypal OAuth APIs so that you can directly get the Paypal account, account status, account type, country etc.

Checkout Verifying Paypal IDs by Implementing Login with Paypal for a detailed tutorial.


问:
Java BufferedWriter Write method
I am creating a CSV file using BufferedWriter from a ResultSet object. A few of the database columns hold null values.

When I call obj.write(rs.get()) I am getting a NullPointerException when the output is null. Is there any other class other than BufferedWriter which I can use to overcome this.

I do not want to check for null condition on the database columns since there is large number of columns. I am new to Java and tried searching for solution but could not find anything.

答:
Just solendil's code, fixed so that it compiles, and formatted a bit:</p>

```<code>package mypackage;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;

public class MyBufferedWriter extends BufferedWriter {

    public MyBufferedWriter(Writer out) {
        super(out);
    }

    @Override
    public void write(String str) throws IOException {
        if (str == null)
            str = "";
        super.write(str);
    }
}
</code>```

Title: Java BufferedWriter Write method

Body:
Just solendil's code, fixed so that it compiles, and formatted a bit:

package mypackage;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;

public class MyBufferedWriter extends BufferedWriter {

    public MyBufferedWriter(Writer out) {
        super(out);
    }

    @Override
    public void write(String str) throws IOException {
        if (str == null)
            str = "";
        super.write(str);
    }
}


问:
Remove duplicates from list of lists in Haskell
Given the list of lists  duplicates = [[1,1,1],[2],[1,1,1]]

How to remove the duplicates so that the result is [[2]]?

Body:
Like this:

Data.MultiSet> [a | (a, 1) <- toOccurList (fromList [[1,1,1],[2],[1,1,1]])]
[[2]]


问:
How can I get VSTS working with private nuget repos which require credentials?
I am trying to set up a CI/CD system and the company has chosen Visual Studio Team Services.

Everything was going well until I noticed my build failing here:

Error:
d:\a_tasks\NuGetInstaller_333b11bd-d341-40d9-afcf-b32d5ce6f23b\0.2.31\node_modules\nuget-task-common\NuGet\3.3.0\NuGet.exe
failed with return code: 1

Packages failed to install

The software project uses Telerik DLL's that are retrieved from a private Telerik nuget repo - which requires credentials to access.

Now obviously there must be a way to tell VSTS in the 'Nuget Restore' build step but I can't find anything online other than create our own hosted company Repo and tell VSTS about it - which isn't helpful because I don't want to host Telerik's own DLL's.

Is there any way to do this or should I move to TeamCity?

答:
It seems you are using Nuget Installer task which is deprecated now.

You can use NuGet task, detail settings as below:

Select restore command -> click New to add the credential from outside feed -> in the new window -> select basic authentication -> input feed URL, username and password -> verify the connect is successful -> Ok.

Save the build definition and queue again, now the nuget packages should be download successful by the NuGet task.


问:
What is the difference between supervised learning and unsupervised learning?
In terms of artificial intelligence and machine learning, what is the difference between supervised and unsupervised learning?
Can you provide a basic, easy explanation with an example? </p>

答:
Supervised Machine Learning

"The process of  an algorithm learning from  training dataset and
  predict the  output. "

Accuracy of  predicted output  directly proportional   to the  training data (length)

Supervised learning is where you have input variables (x) (training dataset) and an output variable (Y) (testing dataset) and you use an algorithm to learn the mapping function from the input to the output.

```<code>Y = f(X)
</code>```

Major types:

Classification (discrete y-axis)

Predictive (continuous y-axis)

Algorithms:

Classification Algorithms:

```<code>Neural Networks
Naïve Bayes classifiers
Fisher linear discriminant
KNN
Decision Tree
Super Vector Machines
</code>```

Predictive Algorithms:

```<code>Nearest  neighbor
Linear Regression,Multi Regression
</code>```

Application  areas:

Classifying  emails as spam

Classifying whether patient has
disease or not

Voice  Recognition

Predict  the HR select particular candidate or  not

Predict the stock market price

Body:
Supervised Machine Learning

"The process of  an algorithm learning from  training dataset and
  predict the  output. "

Accuracy of  predicted output  directly proportional   to the  training data (length)

Supervised learning is where you have input variables (x) (training dataset) and an output variable (Y) (testing dataset) and you use an algorithm to learn the mapping function from the input to the output.

Y = f(X)

Major types:

Classification (discrete y-axis)

Predictive (continuous y-axis)

Algorithms:

Classification Algorithms:

Neural Networks
Naïve Bayes classifiers
Fisher linear discriminant
KNN
Decision Tree
Super Vector Machines

Predictive Algorithms:

Nearest  neighbor
Linear Regression,Multi Regression

Application  areas:

Classifying  emails as spam

Classifying whether patient has
disease or not

Voice  Recognition

Predict  the HR select particular candidate or  not

Predict the stock market price


问:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?</p>

答:
In JSP page :

```<code><c:set var="list_size" value="${list1.size() }"></c:set>
</code>```

Access this value in Javascipt page using :

```<code>var list_size = parseInt($('#list_size').val());
</code>```

I added javascript page in my project externally.

Body:
In JSP page :

<c:set var="list_size" value="${list1.size() }"></c:set>

Access this value in Javascipt page using :

var list_size = parseInt($('#list_size').val());

I added javascript page in my project externally.


问:
How to add button in PHP Mail function?
I'm trying to insert a button in an anchor tag with an href. I want the user to see a button and not a link

"&userid="<?= $userid; ?>"' style=' background-color: #4CAF50;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;'>Click To Reset password
    ```

答:
You can use HTML in your mail like this :</p>

```<code><?php
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";

$message = "<a href='http://example.com/PhpProject3/reset_passwd.php?key=".$email."&userid=".$userid."' style=' background-color: #4CAF50;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;'>Click To Reset password</a>";
$message .= "Other Information ";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

mail($to,$subject,$message,$headers);
?>
</code>```

Title: How to add button in PHP Mail function?

Body:
I'm trying to insert a button in an anchor tag with an href. I want the user to see a button and not a link

<a href='http://example.com/PhpProject3/reset_passwd.php?key="<?= $email; ?>"&userid="<?= $userid; ?>"' style=' background-color: #4CAF50;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;'>Click To Reset password

Body:
You can use HTML in your mail like this :

<?php
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";

$message = "<a href='http://example.com/PhpProject3/reset_passwd.php?key=".$email."&userid=".$userid."' style=' background-color: #4CAF50;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;'>Click To Reset password</a>";
$message .= "Other Information ";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

mail($to,$subject,$message,$headers);
?>


问:
How to perform an HTTP file upload using express on Cloud Functions for Firebase (multer, busboy)
I am trying to upload a file to Cloud Functions, using Express to handle requests there, but i am not succeeding. I created a version that works locally:

serverside js

```<code>const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');

const app = express();
app.use(fileUpload());
app.use(cors());

app.post('/upload', (req, res) => {
    res.send('files: ' + Object.keys(req.files).join(', '));
});
</code>```

clientside js

```<code>const formData = new FormData();
Array.from(this.$refs.fileSelect.files).forEach((file, index) => {
    formData.append('sample' + index, file, 'sample');
});

axios.post(
    url,
    formData,
    {
        headers: { 'Content-Type': 'multipart/form-data' },
    }
);
</code>```

This exact same code seems to break when deployed to Cloud Functions, where req.files is undefined. Does anyone have any idea what is happening here?

EDIT
I also had a go at using multer, which worked fine locally, but once uploaded to Cloud Functions, this got me an empty array (same clientside code):

```<code>const app = express();
const upload = multer();
app.use(cors());

app.post('/upload', upload.any(), (req, res) => {
    res.send(JSON.stringify(req.files));
});
</code>```

答:
To add to the official Cloud Function team answer, you can emulate this behavior locally by doing the following (add this middleware higher than the busboy code they posted, obviously)</p>

```<code>const getRawBody = require('raw-body');
const contentType = require('content-type');

app.use(function(req, res, next){
    if(req.rawBody === undefined && req.method === 'POST' && req.headers['content-type'] !== undefined && req.headers['content-type'].startsWith('multipart/form-data')){
        getRawBody(req, {
            length: req.headers['content-length'],
            limit: '10mb',
            encoding: contentType.parse(req).parameters.charset
        }, function(err, string){
            if (err) return next(err);
            req.rawBody = string;
            next();
        });
    }
    else{
        next();
    }
});
</code>```

Body:
I am trying to upload a file to Cloud Functions, using Express to handle requests there, but i am not succeeding. I created a version that works locally:

serverside js

const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');

const app = express();
app.use(fileUpload());
app.use(cors());

app.post('/upload', (req, res) => {
    res.send('files: ' + Object.keys(req.files).join(', '));
});

clientside js

const formData = new FormData();
Array.from(this.$refs.fileSelect.files).forEach((file, index) => {
    formData.append('sample' + index, file, 'sample');
});

axios.post(
    url,
    formData,
    {
        headers: { 'Content-Type': 'multipart/form-data' },
    }
);

This exact same code seems to break when deployed to Cloud Functions, where req.files is undefined. Does anyone have any idea what is happening here?

EDIT
I also had a go at using multer, which worked fine locally, but once uploaded to Cloud Functions, this got me an empty array (same clientside code):

const app = express();
const upload = multer();
app.use(cors());

app.post('/upload', upload.any(), (req, res) => {
    res.send(JSON.stringify(req.files));
});

Body:
To add to the official Cloud Function team answer, you can emulate this behavior locally by doing the following (add this middleware higher than the busboy code they posted, obviously)

const getRawBody = require('raw-body');
const contentType = require('content-type');

app.use(function(req, res, next){
    if(req.rawBody === undefined && req.method === 'POST' && req.headers['content-type'] !== undefined && req.headers['content-type'].startsWith('multipart/form-data')){
        getRawBody(req, {
            length: req.headers['content-length'],
            limit: '10mb',
            encoding: contentType.parse(req).parameters.charset
        }, function(err, string){
            if (err) return next(err);
            req.rawBody = string;
            next();
        });
    }
    else{
        next();
    }
});


问:
new BufferedReader in class Files cannot be applied to given types

```<code>List< String> list = new ArrayList<>();

try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {

    //br returns as stream and convert it into a List
    list = br.lines().collect(Collectors.toList());

} catch (IOException e) {
     e.printStackTrace();
}

StringBuilder sb = new StringBuilder();
for (String s : list) {
    sb.append(s);
}

String json = sb.toString();
JSONParser parser = new JSONParser();
obj = parser.parse(json);
</code>```

I am getting this error please help !!

答:
I guess that you are using java 7 which has only one version of
Files.newBufferedReader method which takes Charset as a second argument
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newBufferedReader(java.nio.file.Path,%20java.nio.charset.Charset)
In Java 8 you will find the method you need
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedReader-java.nio.file.Path-</p>

Body:
List< String> list = new ArrayList<>();

try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {

    //br returns as stream and convert it into a List
    list = br.lines().collect(Collectors.toList());

} catch (IOException e) {
     e.printStackTrace();
}

StringBuilder sb = new StringBuilder();
for (String s : list) {
    sb.append(s);
}

String json = sb.toString();
JSONParser parser = new JSONParser();
obj = parser.parse(json);

I am getting this error please help !!


问:
How can I omit a "Cout" statement for a specific "if-else" statement?

I'm trying to avoid a cout statement. Specifically,

```<code>cout<< "Enter integer 2: \n"

cin>> i
</code>```

I've tried utilizing the cin.ignore(j) in various places of the 8th if-else statement. That is, option 8 from the user selections.

I want to accomplish this with the last complicated method. I'm in "Introduction to C++" and well, I'm not too familiar with advanced methods.

The goal here is to create a calculator with the given functions under the prototype section.

```<code>#include <iostream>
#include <math.h>
using namespace std;

int menu();
int addition (int a, int b);
int subtract (int a, int b);
int multiply (int a, int b)
int division (int a, int b);
double realDivision (double a, double b);
double quotient (double a, double b);
double remainder (double a, double b);
int factorial (int a);

int main(int argc, const char * argv[])
{
    int choice, i, j;
    choice = menu();

    if (choice == 0)
        return 0;

    cout << "Enter integer 1: \n";
    cin >> i;

    cout << "Enter integer 2: \n";
    cin >> j;

    if (choice == 1)
        cout << addition(i, j) << endl;

    else if (choice == 2)
        cout << subtract(i, j) << endl;

    else if (choice == 3)
        cout << multiply(i, j) << endl;

    else if (choice == 4)
        cout << division(i, j) << endl;

    else if (choice == 5)
        cout << realDivision(i, j) << endl;

    else if (choice == 6)
        cout << quotient(i, j) << endl;

    else if (choice == 7)
        cout << remainder(i, j) << endl;

    else if (choice == 8)
        cout << i << ", factorial = " << factorial(i) << endl;

        return 0;
     }

int menu()
{
  int choice = 10;
   while ((choice > 9) || (choice < 0))
   {
     cout << "Enter 0 to quit\n";
     cout << "Enter 1 for addition\n";
     cout << "Enter 2 for subtraction\n";
     cout << "Enter 3 for Multiplication\n";
     cout << "Enter 4 for Division of two integers\n";
     cout << "Enter 5 for Real Division of two integers\n"
     cout << "Enter 6 for Quotient of a division\n";
     cout << "Enter 7 for Remainder of a division\n";
     cout << "Enter 8 for Factorial of an integer\n";
     cout << "Enter 9 for Exponential of two integers\n";
     cin >> choice;

   }
    return choice;
}

int addition(int a, int b)
{
    return(a+b);
}

int subtract(int a, int b)
{
    return(a-b);
}

int multiply(int a, int b)
{
    return (a * b);
}

int division(int a, int b)
{
    return a/b;
}

double realDivision(double a, double b)
{
    return(a/b);
}

double quotient(double a, double b)
{
    return(a/b);
}

double remainder(double a, double b)
{
    return(a/b);
}

int factorial(int a)
{
    int product = 1;
    while (a > 1)
    {
        product *=a;
        a--;
    }
    return product;
}
</code>```

答:
If the factorial choice is always 8.You can check for choice!=8 before reading the second number.If the choice is 8, it will skip the 2nd number part and then continue else it will read the 2nd number and then continue.

```<code>#include <iostream>
#include <math.h>
using namespace std;

int menu();
int addition (int a, int b);
int subtract (int a, int b);
int multiply (int a, int b)
int division (int a, int b);
double realDivision (double a, double b);
double quotient (double a, double b);
double remainder (double a, double b);
int factorial (int a);

int main(int argc, const char * argv[])
{
    int choice, i, j;
    choice = menu();

    if (choice == 0)
        return 0;

    cout << "Enter integer 1: \n";
    cin >> i;

    if(choice!=8)
    cout << "Enter integer 2: \n";
    cin >> j;

    if (choice == 1)
        cout << addition(i, j) << endl;

    else if (choice == 2)
        cout << subtract(i, j) << endl;

    else if (choice == 3)
        cout << multiply(i, j) << endl;

    else if (choice == 4)
        cout << division(i, j) << endl;

    else if (choice == 5)
        cout << realDivision(i, j) << endl;

    else if (choice == 6)
        cout << quotient(i, j) << endl;

    else if (choice == 7)
        cout << remainder(i, j) << endl;

    else if (choice == 8)
        cout << i << ", factorial = 8" << factorial(i) << endl;

        return 0;
     }

int menu()
{
  int choice = 10;
   while ((choice > 9) || (choice < 0))
   {
     cout << "Enter 0 to quit\n";
     cout << "Enter 1 for addition\n";
     cout << "Enter 2 for subtraction\n";
     cout << "Enter 3 for Multiplication\n";
     cout << "Enter 4 for Division of two integers\n";
     cout << "Enter 5 for Real Division of two integers\n"
     cout << "Enter 6 for Quotient of a division\n";
     cout << "Enter 7 for Remainder of a division\n";
     cout << "Enter 8 for Factorial of an integer\n";
     cout << "Enter 9 for Exponential of two integers\n";
     cin >> choice;

   }
    return choice;
}

int addition(int a, int b)
{
    return(a+b);
}

int subtract(int a, int b)
{
    return(a-b);
}

int multiply(int a, int b)
{
    return (a * b);
}

int division(int a, int b)
{
    return a/b;
}

double realDivision(double a, double b)
{
    return(a/b);
}

double quotient(double a, double b)
{
    return(a/b);
}

double remainder(double a, double b)
{
    return(a/b);
}

int factorial(int a)
{
    int product = 1;
    while (a > 1)
    {
        product *=a;
        a--;
    }
    return product;
}
</code>```

Body:
I'm trying to avoid a cout statement. Specifically,

cout<< "Enter integer 2: \n"

cin>> i

I've tried utilizing the cin.ignore(j) in various places of the 8th if-else statement. That is, option 8 from the user selections.

I want to accomplish this with the last complicated method. I'm in "Introduction to C++" and well, I'm not too familiar with advanced methods.

The goal here is to create a calculator with the given functions under the prototype section.

#include <iostream>
#include <math.h>
using namespace std;

int menu();
int addition (int a, int b);
int subtract (int a, int b);
int multiply (int a, int b)
int division (int a, int b);
double realDivision (double a, double b);
double quotient (double a, double b);
double remainder (double a, double b);
int factorial (int a);

int main(int argc, const char * argv[])
{
    int choice, i, j;
    choice = menu();

    if (choice == 0)
        return 0;

    cout << "Enter integer 1: \n";
    cin >> i;

    cout << "Enter integer 2: \n";
    cin >> j;

    if (choice == 1)
        cout << addition(i, j) << endl;

    else if (choice == 2)
        cout << subtract(i, j) << endl;

    else if (choice == 3)
        cout << multiply(i, j) << endl;

    else if (choice == 4)
        cout << division(i, j) << endl;

    else if (choice == 5)
        cout << realDivision(i, j) << endl;

    else if (choice == 6)
        cout << quotient(i, j) << endl;

    else if (choice == 7)
        cout << remainder(i, j) << endl;

    else if (choice == 8)
        cout << i << ", factorial = " << factorial(i) << endl;

        return 0;
     }

int menu()
{
  int choice = 10;
   while ((choice > 9) || (choice < 0))
   {
     cout << "Enter 0 to quit\n";
     cout << "Enter 1 for addition\n";
     cout << "Enter 2 for subtraction\n";
     cout << "Enter 3 for Multiplication\n";
     cout << "Enter 4 for Division of two integers\n";
     cout << "Enter 5 for Real Division of two integers\n"
     cout << "Enter 6 for Quotient of a division\n";
     cout << "Enter 7 for Remainder of a division\n";
     cout << "Enter 8 for Factorial of an integer\n";
     cout << "Enter 9 for Exponential of two integers\n";
     cin >> choice;

   }
    return choice;
}

int addition(int a, int b)
{
    return(a+b);
}

int subtract(int a, int b)
{
    return(a-b);
}

int multiply(int a, int b)
{
    return (a * b);
}

int division(int a, int b)
{
    return a/b;
}

double realDivision(double a, double b)
{
    return(a/b);
}

double quotient(double a, double b)
{
    return(a/b);
}

double remainder(double a, double b)
{
    return(a/b);
}

int factorial(int a)
{
    int product = 1;
    while (a > 1)
    {
        product *=a;
        a--;
    }
    return product;
}

Body:
If the factorial choice is always 8.You can check for choice!=8 before reading the second number.If the choice is 8, it will skip the 2nd number part and then continue else it will read the 2nd number and then continue.

#include <iostream>
#include <math.h>
using namespace std;

int menu();
int addition (int a, int b);
int subtract (int a, int b);
int multiply (int a, int b)
int division (int a, int b);
double realDivision (double a, double b);
double quotient (double a, double b);
double remainder (double a, double b);
int factorial (int a);

int main(int argc, const char * argv[])
{
    int choice, i, j;
    choice = menu();

    if (choice == 0)
        return 0;

    cout << "Enter integer 1: \n";
    cin >> i;

    if(choice!=8)
    cout << "Enter integer 2: \n";
    cin >> j;

    if (choice == 1)
        cout << addition(i, j) << endl;

    else if (choice == 2)
        cout << subtract(i, j) << endl;

    else if (choice == 3)
        cout << multiply(i, j) << endl;

    else if (choice == 4)
        cout << division(i, j) << endl;

    else if (choice == 5)
        cout << realDivision(i, j) << endl;

    else if (choice == 6)
        cout << quotient(i, j) << endl;

    else if (choice == 7)
        cout << remainder(i, j) << endl;

    else if (choice == 8)
        cout << i << ", factorial = 8" << factorial(i) << endl;

        return 0;
     }

int menu()
{
  int choice = 10;
   while ((choice > 9) || (choice < 0))
   {
     cout << "Enter 0 to quit\n";
     cout << "Enter 1 for addition\n";
     cout << "Enter 2 for subtraction\n";
     cout << "Enter 3 for Multiplication\n";
     cout << "Enter 4 for Division of two integers\n";
     cout << "Enter 5 for Real Division of two integers\n"
     cout << "Enter 6 for Quotient of a division\n";
     cout << "Enter 7 for Remainder of a division\n";
     cout << "Enter 8 for Factorial of an integer\n";
     cout << "Enter 9 for Exponential of two integers\n";
     cin >> choice;

   }
    return choice;
}

int addition(int a, int b)
{
    return(a+b);
}

int subtract(int a, int b)
{
    return(a-b);
}

int multiply(int a, int b)
{
    return (a * b);
}

int division(int a, int b)
{
    return a/b;
}

double realDivision(double a, double b)
{
    return(a/b);
}

double quotient(double a, double b)
{
    return(a/b);
}

double remainder(double a, double b)
{
    return(a/b);
}

int factorial(int a)
{
    int product = 1;
    while (a > 1)
    {
        product *=a;
        a--;
    }
    return product;
}


问:
Get data from a file and randomly show lines without duplicating in C
I need to get Questions from a file and then randomly show them to enter answers.
What I have done was I generate a random number and then file is reading line by line.When it meets the randomize number it will shows the relevant line.
now all working but i don't want to duplicate numbers.How can I fix this.

Here what i tried

```<code>   int main()
{
    int numb;
    int answer;
    int ar[5];
    int count =0;

    numb = randomgen();
    ar[count]=numb;
    char input[512];

    printf("Line number to print :%d\n",numb);
    count++;
    while(count != 6)
    {
        FILE * pToFile= fopen("data.txt","r");
        int line =0;
        while(fgets(input,512,pToFile))
            {
                line++;
                if(line == numb)
                {
                    printf(" %s",input);
                }

            }

            printf("Enter the answer:");

            scanf("%d",&answer);
            printf("\n");
            answermethod(numb,answer); //to check the answers ;WORKING

            numb = randomgen2(ar);
            ar[count] = numb;
            count++;

            fclose(pToFile);
    }

    return 0;

}
    int randomgen()
    {
         int r;
    srand(time(NULL));
    r=rand()%(5)+1;
    return r;

    }

    int randomgen2(int ars[]) //generate random n and search it in the
                            //array if it is not in array return the random
                            //  value.But this is not working
    {
    int r;
    srand(time(NULL));
     r=rand()%(5)+1;
    int num,i,c=0;

    int n= sizeof(ars)/sizeof(ars[0]);
          for(i=0;i<n;i++)
          {
              if(ars[i]==r)
              {
                  //printf("%d",r);

                  randomgen2(ars);
                  c=1;
                  break;
              }

              else
              {
                   printf("not found%d",r);
                  c=0;
              }
          }

            if(c==0)
            {
                printf("nooo");
                return r;
            }
    }
</code>```

答:
Uninitialized variables and the uninitialized array ar will cause undefined behavior.

The file needs to be opened only once. Use rewind to go back to the begining.

As noted in comments, use srand only once. And you have pass the array size to the function because in foo(int ar[]) the size of ar is the pointer size, not the allocation size.

Just check to see if the random number is used already. If it is not used, then store it in the array. The range of random number and array size should match exactly. Don't add +1

```<code>int main(void)
{
    srand((unsigned int)time(NULL));
    FILE *pToFile = fopen("data.txt", "r");
    char input[512];
    int line;
    int arr[5];
    int array_size = sizeof(arr) / sizeof(arr[0]);

    for (int count = 0; count < array_size; count++)
    {
        arr[count] = -1; // initialize to -1 to indicate it is not set
        while(arr[count] == -1)
        {
            arr[count] = rand() % array_size;
            for(int i = 0; i < count; i++)
                if(arr[i] == arr[count])
                    arr[count] = -1;
        }

        rewind(pToFile);
        line = 0;
        while(fgets(input, 512, pToFile))
        {
            if(line++ == arr[count])
            {
                printf("%s", input);
                break;
            }
        }
    }

    fclose(pToFile);
    return 0;
}
</code>```

Body:
I need to get Questions from a file and then randomly show them to enter answers.
What I have done was I generate a random number and then file is reading line by line.When it meets the randomize number it will shows the relevant line.
now all working but i don't want to duplicate numbers.How can I fix this.

Here what i tried

   int main()
{
    int numb;
    int answer;
    int ar[5];
    int count =0;

    numb = randomgen();
    ar[count]=numb;
    char input[512];

    printf("Line number to print :%d\n",numb);
    count++;
    while(count != 6)
    {
        FILE * pToFile= fopen("data.txt","r");
        int line =0;
        while(fgets(input,512,pToFile))
            {
                line++;
                if(line == numb)
                {
                    printf(" %s",input);
                }

            }

            printf("Enter the answer:");

            scanf("%d",&answer);
            printf("\n");
            answermethod(numb,answer); //to check the answers ;WORKING

            numb = randomgen2(ar);
            ar[count] = numb;
            count++;

            fclose(pToFile);
    }

    return 0;

}
    int randomgen()
    {
         int r;
    srand(time(NULL));
    r=rand()%(5)+1;
    return r;

    }

    int randomgen2(int ars[]) //generate random n and search it in the
                            //array if it is not in array return the random
                            //  value.But this is not working
    {
    int r;
    srand(time(NULL));
     r=rand()%(5)+1;
    int num,i,c=0;

    int n= sizeof(ars)/sizeof(ars[0]);
          for(i=0;i<n;i++)
          {
              if(ars[i]==r)
              {
                  //printf("%d",r);

                  randomgen2(ars);
                  c=1;
                  break;
              }

              else
              {
                   printf("not found%d",r);
                  c=0;
              }
          }

            if(c==0)
            {
                printf("nooo");
                return r;
            }
    }

Body:
Uninitialized variables and the uninitialized array ar will cause undefined behavior.

The file needs to be opened only once. Use rewind to go back to the begining.

As noted in comments, use srand only once. And you have pass the array size to the function because in foo(int ar[]) the size of ar is the pointer size, not the allocation size.

Just check to see if the random number is used already. If it is not used, then store it in the array. The range of random number and array size should match exactly. Don't add +1

int main(void)
{
    srand((unsigned int)time(NULL));
    FILE *pToFile = fopen("data.txt", "r");
    char input[512];
    int line;
    int arr[5];
    int array_size = sizeof(arr) / sizeof(arr[0]);

    for (int count = 0; count < array_size; count++)
    {
        arr[count] = -1; // initialize to -1 to indicate it is not set
        while(arr[count] == -1)
        {
            arr[count] = rand() % array_size;
            for(int i = 0; i < count; i++)
                if(arr[i] == arr[count])
                    arr[count] = -1;
        }

        rewind(pToFile);
        line = 0;
        while(fgets(input, 512, pToFile))
        {
            if(line++ == arr[count])
            {
                printf("%s", input);
                break;
            }
        }
    }

    fclose(pToFile);
    return 0;
}


问:
VSTS release completion failure alert for automated deployment
I have a branch in a VSTS project that builds automatically on code push. The release also triggers automatically on the build being completed ('continuous deployment trigger').

This works fine.

If the build fails, I receive an email alert. However if the release fails, I don't receive an email alert. If I trigger the release manually (deployment trigger = manual deployment) and the release fails, then I receive an email.

I think this is because whilst I'm signed up to the 'Deployment completion failures' email subscription, as I don't technically 'request' the build under CI/CD (it's requested under 'Microsoft.VisualStudio.Services.ReleaseManagement').

Is there a way I can receive emails when the automated release fails? More specifically, how can I set up CI/CD in VSTS where if the release fails, the person who requested the build that triggered the release receives an email?

Edit: Screenshot requested.

答: Answer was as per starian chen's suggestion to add a collection level subscription.</p>


问:
How to get the MethodInfo of a Java 8 method reference?
Please have a look at the following code:

```<code>Method methodInfo = MyClass.class.getMethod("myMethod");
</code>```

This works, but the method name is passed as a string, so this will compile even if myMethod does not exist.

On the other hand, Java 8 introduces a method reference feature. It is checked at compile time. It is possible to use this feature to get method info?

```<code>printMethodName(MyClass::myMethod);
</code>```

Full example:

```<code>@FunctionalInterface
private interface Action {

    void invoke();
}

private static class MyClass {

    public static void myMethod() {
    }
}

private static void printMethodName(Action action) {
}

public static void main(String[] args) throws NoSuchMethodException {
    // This works, but method name is passed as a string, so this will compile
    // even if myMethod does not exist
    Method methodInfo = MyClass.class.getMethod("myMethod");

    // Here we pass reference to a method. It is somehow possible to
    // obtain java.lang.reflect.Method for myMethod inside printMethodName?
    printMethodName(MyClass::myMethod);
}
</code>```

In other words I would like to have a code which is the equivalent of the following C# code:

```<code>    private static class InnerClass
    {
        public static void MyMethod()
        {
            Console.WriteLine("Hello");
        }
    }

    static void PrintMethodName(Action action)
    {
        // Can I get java.lang.reflect.Method in the same way?
        MethodInfo methodInfo = action.GetMethodInfo();
    }

    static void Main()
    {
        PrintMethodName(InnerClass.MyMethod);
    }
</code>```

答:
There may not be a reliable way, but under some circumstances:

your MyClass is not final, and has an accessible constructor (limitation of cglib)

your myMethod is not overloaded, and not static

The you can try using cglib to create a proxy of MyClass, then using an MethodInterceptor to report the Method while the method reference is invoked in a following trial run.

Example code:

```<code>public static void main(String[] args) {
    Method m = MethodReferenceUtils.getReferencedMethod(ArrayList.class, ArrayList::contains);
    System.out.println(m);
}
</code>```

You will see the following output:

```<code>public boolean java.util.ArrayList.contains(java.lang.Object)
</code>```

While:

```<code>public class MethodReferenceUtils {

    @FunctionalInterface
    public static interface MethodRefWith1Arg<T, A1> {
        void call(T t, A1 a1);
    }

    public static <T, A1> Method getReferencedMethod(Class<T> clazz, MethodRefWith1Arg<T, A1> methodRef) {
        return findReferencedMethod(clazz, t -> methodRef.call(t, null));
    }

    @SuppressWarnings("unchecked")
    private static <T> Method findReferencedMethod(Class<T> clazz, Consumer<T> invoker) {
        AtomicReference<Method> ref = new AtomicReference<>();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                ref.set(method);
                return null;
            }
        });
        try {
            invoker.accept((T) enhancer.create());
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
        }

        Method method = ref.get();
        if (method == null) {
            throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
        }

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

In the above code, MethodRefWith1Arg is just a syntax sugar for you to reference an non-static method with one arguments. You can create as many as MethodRefWithXArgs for referencing your other methods.

Body:
Please have a look at the following code:

Method methodInfo = MyClass.class.getMethod("myMethod");

This works, but the method name is passed as a string, so this will compile even if myMethod does not exist.

On the other hand, Java 8 introduces a method reference feature. It is checked at compile time. It is possible to use this feature to get method info?

printMethodName(MyClass::myMethod);

Full example:

@FunctionalInterface
private interface Action {

    void invoke();
}

private static class MyClass {

    public static void myMethod() {
    }
}

private static void printMethodName(Action action) {
}

public static void main(String[] args) throws NoSuchMethodException {
    // This works, but method name is passed as a string, so this will compile
    // even if myMethod does not exist
    Method methodInfo = MyClass.class.getMethod("myMethod");

    // Here we pass reference to a method. It is somehow possible to
    // obtain java.lang.reflect.Method for myMethod inside printMethodName?
    printMethodName(MyClass::myMethod);
}

In other words I would like to have a code which is the equivalent of the following C# code:

    private static class InnerClass
    {
        public static void MyMethod()
        {
            Console.WriteLine("Hello");
        }
    }

    static void PrintMethodName(Action action)
    {
        // Can I get java.lang.reflect.Method in the same way?
        MethodInfo methodInfo = action.GetMethodInfo();
    }

    static void Main()
    {
        PrintMethodName(InnerClass.MyMethod);
    }

Body:
There may not be a reliable way, but under some circumstances:

your MyClass is not final, and has an accessible constructor (limitation of cglib)

your myMethod is not overloaded, and not static

The you can try using cglib to create a proxy of MyClass, then using an MethodInterceptor to report the Method while the method reference is invoked in a following trial run.

Example code:

public static void main(String[] args) {
    Method m = MethodReferenceUtils.getReferencedMethod(ArrayList.class, ArrayList::contains);
    System.out.println(m);
}

You will see the following output:

public boolean java.util.ArrayList.contains(java.lang.Object)

While:

public class MethodReferenceUtils {

    @FunctionalInterface
    public static interface MethodRefWith1Arg<T, A1> {
        void call(T t, A1 a1);
    }

    public static <T, A1> Method getReferencedMethod(Class<T> clazz, MethodRefWith1Arg<T, A1> methodRef) {
        return findReferencedMethod(clazz, t -> methodRef.call(t, null));
    }

    @SuppressWarnings("unchecked")
    private static <T> Method findReferencedMethod(Class<T> clazz, Consumer<T> invoker) {
        AtomicReference<Method> ref = new AtomicReference<>();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                ref.set(method);
                return null;
            }
        });
        try {
            invoker.accept((T) enhancer.create());
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
        }

        Method method = ref.get();
        if (method == null) {
            throw new IllegalArgumentException(String.format("Invalid method reference on class [%s]", clazz));
        }

        return method;
    }
}

In the above code, MethodRefWith1Arg is just a syntax sugar for you to reference an non-static method with one arguments. You can create as many as MethodRefWithXArgs for referencing your other methods.


答:
Try this</p>

```<code>  <a href='http://example.com/PhpProject3/reset_passwd.php?key=".$email."&userid=".$userid."' style=' background-color: #4CAF50;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;'>
    <button>Click To Reset password</button>
    </a>";
</code>```

Title: How to add button in PHP Mail function?

Body:
Try this

  <a href='http://example.com/PhpProject3/reset_passwd.php?key=".$email."&userid=".$userid."' style=' background-color: #4CAF50;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;'>
    <button>Click To Reset password</button>
    </a>";


问:
Setting ABI Target with Android CMake Builds
Using Application.mk, it looks like the ABI targets can be selected with the option APP_ABI:

APP_ABI := armeabi-v7a,arm64-v8a,x86,x86_64,mips

I can't seem to find any such options for CMake builds. The file CMakeLists.txt seems to be called with the ANDROID_ABI option passed in, but I can't find any corresponding configuration options in the gradle plugin.

答:
You should use abiFilters:

```<code>android {
  defaultConfig {
    ndk {
        abiFilters "x86"
    }
  }
}
</code>```

Body:
You should use abiFilters:

android {
  defaultConfig {
    ndk {
        abiFilters "x86"
    }
  }
}


问:
jQuery - How can I allow both numpad and number key row input; as well as prevent special characters from being entered?
I want to allow both number pad numeric and oridinary number from keyboard. Currently, it only allows the number key row. I also only want numbers to be entered, but it currently allows special characters.

$(document).ready(function() {
  $('#price').keydown(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'></code>```

答:
Why we don't user input type number. I think just do it easy like this:

<input type='number' id='price'>```

Body:
I want to allow both number pad numeric and oridinary number from keyboard. Currently, it only allows the number key row. I also only want numbers to be entered, but it currently allows special characters.

$(document).ready(function() {
  $('#price').keydown(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});

<input type='text' id='price'>

Body:
Why we don't user input type number. I think just do it easy like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='number' id='price'>


问:
How to change column names in pandas Dataframe using a list of names?
I have been trying to change the column names of a pandas dataframe using a list of names. The following code is being used:

```<code>df.rename(columns = list_of_names, inplace=True)
</code>```

However I got a Type Error each time, with an error message that says "list object is not callable".
  I would like to know why does this happen? And What can I do to solve this problem?
Thank you for your help.

答:
If you need rename (l is your list of name need to change to)

```<code>df.rename(columns=dict(zip(df.columns,l)))
</code>```

Body:
I have been trying to change the column names of a pandas dataframe using a list of names. The following code is being used:

df.rename(columns = list_of_names, inplace=True)

However I got a Type Error each time, with an error message that says "list object is not callable".
  I would like to know why does this happen? And What can I do to solve this problem?
Thank you for your help.

Body:
If you need rename (l is your list of name need to change to)

df.rename(columns=dict(zip(df.columns,l)))


问:
GitHub enterprise login using curl
Hi I am trying to login into GitHub enterprise using curl for internal purposes. I use following command to fetch list of url information:

```<code>curl -u "xplorebitshq" https://api.github.com
</code>```

I have Github enterprise url. So, i tried to login into GitHub enterprise by replacing the "https://api.github.com" with "https://github.kdc.capitalone.com".

```<code>curl -u "enterpriseuser" https://github.kdc.capitalone.com
</code>```

I am getting following error:

```<code>curl: (6) Could not resolve host: github.kdc.capitalone.com
</code>```

What do I need or changed in command to login and fetch list of repositories?

答:
The GitHub enterprise API URL is:

```<code>http(s)://hostname/api/v3/
</code>```

But in your case, the domain itself (github.kdc.capitalone.com) is not resolved by the DNS.

One reason for that (which is not related to the API URL at all) is if you are working behind a proxy.

Don't forget to set a NO_PROXY (or no_proxy) environment variable

```<code>set no_proxy=.capitalone.com,localhost,::1
</code>```

That would avoid any https query to pass by the proxy for a locally accessible network domain.

Title: GitHub enterprise login using curl

Body:
Hi I am trying to login into GitHub enterprise using curl for internal purposes. I use following command to fetch list of url information:

curl -u "xplorebitshq" https://api.github.com

I have Github enterprise url. So, i tried to login into GitHub enterprise by replacing the "https://api.github.com" with "https://github.kdc.capitalone.com".

curl -u "enterpriseuser" https://github.kdc.capitalone.com

I am getting following error:

curl: (6) Could not resolve host: github.kdc.capitalone.com

What do I need or changed in command to login and fetch list of repositories?

Body:
The GitHub enterprise API URL is:

http(s)://hostname/api/v3/

But in your case, the domain itself (github.kdc.capitalone.com) is not resolved by the DNS.

One reason for that (which is not related to the API URL at all) is if you are working behind a proxy.

Don't forget to set a NO_PROXY (or no_proxy) environment variable

set no_proxy=.capitalone.com,localhost,::1

That would avoid any https query to pass by the proxy for a locally accessible network domain.


问:
HTML5 audio control not working on Android
I created a web page with 8 audio tracks, each uses its own audio and source tags:

```<code>HTML

<ul>
  <li> Sleepwalk <br><audio controls> <source src="sleepwalk.mp3" type="audio/mpeg" /> </audio></li>
  <li>Sunny <br><audio controls> <source src="sunny.mp3" type="audio/mpeg" /> </audio></li>
        <li>Georgia on My Mind<br>
          <audio controls> <source src="georgia.mp3" type="audio/mpeg" /> </audio></li>
  <li>All of Me <br><audio controls> <source src="allofme.mp3" type="audio/mpeg" /> </audio></li>
        <li>The Shadow of Your Smile<br>
          <audio controls> <source src="shadow.mp3" type="audio/mpeg" /> </audio></li>
  <li>Mr. Sandman <br><audio controls> <source src="sandman.mp3" type="audio/mpeg" /> </audio></li>
  <li>Chestnuts (The Christmas Song) <br><audio controls> <source src="chestnuts.mp3" type="audio/mpeg" /> </audio></li>
  <li>White Christmas <br><audio controls> <source src="white.mp3" type="audio/mpeg" /> </audio></li>
</ul>
</code>```

On my monitor, this works just fine (at http://mikeytheking.com/guitarmusic.html), but on my Android, I see the left half of each control, but clicking does nothing.

Please advise.

答:
use this..</p>

```<code>        <script type=text/javascript>
    var maudio = document.getElementById('myaudio');

    var soundSprite = [{
            start: 0,
            end: 3000
        },
        {
            start: 3500,
            end: 6789
        }
    ];

    element.addEventListener('touchstart', function(ev) {
        maudio.play();
        playSoundFile(0);
    })

    function playSoundFile(idx) {
        maudio.currentPosition = soundSprite[idx].start;
        var x = setInterval(function() {
            if (maudio.currentPosition >= soundSprite[idx].end) {
                maudio.pause(); // There is no stop() in HTML5
                clearInterval(x);
            }
        }, 50);
    }
</script>

    <audio src="sprite.mp3" controls="none" id="myaudio" />
</code>```

Body:
I created a web page with 8 audio tracks, each uses its own audio and source tags:

HTML

 Sleepwalk
<audio controls> <source src="sleepwalk.mp3" type="audio/mpeg" /> </audio>

Sunny
<audio controls> <source src="sunny.mp3" type="audio/mpeg" /> </audio>

Georgia on My Mind

          <audio controls> <source src="georgia.mp3" type="audio/mpeg" /> </audio>

All of Me
<audio controls> <source src="allofme.mp3" type="audio/mpeg" /> </audio>

The Shadow of Your Smile

          <audio controls> <source src="shadow.mp3" type="audio/mpeg" /> </audio>

Mr. Sandman
<audio controls> <source src="sandman.mp3" type="audio/mpeg" /> </audio>

Chestnuts (The Christmas Song)
<audio controls> <source src="chestnuts.mp3" type="audio/mpeg" /> </audio>

White Christmas
<audio controls> <source src="white.mp3" type="audio/mpeg" /> </audio>

On my monitor, this works just fine (at http://mikeytheking.com/guitarmusic.html), but on my Android, I see the left half of each control, but clicking does nothing.

Please advise.

Body:
use this..

        <script type=text/javascript>
    var maudio = document.getElementById('myaudio');

    var soundSprite = [{
            start: 0,
            end: 3000
        },
        {
            start: 3500,
            end: 6789
        }
    ];

    element.addEventListener('touchstart', function(ev) {
        maudio.play();
        playSoundFile(0);
    })

    function playSoundFile(idx) {
        maudio.currentPosition = soundSprite[idx].start;
        var x = setInterval(function() {
            if (maudio.currentPosition >= soundSprite[idx].end) {
                maudio.pause(); // There is no stop() in HTML5
                clearInterval(x);
            }
        }, 50);
    }
</script>

    <audio src="sprite.mp3" controls="none" id="myaudio" />


问:
what is the db argument's value or usage for this javascript es6 fat arrow function?
```<code>initializeDb( db => {

    // internal middleware
    app.use(middleware({ config, db }));

    // api router
    app.use('/api', api({ config, db }));

    app.server.listen(process.env.PORT || config.port, () => {
        console.log(`Started on port ${app.server.address().port}`);
    });
});
</code>```

https://github.com/developit/express-es6-rest-api/blob/master/src/index.js#L27

Above situation, the db seems pop out of nowhere, to see the context, please click on the link direct to the source code.

I simulated the same way here (https://codepen.io/adamchenwei/pen/vWWmXa) the db shouldn't even be accessible. What exactly the db does then in that specific boilerplate?

答:
db is the argument of the call back function of initializeDb

The code actually looks like this

```<code>'use strict';

initializeDb(function (db) {

    // internal middleware
    app.use(middleware({ config: config, db: db }));

    // api router
    app.use('/api', api({ config: config, db: db }));

    app.server.listen(process.env.PORT || config.port, function () {
        console.log('Started on port ' + app.server.address().port);
    });
});
</code>```

Body:
initializeDb( db => {

    // internal middleware
    app.use(middleware({ config, db }));

    // api router
    app.use('/api', api({ config, db }));

    app.server.listen(process.env.PORT || config.port, () => {
        console.log(`Started on port ${app.server.address().port}`);
    });
});

https://github.com/developit/express-es6-rest-api/blob/master/src/index.js#L27

Above situation, the db seems pop out of nowhere, to see the context, please click on the link direct to the source code.

I simulated the same way here (https://codepen.io/adamchenwei/pen/vWWmXa) the db shouldn't even be accessible. What exactly the db does then in that specific boilerplate?

Body:
db is the argument of the call back function of initializeDb

The code actually looks like this

'use strict';

initializeDb(function (db) {

    // internal middleware
    app.use(middleware({ config: config, db: db }));

    // api router
    app.use('/api', api({ config: config, db: db }));

    app.server.listen(process.env.PORT || config.port, function () {
        console.log('Started on port ' + app.server.address().port);
    });
});


问:
here i am on my node js server 127.0.0.1/8081 and if click button then i want to switch server 127.0.0.1/8000
here I am on my node js server 127.0.0.1/8081 and if click button then I want to switch laravel server 127.0.0.1/8000 </p>

```<code>if (results.length==0){
    return res.redirect('/alert.html');
}
else{
    return res.redirect('/acess');//from here i want switch server to 127.0.0.1/8000
}
</code>```

答:
You have two different servers, 127.0.0.1:8000 and 127.0.0.1:8081.

You are running your nodeJS code on 127.0.0.1:8000 and when you need to redirect to 127.0.0.1:8081, you need to provide full URL instead relative URL.

use res.redirect('http://127.0.0.1:8000/acess')

Your code will become

```<code>if (results.length==0){
    return res.redirect('/alert.html');
}
else{
    return res.redirect('http://127.0.0.1:8000/acess');
}
</code>```

Body:
here I am on my node js server 127.0.0.1/8081 and if click button then I want to switch laravel server 127.0.0.1/8000

if (results.length==0){
    return res.redirect('/alert.html');
}
else{
    return res.redirect('/acess');//from here i want switch server to 127.0.0.1/8000
}

Body:
You have two different servers, 127.0.0.1:8000 and 127.0.0.1:8081.

You are running your nodeJS code on 127.0.0.1:8000 and when you need to redirect to 127.0.0.1:8081, you need to provide full URL instead relative URL.

use res.redirect('http://127.0.0.1:8000/acess')

Your code will become

if (results.length==0){
    return res.redirect('/alert.html');
}
else{
    return res.redirect('http://127.0.0.1:8000/acess');
}