问:
app-debuk.apk stopped working
I'm new to Android programming and it's my first project with Gradle. In the past I used Maven for Java. So I made an application with Android studio and if I click on Run and select my phone it'll build and install the apk to my phone then opens itself and works fine.

So I would like to share my progress with one of my friend, so I clicked on Make Project, and it generated an app-debug.apk in /app/build/outputs/apk/app-debug.apk but if I try that to install my Application Force Close itself after launch with a text: "Unfortunately the app stopped working".

Here is my build.gradle (Module:app):

and my build.gradle (Project: Autosiskola):

the error code:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.androidports.autosiskola/com.androidports.autosiskola.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.androidports.autosiskola.MainActivity" on path: DexPathList[[zip file "/data/app/com.androidports.autosiskola-1/base.apk"],nativeLibraryDirectories=[/data/app/com.androidports.autosiskola-1/lib/arm64, /vendor/lib64, /system/lib64]]

My Main Activity:

```<code>    package com.androidports.autosiskola;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import android.widget.Toast;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MainActivity extends AppCompatActivity {

EditText username, password;
Button login;
ProgressBar progressBar;

Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    username = (EditText) findViewById(R.id.txtUsername);
    password = (EditText) findViewById(R.id.txtPassword);

    login = (Button) findViewById(R.id.btnLogin);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    progressBar.setVisibility(View.GONE);

    conn = DBConnect.Connector();

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (username.toString().trim().isEmpty() && password.toString().isEmpty()) {
                Toast.makeText(MainActivity.this, "Nincs felhasználónév / jelszó megadva!", Toast.LENGTH_SHORT).show();
            } else {
                switch (v.getId()) {
                    case R.id.btnLogin:
                        new doMySQL().execute();
                        break;
                }
            }
        }
    });
}

public class doMySQL extends AsyncTask<Void, Void, String> {

    final String uname = username.getText().toString();
    final String passwd = password.getText().toString();
    String getUsername = null;
    String getPassword = null;
    String getPermission = null;
    String resValue = "undone";
    int exists = 0;

    protected void onPreExecute() {
        progressBar.setVisibility(View.VISIBLE);
    }

    protected String doInBackground(Void... params) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        conn = DBConnect.Connector();

        try {
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.next()) {
                getUsername = rs.getString(1);
            }
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                resValue = "undone";
            }

            pst = conn.prepareStatement("SELECT password FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.next()) {
                getPassword = rs.getString(1);
            }
            pst = conn.prepareStatement("SELECT password FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                resValue = "undone";
            }

            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=? AND password=?");
            pst.setString(1, String.valueOf(uname));
            pst.setString(2, String.valueOf(passwd));
            rs = pst.executeQuery();
            if (rs.next()) {
                exists = 1;
            }
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=? AND password=?");
            pst.setString(1, String.valueOf(uname));
            pst.setString(2, String.valueOf(passwd));
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                exists = 0;
                resValue = "undone";
            }

            if (exists == 1) {
                pst = conn.prepareStatement("SELECT permission FROM userList WHERE username=?");
                pst.setString(1, String.valueOf(uname));
                rs = pst.executeQuery();
                while (rs.next()) {
                    getPermission = rs.getString(1);
                    resValue = "Done";
                }
            }

        } catch (SQLException e) {
            Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
        }

        return resValue;
    }

    protected void onPostExecute(String result) {
        if ("Done".equals(result)) {
            progressBar.setVisibility(View.GONE);
            if ("teacher".equals(getPermission)) {
                Intent openTeacher = new Intent(MainActivity.this, TeacherLogin.class);
                progressBar.setVisibility(View.GONE);
                startActivity(openTeacher);
            } else if ("student".equals(getPermission)) {
                Intent openStudent = new Intent(MainActivity.this, StudentLogin.class);
                progressBar.setVisibility(View.GONE);
                startActivity(openStudent);
            }
        } else if ("undone".equals(result)) {
            Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
    }
}
</code>```

}

The app works when I install it with the Run command on USB, but if I want to install app-debug.apk it didn't work.

I have a mysql-connector-java dependency inside my lib folder, that's all.

答:
Interesting fact: When I copy the app-debug.apk to my SDCard with Windows Explorer the application stop itself after launch. But if I open a new command line and make an:

```<code>adb install app-debug.apk
</code>```

inside the outputs/apk/ folder it works. I think that's the solution.

Title: app-debuk.apk stopped working

Body:
I'm new to Android programming and it's my first project with Gradle. In the past I used Maven for Java. So I made an application with Android studio and if I click on Run and select my phone it'll build and install the apk to my phone then opens itself and works fine.

So I would like to share my progress with one of my friend, so I clicked on Make Project, and it generated an app-debug.apk in /app/build/outputs/apk/app-debug.apk but if I try that to install my Application Force Close itself after launch with a text: "Unfortunately the app stopped working".

Here is my build.gradle (Module:app):

and my build.gradle (Project: Autosiskola):

the error code:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.androidports.autosiskola/com.androidports.autosiskola.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.androidports.autosiskola.MainActivity" on path: DexPathList[[zip file "/data/app/com.androidports.autosiskola-1/base.apk"],nativeLibraryDirectories=[/data/app/com.androidports.autosiskola-1/lib/arm64, /vendor/lib64, /system/lib64]]

My Main Activity:

    package com.androidports.autosiskola;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import android.widget.Toast;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MainActivity extends AppCompatActivity {

EditText username, password;
Button login;
ProgressBar progressBar;

Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    username = (EditText) findViewById(R.id.txtUsername);
    password = (EditText) findViewById(R.id.txtPassword);

    login = (Button) findViewById(R.id.btnLogin);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    progressBar.setVisibility(View.GONE);

    conn = DBConnect.Connector();

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (username.toString().trim().isEmpty() && password.toString().isEmpty()) {
                Toast.makeText(MainActivity.this, "Nincs felhasználónév / jelszó megadva!", Toast.LENGTH_SHORT).show();
            } else {
                switch (v.getId()) {
                    case R.id.btnLogin:
                        new doMySQL().execute();
                        break;
                }
            }
        }
    });
}

public class doMySQL extends AsyncTask<Void, Void, String> {

    final String uname = username.getText().toString();
    final String passwd = password.getText().toString();
    String getUsername = null;
    String getPassword = null;
    String getPermission = null;
    String resValue = "undone";
    int exists = 0;

    protected void onPreExecute() {
        progressBar.setVisibility(View.VISIBLE);
    }

    protected String doInBackground(Void... params) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        conn = DBConnect.Connector();

        try {
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.next()) {
                getUsername = rs.getString(1);
            }
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                resValue = "undone";
            }

            pst = conn.prepareStatement("SELECT password FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.next()) {
                getPassword = rs.getString(1);
            }
            pst = conn.prepareStatement("SELECT password FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                resValue = "undone";
            }

            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=? AND password=?");
            pst.setString(1, String.valueOf(uname));
            pst.setString(2, String.valueOf(passwd));
            rs = pst.executeQuery();
            if (rs.next()) {
                exists = 1;
            }
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=? AND password=?");
            pst.setString(1, String.valueOf(uname));
            pst.setString(2, String.valueOf(passwd));
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                exists = 0;
                resValue = "undone";
            }

            if (exists == 1) {
                pst = conn.prepareStatement("SELECT permission FROM userList WHERE username=?");
                pst.setString(1, String.valueOf(uname));
                rs = pst.executeQuery();
                while (rs.next()) {
                    getPermission = rs.getString(1);
                    resValue = "Done";
                }
            }

        } catch (SQLException e) {
            Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
        }

        return resValue;
    }

    protected void onPostExecute(String result) {
        if ("Done".equals(result)) {
            progressBar.setVisibility(View.GONE);
            if ("teacher".equals(getPermission)) {
                Intent openTeacher = new Intent(MainActivity.this, TeacherLogin.class);
                progressBar.setVisibility(View.GONE);
                startActivity(openTeacher);
            } else if ("student".equals(getPermission)) {
                Intent openStudent = new Intent(MainActivity.this, StudentLogin.class);
                progressBar.setVisibility(View.GONE);
                startActivity(openStudent);
            }
        } else if ("undone".equals(result)) {
            Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
    }
}

}

The app works when I install it with the Run command on USB, but if I want to install app-debug.apk it didn't work.

I have a mysql-connector-java dependency inside my lib folder, that's all.

Body:
Interesting fact: When I copy the app-debug.apk to my SDCard with Windows Explorer the application stop itself after launch. But if I open a new command line and make an:

adb install app-debug.apk

inside the outputs/apk/ folder it works. I think that's the solution.


来源: stackexchange

问:
Only print when run as script?
Is there a better way to only print when run as a script, when __name__ == '__main__' ?

I have some scripts that I also import and use parts of.

Something like the below will work but is ugly, and would have to be defined in each script separately:

```<code>def printif(s):
    if globals()['__name__'] == '__main__':
        print (s)
    return
</code>```

I looked briefly at some of python's logging libraries but would prefer a two lighter solution...

edit:

I ended up doing something like this:

```<code># mylog.py
import sys
import logging

log = logging.getLogger()

#default logging level
log.setLevel(logging.WARNING)

log.addHandler(logging.StreamHandler(sys.stdout))
</code>```

And from the script:

```<code>import log from mylog

...
log.info(...)
log.warning(...)
...

if __name__ == '__main__':
    #override when script is run..
    log.setLevel(logger.INFO)
</code>```

This scheme has minimal code duplication, per script log levels, and a project-wide default level...which is exactly what I wanted.

答:
```<code>run_as_script = False

def printif(s):
    if run_as_script:
        print (s)
    return

if __name__ == '__main__':
    run_as_script = True
</code>```

ContentLicense: CC BY-SA 2.5

Title: Only print when run as script?

Body:
Is there a better way to only print when run as a script, when __name__ == '__main__' ?

I have some scripts that I also import and use parts of.

Something like the below will work but is ugly, and would have to be defined in each script separately:

def printif(s):
    if globals()['__name__'] == '__main__':
        print (s)
    return

I looked briefly at some of python's logging libraries but would prefer a two lighter solution...

edit:

I ended up doing something like this:

# mylog.py
import sys
import logging

log = logging.getLogger()

#default logging level
log.setLevel(logging.WARNING)

log.addHandler(logging.StreamHandler(sys.stdout))

And from the script:

import log from mylog

...
log.info(...)
log.warning(...)
...

if __name__ == '__main__':
    #override when script is run..
    log.setLevel(logger.INFO)

This scheme has minimal code duplication, per script log levels, and a project-wide default level...which is exactly what I wanted.


问:
NodeJs No 'Access-Control-Allow-Origin' header is present on the requested resource
I am trying to access an rss feed using an Ajax request on the client broswer.

```<code>$.ajax({
type: 'GET',
url: 'http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk',
crossDomain: true,
dataType: 'xml',
success: function(responseData, textStatus, jqXHR) {
    console.log(responseData)
},
error: function (responseData, textStatus, errorThrown) {
    alert('failed.');
}
});
</code>```

This is giving me the 'Access-Control-Allow-Origin' error.

I have installed the cors package so it should be enabled on my server, am i missing something?

server.js file

```<code>var express = require('express');
var basicAuth = require('express-basic-auth')
var bodyParser = require('body-parser')
var cors = require('cors');
var app = express();

app.use(cors());

app.get('/', function (req, res) {
//    res.send('Hello World');
    res.sendFile(__dirname + '/views/index.html');
})

var routes = require('./routes');
app.use('/api', routes);

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("App listening at http://%s:%s", host, port)
})
</code>```

Edit* Full error
XMLHttpRequest cannot load http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

答:
Because http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk doesn’t send the Access-Control-Allow-Origin response header, you need to instead make the request through proxy. Do that by changing the value of url in your frontend JavaScript code like this:

```<code>url: 'https://cors-anywhere.herokuapp.com/http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk',
</code>```

The https://cors-anywhere.herokuapp.com/http://feeds.bbci.co.uk/… URL will cause the request to go to https://cors-anywhere.herokuapp.com, a open/public CORS proxy which then sends the request on to the http://feeds.bbci.co.uk/… URL you actually want to request.

And when that proxy gets the response, it’ll take it and add the Access-Control-Allow-Origin response header to it and then pass that back to your requesting frontend code as the response.

That response with the Access-Control-Allow-Origin response header is what the browser sees, so the error message the browser is showing you now goes away, and the browser allows your frontend JavaScript code to access the response.

Or use the code from https://github.com/Rob--W/cors-anywhere/ or such to set up your own proxy.

The reason you need a proxy is that, because http://feeds.bbci.co.uk/… itself doesn’t send the Access-Control-Allow-Origin response header, your browser will refuse to let your frontend JavaScript code access a response from that server cross-origin.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to access an rss feed using an Ajax request on the client broswer.

$.ajax({
type: 'GET',
url: 'http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk',
crossDomain: true,
dataType: 'xml',
success: function(responseData, textStatus, jqXHR) {
    console.log(responseData)
},
error: function (responseData, textStatus, errorThrown) {
    alert('failed.');
}
});

This is giving me the 'Access-Control-Allow-Origin' error.

I have installed the cors package so it should be enabled on my server, am i missing something?

server.js file

var express = require('express');
var basicAuth = require('express-basic-auth')
var bodyParser = require('body-parser')
var cors = require('cors');
var app = express();

app.use(cors());

app.get('/', function (req, res) {
//    res.send('Hello World');
    res.sendFile(__dirname + '/views/index.html');
})

var routes = require('./routes');
app.use('/api', routes);

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("App listening at http://%s:%s", host, port)
})

Edit* Full error
XMLHttpRequest cannot load http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

Body:
Because http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk doesn’t send the Access-Control-Allow-Origin response header, you need to instead make the request through proxy. Do that by changing the value of url in your frontend JavaScript code like this:

url: 'https://cors-anywhere.herokuapp.com/http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk',

The https://cors-anywhere.herokuapp.com/http://feeds.bbci.co.uk/… URL will cause the request to go to https://cors-anywhere.herokuapp.com, a open/public CORS proxy which then sends the request on to the http://feeds.bbci.co.uk/… URL you actually want to request.

And when that proxy gets the response, it’ll take it and add the Access-Control-Allow-Origin response header to it and then pass that back to your requesting frontend code as the response.

That response with the Access-Control-Allow-Origin response header is what the browser sees, so the error message the browser is showing you now goes away, and the browser allows your frontend JavaScript code to access the response.

Or use the code from https://github.com/Rob--W/cors-anywhere/ or such to set up your own proxy.

The reason you need a proxy is that, because http://feeds.bbci.co.uk/… itself doesn’t send the Access-Control-Allow-Origin response header, your browser will refuse to let your frontend JavaScript code access a response from that server cross-origin.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.


问:
Opencv multiply scalar and matrix
I have been trying to achieve something which should pretty trivial and is trivial in Matlab.

Using methods of OpenCV, I want to simply achieve something such as:

```<code>cv::Mat sample = [4 5 6; 4 2 5; 1 4 2];
sample = 5*sample;
</code>```

After which sample should just be:

```<code>[20 25 30; 20 10 25; 5 20 10]
</code>```

I have tried scaleAdd, Mul, Multiply and neither allow a scalar multiplier and require a matrix of the same "size and type". In this scenario I could create a Matrix of Ones and then use the scale parameter but that seems so very extraneous

Any direct simple method would be great!

答:
```<code>Mat A = //data;//source Matrix
Mat B;//destination Matrix
Scalar alpha = new Scalar(5)//factor
Core.multiply(A,alpha,b);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Opencv multiply scalar and matrix

Body:
I have been trying to achieve something which should pretty trivial and is trivial in Matlab.

Using methods of OpenCV, I want to simply achieve something such as:

cv::Mat sample = [4 5 6; 4 2 5; 1 4 2];
sample = 5*sample;

After which sample should just be:

[20 25 30; 20 10 25; 5 20 10]

I have tried scaleAdd, Mul, Multiply and neither allow a scalar multiplier and require a matrix of the same "size and type". In this scenario I could create a Matrix of Ones and then use the scale parameter but that seems so very extraneous

Any direct simple method would be great!


问:
How to determine Storage type? Session- or LocalStorage?
I have a variable of type Storage - this is what variable.constructor.name says. How can I now determine is it localStorage or sessionStorage? I just need the name.

Example code:

```<code>class WebStorage {
  constructor(public storage: Storage) {}

  public getStorageName(): 'LocalStorage' | 'SessionStorage' {
     // how to return proper name?
  }
}
</code>```

答:
I believe you can simply compare it:</p>

```<code>return storage === window.localStorage ? 'LocalStorage' : 'SessionStorage';
</code>```

Body:
I have a variable of type Storage - this is what variable.constructor.name says. How can I now determine is it localStorage or sessionStorage? I just need the name.

Example code:

class WebStorage {
  constructor(public storage: Storage) {}

  public getStorageName(): 'LocalStorage' | 'SessionStorage' {
     // how to return proper name?
  }
}

Body:
I believe you can simply compare it:

return storage === window.localStorage ? 'LocalStorage' : 'SessionStorage';


问:
Regex making the browser unresponsive
I have the following regex which works fine at parsing a gradient

```<code>/(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(]*)*)\)/g
</code>```

When an invalid string is passed to the regex.exec function like so:

```<code>var regex = /(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(]*)*)\)/g;
var test = "radial-gradient( circle farthest-corner, white";
regex.exec(test);
</code>```

The browser hangs with an unresponsive script until it times out.

When I tried this as a regex101, I get a timeout with the message

Your expression took too long to finish and was terminated. Please
  increase the timeout and try again.

Can you help me rewrite the regex so it won't timeout if it cannot find a match? I, of course, would also like to know why it times out.

答:
There is no need to keep a double nested star quantifier:

```<code>/(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(])*)\)/g
</code>```

See demo

Title: Regex making the browser unresponsive

Body:
I have the following regex which works fine at parsing a gradient

/(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(]*)*)\)/g

When an invalid string is passed to the regex.exec function like so:

var regex = /(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(]*)*)\)/g;
var test = "radial-gradient( circle farthest-corner, white";
regex.exec(test);

The browser hangs with an unresponsive script until it times out.

When I tried this as a regex101, I get a timeout with the message

Your expression took too long to finish and was terminated. Please
  increase the timeout and try again.

Can you help me rewrite the regex so it won't timeout if it cannot find a match? I, of course, would also like to know why it times out.

Body:
There is no need to keep a double nested star quantifier:

/(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(])*)\)/g

See demo


问:
ValueError: output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: None
Hello this is my code for Implementing CNN with Keras backend with tensor flow, for classifying image
I don't know what part i am doing wrong.

```<code>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

img_width, img_height = 224, 224

train_data_dir = '/Users/CK/data/train'
validation_data_dir = '/Users/CK/data/validation'

nb_train_samples = 47000
nb_validation_samples = 47000
epochs = 50
batch_size = 10

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(12,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(12,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(12,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='categorical_crossentropy', optimizer = 'adam', metrics=['accuracy'])

train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True
        )

test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(train_data_dir, target_size = (img_width, img_height),
                                                    batch_size=batch_size, class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(validation_data_dir,target_size=(img_width, img_height),
                                                        batch_size=batch_size, class_mode='categorical')

model.fit_generator(train_generator,
                    steps_per_epoch=nb_train_samples// batch_size, epochs=epochs,
                    validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)
</code>```

But then I got an error

```<code>runfile('/Users/CK/Desktop/test.py', wdir='/Users/CK/Desktop')
Found 46827 images belonging to 9 classes.
Found 46827 images belonging to 9 classes.
Epoch 1/50
Exception in thread Thread-7:
Traceback (most recent call last):
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/engine/training.py", line 612, in data_generator_task
    generator_output = next(self._generator)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 727, in __next__
    return self.next(*args, **kwargs)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 960, in next
    target_size=self.target_size)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 318, in load_img
    raise ImportError('Could not import PIL.Image. '
ImportError: Could not import PIL.Image. The use of `array_to_img` requires PIL.

Traceback (most recent call last):

  File "<ipython-input-13-15de1a62b9cf>", line 1, in <module>
    runfile('/Users/CK/Desktop/test.py', wdir='/Users/CK/Desktop')

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/CK/Desktop/test.py", line 66, in <module>
    validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/models.py", line 1110, in fit_generator
    initial_epoch=initial_epoch)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/engine/training.py", line 1865, in fit_generator
    str(generator_output))

ValueError: output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: None
</code>```

How do i fix problem? I appreciate if you guys help to fix the code with details. thx

答: You must make file into train_data_dir,validation_data_dir and next you must carry images into this file.</p>

Body:
Hello this is my code for Implementing CNN with Keras backend with tensor flow, for classifying image
I don't know what part i am doing wrong.

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

img_width, img_height = 224, 224

train_data_dir = '/Users/CK/data/train'
validation_data_dir = '/Users/CK/data/validation'

nb_train_samples = 47000
nb_validation_samples = 47000
epochs = 50
batch_size = 10

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(12,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(12,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(12,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='categorical_crossentropy', optimizer = 'adam', metrics=['accuracy'])

train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True
        )

test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(train_data_dir, target_size = (img_width, img_height),
                                                    batch_size=batch_size, class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(validation_data_dir,target_size=(img_width, img_height),
                                                        batch_size=batch_size, class_mode='categorical')

model.fit_generator(train_generator,
                    steps_per_epoch=nb_train_samples// batch_size, epochs=epochs,
                    validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)

But then I got an error

runfile('/Users/CK/Desktop/test.py', wdir='/Users/CK/Desktop')
Found 46827 images belonging to 9 classes.
Found 46827 images belonging to 9 classes.
Epoch 1/50
Exception in thread Thread-7:
Traceback (most recent call last):
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/engine/training.py", line 612, in data_generator_task
    generator_output = next(self._generator)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 727, in __next__
    return self.next(*args, **kwargs)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 960, in next
    target_size=self.target_size)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 318, in load_img
    raise ImportError('Could not import PIL.Image. '
ImportError: Could not import PIL.Image. The use of `array_to_img` requires PIL.

Traceback (most recent call last):

  File "<ipython-input-13-15de1a62b9cf>", line 1, in <module>
    runfile('/Users/CK/Desktop/test.py', wdir='/Users/CK/Desktop')

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/CK/Desktop/test.py", line 66, in <module>
    validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/models.py", line 1110, in fit_generator
    initial_epoch=initial_epoch)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/engine/training.py", line 1865, in fit_generator
    str(generator_output))

ValueError: output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: None

How do i fix problem? I appreciate if you guys help to fix the code with details. thx


问:
POST form data includes GET parameters used to generate the form
This one blew my mind for a while and now I think I know what it is.

I have this basic form that uses POST to submit the values.

```<code><form action="./change" method="post">
    <p class="fieldName">Username (your email address):</p>
    <input type="text" name="thetaname"/>
    <p class="fieldName">Password:</p>
    <input type="password" name="thetaword"/>
    <p class="fieldName">Confirm Password:</p>
    <input type="password" name="confirm"/>
    <input type="hidden" name="authkey" value="djj"/>
    <p class="errorMsg"></p>
    <br><br>
    <input type="submit" value="Submit"/>
</form>
</code>```

and it submits to the same location that originally created the form. The issue seems to be that the form is originally created with a GET parameter on the URL and the form is a POST. When I look at the log, it looks like the GET parameter is included on the post and my Spring app is getting confused.

I'm using GET for the original because I'm emailing the link to the user. I'm using POST on the submit because I want to make sure the passwords and stuff are encrypted.

I'm running NGINX in front of Spring boot and it's returning an empty string from the submit.

The GET is listed as GET only on my method and POST as POST only on my method in my controller.

Ideas?

答:
I assume that your controller is within a Servlet container. In that case Servlet will combine both url query parameters and POST parameters together. You can always get all of them via getParameterValues. See also this post:
How do I separate out query string params from POST data in a java servlet

Body:
This one blew my mind for a while and now I think I know what it is.

I have this basic form that uses POST to submit the values.

<form action="./change" method="post">

Username (your email address):

    <input type="text" name="thetaname"/>

Password:

    <input type="password" name="thetaword"/>

Confirm Password:

    <input type="password" name="confirm"/>
    <input type="hidden" name="authkey" value="djj"/>

    <input type="submit" value="Submit"/>
</form>

and it submits to the same location that originally created the form. The issue seems to be that the form is originally created with a GET parameter on the URL and the form is a POST. When I look at the log, it looks like the GET parameter is included on the post and my Spring app is getting confused.

I'm using GET for the original because I'm emailing the link to the user. I'm using POST on the submit because I want to make sure the passwords and stuff are encrypted.

I'm running NGINX in front of Spring boot and it's returning an empty string from the submit.

The GET is listed as GET only on my method and POST as POST only on my method in my controller.

Ideas?


问:
Where is the webpack.config.js in angular-cli new project?
I'm looking into webpack and also angular-cli, and even though angular-cli is supposed to use webpack, I can't see any webpack.config.js file when I create a new project with ng new

Does anybody know how does this work in angular-cli?

答:
It's not possible to edit webpack in angular-cli project.

There is a workaround repo. Hope this might help. here. Or you can use a scaffolder too if you do it too often https://www.npmjs.com/package/es6-scaffolder. Just choose the angular 2 webpack scaffold from the options.


问:
bootstrap datepicker focusout when clicking on the calendar
I am using this Bootstrap datepicker in my ASP.NET project. I set a function for every input that will check its value on the 'focusout' event. If the input's value is empty, the input will be marked red like this:

But the issue is, looks like the bootstrap datepicker will trigger its input's focusout event whenever user clicks on the calendar. Which means, if the datepicker's input is empty before user chooses the date, after user clicks on any date on the calendar, the input will still be marked red.

any ideas?
I was planning to change the focusout behavior for the datepicker's input. The new function will check if the calendar is on the screen first, if true, then do nothing, else check the input's value. The logic should work but sadly I don't know how to check if the calendar is on or not.

答: I just figured it out. It's every easy, just use the 'hide' event rather than the focusout event for the datepickers.</p>


问:
What is correct length of RESTful app uri?
I'm creating a restful web service. As JPA I use Hibernate.
I have such entities like Country, City, Store, Sale and others.

Is it a good idea to have URIs like this in terms of length and nesting: http://example.com/countries/{countryId}/cities/{cityId}/sales/{saleId}/article/{articleId}  ?

Is there any rule of number of nestings? I mean the number of pairs "entity/{entityId}" ?

答:
URIs are opaque. As far as HTTP and the RESTful principles behind it go, there's no difference between http://example.com/countries/{countryId}/cities/{cityId}/sales/{saleId}/article/{articleId}, http://example.net/sfdaikwjepfiaosnd and http://example.org/ followed by the URI-encoded contents of Finnegans Wake. Indeed it's perfectly possible for all three of those to be URIs for the same resource, perhaps with one permanently redirecting to the other.

So it's non-REST concerns that are most at work here.

One is that if you are at risk of going beyond practical size limits you will have problems.

Another is that entities containing lots of URIs will obviously be shorter if those URIs are small. It's not generally a big concern, but it does have a bit of an effect on network use if URIs are truly massive and every entity contains kilobyte upon kilobyte of such URIs.

Another is just how useful the modelling is: If calling code will never care about the country when it wants an article then your modelling isn't helping that calling code.

Related to that is the practicality of relative links in helping the HATEOS aspect of REST: If you are likely to often be able to just have article/2 as a relative link that is useful in the entity describing a sale, or a (potentially hard-coded) ../../ to get to the entity describing a sale from one describing an article then this is convenient. The question is are you making the most useful links the most convenient. For example, if it is far more common to go from country to city than country to anything else, then why have the /cities/ part to the path, and not just {countryid}/{cityid}?

This relative link matter can counter the question of large URIs causing large entities: If the majority of URIs in an entity are "close" to the resource the entity describes then the majority of URIs can be represented by very small relative URIs.

Another aspect is whether those IDs are human-reader-friendly. Is the ID for New York something like 193 or something like NewYork or New%20York or perhaps Nueva%20York? To a REST perspective those are all of equal value, but 193 gives shorter URIs with advantages noted above while the others are handier to deal with as a consuming developer or when debugging.

Nesting also affects this human-readable aspect. On the one hand lots of nesting can make each element within that simple to identify but on the other it can be confusing in itself to have too many sections in the path. For the most part though if the split is understandable then a human reader can filter out much of the URI and focus on the part they care about.

In all the only hard limit is that of the practical URI size limits, and beyond that there aren't so much strict rules as pros and cons to consider the trade-offs of in your design.


问:
Is there a better way to write this navigation statement?
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!</p>

```<code>$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});
</code>```

答:
```<code>$('.nav li a').bind('click', function() {
    $('.nav li a').removeClass('active');
    $(this).addClass('active')
});
</code>```

Body:
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!

$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});


问:
Bash. Using ccze without altering data for parsing
I have a complex command on my bash script which prints a lot of info on stdout. This command is complex and takes some time to finish but is fully working. At the same time, I'm using a pipe with tee to write it into a file for a post-parsing task.

```<code>cmd="myComplexCommand | tee /dev/fd/5"
exec 5>&1
stored_output=$(eval "${cmd}")
</code>```

Until here everything is working.

Now, I'm trying to implement ccze to colorize screen output. Usually to use it on any command is as simple as:

```<code>anyCommand | ccze -A
</code>```

And everything is printed in a beauty colorized way. The problem is if I try to apply this to my particular case, after using the pipe to ccze on my myComplexCommand, the output on screen is colorized (nice!) but it alters the output stored on the file I want to parse on my post-parse task and it doesn't work.

Is there a Bash way to print a command using ccze in a beauty way on screen and at the same time store it in a file (without ccze modifications) to parse it later?

答:
tee to file at a point in the pipeline before the colorization takes place:

```<code>myComplexCommand | tee filename | ccze -A
</code>```

Incidentally, with bash 4.1 or later, if you want to send a lot of data both to a file and in colorized form to the TTY, you might put both those operations in a single process substitution:

```<code>exec {stdout_backup}>&1
exec {store_and_colorize}> >(tee filename | ccze -A | tee /dev/fd/"$stdout_backup")
</code>```

and then reuse that process substitution as many times as you like:

```<code>result=$(something >&$store_and_colorize)
another_result=$(something_else >&$store_and_colorize)
</code>```

That way you've got exactly one copy of ccze persisting across multiple uses.

Body:
I have a complex command on my bash script which prints a lot of info on stdout. This command is complex and takes some time to finish but is fully working. At the same time, I'm using a pipe with tee to write it into a file for a post-parsing task.

cmd="myComplexCommand | tee /dev/fd/5"
exec 5>&1
stored_output=$(eval "${cmd}")

Until here everything is working.

Now, I'm trying to implement ccze to colorize screen output. Usually to use it on any command is as simple as:

anyCommand | ccze -A

And everything is printed in a beauty colorized way. The problem is if I try to apply this to my particular case, after using the pipe to ccze on my myComplexCommand, the output on screen is colorized (nice!) but it alters the output stored on the file I want to parse on my post-parse task and it doesn't work.

Is there a Bash way to print a command using ccze in a beauty way on screen and at the same time store it in a file (without ccze modifications) to parse it later?

Body:
tee to file at a point in the pipeline before the colorization takes place:

myComplexCommand | tee filename | ccze -A

Incidentally, with bash 4.1 or later, if you want to send a lot of data both to a file and in colorized form to the TTY, you might put both those operations in a single process substitution:

exec {stdout_backup}>&1
exec {store_and_colorize}> >(tee filename | ccze -A | tee /dev/fd/"$stdout_backup")

and then reuse that process substitution as many times as you like:

result=$(something >&$store_and_colorize)
another_result=$(something_else >&$store_and_colorize)

That way you've got exactly one copy of ccze persisting across multiple uses.


问:
Return a list of Facebook friends in Java
How would I get a list of friends that like a Facebook user post. I tried this code:

```<code>public class main {
public static void main(String[] args) throws IOException {
    String accessToken = "EAACEdEoseZBhf0e4WXHuNaItvLeoAZD";
    FacebookClient fbclient = new DefaultFacebookClient(accessToken);
    Connection<Post> result = fbclient.fetchConnection("me/feed", Post.class);
    int counter = 0;
    for (List<Post> page : result) {
        for (Post aPost : page) {
            Date time = aPost.getCreatedTime();
            Calendar c = Calendar.getInstance();
            c.add(Calendar.YEAR, -10);
            Date db = c.getTime();
            {
                if (!time.before(db)) {
                    System.out.println("created time     " + time + "\r\n");
                    System.out.println("Id Poste: fb.com/" + aPost.getId() + "\r\n");
                    System.out.println(" L(userx)    " + aPost.getLikes());
                    counter++;
                } else {
                    System.out.println("date hors période" + "\r\n");
                }
            }
        }
    }
}
</code>```

but the result of the list of like is:

Likes[data=[NamedFacebookType[id=758248010897019 metadata=null name=Toka Ep Bouzidi type=null], NamedFacebookType[id=836615436419028 metadata=null name=Basma Youssfi type=null], NamedFacebookType[id=200283693703077 metadata=null name=Sahar Hmidet type=null], NamedFacebookType[id=1589600437936215 metadata=null name=Fifi Daly Omm Omar type=null], NamedFacebookType[id=2285678608326303 metadata=null name=Rà Nou type=null], NamedFacebookType[id=149760905397346 metadata=null name=Awatef Cherif type=null], NamedFacebookType[id=197868283998495 metadata=null name=Samar Maamouri type=null], NamedFacebookType[id=191663454652822 metadata=null name=Ben Ali Fatma Benali type=null], NamedFacebookType[id=1594576777456573 metadata=null name=Rania Trigui type=null], NamedFacebookType[id=10204633957434960 metadata=null name=Gasmi Ghassen type=null]] totalCount=0]

===================================

I need it to return the names of the user's friends.

答:
```<code>System.out.println("Id Poste: fb.com/" + aPost.getLikes() + "\r\n");
</code>```

Post.getLikes()
will return an Object of Type Post.like() that turns into "Object-gibberish" when trying to be printed. For the Like-count use Post.getLikeCount() [can't like source due to low rep, sorry]

For a more detailed answer, please specify your question a bit. What should the Output look like?

Body:
How would I get a list of friends that like a Facebook user post. I tried this code:

public class main {
public static void main(String[] args) throws IOException {
    String accessToken = "EAACEdEoseZBhf0e4WXHuNaItvLeoAZD";
    FacebookClient fbclient = new DefaultFacebookClient(accessToken);
    Connection<Post> result = fbclient.fetchConnection("me/feed", Post.class);
    int counter = 0;
    for (List<Post> page : result) {
        for (Post aPost : page) {
            Date time = aPost.getCreatedTime();
            Calendar c = Calendar.getInstance();
            c.add(Calendar.YEAR, -10);
            Date db = c.getTime();
            {
                if (!time.before(db)) {
                    System.out.println("created time     " + time + "\r\n");
                    System.out.println("Id Poste: fb.com/" + aPost.getId() + "\r\n");
                    System.out.println(" L(userx)    " + aPost.getLikes());
                    counter++;
                } else {
                    System.out.println("date hors période" + "\r\n");
                }
            }
        }
    }
}

but the result of the list of like is:

Likes[data=[NamedFacebookType[id=758248010897019 metadata=null name=Toka Ep Bouzidi type=null], NamedFacebookType[id=836615436419028 metadata=null name=Basma Youssfi type=null], NamedFacebookType[id=200283693703077 metadata=null name=Sahar Hmidet type=null], NamedFacebookType[id=1589600437936215 metadata=null name=Fifi Daly Omm Omar type=null], NamedFacebookType[id=2285678608326303 metadata=null name=Rà Nou type=null], NamedFacebookType[id=149760905397346 metadata=null name=Awatef Cherif type=null], NamedFacebookType[id=197868283998495 metadata=null name=Samar Maamouri type=null], NamedFacebookType[id=191663454652822 metadata=null name=Ben Ali Fatma Benali type=null], NamedFacebookType[id=1594576777456573 metadata=null name=Rania Trigui type=null], NamedFacebookType[id=10204633957434960 metadata=null name=Gasmi Ghassen type=null]] totalCount=0]

===================================

I need it to return the names of the user's friends.

Body:
System.out.println("Id Poste: fb.com/" + aPost.getLikes() + "\r\n");

Post.getLikes()
will return an Object of Type Post.like() that turns into "Object-gibberish" when trying to be printed. For the Like-count use Post.getLikeCount() [can't like source due to low rep, sorry]

For a more detailed answer, please specify your question a bit. What should the Output look like?


问:
PhpStorm extremely slow while editing vue.js files
I'm using PhpStorm 2017.1.4 with the vue.js plugin. The problem I have is: this plugin is extremely slow and makes coding impossible as you type and you don't see what you type only with 1 to 2 seconds lag. It takes 95% of allocated memory. It takes 50% of the CPU usage.

The project I'm working on is new and I have only one file open of less than 70 lines.

Settings offers to install for vue.js plugin v171.4424.63
I tried to install an earlier version of the plugin v171.3780.63 from https://plugins.jetbrains.com/plugin/9442-vue-js but the result is the same.

Installing more recent versions wasn't supported by PhpStorm and showed it in red with the message "plugin is not compatible with current PhpStorm installation".

I already opened an issue on https://youtrack.jetbrains.com/issue/WI-36715. But what do I do until they fix the issue? code on notepad?

Is there anything I can do to speed things up?

答:
I have just found what was making my specific project so slow and not other ones: I am using Laravel mix tool for versioning my js and sass files. I had more than 200 generated copies of each stored in the public directory. Edit <s>Even if I have added public\js and public\css to the .gitignore, phpStorm VCS (version control)</s> PhpStorm was taking almost all ressource to index these files. Now I deleted the unused files, the plugin is fast as it should be.

The question that remains now is why laravel mix is not deleting the previous versions of built css and js files?


问:
Many issues with reading and writing in NIO
I'm practicing with NIO and trying to make a simple app with client and server sides. This app should just send message in bytes from clien to server and get other message as response. My code is down here. But I have a lot of different issues.

Sometimes lines int bytesRead = socketChannel.read(byteBuffer); or bytesRead = socketChannel.read(byteBuffer); from method readMessage() reads endless sequence of zero bytes and throws OOM error.

Sometimes response from server looks like that instead of {"class":"server.PasswordHashResponse","xoredHash":"RV5GX1JVAwADBEVZWwFGTAhZQ1FGX1tYQ11ZVwA\u003d"}.

Sometimes response has odd tail like this: {"class":"server.PasswordHashResponse","xoredHash":"RV5GX1JVAwADBEVZWwFGTAhZQ1FGX1tYQ11ZVwA\u003d"}YQ11ZVwA\u003d

Both server and cliend use same methods for reading and writing.
I send from client {"class":"server.PasswordHashRequest","login":"admin"}
 and expect {"class":"server.PasswordHashResponse","xoredHash":"RV5GX1JVAwADBEVZWwFGTAhZQ1FGX1tYQ11ZVwA\u003d"}.
With the same code I can get one issue now and other issue few minutes later.
I've tried anything I know. Did I managed to get segfault in Java?

Client side code:

```<code>    @Test
public void main() throws Exception {
    System.out.println("Opening socket");
    InetSocketAddress socketAddress = new InetSocketAddress("localhost", 9090);
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    Selector selector = Selector.open();
    socketChannel.register(selector, OP_CONNECT);
    socketChannel.connect(socketAddress);
    PasswordHashRequest request = new PasswordHashRequest("admin");
    System.out.println("Socket open");
    while (true) {
        System.out.println("Client selector awoken");
        selector.select();
        for (SelectionKey selectionKey : selector.selectedKeys()) {
            if (selectionKey.isConnectable()) {
                socketChannel.finishConnect();
                selectionKey.interestOps(OP_WRITE);
            } else if (selectionKey.isReadable()) {
                String response = ServerManager.readMessage((SocketChannel) selectionKey.channel());
                System.out.println(response);
                server.interrupt();
            } else if (selectionKey.isWritable()) {
                ServerManager.sendMessage(request, (SocketChannel) selectionKey.channel());
                System.out.println("Request sent");
                selectionKey.interestOps(OP_READ);
            }
        }
    }
}
</code>```

Server side code:

```<code>    public void run() {
    System.out.println("Main thread started");
    while (true) {
        try {
            // Get ready channels
            int readyChannels = selector.select();
            if (readyChannels == 0) { continue; }

            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            // Handle Events
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();

                // New Client
                if (key.isAcceptable()) {
                    System.out.println("New Client Accepted");
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                    serverSocketChannel.configureBlocking(false);

                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    SelectionKey clientKey = socketChannel.register(selector, SelectionKey.OP_READ);
                    Random randomInt = new Random(System.currentTimeMillis());
                    clientKey.attach(randomInt.nextInt(Integer.SIZE - 1));
                }
                // Client has sent data
                else if (key.isReadable()) {
                    handleInput(key);
                }

                keyIterator.remove();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Read method:

```<code>    public static String readMessage(SocketChannel socketChannel) throws IOException {
    ByteBuffer byteBuffer = ByteBuffer.allocate(16);
    byteBuffer.clear();
    StringBuilder stringBuilder = new StringBuilder();
    int bytesRead = socketChannel.read(byteBuffer);
    while (bytesRead != -1) {
        byteBuffer.flip();
        String byteString = new String(byteBuffer.array(), Charset.forName("UTF-8"));
        stringBuilder.append(byteString);
        byteBuffer.clear();
        bytesRead = socketChannel.read(byteBuffer);
    }
    socketChannel.shutdownInput();
    return stringBuilder.toString();
}
</code>```

Write method:

```<code>    public static void writeMessage(String message, SocketChannel channel) throws IOException {
    message += "\r\n";
    System.out.println(message);
    int bufferLength = 16;
    byte[] responseBytes = message.getBytes();
    int offset = 0;
    ByteBuffer buf = ByteBuffer.allocate(bufferLength);
    while (responseBytes.length > offset) {
        buf.clear();
        int div = responseBytes.length - offset;
        if (div >= bufferLength) {
            buf.put(responseBytes, offset, bufferLength);
        } else {
            buf.put(responseBytes, offset, div);
        }
        buf.flip();
        channel.write(buf);
        offset += bufferLength;
    }
    channel.shutdownOutput();
}
</code>```

答:
Your read method should stop reading if bytesRead <= 0

It should take account of the buffer limit when constructing the string

Your write method should stop trying write if write() returns zero, and then (and only then) register the channel for OP_WRITE, and only continue writing when it fires.

See many similar questions here on all this.

Body:
I'm practicing with NIO and trying to make a simple app with client and server sides. This app should just send message in bytes from clien to server and get other message as response. My code is down here. But I have a lot of different issues.

Sometimes lines int bytesRead = socketChannel.read(byteBuffer); or bytesRead = socketChannel.read(byteBuffer); from method readMessage() reads endless sequence of zero bytes and throws OOM error.

Sometimes response from server looks like that instead of {"class":"server.PasswordHashResponse","xoredHash":"RV5GX1JVAwADBEVZWwFGTAhZQ1FGX1tYQ11ZVwA\u003d"}.

Sometimes response has odd tail like this: {"class":"server.PasswordHashResponse","xoredHash":"RV5GX1JVAwADBEVZWwFGTAhZQ1FGX1tYQ11ZVwA\u003d"}YQ11ZVwA\u003d

Both server and cliend use same methods for reading and writing.
I send from client {"class":"server.PasswordHashRequest","login":"admin"}
 and expect {"class":"server.PasswordHashResponse","xoredHash":"RV5GX1JVAwADBEVZWwFGTAhZQ1FGX1tYQ11ZVwA\u003d"}.
With the same code I can get one issue now and other issue few minutes later.
I've tried anything I know. Did I managed to get segfault in Java?

Client side code:

    @Test
public void main() throws Exception {
    System.out.println("Opening socket");
    InetSocketAddress socketAddress = new InetSocketAddress("localhost", 9090);
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    Selector selector = Selector.open();
    socketChannel.register(selector, OP_CONNECT);
    socketChannel.connect(socketAddress);
    PasswordHashRequest request = new PasswordHashRequest("admin");
    System.out.println("Socket open");
    while (true) {
        System.out.println("Client selector awoken");
        selector.select();
        for (SelectionKey selectionKey : selector.selectedKeys()) {
            if (selectionKey.isConnectable()) {
                socketChannel.finishConnect();
                selectionKey.interestOps(OP_WRITE);
            } else if (selectionKey.isReadable()) {
                String response = ServerManager.readMessage((SocketChannel) selectionKey.channel());
                System.out.println(response);
                server.interrupt();
            } else if (selectionKey.isWritable()) {
                ServerManager.sendMessage(request, (SocketChannel) selectionKey.channel());
                System.out.println("Request sent");
                selectionKey.interestOps(OP_READ);
            }
        }
    }
}

Server side code:

    public void run() {
    System.out.println("Main thread started");
    while (true) {
        try {
            // Get ready channels
            int readyChannels = selector.select();
            if (readyChannels == 0) { continue; }

            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            // Handle Events
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();

                // New Client
                if (key.isAcceptable()) {
                    System.out.println("New Client Accepted");
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                    serverSocketChannel.configureBlocking(false);

                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    SelectionKey clientKey = socketChannel.register(selector, SelectionKey.OP_READ);
                    Random randomInt = new Random(System.currentTimeMillis());
                    clientKey.attach(randomInt.nextInt(Integer.SIZE - 1));
                }
                // Client has sent data
                else if (key.isReadable()) {
                    handleInput(key);
                }

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

Read method:

    public static String readMessage(SocketChannel socketChannel) throws IOException {
    ByteBuffer byteBuffer = ByteBuffer.allocate(16);
    byteBuffer.clear();
    StringBuilder stringBuilder = new StringBuilder();
    int bytesRead = socketChannel.read(byteBuffer);
    while (bytesRead != -1) {
        byteBuffer.flip();
        String byteString = new String(byteBuffer.array(), Charset.forName("UTF-8"));
        stringBuilder.append(byteString);
        byteBuffer.clear();
        bytesRead = socketChannel.read(byteBuffer);
    }
    socketChannel.shutdownInput();
    return stringBuilder.toString();
}

Write method:

    public static void writeMessage(String message, SocketChannel channel) throws IOException {
    message += "\r\n";
    System.out.println(message);
    int bufferLength = 16;
    byte[] responseBytes = message.getBytes();
    int offset = 0;
    ByteBuffer buf = ByteBuffer.allocate(bufferLength);
    while (responseBytes.length > offset) {
        buf.clear();
        int div = responseBytes.length - offset;
        if (div >= bufferLength) {
            buf.put(responseBytes, offset, bufferLength);
        } else {
            buf.put(responseBytes, offset, div);
        }
        buf.flip();
        channel.write(buf);
        offset += bufferLength;
    }
    channel.shutdownOutput();
}


问:
English Language Regex in C#
I need a regex pattern which can detect if the given text is in English or not, but I want to include the following:

Allowing spaces

Allowing numbers and words

Allowing multiple lines and tabs

Allowing all special characters !@#$%^&*()_-+={}|/<>~`':";[]

Allowing URLs, emails

If the given text contains any character rather than English, it should be considered a non-English text, this should be applied if the text contains Arabic letters/words like "ا ب ت ... etc." and the same for French "é, â ... etc." and also all of the other languages

In brief, I need to know if the given text, any text with any format, is in English or not. I tried a lot of patterns but I didn't get it, and actually, I don't need to use any language detector as the application will be used offline.

Samples of the texts which should not be accepted:

Hello! ... é

مرحبا بك

للتحميل اضغط هنا ... http://www.google.com

So, if the text contains non-English letter, it should be considered non-English text.

答:
This should work:

```<code>@"[^\t\w\d\s$-/:-?{-~!"^_`\[\]]+"
</code>```

If there is a match, there ARE non-english letters/characters.

BTW, you are just testing if the text contains only those characters where a English speaking person would normally use, NOT what language it is in.
To detect a language you need stuffs like Natural Language Processing but NOT regex.

Title: English Language Regex in C#

Body:
This should work:

@"[^\t\w\d\s$-/:-?{-~!"^_`\[\]]+"

If there is a match, there ARE non-english letters/characters.

BTW, you are just testing if the text contains only those characters where a English speaking person would normally use, NOT what language it is in.
To detect a language you need stuffs like Natural Language Processing but NOT regex.


问:
Setting Image to size relative to screen size?
I'm very new to React-Native and Javascript and have been trying to learn. I'm trying to set an image's width to the screen size divided by 10. I set up a constructor and a state with the screen width and height, but am unable to use the state to set the width or height of my image.

```<code>constructor(props) {
     super(props);
     const { width, height } = Dimensions.get("window")
     this.state = {
       width,
       height
     }
}
</code>```

If I do this...

```<code><Image source={require('./my-icon.png')} style={{width: {this.state.width}, height: 40}}/>
</code>```

It gives me an error saying that 'this' is a reserved word.

答:
I fixed it. I guess I made a dumb mistake. I removed the brackets and it worked.</p>

```<code><Image source={require('./my-icon.png')} style={{width: this.state.width/10, height: 40}}/>
</code>```

Body:
I'm very new to React-Native and Javascript and have been trying to learn. I'm trying to set an image's width to the screen size divided by 10. I set up a constructor and a state with the screen width and height, but am unable to use the state to set the width or height of my image.

constructor(props) {
     super(props);
     const { width, height } = Dimensions.get("window")
     this.state = {
       width,
       height
     }
}

If I do this...

<Image source={require('./my-icon.png')} style={{width: {this.state.width}, height: 40}}/>

It gives me an error saying that 'this' is a reserved word.

Body:
I fixed it. I guess I made a dumb mistake. I removed the brackets and it worked.

<Image source={require('./my-icon.png')} style={{width: this.state.width/10, height: 40}}/>


问:
How to continue to next loop iteration only after a button press in javascript?
I have code similar to this:

```<code>for(i = 0; i < array_of_questions.length; i++){
  // call function that gathers necessary data + appends question to screen
  // Now it needs to wait until the user presses a button to continue on to the next iteration. Right now it is set up like this:

  $("#submit_button").on('click', function() {

            //save data

        });
}
</code>```

My problem now is that it calls the function correctly... for all of the iterations. The on click function defines what would happen if the button was clicked but the loop continues after that. I'm always left with the last question displayed.

What is the best approach to fix this?

答:
You don't need to attach the click handler in any loop.

Use a global variable as counter for the array index and increment it whenever you click the button:

```<code>var array_of_questions = ["Question1", "question2", "question3"];
var counter = 0;

$("#submit_button").on('click', function() {
  //save data
  if (counter < array_of_questions.length) {
    $("#display").append("<div>" + array_of_questions[counter] + "</div>");
    counter++;
  }
});
</code>```

Demo:

var array_of_questions = ["Question1", "question2", "question3"];
var counter = 0;

$("#submit_button").on('click', function() {

  //save data
  if (counter < array_of_questions.length) {
    $("#display").append("
" + array_of_questions[counter] + "
");
    counter++;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="submit_button">Click me!</button>
<div id="display"></div></code>```

Body:
I have code similar to this:

for(i = 0; i < array_of_questions.length; i++){
  // call function that gathers necessary data + appends question to screen
  // Now it needs to wait until the user presses a button to continue on to the next iteration. Right now it is set up like this:

  $("#submit_button").on('click', function() {

            //save data

        });
}

My problem now is that it calls the function correctly... for all of the iterations. The on click function defines what would happen if the button was clicked but the loop continues after that. I'm always left with the last question displayed.

What is the best approach to fix this?

Body:
You don't need to attach the click handler in any loop.

Use a global variable as counter for the array index and increment it whenever you click the button:

var array_of_questions = ["Question1", "question2", "question3"];
var counter = 0;

$("#submit_button").on('click', function() {
  //save data
  if (counter < array_of_questions.length) {
    $("#display").append("<div>" + array_of_questions[counter] + "</div>");
    counter++;
  }
});

Demo:

var array_of_questions = ["Question1", "question2", "question3"];
var counter = 0;

$("#submit_button").on('click', function() {

  //save data
  if (counter < array_of_questions.length) {
    $("#display").append("<div>" + array_of_questions[counter] + "</div>");
    counter++;
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="submit_button">Click me!</button>
<div id="display"></div>


问:
async / await: If it doen't use threads what is it doing to running processing at the same time?
I am doing a little research to understand async / await of C# better.

I found a web site that has the following code to show how much slower synchronous processing is vs async / await:

```<code> public IActionResult Index()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var content = service.GetContent();
            var count = service.GetCount();
            var name = service.GetName();

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

            return View();
        }

        [HttpGet]
        public async Task<ActionResult> IndexAsync()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var contentTask = service.GetContentAsync();
            var countTask = service.GetCountAsync();
            var nameTask = service.GetNameAsync();

            var content = await contentTask;
            var count = await countTask;
            var name = await nameTask;

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
            return View("Index");
        }

        public class ContentManagement
        {
            public string GetContent()
            {
                Thread.Sleep(2000);
                return "content";
            }

            public int GetCount()
            {
                Thread.Sleep(5000);
                return 4;
            }

            public string GetName()
            {
                Thread.Sleep(3000);
                return "Matthew";
            }
            public async Task<string> GetContentAsync()
            {
                await Task.Delay(2000);
                return "content";
            }

            public async Task<int> GetCountAsync()
            {
                await Task.Delay(5000);
                return 4;
            }

            public async Task<string> GetNameAsync()
            {
                await Task.Delay(3000);
                return "Matthew";
            }
        }
</code>```

I understand the above code at a high level and why it performs faster.

What I don't understand is if threads are not being used, how is the processing running at the same time?

I have read in a couple of places that async / await does not create new threads to do the processing. So, what is async / await  doing to allow processing to happen at the same time? The three await Task.Delay are running in parallel, correct?  If it is not creating 3 threads, what is it doing?

I just want to understand what is happening at a high level.

Let me know.

Thanks in advance.

答:
if threads are not being used, how is the processing running at the same time?

Threads let you parallelize computations on the same system. When communications or other I/O are involved, there is a different system with which your code communicates. When you initiate the task, the other system starts doing work. This happens in parallel to your system, which is free to do whatever else it needs to do until you await the task.

The three await Task.Delay are running in parallel, correct?

They are not exactly running, they are sleeping in parallel. Sleeping takes very little resources. That's why they appear to be "running" in parallel.

Body:
I am doing a little research to understand async / await of C# better.

I found a web site that has the following code to show how much slower synchronous processing is vs async / await:

 public IActionResult Index()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var content = service.GetContent();
            var count = service.GetCount();
            var name = service.GetName();

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

            return View();
        }

        [HttpGet]
        public async Task<ActionResult> IndexAsync()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var contentTask = service.GetContentAsync();
            var countTask = service.GetCountAsync();
            var nameTask = service.GetNameAsync();

            var content = await contentTask;
            var count = await countTask;
            var name = await nameTask;

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
            return View("Index");
        }

        public class ContentManagement
        {
            public string GetContent()
            {
                Thread.Sleep(2000);
                return "content";
            }

            public int GetCount()
            {
                Thread.Sleep(5000);
                return 4;
            }

            public string GetName()
            {
                Thread.Sleep(3000);
                return "Matthew";
            }
            public async Task<string> GetContentAsync()
            {
                await Task.Delay(2000);
                return "content";
            }

            public async Task<int> GetCountAsync()
            {
                await Task.Delay(5000);
                return 4;
            }

            public async Task<string> GetNameAsync()
            {
                await Task.Delay(3000);
                return "Matthew";
            }
        }

I understand the above code at a high level and why it performs faster.

What I don't understand is if threads are not being used, how is the processing running at the same time?

I have read in a couple of places that async / await does not create new threads to do the processing. So, what is async / await  doing to allow processing to happen at the same time? The three await Task.Delay are running in parallel, correct?  If it is not creating 3 threads, what is it doing?

I just want to understand what is happening at a high level.

Let me know.

Thanks in advance.


问:
Pset4 (cs50) recover does not work properly. It compiles, but does not recover more than 2 jpegs. Is something wrong with checking for JPEG signature?
I am learning how to code and I have no experience with that at all. I've successful got to PSET4 and stuck on recover. I've read everything online about this problem and i found out that many people have similar code as I do and it works. Does not work for me whatsoever. Please have a look and give me a hint what did I do wrong and how to correct it.
Here is everything about the pset4 recover i downloaded their card.raw from here card.raw</p>

```<code>/** recovering JPEG files from a memory card
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef uint8_t BYTE;

int main(int argc, char* argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr,
            "Usage: ./recover infile (the name of a forensic image from which to recover JPEGs)\n");
        return 1;
    }

    // open input file (forensic image)
    FILE* inptr = fopen(argv[1], "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", argv[1]);
        return 2;
    }

    FILE* outptr = NULL;

    // create a pointer array of 512 elements to store 512 bytes from the memory card
    BYTE* buffer = malloc(sizeof(BYTE) * 512);
    if (buffer == NULL)
    {
        return 3;
    }

    // count amount of jpeg files found
    int jpeg = 0;

    // string for a file name using sprintf
    char filename[8] = { 0 };

    // read memory card untill the end of file
    while (fread(buffer, sizeof(BYTE) * 512, 1, inptr) != 0)
    {
        // check if jpeg is found
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
            && (buffer[3] >= 0xe0 || buffer[3] <= 0xef))
        {
            if (jpeg > 0)
            {
                fclose(outptr);
            }
            sprintf(filename, "%03d.JPEG", jpeg);
            outptr = fopen(filename, "w");
            jpeg++;
        }

        if (jpeg > 0)
        {
            fwrite(buffer, sizeof(BYTE) * 512, 1, outptr);
        }
    }

    // free memory
    free(buffer);

    // close filename
    fclose(outptr);

    // close input file (forensic image)
    fclose(inptr);

    return 0;
}
</code>```

答:
The main problem is that you invoke undefined behavior because filename is not enough big. sprintf() need be 9 and 17 bytes with your code but you only has 8. So you have a buffer overflow.

Just change:

```<code>char filename[8] = { 0 };
</code>```

to

```<code>char filename[17] = { 0 };
</code>```

Because, you use an int, this value is implemented defined but in many system has an int with 32 bits. So the value possible are between -2^31 and 2^31 - 1 that make a maximum of 11 chars (-2147483648). We add the number of chars in ".JPEG", 5. We have 16 but you forget the null terminate byte of a c-string. So we are 17 maximum.

Modern compiler warning you: gcc version 7.1.1 20170516 (GCC):

In function ‘main’:
  warning: ‘sprintf’ writing a terminating nul past the end of the destination [-Wformat-overflow ]
  sprintf(filename, "%03d.JPEG", jpeg++);
                              ^
note: ‘sprintf’ output between 9 and 17 bytes into a destination of size 8
  sprintf(filename, "%03d.JPEG", jpeg++);
  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```

<p>Plus, your <code>typedef</code> is useless because a <code>char</code> world be always a byte in C. More than that you don't need a byte but an octet so like <code>char</code>, <code>uint8_t</code> would be always an octet in C. So you don't need <code>typedef</code>.</p>

<p>Again one thing, you allocate your buffer but it's useless because your buffer has a constant size. So just create an array is more simple.</p>

```#include <stdint.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  if (argc != 2) {
    fprintf(stderr, "Usage: ./recover infile (the name of a forensic image "
                    "from which to recover JPEGs)\n");
    return 1;
  }

  FILE *inptr = fopen(argv[1], "r");
  if (inptr == NULL) {
    fprintf(stderr, "Could not open %s.\n", argv[1]);
    return 2;
  }

  FILE *outptr = NULL;
  uint8_t buffer[512];
  size_t const buffer_size = sizeof buffer / sizeof *buffer;
  size_t jpeg = 0;
  while (fread(buffer, sizeof *buffer, buffer_size, inptr) == buffer_size) {
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&
        buffer[3] == 0xe0) {
      if (outptr != NULL) {
        fclose(outptr);
      }

      char filename[26];
      sprintf(filename, "%03zu.JPEG", jpeg++);
      outptr = fopen(filename, "w");
    }
    if (outptr != NULL) {
      fwrite(buffer, sizeof *buffer, buffer_size, outptr);
    }
  }

  if (outptr != NULL) {
    fwrite(buffer, sizeof *buffer, buffer_size, outptr);
  }

  if (outptr != NULL) {
    fclose(outptr);
  }

  fclose(inptr);
}
```

Note: This example is clearly not perfect, this will be better to make a true parser for jpeg file to have a better control flow. Here we suppose that all gonna be right.

Body:
I am learning how to code and I have no experience with that at all. I've successful got to PSET4 and stuck on recover. I've read everything online about this problem and i found out that many people have similar code as I do and it works. Does not work for me whatsoever. Please have a look and give me a hint what did I do wrong and how to correct it.
Here is everything about the pset4 recover i downloaded their card.raw from here card.raw

/** recovering JPEG files from a memory card
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef uint8_t BYTE;

int main(int argc, char* argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr,
            "Usage: ./recover infile (the name of a forensic image from which to recover JPEGs)\n");
        return 1;
    }

    // open input file (forensic image)
    FILE* inptr = fopen(argv[1], "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", argv[1]);
        return 2;
    }

    FILE* outptr = NULL;

    // create a pointer array of 512 elements to store 512 bytes from the memory card
    BYTE* buffer = malloc(sizeof(BYTE) * 512);
    if (buffer == NULL)
    {
        return 3;
    }

    // count amount of jpeg files found
    int jpeg = 0;

    // string for a file name using sprintf
    char filename[8] = { 0 };

    // read memory card untill the end of file
    while (fread(buffer, sizeof(BYTE) * 512, 1, inptr) != 0)
    {
        // check if jpeg is found
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
            && (buffer[3] >= 0xe0 || buffer[3] <= 0xef))
        {
            if (jpeg > 0)
            {
                fclose(outptr);
            }
            sprintf(filename, "%03d.JPEG", jpeg);
            outptr = fopen(filename, "w");
            jpeg++;
        }

        if (jpeg > 0)
        {
            fwrite(buffer, sizeof(BYTE) * 512, 1, outptr);
        }
    }

    // free memory
    free(buffer);

    // close filename
    fclose(outptr);

    // close input file (forensic image)
    fclose(inptr);

    return 0;
}

Body:
The main problem is that you invoke undefined behavior because filename is not enough big. sprintf() need be 9 and 17 bytes with your code but you only has 8. So you have a buffer overflow.

Just change:

char filename[8] = { 0 };

to

char filename[17] = { 0 };

Because, you use an int, this value is implemented defined but in many system has an int with 32 bits. So the value possible are between -2^31 and 2^31 - 1 that make a maximum of 11 chars (-2147483648). We add the number of chars in ".JPEG", 5. We have 16 but you forget the null terminate byte of a c-string. So we are 17 maximum.

Modern compiler warning you: gcc version 7.1.1 20170516 (GCC):

In function ‘main’:
  warning: ‘sprintf’ writing a terminating nul past the end of the destination [-Wformat-overflow ]
  sprintf(filename, "%03d.JPEG", jpeg++);
                              ^
note: ‘sprintf’ output between 9 and 17 bytes into a destination of size 8
  sprintf(filename, "%03d.JPEG", jpeg++);
  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Plus, your typedef is useless because a char world be always a byte in C. More than that you don't need a byte but an octet so like char, uint8_t would be always an octet in C. So you don't need typedef.

Again one thing, you allocate your buffer but it's useless because your buffer has a constant size. So just create an array is more simple.

#include <stdint.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  if (argc != 2) {
    fprintf(stderr, "Usage: ./recover infile (the name of a forensic image "
                    "from which to recover JPEGs)\n");
    return 1;
  }

  FILE *inptr = fopen(argv[1], "r");
  if (inptr == NULL) {
    fprintf(stderr, "Could not open %s.\n", argv[1]);
    return 2;
  }

  FILE *outptr = NULL;
  uint8_t buffer[512];
  size_t const buffer_size = sizeof buffer / sizeof *buffer;
  size_t jpeg = 0;
  while (fread(buffer, sizeof *buffer, buffer_size, inptr) == buffer_size) {
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&
        buffer[3] == 0xe0) {
      if (outptr != NULL) {
        fclose(outptr);
      }

      char filename[26];
      sprintf(filename, "%03zu.JPEG", jpeg++);
      outptr = fopen(filename, "w");
    }
    if (outptr != NULL) {
      fwrite(buffer, sizeof *buffer, buffer_size, outptr);
    }
  }

  if (outptr != NULL) {
    fwrite(buffer, sizeof *buffer, buffer_size, outptr);
  }

  if (outptr != NULL) {
    fclose(outptr);
  }

  fclose(inptr);
}

Note: This example is clearly not perfect, this will be better to make a true parser for jpeg file to have a better control flow. Here we suppose that all gonna be right.


答:
In theory it is possible, if regex contained every word from English dictionary.

You can create a regex that detects non-English characters. That will detect text that is definitely not English, but won't be able to confirm it definitely is.

Title: English Language Regex in C#

Body:
I need a regex pattern which can detect if the given text is in English or not, but I want to include the following:

Allowing spaces

Allowing numbers and words

Allowing multiple lines and tabs

Allowing all special characters !@#$%^&*()_-+={}|/<>~`':";[]

Allowing URLs, emails

If the given text contains any character rather than English, it should be considered a non-English text, this should be applied if the text contains Arabic letters/words like "ا ب ت ... etc." and the same for French "é, â ... etc." and also all of the other languages

In brief, I need to know if the given text, any text with any format, is in English or not. I tried a lot of patterns but I didn't get it, and actually, I don't need to use any language detector as the application will be used offline.

Samples of the texts which should not be accepted:

Hello! ... é

مرحبا بك

للتحميل اضغط هنا ... http://www.google.com

So, if the text contains non-English letter, it should be considered non-English text.


问:
Extraction IO data inside other Monad
I am using HDBC-Sqlite3, I would like to make queries depending on the page I am in. And I would like to get the data out of the IO Monad. It should be possible because "get" is already not pure. How is it done in Haskell in general?

```<code>  main = do
  conn <- connectSqlite3 "test.db"
  scotty 3000 $ do
    get "/" $ do
      x <- quickQuery' conn "SELECT * from definitions" [] -- Here, how to do it?
      blaze $ Mathskell.Views.Read.render conn
</code>```

The problem is that I'm in a "do" where the Monad is ActionM and not IO.

I thought about constructing an ActionM from the IO, and then using the x <- ... syntax, is it a good solution?
I also saw the existence of liftIO/liftM but I didn't understand how/when to use it either.

答:
I'm not familiar with that specific library, but typically one injects an IO action into another monad with liftIO. This is indeed what you hint at in your question.

I would try something like

```<code>get "/" $ do
  x <- liftIO $ quickQuery' conn "SELECT * from definitions" []
  blaze $ Mathskell.Views.Read.render conn
</code>```

This should work as long as the outer monad has a MonadIO instance.

Title: Extraction IO data inside other Monad

Body:
I am using HDBC-Sqlite3, I would like to make queries depending on the page I am in. And I would like to get the data out of the IO Monad. It should be possible because "get" is already not pure. How is it done in Haskell in general?

  main = do
  conn <- connectSqlite3 "test.db"
  scotty 3000 $ do
    get "/" $ do
      x <- quickQuery' conn "SELECT * from definitions" [] -- Here, how to do it?
      blaze $ Mathskell.Views.Read.render conn

The problem is that I'm in a "do" where the Monad is ActionM and not IO.

I thought about constructing an ActionM from the IO, and then using the x <- ... syntax, is it a good solution?
I also saw the existence of liftIO/liftM but I didn't understand how/when to use it either.

Body:
I'm not familiar with that specific library, but typically one injects an IO action into another monad with liftIO. This is indeed what you hint at in your question.

I would try something like

get "/" $ do
  x <- liftIO $ quickQuery' conn "SELECT * from definitions" []
  blaze $ Mathskell.Views.Read.render conn

This should work as long as the outer monad has a MonadIO instance.


问:
Error parsing parameter, amazon aws emr
I'm trying to create a step by Linux console:

```<code>aws emr add-steps --cluster-id j-XXXXXXXXXX --steps Type=CUSTOM_JAR,Name="S3DistCp step",Jar=/home/hadoop/lib/emr-s3distcp-1.0.jar,\
Args=["--s3Endpoint,s3-eu-west-1.amazonaws.com","--src,s3://folder-name/logs/j-XXXXXXXXXX/node/","--dest,hdfs:///output","--srcPattern,.*[a-zA-Z,]+"]
</code>```

I jump the following error

Error parsing parameter '--steps': Expected: ',', received: '+' for input

How I can fix it?

I'm looking for a solution to upload multiple files to S3 and S3DistCp the Hive gather for Amazon EMR. Is there any other way?

I have another question:
Now I am creating an SSH tunnel to connect to Hive, how I could connect with PHP?

At the moment I have solved the error by removing "src Pattern", however gives me another error, I include image below

Image error

This is the error that appears

```<code>INFO Synchronously wait child process to complete : hadoop jar /var/lib/aws/emr/step-runner/hadoop-
INFO waitProcessCompletion ended with exit code 1 : hadoop jar
/var/lib/aws/emr/step-runner/hadoop-
INFO total process run time: 2 seconds
2016-07-12T14:26:48.744Z INFO Step created jobs:
2016-07-12T14:26:48.744Z WARN Step failed with exitCode 1 and took 2 seconds
</code>```

Thx!!!

答:
Try the JSON configuration

```<code>[
    {
        "Name":"S3DistCp step",
        "Args":["s3-dist-cp","--s3Endpoint=s3.amazonaws.com","--src=s3://mybucket/logs/j-3GYXXXXXX9IOJ/node/","--dest=hdfs:///output","--srcPattern=.*[a-zA-Z,]+"],
        "ActionOnFailure":"CONTINUE",
        "Type":"CUSTOM_JAR",
        "Jar":"command-runner.jar"
    }
]
</code>```

aws emr add-steps --cluster-id j-3GYXXXXXX9IOK --steps file://./myStep.json

http://docs.aws.amazon.com/emr/latest/ReleaseGuide/UsingEMR_s3distcp.html#UsingEMR_s3distcp.step

Title: Error parsing parameter, amazon aws emr

Body:
I'm trying to create a step by Linux console:

aws emr add-steps --cluster-id j-XXXXXXXXXX --steps Type=CUSTOM_JAR,Name="S3DistCp step",Jar=/home/hadoop/lib/emr-s3distcp-1.0.jar,\
Args=["--s3Endpoint,s3-eu-west-1.amazonaws.com","--src,s3://folder-name/logs/j-XXXXXXXXXX/node/","--dest,hdfs:///output","--srcPattern,.*[a-zA-Z,]+"]

I jump the following error

Error parsing parameter '--steps': Expected: ',', received: '+' for input

How I can fix it?

I'm looking for a solution to upload multiple files to S3 and S3DistCp the Hive gather for Amazon EMR. Is there any other way?

I have another question:
Now I am creating an SSH tunnel to connect to Hive, how I could connect with PHP?

At the moment I have solved the error by removing "src Pattern", however gives me another error, I include image below

Image error

This is the error that appears

INFO Synchronously wait child process to complete : hadoop jar /var/lib/aws/emr/step-runner/hadoop-
INFO waitProcessCompletion ended with exit code 1 : hadoop jar
/var/lib/aws/emr/step-runner/hadoop-
INFO total process run time: 2 seconds
2016-07-12T14:26:48.744Z INFO Step created jobs:
2016-07-12T14:26:48.744Z WARN Step failed with exitCode 1 and took 2 seconds

Thx!!!

Body:
Try the JSON configuration

[
    {
        "Name":"S3DistCp step",
        "Args":["s3-dist-cp","--s3Endpoint=s3.amazonaws.com","--src=s3://mybucket/logs/j-3GYXXXXXX9IOJ/node/","--dest=hdfs:///output","--srcPattern=.*[a-zA-Z,]+"],
        "ActionOnFailure":"CONTINUE",
        "Type":"CUSTOM_JAR",
        "Jar":"command-runner.jar"
    }
]

aws emr add-steps --cluster-id j-3GYXXXXXX9IOK --steps file://./myStep.json

http://docs.aws.amazon.com/emr/latest/ReleaseGuide/UsingEMR_s3distcp.html#UsingEMR_s3distcp.step