问:
Terminate subprocess in python doesn't work
I want to terminate a subprocess, but it doesn't work. Here's my code:

```<code>import os
import subprocess

p = subprocess.Popen(['gnome-terminal','-e','tshark -i eth0 -w /root/Desktop/test.pcap'])
q = subprocess.Popen(['python','avtp2.py'])

if q.wait() == 0:
  p.terminate()
</code>```

Do you know why?

Greetz

答:
This works:</p>

```<code>import os
import subprocess
from subprocess import check_output
import signal

p = subprocess.Popen(['gnome-terminal','-e','tshark -i eth0 -w /root/Desktop/test.pcap'],shell=False)
q = subprocess.Popen(['python','avtp2.py'])

if q.wait() == 0:
  p_pid = check_output(["pidof","tshark"]).split()
  os.kill(int(p_pid[0]), signal.SIGINT)
</code>```

Body:
I want to terminate a subprocess, but it doesn't work. Here's my code:

import os
import subprocess

p = subprocess.Popen(['gnome-terminal','-e','tshark -i eth0 -w /root/Desktop/test.pcap'])
q = subprocess.Popen(['python','avtp2.py'])

if q.wait() == 0:
  p.terminate()

Do you know why?

Greetz

Body:
This works:

import os
import subprocess
from subprocess import check_output
import signal

p = subprocess.Popen(['gnome-terminal','-e','tshark -i eth0 -w /root/Desktop/test.pcap'],shell=False)
q = subprocess.Popen(['python','avtp2.py'])

if q.wait() == 0:
  p_pid = check_output(["pidof","tshark"]).split()
  os.kill(int(p_pid[0]), signal.SIGINT)


来源: stackexchange

问:
find common rows of matching column from two tables
I have two tables with a column values mostly matching with each other.

How can I find row that are matching in common to that column.

Here is my fiddle

It is showing Error at B

答:
I think JOIN will work, please try below:</p>

```<code>SELECT A.ProductName
FROM ForgeRock AS A
JOIN ForgeRock1 AS B ON A.ProductName = B.ProductName;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think JOIN will work, please try below:

SELECT A.ProductName
FROM ForgeRock AS A
JOIN ForgeRock1 AS B ON A.ProductName = B.ProductName;


问:
How to print the JSON object in Android using a try block
I need to get the JSON object from MySQL database, and to print it as string. Also, I need to pass that string to a try block to open required class activity. Here, I have attached my code below, check my code and let me know.

My JSON object sample:

```<code>{ "id": "381", "task": "user_confirm", "message": "New booking details" }
</code>```

My Android Code:

```<code>public void onMessageReceived(final RemoteMessage remoteMessage) {
    Intent intent = new Intent(this, Login_Activity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle(getResources().getString(R.string.app_name));
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.mipmap.main_logo);
    notificationBuilder.setContentIntent(pendingIntent);

    Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bike_start);
    notificationBuilder.setSound(path);
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());

    if (remoteMessage.getData().size() > 0) {
        try {
            JSONObject json = new JSONObject(remoteMessage.getData());
            Log.e("JsonOutput", json.toString());
            sendNotification(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
    if (remoteMessage.getNotification()!=null){
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    //        sendNotification1(String.valueOf(remoteMessage), image);
    // Log.e("body", body);
}

private void sendNotification(JSONObject json) {
    Log.e(TAG, "Notifications JSON1 " + json.toString());

    try {
         JSONObject data = json.getJSONObject("data");
         Log.d("data", String.valueOf(data));
         //parsing json data
         id = data.get("id").toString();
         message = data.get("message").toString();
         task = data.get("task").toString();
         Log.d("Id values", id);
         Log.d("Message", message);
    }
}
</code>```

Output:

Notifications JSON1 {"id":"381","task":"user_confirm","message":"New booking details"}

答:
As per your attached JSON response, there is no JSONObject named "data" in your JSON data.

Parse JSON data as below:

```<code>if (remoteMessage.getData().size() > 0) {
    try {
        JSONObject json = new JSONObject(remoteMessage.getData().toString());
        Log.e("JsonOutput", json.toString());
        sendNotification(json);
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}
...........
.......................

private void sendNotification(JSONObject json) {
    Log.e(TAG, "Notifications JSON1 " + json.toString());

    try {
         // Parsing id, task and message from json JSONObject
         String id = json.getString("id");
         String task = json.getString("task");
         String message = json.getString("message");

         Log.d("Id: ", id);
         Log.d("Task: ", task);
         Log.d("Message: ", message);

    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}
</code>```

Hope this will work~

Body:
I need to get the JSON object from MySQL database, and to print it as string. Also, I need to pass that string to a try block to open required class activity. Here, I have attached my code below, check my code and let me know.

My JSON object sample:

{ "id": "381", "task": "user_confirm", "message": "New booking details" }

My Android Code:

public void onMessageReceived(final RemoteMessage remoteMessage) {
    Intent intent = new Intent(this, Login_Activity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle(getResources().getString(R.string.app_name));
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.mipmap.main_logo);
    notificationBuilder.setContentIntent(pendingIntent);

    Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bike_start);
    notificationBuilder.setSound(path);
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());

    if (remoteMessage.getData().size() > 0) {
        try {
            JSONObject json = new JSONObject(remoteMessage.getData());
            Log.e("JsonOutput", json.toString());
            sendNotification(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
    if (remoteMessage.getNotification()!=null){
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    //        sendNotification1(String.valueOf(remoteMessage), image);
    // Log.e("body", body);
}

private void sendNotification(JSONObject json) {
    Log.e(TAG, "Notifications JSON1 " + json.toString());

    try {
         JSONObject data = json.getJSONObject("data");
         Log.d("data", String.valueOf(data));
         //parsing json data
         id = data.get("id").toString();
         message = data.get("message").toString();
         task = data.get("task").toString();
         Log.d("Id values", id);
         Log.d("Message", message);
    }
}

Output:

Notifications JSON1 {"id":"381","task":"user_confirm","message":"New booking details"}

Body:
As per your attached JSON response, there is no JSONObject named "data" in your JSON data.

Parse JSON data as below:

if (remoteMessage.getData().size() > 0) {
    try {
        JSONObject json = new JSONObject(remoteMessage.getData().toString());
        Log.e("JsonOutput", json.toString());
        sendNotification(json);
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}
...........
.......................

private void sendNotification(JSONObject json) {
    Log.e(TAG, "Notifications JSON1 " + json.toString());

    try {
         // Parsing id, task and message from json JSONObject
         String id = json.getString("id");
         String task = json.getString("task");
         String message = json.getString("message");

         Log.d("Id: ", id);
         Log.d("Task: ", task);
         Log.d("Message: ", message);

    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

Hope this will work~


问:
Deploying Spring WAR to Tomcat-based docker
I have followed through Spring's Building a RESTful Web Service tutorial and created a dummy webapp (with "Build with Maven" instructions). I build and package the WAR. Then I run it with this command:

```<code>java -jar ./target/Dummy-1.0-SNAPSHOT.war
</code>```

I can see the dummy JSON endpoint at http://localhost:8080/greeting/.

Now I want to containerize the app with Docker so I can further test it without the needs to install Tomcat to system space. This is the Dockerfile I created:

```<code>FROM tomcat:7-jre8-alpine

# copy the WAR bundle to tomcat
COPY /target/Dummy-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/app.war

# command to run
CMD ["catalina.sh", "run"]
</code>```

I build and run the docker binding to http://localhost:8080. I can see the Tomcat welcome page on "http://localhost:8080". But I couldn't see my app on neither:

http://localhost:8080/app/

http://localhost:8080/app/greeting/

http://localhost:8080/greeting/

How should I track down the issue? What could be the problem?

Update 1: The Tomcat admin interface screenshot

答:
The Application.java file in the example looks like this:

```<code>package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

This is a valid SpringBoot application, but NOT a deployable application to Tomcat. To make it deployable, you can can:

redefineApplication to extend SpringBootServletInitializer from Spring framework web support; then

override the configure method:

```<code>package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
</code>```

No need to change the pom.xml file (or any other configurations).

After rebuilding the dockerfile and run it with proper port binding, the greeting example endpoint will be available through: http://localhost:8080/app/greeting/

References

Spring Boot War deployed to Tomcat

Spring Boot Reference Guide: Create a deployable war file

Body:
I have followed through Spring's Building a RESTful Web Service tutorial and created a dummy webapp (with "Build with Maven" instructions). I build and package the WAR. Then I run it with this command:

java -jar ./target/Dummy-1.0-SNAPSHOT.war

I can see the dummy JSON endpoint at http://localhost:8080/greeting/.

Now I want to containerize the app with Docker so I can further test it without the needs to install Tomcat to system space. This is the Dockerfile I created:

FROM tomcat:7-jre8-alpine

# copy the WAR bundle to tomcat
COPY /target/Dummy-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/app.war

# command to run
CMD ["catalina.sh", "run"]

I build and run the docker binding to http://localhost:8080. I can see the Tomcat welcome page on "http://localhost:8080". But I couldn't see my app on neither:

http://localhost:8080/app/

http://localhost:8080/app/greeting/

http://localhost:8080/greeting/

How should I track down the issue? What could be the problem?

Update 1: The Tomcat admin interface screenshot

Body:
The Application.java file in the example looks like this:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

This is a valid SpringBoot application, but NOT a deployable application to Tomcat. To make it deployable, you can can:

redefineApplication to extend SpringBootServletInitializer from Spring framework web support; then

override the configure method:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

No need to change the pom.xml file (or any other configurations).

After rebuilding the dockerfile and run it with proper port binding, the greeting example endpoint will be available through: http://localhost:8080/app/greeting/

References

Spring Boot War deployed to Tomcat

Spring Boot Reference Guide: Create a deployable war file


问:
stream reduction incompatible types
I'm trying to create a finder which takes several predicates and reduces them:

```<code>public static <T extends BusinessInterface> Collection<T> findOr(
    Context pContext, Class<T> pClass, Predicate<? super T>... pPredicates) {
  Predicate<? super T> lReducedPredicate =
      Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
  return find(pContext, pClass, lReducedPredicate);
}
</code>```

Unfortunately I get following compiler error:

Predicate lReducedPredicate = Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
  incompatible types: Predicate cannot be converted to Predicate
  where T is a type-variable:
  T extends BusinessInterface declared in method findOr(Context,Class,Predicate...)
  where CAP#1,CAP#2 are fresh type-variables:
  CAP#1 extends Object super: T from capture of ? super T
  CAP#2 extends Object super: T from capture of ? super T

I get not errors in Eclipse and I have no idea what is going wrong.

Any help is really appreciated :).

答:
One way to solve this is using

```<code>public static <T extends BusinessInterface> Collection<T> findOr(
    Context pContext, Class<T> pClass, Predicate<? super T>... pPredicates) {
  Predicate<? super T> lReducedPredicate = Arrays.asList(pPredicates).stream()
    .reduce((a,b) -> t -> a.test(t) || b.test(t)).orElse(r -> false);
  return find(pContext, pClass, lReducedPredicate);
}
</code>```

While you can’t invoke the or method on a Predicate<? super T> instance with another Predicate<? super T> as argument, you can create the same function, or would return, yourself, as passing a T instance to either test method is valid.

Title: stream reduction incompatible types

Body:
I'm trying to create a finder which takes several predicates and reduces them:

public static <T extends BusinessInterface> Collection<T> findOr(
    Context pContext, Class<T> pClass, Predicate<? super T>... pPredicates) {
  Predicate<? super T> lReducedPredicate =
      Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
  return find(pContext, pClass, lReducedPredicate);
}

Unfortunately I get following compiler error:

Predicate lReducedPredicate = Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
  incompatible types: Predicate cannot be converted to Predicate
  where T is a type-variable:
  T extends BusinessInterface declared in method findOr(Context,Class,Predicate...)
  where CAP#1,CAP#2 are fresh type-variables:
  CAP#1 extends Object super: T from capture of ? super T
  CAP#2 extends Object super: T from capture of ? super T

I get not errors in Eclipse and I have no idea what is going wrong.

Any help is really appreciated :).

Body:
One way to solve this is using

public static <T extends BusinessInterface> Collection<T> findOr(
    Context pContext, Class<T> pClass, Predicate<? super T>... pPredicates) {
  Predicate<? super T> lReducedPredicate = Arrays.asList(pPredicates).stream()
    .reduce((a,b) -> t -> a.test(t) || b.test(t)).orElse(r -> false);
  return find(pContext, pClass, lReducedPredicate);
}

While you can’t invoke the or method on a Predicate<? super T> instance with another Predicate<? super T> as argument, you can create the same function, or would return, yourself, as passing a T instance to either test method is valid.


问:
ru.yandex.qatools.allure.jenkins.execption.AllurePluginException: Can not generate Allure Report, exit code: 255
[protracsol] $ "C:\Program Files (x86)\Jenkins\tools\ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation\latest\bin\allure.bat" generate "D:\jenkins-workspace\workspace\protracsol\allure-results" -o "D:\jenkins-workspace\workspace\protracorsol\allure-report"
\Jenkins\tools\ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation\latest\bin.. was unexpected at this time.
ERROR: Build step failed with exception
ru.yandex.qatools.allure.jenkins.execption.AllurePluginException: Can not generate Allure Report, exit code: 255</p>

答: update the commandline tool in jenkins to the latest version. I encountered the same issue and doing this fixed it.</p>


问:
Loading JSON string into a pie chart in highcharts
I need to include my json String output to a highcharts --pie chart category
but chart is not loading properly

This is my JSON string

```<code>var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\"name\":\"Telenav\"}":{"y":13.59}}

Highcharts.chart('container', {
    chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
    },
    title: {
        text: ''
    },
    tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
            }
        }
    },
    series: [{
        name: 'Brands',
        colorByPoint: true,
        data: json
    }]
});
</code>```

Below is the chart what I'm getting when loading this jsonstring.
Can any one help me with this because I'm new to this.Thanks in advance.

答:
Try formatting your json this way

```<code>var json = [{name: "BillToMobile", y: 2.35}, {name: "Telenav", y: 13.59}]
</code>```

To convert the json you have you can use this:

ES5 or earlier

```<code>var properJson = [];
for (var i in json) {
   var item = JSON.parse(i);
   for (var j in json[i]) {
      item[j] = json[i][j];
   }
   properJson.push(item);
}
</code>```

ES6

```<code>var properJson = [];
for (var i in json) {
   var item = JSON.parse(i);
   Object.assign(item, json[i]);
   properJson.push(item);
}
</code>```

Body:
I need to include my json String output to a highcharts --pie chart category
but chart is not loading properly

This is my JSON string

var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\"name\":\"Telenav\"}":{"y":13.59}}

Highcharts.chart('container', {
    chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
    },
    title: {
        text: ''
    },
    tooltip: {
        pointFormat: '{series.name}: {point.percentage:.1f}%'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '{point.name}: {point.percentage:.1f} %',
                style: {
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
            }
        }
    },
    series: [{
        name: 'Brands',
        colorByPoint: true,
        data: json
    }]
});

Below is the chart what I'm getting when loading this jsonstring.
Can any one help me with this because I'm new to this.Thanks in advance.

Body:
Try formatting your json this way

var json = [{name: "BillToMobile", y: 2.35}, {name: "Telenav", y: 13.59}]

To convert the json you have you can use this:

ES5 or earlier

var properJson = [];
for (var i in json) {
   var item = JSON.parse(i);
   for (var j in json[i]) {
      item[j] = json[i][j];
   }
   properJson.push(item);
}

ES6

var properJson = [];
for (var i in json) {
   var item = JSON.parse(i);
   Object.assign(item, json[i]);
   properJson.push(item);
}


问:
How to set up Jenkins with Nginx and a Node.js application

What I want

Hi, my problem is the following: I want to access Jenkins which I have running on my server through my browser at https://my-domain.com/jenkins.

What I have

I have DO droplet with Ubuntu 16.04 which runs Nginx which works as a proxy server, forwarding all the traffic towards my Node.js application through https, which works fine when I visit my site at https://my-domain.com.

I have successfully installed and run Jenkins (if I run a systemctl status jenkins I can see that it's active), however I can't figure out, how my Nginx should be configured to access Jenkins properly.

What I tried to do is to set up a new location for it, but the result is that if I visit https://my-domain.com/jenkins it redirects to https://my-domain.com/login?from=%2Fjenkins and serves my Node.js application.

Nginx config (/etc/nginx/sites-enabled/default)

```<code> server {
        listen 80;
        listen [::]:80 default_server ipv6only=on;
        return 301 https://$host$request_uri;
    }

# HTTPS — proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name my-domain.com;

    # Access and error log for Jenkins
    access_log /var/log/nginx/jenkins.access.log;
    error_log /var/log/nginx/jenkins.error.log;

    # Use the Let’s Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/my-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/my-domain.com/privkey.pem;

# Include the SSL configuration from cipherli.st
include snippets/ssl-params.conf;

location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:5000/;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;

    # Settings for Jenkins
    # include /etc/nginx/proxy_params;
    # proxy_pass http://localhost:8080;
    # proxy_read_timeout 90s;
    # proxy_redirect http://localhost:8080 https://my-domain.com;
}

location /jenkins {
    include /etc/nginx/proxy_params;
    proxy_pass http://localhost:8080;
    proxy_read_timeout 90s;
}
}
</code>```

Maybe the actual issue is not with the Nginx configuration but with Jenkins? Thanks in advance!

答:
Ok, I have figured it out. I realized that instead of proxy_pass http://localhost:8080; I had to use proxy_pass http://localhost:8080/jenkins/;, and redirect to https with proxy_redirect http:// https://;

For further help please visit: https://wiki.jenkins.io/display/JENKINS/Jenkins+behind+an+NGinX+reverse+proxy

Body:
What I want

Hi, my problem is the following: I want to access Jenkins which I have running on my server through my browser at https://my-domain.com/jenkins.

What I have

I have DO droplet with Ubuntu 16.04 which runs Nginx which works as a proxy server, forwarding all the traffic towards my Node.js application through https, which works fine when I visit my site at https://my-domain.com.

I have successfully installed and run Jenkins (if I run a systemctl status jenkins I can see that it's active), however I can't figure out, how my Nginx should be configured to access Jenkins properly.

What I tried to do is to set up a new location for it, but the result is that if I visit https://my-domain.com/jenkins it redirects to https://my-domain.com/login?from=%2Fjenkins and serves my Node.js application.

Nginx config (/etc/nginx/sites-enabled/default)

 server {
        listen 80;
        listen [::]:80 default_server ipv6only=on;
        return 301 https://$host$request_uri;
    }

# HTTPS — proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name my-domain.com;

    # Access and error log for Jenkins
    access_log /var/log/nginx/jenkins.access.log;
    error_log /var/log/nginx/jenkins.error.log;

    # Use the Let’s Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/my-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/my-domain.com/privkey.pem;

# Include the SSL configuration from cipherli.st
include snippets/ssl-params.conf;

location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:5000/;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;

    # Settings for Jenkins
    # include /etc/nginx/proxy_params;
    # proxy_pass http://localhost:8080;
    # proxy_read_timeout 90s;
    # proxy_redirect http://localhost:8080 https://my-domain.com;
}

location /jenkins {
    include /etc/nginx/proxy_params;
    proxy_pass http://localhost:8080;
    proxy_read_timeout 90s;
}
}

Maybe the actual issue is not with the Nginx configuration but with Jenkins? Thanks in advance!


问:
Import DataSet into SQL Server 2008 Express
I have a very large DataSet containing about 160.000 records. If I loop trough the dataset and import every record, it can take about 20 minutes before the complete dataset is imported into the SQL Server.

Isn't there a faster way for importing the dataset at once in the database?

The dataset is created from a file I process which the user provides, then I have 1 table called lets say "ImportTable" containing about 14 columns. The columns correspond with the columns in the DataSet.

I use Visual Studio 2010 professional with c#.

Thanks in advance!

答: You may want to take a look at the bcp command line utility. It lets you load data directly from a file into a table in the database. Depending on how the user generated file looks, you may need to re-format it, but if it has a simple delimited format you can probably use it as-is with bcp.

ContentLicense: CC BY-SA 2.5


问:
I'm trying to create an Ad - Hoc bulid but failed
So I'm trying to create an Ad - Hoc bulid but after trying to export this archive, I keep getting the following error:

答:
First of try and edit the distribution profile and download it again then restart the xcode.

If that don't work then try this....

go to keychain access, -> Show Expired Certificates, and check your expired certificates and delete them from both the login and System keychains.

Then download a new one from https://developer.apple.com/certificationauthority/AppleWWDRCA.cer and add it to and add it to Keychain access -> certificates


问:
How to classify my array of object compared to my table?
I want to reorder my array of object, I want it follows (const quote) the theme position (const themeOrder).

```<code>const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];
</code>```

I want a result like

```<code>newQuote = [{
  theme: 'tech'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'spirituality'
}]
</code>```

答:
Use a Map to create key/value pairs of theme/order (index). When you sort, translate the theme names to the index numbers, and sort by these values.

const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];

const themeOrder = ['tech', 'politic', 'military', 'spirituality'];
const order = themeOrder.reduce((map, key, index) => map.set(key, index), new Map());

quote.sort((a, b) => order.get(a.theme) - order.get(b.theme));

console.log(quote);```

Body:
I want to reorder my array of object, I want it follows (const quote) the theme position (const themeOrder).

const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];

I want a result like

newQuote = [{
  theme: 'tech'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'spirituality'
}]


问:
Send form-urlencoded parameters in post request android volley
I want to make a POST JSONObjectRequest with form urlencoded parameters. How can I do this? I've tried the following code, but to no avail.

```<code>final String api = "http://api.url";
final JSONObject jobj = new JSONObject();
jobj.put("Username", "usr");
jobj.put("Password", "passwd");
jobj.put("grant_type", "password");

final JsonObjectRequest jor = new JsonObjectRequest(

    Request.Method.POST,
    api, jobj,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
            //do other things with the received JSONObject
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
        }
    }) {

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> pars = new HashMap<String, String>();
        pars.put("Content-Type", "application/x-www-form-urlencoded");
        return pars;
    }
};

//add to the request queue
requestqueue.AddToRequestQueue(jor);
</code>```

I'm getting a 400 bad request with the api call! How can I fix it?

答:
```<code>public void sendUserRegistrationRequest(final UserRequest userRequest, final ResponseListener responseListener) {
    String url = Api.POST_NRNA_REGISTRATION;

    StringRequest userRegistrationRequest = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            JSONObject jsonObject = GsonUtils.getJSONObject(response);
            LoggerUtils.log(TAG, "" + jsonObject.toString());

        }
    }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            LoggerUtils.log(TAG, GsonUtils.toString(error));
            responseListener.onError(GsonUtils.toString(error));
        }
    }) {

        //use this if you have to use form posting : for application/x-www-form-urlencoded;
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return GsonUtils.getHashMap(userRequest);
        }

        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }

    };
    VolleyRequestQueue.getInstance(context).addToRequestQueue(userRegistrationRequest);
}
</code>```

Use this if you have to send like "application/json"

```<code>        @Override
        public byte[] getBody() throws AuthFailureError {
            String jsonData = GsonUtils.toString(userRequest);
            return jsonData.getBytes();
        }

        @Override
        public String getBodyContentType() {
            return "application/json";
        }

public class GsonUtils {

public static String TAG = GsonUtils.class.getSimpleName();

public static <T> T toObject(String data, Class<T> type) {
    Gson gson = new Gson();
    return gson.fromJson(data, type);
}

public static String toString(Object src) {
    if (src == null) {
        return null;
    }
    GsonBuilder builder = new GsonBuilder();
    builder.setPrettyPrinting();
    Gson gson = builder.create();
    return gson.toJson(src);
}

public static <T> T toObject(String data, Type type) {
    try {
        Gson gson = new Gson();
        return gson.fromJson(data, type);
    } catch (Exception ex) {
        Timber.v(ex.getMessage());
        return null;
    }
}

public static JSONObject getJSONObject(Object src) {
    String data = toString(src);
    LoggerUtils.log(TAG, data);
    try {
        return new JSONObject(data);
    } catch (JSONException e) {
        LoggerUtils.log(TAG, e.getMessage());
    }
    return null;
}

public static JSONObject getJSONObject(String data) {
    try {
        return new JSONObject(data);
    } catch (JSONException e) {
        LoggerUtils.log(TAG, e.getMessage());
    }
    return null;
}

public static HashMap<String, String> getHashMap(Object src) {
    String data = toString(src);
    LoggerUtils.log(TAG, data);
    return toObject(data, new TypeToken<HashMap<String, String>>() {
    }.getType());
}
</code>```

}

ContentLicense: CC BY-SA 4.0

Body:
I want to make a POST JSONObjectRequest with form urlencoded parameters. How can I do this? I've tried the following code, but to no avail.

final String api = "http://api.url";
final JSONObject jobj = new JSONObject();
jobj.put("Username", "usr");
jobj.put("Password", "passwd");
jobj.put("grant_type", "password");

final JsonObjectRequest jor = new JsonObjectRequest(

    Request.Method.POST,
    api, jobj,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
            //do other things with the received JSONObject
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
        }
    }) {

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> pars = new HashMap<String, String>();
        pars.put("Content-Type", "application/x-www-form-urlencoded");
        return pars;
    }
};

//add to the request queue
requestqueue.AddToRequestQueue(jor);

I'm getting a 400 bad request with the api call! How can I fix it?

Body:
public void sendUserRegistrationRequest(final UserRequest userRequest, final ResponseListener responseListener) {
    String url = Api.POST_NRNA_REGISTRATION;

    StringRequest userRegistrationRequest = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            JSONObject jsonObject = GsonUtils.getJSONObject(response);
            LoggerUtils.log(TAG, "" + jsonObject.toString());

        }
    }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            LoggerUtils.log(TAG, GsonUtils.toString(error));
            responseListener.onError(GsonUtils.toString(error));
        }
    }) {

        //use this if you have to use form posting : for application/x-www-form-urlencoded;
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return GsonUtils.getHashMap(userRequest);
        }

        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }

    };
    VolleyRequestQueue.getInstance(context).addToRequestQueue(userRegistrationRequest);
}

Use this if you have to send like "application/json"

        @Override
        public byte[] getBody() throws AuthFailureError {
            String jsonData = GsonUtils.toString(userRequest);
            return jsonData.getBytes();
        }

        @Override
        public String getBodyContentType() {
            return "application/json";
        }

public class GsonUtils {

public static String TAG = GsonUtils.class.getSimpleName();

public static <T> T toObject(String data, Class<T> type) {
    Gson gson = new Gson();
    return gson.fromJson(data, type);
}

public static String toString(Object src) {
    if (src == null) {
        return null;
    }
    GsonBuilder builder = new GsonBuilder();
    builder.setPrettyPrinting();
    Gson gson = builder.create();
    return gson.toJson(src);
}

public static <T> T toObject(String data, Type type) {
    try {
        Gson gson = new Gson();
        return gson.fromJson(data, type);
    } catch (Exception ex) {
        Timber.v(ex.getMessage());
        return null;
    }
}

public static JSONObject getJSONObject(Object src) {
    String data = toString(src);
    LoggerUtils.log(TAG, data);
    try {
        return new JSONObject(data);
    } catch (JSONException e) {
        LoggerUtils.log(TAG, e.getMessage());
    }
    return null;
}

public static JSONObject getJSONObject(String data) {
    try {
        return new JSONObject(data);
    } catch (JSONException e) {
        LoggerUtils.log(TAG, e.getMessage());
    }
    return null;
}

public static HashMap<String, String> getHashMap(Object src) {
    String data = toString(src);
    LoggerUtils.log(TAG, data);
    return toObject(data, new TypeToken<HashMap<String, String>>() {
    }.getType());
}

}


问:
Display ASP.Net MSChart / File Issue
I’ve add MSChart to a webpage and I’m also using a Survey page I got from 4GuysFromRolla.  Both work on my development machine but when I move them to my hosting site there are issues.

With MSChart page the chart is not displayed although it’s included the Page Source code:

```<code>src="/ClubInformationTracking/ChartImg.axd?i=chart_3d90c53b0f844807a2491a1d79a636a1_0.png&g=75fecf0f14cf4121b623691d383263aa" alt="" style="height:300px;width:700px;border-width:0px;" />
</code>```

And when I try to open the Survey page I get this:
Parser Error Message: Could not load file or assembly 'sstchur.web.survey' or one of its dependencies. The system cannot find the file specified.

Source Error:

```<code><%@ Register TagPrefix = "sstchur" Namespace = "sstchur.web.survey" Assembly = "sstchur.web.survey" %>
<%@ Page Language = "C#" %>
</code>```

Assembly Load Trace: The following information can be helpful to determine why the assembly sstchur.web.survey could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.

Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

The Hosting site is using Version 4.0 and the dll needed for the survey is in the BIN directory.

When I moved my files to the hosting site I had to change every instance when I referred to a file from:

```<code>“~/FileName”
</code>```

To

```<code>“FileName”
</code>```

I’ve tried all of the “fixes” I could find for the MSChart that involved changes to the web.config file but because of the error messages associated with the Survey page I’m guessing this is the issue.

Any suggestions?

答:
The /Bin folder is in a subdirectory.

Root/public/ClubInformationTracking/BIN

Title: Display ASP.Net MSChart / File Issue

Body:
I’ve add MSChart to a webpage and I’m also using a Survey page I got from 4GuysFromRolla.  Both work on my development machine but when I move them to my hosting site there are issues.

With MSChart page the chart is not displayed although it’s included the Page Source code:

src="/ClubInformationTracking/ChartImg.axd?i=chart_3d90c53b0f844807a2491a1d79a636a1_0.png&g=75fecf0f14cf4121b623691d383263aa" alt="" style="height:300px;width:700px;border-width:0px;" />

And when I try to open the Survey page I get this:
Parser Error Message: Could not load file or assembly 'sstchur.web.survey' or one of its dependencies. The system cannot find the file specified.

Source Error:

<%@ Register TagPrefix = "sstchur" Namespace = "sstchur.web.survey" Assembly = "sstchur.web.survey" %>
<%@ Page Language = "C#" %>

Assembly Load Trace: The following information can be helpful to determine why the assembly sstchur.web.survey could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.

Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

The Hosting site is using Version 4.0 and the dll needed for the survey is in the BIN directory.

When I moved my files to the hosting site I had to change every instance when I referred to a file from:

“~/FileName”

To

“FileName”

I’ve tried all of the “fixes” I could find for the MSChart that involved changes to the web.config file but because of the error messages associated with the Survey page I’m guessing this is the issue.

Any suggestions?


问:
Rename List item when there is the same string multiple time
I have List of names like:

```<code>var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};
</code>```

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

```<code>Allan
Michael
Jhon
Smith
George
Jhon2
</code>```

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

答:
Check this solution:

```<code>public List<string> AddName(IEnumerable<string> list, string name)
{
var suffixSelector = new Regex("^(?<name>[A-Za-z]+)(?<suffix>\\d?)$",
   RegexOptions.Singleline);

var namesMap = list.Select(n => suffixSelector.Match(n))
    .Select(x => new {name = x.Groups["name"].Value, suffix = x.Groups["suffix"].Value})
    .GroupBy(x => x.name)
    .ToDictionary(x => x.Key, x => x.Count());

if (namesMap.ContainsKey(name))
    namesMap[name] = namesMap[name] + 1;

return namesMap.Select(x => x.Key).Concat(
    namesMap.Where(x => x.Value > 1)
        .SelectMany(x => Enumerable.Range(2, x.Value - 1)
        .Select(i => $"{x.Key}{i}"))).ToList();
}
</code>```

It handle case when you already has 'Jhon2' in the list

Body:
I have List of names like:

var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

Allan
Michael
Jhon
Smith
George
Jhon2

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

Body:
Check this solution:

public List<string> AddName(IEnumerable<string> list, string name)
{
var suffixSelector = new Regex("^(?<name>[A-Za-z]+)(?<suffix>\\d?)$",
   RegexOptions.Singleline);

var namesMap = list.Select(n => suffixSelector.Match(n))
    .Select(x => new {name = x.Groups["name"].Value, suffix = x.Groups["suffix"].Value})
    .GroupBy(x => x.name)
    .ToDictionary(x => x.Key, x => x.Count());

if (namesMap.ContainsKey(name))
    namesMap[name] = namesMap[name] + 1;

return namesMap.Select(x => x.Key).Concat(
    namesMap.Where(x => x.Value > 1)
        .SelectMany(x => Enumerable.Range(2, x.Value - 1)
        .Select(i => $"{x.Key}{i}"))).ToList();
}

It handle case when you already has 'Jhon2' in the list


问:
ORA-01031: insufficient privileges as sysdba for sys (even after giving orapwd command)
I have installed an oracle 11g instance on a linux machine. After doing a DB bounce by issuing shutdown immediate and startup. Not able to login as sys/password@sid as sysdba. Even issued a

```<code>orapwd file=orapwsid  password=password entries=30 force=y
</code>```

command, which created a pwd file also.

But still not able to login as sys. I can connect to the DB by scott and other users created but not as a sysdba.
Request you to help me.

答:
I got into same issue but did not know that I have to switch to oracle user to get dba access.

```<code>$ cd ORACLE_HOME/xe/bin
$ ls -la oracle
-rwsr-s--x 1 oracle dba 165700472 Aug 28  2011 oracle
$ su oracle
$ sqlplus sys as sysdba
</code>```

You should be able to login without any issues

Body:
I have installed an oracle 11g instance on a linux machine. After doing a DB bounce by issuing shutdown immediate and startup. Not able to login as sys/password@sid as sysdba. Even issued a

orapwd file=orapwsid  password=password entries=30 force=y

command, which created a pwd file also.

But still not able to login as sys. I can connect to the DB by scott and other users created but not as a sysdba.
Request you to help me.

Body:
I got into same issue but did not know that I have to switch to oracle user to get dba access.

$ cd ORACLE_HOME/xe/bin
$ ls -la oracle
-rwsr-s--x 1 oracle dba 165700472 Aug 28  2011 oracle
$ su oracle
$ sqlplus sys as sysdba

You should be able to login without any issues


问:
Scintilla: How do you find the byte position given a specific character position
Given a specific character index on a line, e.g. 10th character on line 3, is there an easy way to calculate Scintilla's 'position' of that character?

It's straight forward when using ASCII characters but I can't see an easy way to do it when using multi-byte UTF-8 characters, where a single character may take up several byte positions.

答: You should start at the beginning of the string and index into the string however many bytes correspond to the character in the current position, (so that you now index the next character), and keep a count of how many characters you have seen so far. This linear-time indexing is one of the drawbacks of UTF-8. Maybe Scintilla already has a facility to do this.</p>


问:
Powerbuilder 12.5 - run windows command
I'm working on a Powerbuilder 12.5 program, which is a xml to docx converter. It takes xml files and pictures and stacks them in a folder, which needs to be zip-ed as a .docx file.

I can do that with windows cmd command zip -r 'path'.docx *, which generates a word file, which is opened in MS Word. 'path' is where the user saves the file in file explorer and the name of the file - is dynamicaly generated

How could I run this command from Powerbuilder. The problem is, that if I run the run() function it opens the cmd in the preset path, which is c:\Users\ME\

I did try CD 'new_path && zip -r new_path.docx *, however it is not working. it zips the c:\Users\ME folder.

Any better ideas?

答:
You can try to set current directory before, just declare SetCurrentDirectoryA in your external functions :</p>

```<code>FUNCTION LONG SetCurrentDirectoryA(REF STRING curdir) LIBRARY "Kernel32.dll"
</code>```

Title: Powerbuilder 12.5 - run windows command

Body:
You can try to set current directory before, just declare SetCurrentDirectoryA in your external functions :

FUNCTION LONG SetCurrentDirectoryA(REF STRING curdir) LIBRARY "Kernel32.dll"


问:
How to re-write function without generic object injection sink in AngularJS?
I have a function and it works just fine, but codacy inspection says it is bad practice to do so. I understand that it even looks unsafe, but I cannot come up with how to do it another, better, way.

```<code>    function getCount(i) {

        var iCount = iCount || 0;

        for (var item in this.items) {
            for (var level1 in this.items[item]) {
                for (var level2 in this.items[item][level1]) {
                    for (var level3 in this.items[item][level1][level2]) {
                        if (this.items[item][level1][level2][level3] == i) {
                            iCount++;
                        }
                    }
                }
            }
        }
        return iCount;
    }
</code>```

After Icycool's advices I came up with something more acceptable. I tried to use forEach loop, but it didn't work so I decided to use a fori. Though it is not perfect it'll do for now:

```<code>    function getCount(i) {
        var iCount = iCount || 0;
            for (var y = 0; y < this.items["content"].length; y++) {
                if (this.items["content"][y]["custom_object"]["id"] === i) {
                    iCount++;
                }
            }
        return iCount;
    }
</code>```

答:
You can simplify it with a recursive function.</p>

```<code>function getCount(i, items) {
  var count = 0;

  items.forEach(function(item) {
    if (item.isArray) count += getCount(i, item);
    else if (item == i) count++;
  });

  return count;
}
</code>```

Body:
I have a function and it works just fine, but codacy inspection says it is bad practice to do so. I understand that it even looks unsafe, but I cannot come up with how to do it another, better, way.

    function getCount(i) {

        var iCount = iCount || 0;

        for (var item in this.items) {
            for (var level1 in this.items[item]) {
                for (var level2 in this.items[item][level1]) {
                    for (var level3 in this.items[item][level1][level2]) {
                        if (this.items[item][level1][level2][level3] == i) {
                            iCount++;
                        }
                    }
                }
            }
        }
        return iCount;
    }

After Icycool's advices I came up with something more acceptable. I tried to use forEach loop, but it didn't work so I decided to use a fori. Though it is not perfect it'll do for now:

    function getCount(i) {
        var iCount = iCount || 0;
            for (var y = 0; y < this.items["content"].length; y++) {
                if (this.items["content"][y]["custom_object"]["id"] === i) {
                    iCount++;
                }
            }
        return iCount;
    }

Body:
You can simplify it with a recursive function.

function getCount(i, items) {
  var count = 0;

  items.forEach(function(item) {
    if (item.isArray) count += getCount(i, item);
    else if (item == i) count++;
  });

  return count;
}


问:
failed to download the latest files using PHP, ssh2 via SFTP
```<code>#!/usr/bin/php
<?php
  $username = "backup";
  $password = "xxxxxxx";
  $url      = '192.168.1.100';
  // Make our connection
  $connection = ssh2_connect($url);

  // Authenticate
  if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

  // Create our SFTP resource
  if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

  $localDir  = 'file:///home/hhh/Downloads/dbs';
  $remoteDir = '/home/backup/Dropbox/dbs';
  // download all the files
  $dir = ('ssh2.sftp://' . $sftp . $remoteDir);
  $numberOfFiles = 10;
  $pattern = '/\.(aes|AES)$/'; // check only file with these ext.
  $newstamp = 2;
  $newname = "";

  if ($handle = opendir($dir)) {
       while (false !== ($fname = readdir($handle)))  {
         // Eliminate current directory, parent directory
         if (preg_match('/^\.{1,2}$/',$fname)) continue;
         // Eliminate other pages not in pattern
         if (! preg_match($pattern,$fname)) continue;
         $timedat = filemtime("$dir/$fname");
         $fils[$fname] = $timedat;
         if ($timedat > $newstamp) {
            $newstamp = $timedat;
            $newname = $fname;
          }
         }
        }
  closedir ($handle);

  arsort ($fils, SORT_NUMERIC);
  sfor($i = 0; $i < $numberOfFiles ; $i++)
  $fils2 = array_keys($fils);
  $i = 0;

  foreach($fils2 as $s){
    $i++;
    echo "$i " . $s . "<br>\n";
    if($i == $numberOfFiles )break;
  }
  // $newstamp is the time for the latest file
  // $newname is the name of the latest file
  // print last mod.file - format date as you like

$rttp = ssh2_scp_recv($connection, "$remoteDir/$newname", "$localDir/$newname")

?>
</code>```

I have been trying to download the latest FILES from a directory using sftp. I have only managed to download ONE file instead to 10. I also was able to tweak it to download all the files but that is not i what I was after.

I would like to make it work so that I can be able to download a certain X number of files.

答:
```<code>#!/usr/bin/php

<?php
$username = "user";
$password = "password";
$url      = "host ip";
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

//$dir
$localDir  = "/path/to/localdir/".date('Y-m-d');
exec("mkdir -p '$localDir'");
echo $localDir;

$remoteDir = "/path/to/remotedir";
 // download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        if (substr($file, 0, 11)== date('d-M-Y')) {

            //date('d-M-Y', strtotime('yesterday') #for retriving the previous day
            # code...
             // echo $file;
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
 ?>
</code>```

This downloads the latest files from a remote directory and creates a new local directory by date where it downloads the new remote files

Body:
#!/usr/bin/php
<?php
  $username = "backup";
  $password = "xxxxxxx";
  $url      = '192.168.1.100';
  // Make our connection
  $connection = ssh2_connect($url);

  // Authenticate
  if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

  // Create our SFTP resource
  if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

  $localDir  = 'file:///home/hhh/Downloads/dbs';
  $remoteDir = '/home/backup/Dropbox/dbs';
  // download all the files
  $dir = ('ssh2.sftp://' . $sftp . $remoteDir);
  $numberOfFiles = 10;
  $pattern = '/\.(aes|AES)$/'; // check only file with these ext.
  $newstamp = 2;
  $newname = "";

  if ($handle = opendir($dir)) {
       while (false !== ($fname = readdir($handle)))  {
         // Eliminate current directory, parent directory
         if (preg_match('/^\.{1,2}$/',$fname)) continue;
         // Eliminate other pages not in pattern
         if (! preg_match($pattern,$fname)) continue;
         $timedat = filemtime("$dir/$fname");
         $fils[$fname] = $timedat;
         if ($timedat > $newstamp) {
            $newstamp = $timedat;
            $newname = $fname;
          }
         }
        }
  closedir ($handle);

  arsort ($fils, SORT_NUMERIC);
  sfor($i = 0; $i < $numberOfFiles ; $i++)
  $fils2 = array_keys($fils);
  $i = 0;

  foreach($fils2 as $s){
    $i++;
    echo "$i " . $s . "
\n";
    if($i == $numberOfFiles )break;
  }
  // $newstamp is the time for the latest file
  // $newname is the name of the latest file
  // print last mod.file - format date as you like

$rttp = ssh2_scp_recv($connection, "$remoteDir/$newname", "$localDir/$newname")

?>

I have been trying to download the latest FILES from a directory using sftp. I have only managed to download ONE file instead to 10. I also was able to tweak it to download all the files but that is not i what I was after.

I would like to make it work so that I can be able to download a certain X number of files.

Body:
#!/usr/bin/php

<?php
$username = "user";
$password = "password";
$url      = "host ip";
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

//$dir
$localDir  = "/path/to/localdir/".date('Y-m-d');
exec("mkdir -p '$localDir'");
echo $localDir;

$remoteDir = "/path/to/remotedir";
 // download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        if (substr($file, 0, 11)== date('d-M-Y')) {

            //date('d-M-Y', strtotime('yesterday') #for retriving the previous day
            # code...
             // echo $file;
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
 ?>

This downloads the latest files from a remote directory and creates a new local directory by date where it downloads the new remote files


问:
Previewing Mailers on non-development tiers
I have several mailer previews under spec/mailer/previews. On development I can view all the previews under /rails/mailers/. However by default this functionality does not exist on other environments.

I wanted to enable it on the staging environment and took a queue from this post here.

I made the following changes -

config/routes.rb

```<code># Add the routes manually
if Rails.env.staging?
  get "/rails/mailers" => "rails/mailers#index"
  get "/rails/mailers/*path" => "rails/mailers#preview"
end
</code>```

config/environments/staging.rb

```<code>Rails.application.configure do
  # Define the mailer preview path
  config.action_mailer.preview_path = "spec/mailers/previews"

  # Specifically add that path and all files under it to the autoload paths
  config.autoload_paths = Dir["#{config.root}/#{config.action_mailer.preview_path}/**"]
end

class ::Rails::MailersController
  include Rails.application.routes.url_helpers

  # Override the method just for this controller so `MailersController` thinks
  # all requests are local.
  def local_request?
    true
  end
end
</code>```

However on staging, I'm getting the following error when trying to load the /rails/mailers page -

```<code>LoadError (No such file to load -- spec/mailers/previews/admin_mailer_preview):
</code>```

The odd thing is... that file definitely exists. And when I check the autoload paths on staging that file is definitely in the Array/list.

Any thoughts on what might be happening here, or how else I should go about exposing that endpoint?

Thanks!

答:
Having consider_all_requests_local = true or patching local_request? can be security issue. Here is solution we use, it uses authentication to allow only admins to access previews:

# in any enviroment
config.action_mailer.show_previews = true

# in initializers/mailer_previews.rb
# (use your own authentication methods)

# Allow admins to see previews if show_previews enabled.
# It does not affect dev env, as this setting is nil there.
if Rails.application.config.action_mailer.show_previews
  Rails::MailersController.prepend_before_action do
    authenticate_user!
    head :forbidden unless current_user.admin?
  end
end

# If you use rspec-rails, it makes rails use spec/mailers/previews
# as previews path. Most likely you don't have rspec-rails on
# staging/production, so need to add this to application.rb:
#
# Make previews available in environments without rspec-rails.
config.action_mailer.preview_path = Rails.root.join('spec', 'mailers', 'previews')

# Bonus: specs. Update with your `sign_in` implementation
# and have `config.action_mailer.show_previews = true` in test.rb
RSpec.describe Rails::MailersController do
  shared_examples 'visible to admin only' do
    it { should redirect_to new_user_session_path }

    context 'for signed in user' do
      sign_in { create(:user) }
      it { should be_forbidden }

      context 'admin' do
        let(:current_user) { create(:user, admin: true) }
        it { should be_ok }
      end
    end
  end

  describe '#index' do
    subject { get('/rails/mailers') && response }
    include_examples 'visible to admin only'
  end

  describe '#preview' do
    subject { get('/rails/mailers/devise/mailer') && response }
    include_examples 'visible to admin only'
  end
end
```

Body:
I have several mailer previews under spec/mailer/previews. On development I can view all the previews under /rails/mailers/. However by default this functionality does not exist on other environments.

I wanted to enable it on the staging environment and took a queue from this post here.

I made the following changes -

config/routes.rb

# Add the routes manually
if Rails.env.staging?
  get "/rails/mailers" => "rails/mailers#index"
  get "/rails/mailers/*path" => "rails/mailers#preview"
end

config/environments/staging.rb

Rails.application.configure do
  # Define the mailer preview path
  config.action_mailer.preview_path = "spec/mailers/previews"

  # Specifically add that path and all files under it to the autoload paths
  config.autoload_paths = Dir["#{config.root}/#{config.action_mailer.preview_path}/**"]
end

class ::Rails::MailersController
  include Rails.application.routes.url_helpers

  # Override the method just for this controller so `MailersController` thinks
  # all requests are local.
  def local_request?
    true
  end
end

However on staging, I'm getting the following error when trying to load the /rails/mailers page -

LoadError (No such file to load -- spec/mailers/previews/admin_mailer_preview):

The odd thing is... that file definitely exists. And when I check the autoload paths on staging that file is definitely in the Array/list.

Any thoughts on what might be happening here, or how else I should go about exposing that endpoint?

Thanks!


问:
How can I merge array's items?
I have an array like this:

```<code>$arr = array ( [0] => array("red","green"),
               [1] => array("blue","yellow")
             );
</code>```

And this is expected result:

```<code>Array ( [0] => red [1] => green [2] => blue [3] => yellow )
</code>```

See? I want to merge all items of $arr (which are also array themselves). How can I do that?

I can do a loop on it and then use array_merge() every time like this:

```<code>$res = [];
foreach ( $arr as $item ) {
    $res = array_merge($res, $item);
}
</code>```

It works as well. But I guess I can write it better. Any idea?

答:
You can do trick with call_user_func_array:

```<code>$result = call_user_func_array('array_merge', $arr);
</code>```

This trick is possible, because array_merge accept dynamic arguments count.

Title: How can I merge array's items?

Body:
I have an array like this:

$arr = array ( [0] => array("red","green"),
               [1] => array("blue","yellow")
             );

And this is expected result:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

See? I want to merge all items of $arr (which are also array themselves). How can I do that?

I can do a loop on it and then use array_merge() every time like this:

$res = [];
foreach ( $arr as $item ) {
    $res = array_merge($res, $item);
}

It works as well. But I guess I can write it better. Any idea?

Body:
You can do trick with call_user_func_array:

$result = call_user_func_array('array_merge', $arr);

This trick is possible, because array_merge accept dynamic arguments count.


问:
Resizing QTableView section with custom editor
I have an application with a QTableView and a model derived from QAbstractItemModel: the first column of the table contains a text (a label for each row), while the second column shows a value that can be selected using a QComboBox created from a custom item delegate. The content of the table may change dynamically (number of rows, language...).

I'd like to resize columns so the second one fits the content and the first one stretches occupying the remaining space.

My first attempt was:

```<code>tblData->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
tblData->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
</code>```

Result:

The problem is that when the QComboBox is selected it doesn't fit the section and it is clipped:

I've managed to solve this issue by manually increasing the width:

```<code>tblData->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
tblData->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
tblData->resizeColumnToContents(1);
tblData->horizontalHeader()->resizeSection(1, tblData->horizontalHeader()->sectionSize(1) + 40);
</code>```

Now the issue here is that by using such constant (40 in this case) the width of the section will vary depending on values displayed rather than in all the possible values (if the largest ones are already displayed vs if only the shortest). Also, that constant will be dependant to the style used, since it is also related to the space consumed by the QComboBox.

I've thought about using the Qt::SizeHintRole to manually compute the section width, but it is completely ignored. Even if it was, I cannot compute the actual width of the text (using QFontMetrics::width) because I don't have any font information in the model.

Another approach I've tried is to set the adjust size policy of the QComboBox in the QItemDelegate::createEditor method:

```<code>QWidget* myItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const {
  auto comboBox = new QComboBox(parent);
  comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
  // ...
}
</code>```

But now the combo boxes are either clipped or shortened.

How can I solve set the section size based on the complete range of content instead of just visible data?

I'm self-answering the question with the best approach I've found so far, and the one I'm using in the project right now, but I'm not convinced with it (I detail reasons on the answer) so I'd like to know the correct way to do it. Thanks!

答: The sizeHint in the delegate is the right way to go but, instead of creating an editor, fill a QStyleOptionComboBox struct and use qApp->style()->sizeFromContents(QStyle::CT_ComboBox, &opt, sh, nullptr);, where sh is the size of the internal string. You can use QFontMetrics to calculate that or just call the base class QStyledItemDelegate::sizeHint(...).

Body:
I have an application with a QTableView and a model derived from QAbstractItemModel: the first column of the table contains a text (a label for each row), while the second column shows a value that can be selected using a QComboBox created from a custom item delegate. The content of the table may change dynamically (number of rows, language...).

I'd like to resize columns so the second one fits the content and the first one stretches occupying the remaining space.

My first attempt was:

tblData->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
tblData->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);

Result:

The problem is that when the QComboBox is selected it doesn't fit the section and it is clipped:

I've managed to solve this issue by manually increasing the width:

tblData->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
tblData->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
tblData->resizeColumnToContents(1);
tblData->horizontalHeader()->resizeSection(1, tblData->horizontalHeader()->sectionSize(1) + 40);

Now the issue here is that by using such constant (40 in this case) the width of the section will vary depending on values displayed rather than in all the possible values (if the largest ones are already displayed vs if only the shortest). Also, that constant will be dependant to the style used, since it is also related to the space consumed by the QComboBox.

I've thought about using the Qt::SizeHintRole to manually compute the section width, but it is completely ignored. Even if it was, I cannot compute the actual width of the text (using QFontMetrics::width) because I don't have any font information in the model.

Another approach I've tried is to set the adjust size policy of the QComboBox in the QItemDelegate::createEditor method:

QWidget* myItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const {
  auto comboBox = new QComboBox(parent);
  comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
  // ...
}

But now the combo boxes are either clipped or shortened.

How can I solve set the section size based on the complete range of content instead of just visible data?

I'm self-answering the question with the best approach I've found so far, and the one I'm using in the project right now, but I'm not convinced with it (I detail reasons on the answer) so I'd like to know the correct way to do it. Thanks!


问:
Adding a package with pre-release dependencies
Using LINQPad I've added a private feed to Visual Studio Team Services. However one of my packages requires a pre-release package: Quartz.Net in my case. I've ticked Include Prerelease but I think it's getting confused and trying to load the package from my private feed rather than NuGet.

I've tried to work around the issue by loading the package into the local package cache. LINQPad doesn't seem to consider this. Other than uploading these packages into my own private feed, what options do I have? I'm not going to alter my own packages to get around LINQPad's shortcomings.

Note: I've setup the VSTS feed according this question.

Here is what my NuGet feeds look like in LINQPad

答:
Changing the package to pre-release fixes this issue, and add the pre-release packages dependencies to my own feed.

Now LINQPad attempts to add the package. Mind you I now get another error;

"There are no usable .NET assemblies in package
  'MyPackage.Common(Prerelease)'

That's down to NET Standard & NET47 support.


问:
Gitlab run docker inside docker
I'm using gitlab 9.3.3-ce.0 and gitlab runner with docker executor. I want to build images inside this docker-executor. How to do it?

I'm trying to connect to outer docker using this section inside /etc/gitlab-runner/config.toml:

```<code>[runners.docker]
    tls_verify = false
    image = "java:8"
    privileged = true
    disable_cache = false
    volumes = ["/var/images", "/var/lib/docker:/var/lib/docker",
               "/var/run/docker.sock:/var/run/docker.sock",
               "/usr/bin/docker:/usr/bin/docker"]
    shm_size = 0
</code>```

But when I try to execute inside docker docker info I get:

```<code>/usr/bin/docker: No such file or directory
</code>```

But it should exist:

```<code>$ which docker
/usr/bin/docker
</code>```

答:
You need to use the docker in docker service:

```<code>image: docker:latest

# When using dind, it's wise to use the overlayfs driver for
# improved performance. - THIS DOES NOT ALWAYS WORK!
variables:
  DOCKER_DRIVER: overlay

services:
- docker:dind

before_script:
- docker info

build:
  stage: build
  script:
  - docker build -t my-docker-image .
  - docker run my-docker-image /script/to/run/tests
</code>```

see https://docs.gitlab.com/ce/ci/docker/using_docker_build.html#use-docker-in-docker-executor

Title: Gitlab run docker inside docker

Body:
I'm using gitlab 9.3.3-ce.0 and gitlab runner with docker executor. I want to build images inside this docker-executor. How to do it?

I'm trying to connect to outer docker using this section inside /etc/gitlab-runner/config.toml:

[runners.docker]
    tls_verify = false
    image = "java:8"
    privileged = true
    disable_cache = false
    volumes = ["/var/images", "/var/lib/docker:/var/lib/docker",
               "/var/run/docker.sock:/var/run/docker.sock",
               "/usr/bin/docker:/usr/bin/docker"]
    shm_size = 0

But when I try to execute inside docker docker info I get:

/usr/bin/docker: No such file or directory

But it should exist:

$ which docker
/usr/bin/docker

Body:
You need to use the docker in docker service:

image: docker:latest

# When using dind, it's wise to use the overlayfs driver for
# improved performance. - THIS DOES NOT ALWAYS WORK!
variables:
  DOCKER_DRIVER: overlay

services:
- docker:dind

before_script:
- docker info

build:
  stage: build
  script:
  - docker build -t my-docker-image .
  - docker run my-docker-image /script/to/run/tests

see https://docs.gitlab.com/ce/ci/docker/using_docker_build.html#use-docker-in-docker-executor


问:
Android studio 2.3 always hangs out
I'm using Android Studio 2.3 within gradle 2.3.3. I face a weird problem and being stuck for a week. It hangs out very often when I type some lines of code, right before it shows the auto complete box.
Or if I didn't type anything but use Command-clickto find implementation of a variable or method, it show the dialog says Resolving Reference and hangs there.
Sometime, if I switch to another application for awhile and switch back to view Android Studio, it hangs as well.

I already tried many different methods but didn't help, including:

Remove Android studio completely follow this answer then download and install again.

Go to menu File > Invalidate Cache/Restart...

Remove JDK and install again. I'm using JDK jdk-8u131-macosx-x64 downloaded from here

Delete all build folders and Rebuild Project

Rollback to my project's stable source code that I built successfully in the past.

Try to use Android Studio 3.0 Preview

Downgrade or upgrade Gradle Plugin

Download and replace the JDK bundle with Android studio follow this thread

All above methods didn't help to keep my Android Studio stability.

I am using Macbook with 16Gb of RAM, core i7, MacOS Sierra 10.12.5 and I don't think the hang is regarding to my laptop specification,

So I report my situation here and hope someone can help to give me new recommendation. Any idea or suggestion are appreciated.

Update: I check the logs of Android Studio under ~/Library/Logs/Android Studio2.3/ and see some exception log files. Below is the latest one:

```<code>2017-07-04 19:14:35,633 [1233357]   INFO - roid.sdk.MessageBuildingSdkLog - Exception from KotlinOutputParser
2017-07-04 19:14:35,633 [1233357]   INFO - roid.sdk.MessageBuildingSdkLog - com.android.ide.common.blame.Message.<init>(com.android.ide.common.blame.Message$Kind, java.lang.String, java.lang.String, com.google.common.collect.ImmutableList)
java.lang.NoSuchMethodException: com.android.ide.common.blame.Message.<init>(com.android.ide.common.blame.Message$Kind, java.lang.String, java.lang.String, com.google.common.collect.ImmutableList)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper$simpleMessageConstructor$2.invoke(KotlinOutputParserHelper.kt:171)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper$simpleMessageConstructor$2.invoke(KotlinOutputParserHelper.kt:143)
    at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:130)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper.getSimpleMessageConstructor(KotlinOutputParserHelper.kt)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper.createNewMessage(KotlinOutputParserHelper.kt:272)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper.createMessage(KotlinOutputParserHelper.kt:250)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper.createMessage$default(KotlinOutputParserHelper.kt:244)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelperKt.parse(KotlinOutputParserHelper.kt:41)
    at org.jetbrains.kotlin.android.KotlinOutputParser.parse(KotlinOutputParser.java:28)
    at com.android.ide.common.blame.parser.ToolOutputParser.parseToolOutput(ToolOutputParser.java:86)
    at com.android.tools.idea.gradle.output.parser.BuildOutputParser.parseGradleOutput(BuildOutputParser.java:43)
    at com.android.tools.idea.gradle.project.build.invoker.GradleTasksExecutor$GradleTasksExecutorImpl.lambda$collectMessages$5(GradleTasksExecutor.java:516)
    at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:307)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Update 2 Sometime Android Studio show a dialog for error report, with this message inside:

```<code>Cannot add jps/kotlin-jps-plugin.jar from plugin 'Kotlin' to external compiler classpath: home directory of plugin not found
</code>```

答:
Finally I can build and continue coding without crash ( at least after 1 hour I don't get crash).
For the Android Studio 2.3, I select File > Power Save Mode so it won't hang out any more. The worse thing is I can't use intelligent auto complete or auto-build at background.

Then, I install again Android studio 3.0 Preview Canary 5, using Gradle tool 3.0.0 alpha5. Fix all compile warnings (such as replace deprecated gradle functions by new ones), update all libraries to latest version,... It works!

Now I got 2 versions of Android Studio running concurrently. The old one running with Power Save Mode, the new one running with normal mode.

Title: Android studio 2.3 always hangs out

Body:
I'm using Android Studio 2.3 within gradle 2.3.3. I face a weird problem and being stuck for a week. It hangs out very often when I type some lines of code, right before it shows the auto complete box.
Or if I didn't type anything but use Command-clickto find implementation of a variable or method, it show the dialog says Resolving Reference and hangs there.
Sometime, if I switch to another application for awhile and switch back to view Android Studio, it hangs as well.

I already tried many different methods but didn't help, including:

Remove Android studio completely follow this answer then download and install again.

Go to menu File > Invalidate Cache/Restart...

Remove JDK and install again. I'm using JDK jdk-8u131-macosx-x64 downloaded from here

Delete all build folders and Rebuild Project

Rollback to my project's stable source code that I built successfully in the past.

Try to use Android Studio 3.0 Preview

Downgrade or upgrade Gradle Plugin

Download and replace the JDK bundle with Android studio follow this thread

All above methods didn't help to keep my Android Studio stability.

I am using Macbook with 16Gb of RAM, core i7, MacOS Sierra 10.12.5 and I don't think the hang is regarding to my laptop specification,

So I report my situation here and hope someone can help to give me new recommendation. Any idea or suggestion are appreciated.

Update: I check the logs of Android Studio under ~/Library/Logs/Android Studio2.3/ and see some exception log files. Below is the latest one:

2017-07-04 19:14:35,633 [1233357]   INFO - roid.sdk.MessageBuildingSdkLog - Exception from KotlinOutputParser
2017-07-04 19:14:35,633 [1233357]   INFO - roid.sdk.MessageBuildingSdkLog - com.android.ide.common.blame.Message.<init>(com.android.ide.common.blame.Message$Kind, java.lang.String, java.lang.String, com.google.common.collect.ImmutableList)
java.lang.NoSuchMethodException: com.android.ide.common.blame.Message.<init>(com.android.ide.common.blame.Message$Kind, java.lang.String, java.lang.String, com.google.common.collect.ImmutableList)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper$simpleMessageConstructor$2.invoke(KotlinOutputParserHelper.kt:171)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper$simpleMessageConstructor$2.invoke(KotlinOutputParserHelper.kt:143)
    at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:130)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper.getSimpleMessageConstructor(KotlinOutputParserHelper.kt)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper.createNewMessage(KotlinOutputParserHelper.kt:272)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper.createMessage(KotlinOutputParserHelper.kt:250)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelper.createMessage$default(KotlinOutputParserHelper.kt:244)
    at org.jetbrains.kotlin.android.KotlinOutputParserHelperKt.parse(KotlinOutputParserHelper.kt:41)
    at org.jetbrains.kotlin.android.KotlinOutputParser.parse(KotlinOutputParser.java:28)
    at com.android.ide.common.blame.parser.ToolOutputParser.parseToolOutput(ToolOutputParser.java:86)
    at com.android.tools.idea.gradle.output.parser.BuildOutputParser.parseGradleOutput(BuildOutputParser.java:43)
    at com.android.tools.idea.gradle.project.build.invoker.GradleTasksExecutor$GradleTasksExecutorImpl.lambda$collectMessages$5(GradleTasksExecutor.java:516)
    at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:307)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Update 2 Sometime Android Studio show a dialog for error report, with this message inside:

Cannot add jps/kotlin-jps-plugin.jar from plugin 'Kotlin' to external compiler classpath: home directory of plugin not found


问:
unsupported pseudo: in-viewport
I'm following this guide to detect when my video element comes in viewport then do "x", but keep getting the title error. Not sure if because Im using wordpress with gulp and piling.js

My page uses Piling and I have a video section, when I scroll to that "stack", I want the video to start play but it starts to play on page load.

```<code>// inside document.ready()

 $('video').each(function(){
    if ($(this).is(":in-viewport")) {
        $(this)[0].play();
    } else {
        $(this)[0].pause();
    }
})
</code>```

Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: in-viewport

```<code><div id='<ID-CHANGES-INSIDE-LOOP>' class='image-block'>
  <video autoplay>
    <source class='video' src='movie.mp4' type='video/mp4'>
  </video>
</div>
</code>```

Is using Piling making this difficult to work?

答:
the pseudo property :in-viewport needs to be attached by a plugin (which I cannot find anymore) -

maybe try the try the OnScreen Basic Visibility Detection instead; it does about the same.

Title: unsupported pseudo: in-viewport

Body:
I'm following this guide to detect when my video element comes in viewport then do "x", but keep getting the title error. Not sure if because Im using wordpress with gulp and piling.js

My page uses Piling and I have a video section, when I scroll to that "stack", I want the video to start play but it starts to play on page load.

// inside document.ready()

 $('video').each(function(){
    if ($(this).is(":in-viewport")) {
        $(this)[0].play();
    } else {
        $(this)[0].pause();
    }
})

Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: in-viewport

<div id='<ID-CHANGES-INSIDE-LOOP>' class='image-block'>
  <video autoplay>
    <source class='video' src='movie.mp4' type='video/mp4'>
  </video>

Is using Piling making this difficult to work?


问:
Need help to draw control-flow graph with GLEE and C#
I am trying to draw a control-flow graph(CFG) from source code using the GLEE graph library and C# language. Problem is, I am new to GLEE. I need a tutorial or sample programs/projects to help me get started quickly with GLEE. The source for which I need to draw a CFG has the following structure:

```<code>begin myProcedure
  statement 1;
  statement 2;
  if(condition) then
    statement 3;
  else
    statement 4;
  end if
end myProcedure
</code>```

Any ideas?

答:
In order to draw a graph using glee is a quite easy task once you have parsed your source code, for making graph using glee you can follow this simple tutorial :

http://chalaki.com/how-to-program-msagl-glee-to-create-hierarchical-graph-layouts/519/

Body:
I am trying to draw a control-flow graph(CFG) from source code using the GLEE graph library and C# language. Problem is, I am new to GLEE. I need a tutorial or sample programs/projects to help me get started quickly with GLEE. The source for which I need to draw a CFG has the following structure:

begin myProcedure
  statement 1;
  statement 2;
  if(condition) then
    statement 3;
  else
    statement 4;
  end if
end myProcedure

Any ideas?


问:
fopen does not return
I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

```<code>printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);
</code>```

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance,
Souvik

答:
I notice you don't close the file if you open it successfully.

Is it possible you that you have run it before and killed it, and now you have a process out there which has the file open, and locked?

If so, then maybe fopen is waiting for the lock to be released.

Title: fopen does not return

Body:
I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance,
Souvik


问:
Show NULL values in result table when SQL query is executed
I have a script that executes SQL files and prints the result in the console (for now). The problem is that I need to make difference between the NULL values and the empty strings that are returned in the Result table.

This is what the query returns in the Management Studio:

You can see that it contains strings, empty strings and NULL values.

This is what the query returns in the PowerShell IDE:

There is no difference between NULL and empty.

Also the last few columns are cut and only the first 10 are printed.

How can I fix that?

Here is my code:

```<code>$ConnectionString = "Data Source=...;Initial Catalog=...;User Id=..;Password=.."
$FolderToSQLFiles = "C:\SQLFilesTestFolder";

#function that executes sql queries and return result tables
function GetSQLresults {
    Param(
        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True, Position=0)] $SQLqueryText, # sql query text returned from file
    )

    $objConnection = New-Object System.Data.SqlClient.SqlConnection;
    $objConnection.ConnectionString = $ConnectionString

    $objConnection.Open();

    $ObjCmd = New-Object System.Data.SqlClient.SqlCommand;
    $ObjCmd.CommandText = $SQLqueryText;
    $ObjCmd.Connection = $objConnection;
    $ObjCmd.CommandTimeout = 0;

    $objAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
    $objAdapter.SelectCommand = $ObjCmd;
    $objDataSet = New-Object System.Data.DataSet;

    $objAdapter.Fill($objDataSet);

    $ResultSets = @(); #adding all result tables to array

    for ($i=0; $i -lt $objDataSet.Tables.Count; $i++) {
        $tmpResultTable = $objDataSet.Tables[$i] | Format-Table | Out-String;
        $ResultSets += $tmpResultTable;
    }

    return $ResultSets

    $query = $null;

    $objDataSet = $null;

    $objConnection.Close();
    $objConnection = $null;
}

Get-ChildItem $FolderToSQLFiles -Filter *.sql | Foreach-Object {
    $tmpSQLfilePath = $_.FullName #getting the sql file full path
    $tmpSQLfileContent = (Get-Content $tmpSQLfilePath) -join "`n"  #getting the content of the sql

    GetSQLresults -SQLqueryText $tmpSQLfileContent  #passing the sql query to the executing funciton
}
</code>```

答:
PowerShell automatically transforms null values into empty strings for output. You need to check the type of the values in your field and adjust the output/value accordingly.

Something like this should work:

```<code>GetSQLresults ... |
    Select-Object -Property *,@{n='Col006',e={
        if ($_.Col006 -is [DBNull]) {'NULL'} else {$_.Col006}
    }} -Exclude Col006
</code>```

Body:
I have a script that executes SQL files and prints the result in the console (for now). The problem is that I need to make difference between the NULL values and the empty strings that are returned in the Result table.

This is what the query returns in the Management Studio:

You can see that it contains strings, empty strings and NULL values.

This is what the query returns in the PowerShell IDE:

There is no difference between NULL and empty.

Also the last few columns are cut and only the first 10 are printed.

How can I fix that?

Here is my code:

$ConnectionString = "Data Source=...;Initial Catalog=...;User Id=..;Password=.."
$FolderToSQLFiles = "C:\SQLFilesTestFolder";

#function that executes sql queries and return result tables
function GetSQLresults {
    Param(
        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True, Position=0)] $SQLqueryText, # sql query text returned from file
    )

    $objConnection = New-Object System.Data.SqlClient.SqlConnection;
    $objConnection.ConnectionString = $ConnectionString

    $objConnection.Open();

    $ObjCmd = New-Object System.Data.SqlClient.SqlCommand;
    $ObjCmd.CommandText = $SQLqueryText;
    $ObjCmd.Connection = $objConnection;
    $ObjCmd.CommandTimeout = 0;

    $objAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
    $objAdapter.SelectCommand = $ObjCmd;
    $objDataSet = New-Object System.Data.DataSet;

    $objAdapter.Fill($objDataSet);

    $ResultSets = @(); #adding all result tables to array

    for ($i=0; $i -lt $objDataSet.Tables.Count; $i++) {
        $tmpResultTable = $objDataSet.Tables[$i] | Format-Table | Out-String;
        $ResultSets += $tmpResultTable;
    }

    return $ResultSets

    $query = $null;

    $objDataSet = $null;

    $objConnection.Close();
    $objConnection = $null;
}

Get-ChildItem $FolderToSQLFiles -Filter *.sql | Foreach-Object {
    $tmpSQLfilePath = $_.FullName #getting the sql file full path
    $tmpSQLfileContent = (Get-Content $tmpSQLfilePath) -join "`n"  #getting the content of the sql

    GetSQLresults -SQLqueryText $tmpSQLfileContent  #passing the sql query to the executing funciton
}

Body:
PowerShell automatically transforms null values into empty strings for output. You need to check the type of the values in your field and adjust the output/value accordingly.

Something like this should work:

GetSQLresults ... |
    Select-Object -Property *,@{n='Col006',e={
        if ($_.Col006 -is [DBNull]) {'NULL'} else {$_.Col006}
    }} -Exclude Col006


问:
Travelport uAPI ticketing
I'm getting following error when I request to ticket

"Host error during ticket issue. INVALID ND LINKAGE"

Request I've sent is

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
    <air:AirTicketingReq xmlns:air="http://www.travelport.com/schema/air_v35_0" AuthorizedBy="Travelport" BulkTicket="false" ReturnInfoOnFail="true" TargetBranch="P7038833" TraceId="trace">
        <com:BillingPointOfSaleInfo xmlns:com="http://www.travelport.com/schema/common_v35_0" OriginApplication="UAPI"/>
        <air:AirReservationLocatorCode>K8H3JM</air:AirReservationLocatorCode>
    </air:AirTicketingReq>
</soapenv:Body>
</code>```

Am I supposed to include any additional information?

答:
You need to contact the account manager: "Please contact your Travelport Account Manager to ask for trial credentials with ticketing provisioned on it."

https://github.com/Travelport/travelport-uapi-tutorial/issues/118

Title: Travelport uAPI ticketing

Body:
I'm getting following error when I request to ticket

"Host error during ticket issue. INVALID ND LINKAGE"

Request I've sent is

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
    <air:AirTicketingReq xmlns:air="http://www.travelport.com/schema/air_v35_0" AuthorizedBy="Travelport" BulkTicket="false" ReturnInfoOnFail="true" TargetBranch="P7038833" TraceId="trace">
        <com:BillingPointOfSaleInfo xmlns:com="http://www.travelport.com/schema/common_v35_0" OriginApplication="UAPI"/>
        <air:AirReservationLocatorCode>K8H3JM</air:AirReservationLocatorCode>
    </air:AirTicketingReq>
</soapenv:Body>

Am I supposed to include any additional information?


问:
how to take error logs in postgresql
In postgresql am change following settings for postgresql.conf file.But,logging file is display empty.I want to log all error returned from postgresql.</p>

```<code>log_destination = 'stderr,csvlog,syslog'

logging_collector = on

log_directory = 'pg_log'

log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'

syslog_facility = 'LOCAL7'

syslog_ident = 'postgres' log_min_duration_statement = 0

log_statement = 'all'
</code>```

答:
Set the following:

```<code>log_min_error_statement = error
log_min_messages = error
</code>```

Don't forget to run pg_ctl reload after changing postgresql.conf.

Title: how to take error logs in postgresql

Body:
In postgresql am change following settings for postgresql.conf file.But,logging file is display empty.I want to log all error returned from postgresql.

log_destination = 'stderr,csvlog,syslog'

logging_collector = on

log_directory = 'pg_log'

log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'

syslog_facility = 'LOCAL7'

syslog_ident = 'postgres' log_min_duration_statement = 0

log_statement = 'all'

Body:
Set the following:

log_min_error_statement = error
log_min_messages = error

Don't forget to run pg_ctl reload after changing postgresql.conf.


Title: replace parts of variable string in dataframe

Body:
I have data frame:

     SINGLE_MEM                     crd
1          5        -97.75514500005232 30.263874000727306
2          8        -97.81095799930782 30.234157000528484)))
3          3        ((-97.68044500036247 30.267636999839592
4          2        -97.71808637589912 30.1848525102668))
5         10        -97.76847799967814 30.432537999903005
6          6        -97.6937453403672  30.46382579769979

In crd column i have coordinates in character. I need to replace all '( )'
on a gaps. I replace ')', '))', ')))' by

df$crd <- gsub(")))", "", df$crd)
df$crd <- gsub("))", "", df$crd)
df$crd <- gsub(")", "", df$crd)

but i cant replace a '(', '((', '(((' because i have an error: Error in gsub ("((", "", df $ crd): Incorrect regular expression '((', reason 'Missing') ''

Body:
You can use

gsub("[()]+", "", df$crd)