问:
Knocking back the Player in a Unity 2D TopDown Game
When something hits the Player, maybe an enemy or spikes etc., I want him to get knocked back in the oppisite direction of the enemy.

So what I already got:

```<code>public void ChangeHealth(float healthToAdd, Vector2 objectPosition) // Change the players health, objectPosition = enemies position or something else
    {
        if (healthToAdd < 0) // incoming damage
        {
            // ... other stuff

            Knockback(objectPosition);
        }

        // ... other stuff
    }

    void Knockback(Vector2 objectPosition) // Knockback routine
    {
        Vector2 knockbackPosition = new Vector2( , ); // calculation is missing here! Calculate the new position by the knockback direction

        rigid.MovePosition(Vector2.MoveTowards(playerPos, knockbackPosition, 2 * Time.deltaTime)); // the knock back
    }

    private void Update() // !! TEST !!
    {
        if (Input.GetKeyDown(KeyCode.E)) // TEST routine
        {
            ChangeHealth(-7, new Vector2(10,10)); // decrease players health by 7 and knock him back
        }
    }
</code>```

And what is missing:

```<code>Vector2 knockbackPosition = new Vector2( , );
</code>```

I am looking for a calculation like this picture is showing:

答:
```<code>Vector2 knockbackPosition =
    transform.position + (transform.position - objectPosition).normalized *a
</code>```

To understand why is it equal to that you have to read through.

There are three points: E,P,K (Enemy, Player, Knockback)

And one scalar number: a (the greater this value is, the more knockback you'll have)

Now from your picture:

PK = EP*a

expand vectors into distances between two points:

(K-P) = (P-E)*a

calculate the location of K:

K = P + (P-E)*a

There is one problem though. (thanks to Rotem) with this formula as it is:

you'd expect a bigger knockback from a closer opponent.

We don't want the knockback to be dependent on the distance between P and E.

To remove the dependency on the former, normalize the vector before multiplying by a

So we add .normalized to use just the direction of (P-E) instead of its original vector

Body:
When something hits the Player, maybe an enemy or spikes etc., I want him to get knocked back in the oppisite direction of the enemy.

So what I already got:

public void ChangeHealth(float healthToAdd, Vector2 objectPosition) // Change the players health, objectPosition = enemies position or something else
    {
        if (healthToAdd < 0) // incoming damage
        {
            // ... other stuff

            Knockback(objectPosition);
        }

        // ... other stuff
    }

    void Knockback(Vector2 objectPosition) // Knockback routine
    {
        Vector2 knockbackPosition = new Vector2( , ); // calculation is missing here! Calculate the new position by the knockback direction

        rigid.MovePosition(Vector2.MoveTowards(playerPos, knockbackPosition, 2 * Time.deltaTime)); // the knock back
    }

    private void Update() // !! TEST !!
    {
        if (Input.GetKeyDown(KeyCode.E)) // TEST routine
        {
            ChangeHealth(-7, new Vector2(10,10)); // decrease players health by 7 and knock him back
        }
    }

And what is missing:

Vector2 knockbackPosition = new Vector2( , );

I am looking for a calculation like this picture is showing:

Body:
Vector2 knockbackPosition =
    transform.position + (transform.position - objectPosition).normalized *a

To understand why is it equal to that you have to read through.

There are three points: E,P,K (Enemy, Player, Knockback)

And one scalar number: a (the greater this value is, the more knockback you'll have)

Now from your picture:

PK = EP*a

expand vectors into distances between two points:

(K-P) = (P-E)*a

calculate the location of K:

K = P + (P-E)*a

There is one problem though. (thanks to Rotem) with this formula as it is:

you'd expect a bigger knockback from a closer opponent.

We don't want the knockback to be dependent on the distance between P and E.

To remove the dependency on the former, normalize the vector before multiplying by a

So we add .normalized to use just the direction of (P-E) instead of its original vector


来源: stackexchange

问:
manipulating multidimensional array
I have a multi-dimensional array. Since the value of the string "volvo" is present twice, I want to combine those keys. Here's the source array:

```<code>Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 22
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )

    [3] => Array
        (
            [0] => Volvo
            [1] => 17
        )

)
</code>```

and I'd like to convert it to this one:

```<code>Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 39
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )
)
</code>```

答:
```<code>$keyValueCars = [];
foreach($cars as $car){
   $brand = $car[0];
   $total = $car[1];
   if(!isset($keyValueCars[$brand])){
       $keyValueCars[$brand] = total;
   }
   else{
       $keyValueCars[$brand] += total;
   }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: manipulating multidimensional array

Body:
I have a multi-dimensional array. Since the value of the string "volvo" is present twice, I want to combine those keys. Here's the source array:

Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 22
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )

    [3] => Array
        (
            [0] => Volvo
            [1] => 17
        )

)

and I'd like to convert it to this one:

Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 39
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )
)


问:
How to store array of objects in db.json from json-server
I am creating a fake backend using json-server to store some data in json format. The data is complex as follows -

```<code>   {
        "id": 0,
        "quizName": "Which Harry Potter Character Are You?",
        "characters": ["Harry", "Ron", "Hermoine"],
        "qa": [{
                "question": "Do you play Chess?",
                "answers": [{
                        "name": "yes",
                        "charscore": [0, 1, 0]
                    },
                    {
                        "name": "no",
                        "charscore": [1, 0, 1]
                    }
                ]
            },
            {
                "question": "Do you spell magic correctly?",
                "answers": [{
                        "name": "yes",
                        "charscore": [0, 0, 1]
                    },
                    {
                        "name": "no",
                        "charscore": [1, 1, 0]
                    }
                ]
            },
            {
                "question": "Do you have a Scar?",
                "answers": [{
                        "name": "yes",
                        "charscore": [1, 0, 0]
                    },
                    {
                        "name": "no",
                        "charscore": [0, 1, 1]
                    }
                ]
            }
        ]
    }
</code>```

But when I do jQuery POST to the json-server, the json data is stored as follows -

```<code>{
  "quizName": "Which Harry Potter Character Are You?",
  "characters[]": [
    "Harry",
    "Ron",
    "Hermoine"
  ],
  "qa[0][question]": "Do you play Chess?",
  "qa[0][answers][0][name]": "yes",
  "qa[0][answers][0][charscore][]": [
    "0",
    "1",
    "0"
  ],
  "qa[0][answers][1][name]": "no",
  "qa[0][answers][1][charscore][]": [
    "1",
    "0",
    "1"
  ],
  "qa[1][question]": "Do you spell magic correctly?",
  "qa[1][answers][0][name]": "yes",
  "qa[1][answers][0][charscore][]": [
    "0",
    "0",
    "1"
  ],
  "qa[1][answers][1][name]": "no",
  "qa[1][answers][1][charscore][]": [
    "1",
    "1",
    "0"
  ],
  "qa[2][question]": "Do you have a Scar?",
  "qa[2][answers][0][name]": "yes",
  "qa[2][answers][0][charscore][]": [
    "1",
    "0",
    "0"
  ],
  "qa[2][answers][1][name]": "no",
  "qa[2][answers][1][charscore][]": [
    "0",
    "1",
    "1"
  ],
  "id": 1
}
</code>```

The post method is as follows-

```<code>$.post(this.serverUrl, val, function (serverResponse) {
      //val contains the expected javascript object
      console.log(serverResponse);
});
</code>```

How can I store the values correctly in json-server?

答:
Modifying the AJAX call to send stringify object and setting the contentType: "application/json" did the trick

Modified the AJAX call as below-

```<code>$.ajax({
      type: "POST",
      url: this.serverUrl,
      data: JSON.stringify(val),
      contentType: "application/json"
 });
</code>```

Body:
I am creating a fake backend using json-server to store some data in json format. The data is complex as follows -

   {
        "id": 0,
        "quizName": "Which Harry Potter Character Are You?",
        "characters": ["Harry", "Ron", "Hermoine"],
        "qa": [{
                "question": "Do you play Chess?",
                "answers": [{
                        "name": "yes",
                        "charscore": [0, 1, 0]
                    },
                    {
                        "name": "no",
                        "charscore": [1, 0, 1]
                    }
                ]
            },
            {
                "question": "Do you spell magic correctly?",
                "answers": [{
                        "name": "yes",
                        "charscore": [0, 0, 1]
                    },
                    {
                        "name": "no",
                        "charscore": [1, 1, 0]
                    }
                ]
            },
            {
                "question": "Do you have a Scar?",
                "answers": [{
                        "name": "yes",
                        "charscore": [1, 0, 0]
                    },
                    {
                        "name": "no",
                        "charscore": [0, 1, 1]
                    }
                ]
            }
        ]
    }

But when I do jQuery POST to the json-server, the json data is stored as follows -

{
  "quizName": "Which Harry Potter Character Are You?",
  "characters[]": [
    "Harry",
    "Ron",
    "Hermoine"
  ],
  "qa[0][question]": "Do you play Chess?",
  "qa[0][answers][0][name]": "yes",
  "qa[0][answers][0][charscore][]": [
    "0",
    "1",
    "0"
  ],
  "qa[0][answers][1][name]": "no",
  "qa[0][answers][1][charscore][]": [
    "1",
    "0",
    "1"
  ],
  "qa[1][question]": "Do you spell magic correctly?",
  "qa[1][answers][0][name]": "yes",
  "qa[1][answers][0][charscore][]": [
    "0",
    "0",
    "1"
  ],
  "qa[1][answers][1][name]": "no",
  "qa[1][answers][1][charscore][]": [
    "1",
    "1",
    "0"
  ],
  "qa[2][question]": "Do you have a Scar?",
  "qa[2][answers][0][name]": "yes",
  "qa[2][answers][0][charscore][]": [
    "1",
    "0",
    "0"
  ],
  "qa[2][answers][1][name]": "no",
  "qa[2][answers][1][charscore][]": [
    "0",
    "1",
    "1"
  ],
  "id": 1
}

The post method is as follows-

$.post(this.serverUrl, val, function (serverResponse) {
      //val contains the expected javascript object
      console.log(serverResponse);
});

How can I store the values correctly in json-server?

Body:
Modifying the AJAX call to send stringify object and setting the contentType: "application/json" did the trick

Modified the AJAX call as below-

$.ajax({
      type: "POST",
      url: this.serverUrl,
      data: JSON.stringify(val),
      contentType: "application/json"
 });


问:
How to make automatic grader with Python3
I'm a beginner for coding.
I'm struggling to make student grader which each student names would be corresponded to each grade averages and show total average score among students.
This is my code :

```<code>Ken = [5,8,9]
Hiro = [10,11,20]
Nick = [20,20,20]

list1 = [Ken,Hiro,Nick]

total_average = 0
for j in list1:
   x = 0
   count = 0
   for i in j:
       x += i
       count += 1

   average = x / count
   print (round(average,2))
   total_average += average

final_average = total_average / len(list1)
print (round(final_average,2))
</code>```

and result is :

```<code>7.33
13.67
20.0
13.67
</code>```

However, I actually want to make code which returns like :

```<code>13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67}
</code>```

How could I express like this ?

It would be greatly appreciated if you could explain the details !!

答:
I would suggest representing a student as a dictionary with {name, scores, average_score}. All your students would be a list of dictionaries:

```<code>students = [
    {'name': 'Ken', 'scores': [5, 8, 9], 'average_score': 0.0},
    {'name': 'Hiro', ...},
    ...
]
</code>```

Now you would iterate over them like this:

```<code>for student in students:
    # Access the attributes like this:
    print(student['name'], student['scores'])

    # calculate your average value ...

    student['average_value'] = x/count
print(students) # you can print the whole dictionary and look at the results
</code>```

With the students all in a list, it's easy to do the formatting you want -- just loop through all students and print their name and their average score in whatever order you want.

Body:
I'm a beginner for coding.
I'm struggling to make student grader which each student names would be corresponded to each grade averages and show total average score among students.
This is my code :

Ken = [5,8,9]
Hiro = [10,11,20]
Nick = [20,20,20]

list1 = [Ken,Hiro,Nick]

total_average = 0
for j in list1:
   x = 0
   count = 0
   for i in j:
       x += i
       count += 1

   average = x / count
   print (round(average,2))
   total_average += average

final_average = total_average / len(list1)
print (round(final_average,2))

and result is :

7.33
13.67
20.0
13.67

However, I actually want to make code which returns like :

13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67}

How could I express like this ?

It would be greatly appreciated if you could explain the details !!

Body:
I would suggest representing a student as a dictionary with {name, scores, average_score}. All your students would be a list of dictionaries:

students = [
    {'name': 'Ken', 'scores': [5, 8, 9], 'average_score': 0.0},
    {'name': 'Hiro', ...},
    ...
]

Now you would iterate over them like this:

for student in students:
    # Access the attributes like this:
    print(student['name'], student['scores'])

    # calculate your average value ...

    student['average_value'] = x/count
print(students) # you can print the whole dictionary and look at the results

With the students all in a list, it's easy to do the formatting you want -- just loop through all students and print their name and their average score in whatever order you want.


问:
Error Stackoverflow in android studio?
I want to make a application that show text from db file to listview but it
  shows error

These classes of my application

```<code>package com.example.dell.externalfilestoragedatabasedemo.database;

    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    /**
     * Created by dell on 4/2/2017.
     */

    public class DatabaseHelper extends SQLiteOpenHelper {

        String DB_PATH = null;
        private static String DB_NAME = "lib.db";
        private SQLiteDatabase myDatabase;
        private final Context myContext;

        public DatabaseHelper(Context context) {
            super(context, DB_NAME, null, 1);
            myContext = context;
            this.DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
            Log.e("Path 1", DB_PATH);
        }

        public void createDatabase() throws IOException {

            boolean dbExist = checkDataBase();
            if (dbExist) {

            } else {
                this.getReadableDatabase();
                try {
                    copyDatabase();
                } catch (IOException e) {
                    throw new Error("Error Copying Database");
                }
            }

        }

        private void copyDatabase() throws IOException {
            InputStream is;
            is = myContext.getAssets().open(DB_NAME);
            String outFileName = DB_PATH + DB_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte buffer[] = new byte[10];
            int length;
            while ((length = is.read(buffer)) > 0) {

                myOutput.write(buffer, 0, length);
     }
            myOutput.flush();
            myOutput.close();
            is.close();
 }
private boolean checkDataBase() {
            SQLiteDatabase checkDb = null;
            try {
                String myPath = DB_PATH + DB_NAME;
                checkDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
            } catch (SQLException e) {

            }
            if (checkDb != null) {
                checkDb.close();
            }
            return checkDb != null ? true : false;
        }
public void openDatabase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
            myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        }

        @Override
        public synchronized void close() {
            if (myDatabase != null) {
                myDatabase.close();
            }
            super.close();
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {

        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

            if (newVersion > oldVersion) {
                try {
                    copyDatabase();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public Cursor query(String table, String []columns, String selections, String []selectionArgs, String groupBy, String having, String orderBy){

            return query(table,columns,selections,selectionArgs,groupBy,having,orderBy);
        }

        public Cursor query(String sql){
            return query(sql);
        }

    }
</code>```

MainActivity is Here:

```<code>package com.example.dell.externalfilestoragedatabasedemo;

import android.database.Cursor;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.dell.externalfilestoragedatabasedemo.constantsToUse.UsefulConstants;
import com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private Cursor cousor;
    String SQl="SELECT Topic FROM TopicTable";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.listView = (ListView) findViewById(R.id.listView);
        copyDatabase();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item index
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) listView.getItemAtPosition(position);

                switch (itemValue){

                    case "Education":
                        UsefulConstants.tableConstant=01;
                        SQl="SELECT Educational_Field FROM Education";
                        break;

                    case "Story":
                        UsefulConstants.tableConstant=02;
                        break;

                    case "Health":
                        UsefulConstants.tableConstant=03;
                        break;

                    case "Competitive":
                        UsefulConstants.tableConstant=11;
                        break;

                    case "Commerce":
                        UsefulConstants.tableConstant=12;
                        break;

                    case "Biology":
                        UsefulConstants.tableConstant=13;
                        break;

                    case "Art":
                        UsefulConstants.tableConstant=14;
                        break;

                    case "Technical ":
                        UsefulConstants.tableConstant=15;
                        SQl="SELECT Technologies FROM Technical";
                        break;

                }

                // Show Alert
                Toast.makeText(getApplicationContext(),
                        "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                        .show();

            }

        });

    }

    private void copyDatabase(){
    DatabaseHelper myDb= new DatabaseHelper(this);
    try {
        myDb.createDatabase();
        UsefulConstants.databaseHelper=myDb;
    } catch (IOException e) {
        throw new Error("Unable to Create Database");
    }
    try {
        myDb.openDatabase();
    }
    catch (SQLException e){
        throw e;
    }
    Toast.makeText(this,"Success",Toast.LENGTH_LONG).show();
    showListView();

}

    private void showListView() {

        Cursor cursor=UsefulConstants.databaseHelper.query(SQl);
        if (cursor != null) {
            Toast.makeText(this, "Done", Toast.LENGTH_LONG).show();
            cursor.moveToFirst();
            String[] data = new String[cursor.getCount()];
            int i = 0;
            for (; i < cursor.getCount(); i++) {
                data[i] = cursor.getString(0);
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, android.R.id.text1, data);

            // Assign adapter to ListView
            listView.setAdapter(adapter);
        } else if (cursor == null)
            Toast.makeText(this, Boolean.toString(cursor != null), Toast.LENGTH_LONG).show();

    }

}
</code>```

It shows error :

```<code> com.example.dell.externalfilestoragedatabasedemo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.dell.externalfilestoragedatabasedemo, PID: 12227
                                                                                java.lang.StackOverflowError: stack size 8MB
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.examp
</code>```

le.dell.externalfiles

Please help me to out of this

答:
Problem in this part of code:

```<code>public Cursor query(String table, String []columns, String selections, String []selectionArgs, String groupBy, String having, String orderBy){
     return query(table,columns,selections,selectionArgs,groupBy,having,orderBy);
}
</code>```

You return from query method the same method and you have infinite recursion. You should return something else

Title: Error Stackoverflow in android studio?

Body:
I want to make a application that show text from db file to listview but it
  shows error

These classes of my application

package com.example.dell.externalfilestoragedatabasedemo.database;

    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    /**
     * Created by dell on 4/2/2017.
     */

    public class DatabaseHelper extends SQLiteOpenHelper {

        String DB_PATH = null;
        private static String DB_NAME = "lib.db";
        private SQLiteDatabase myDatabase;
        private final Context myContext;

        public DatabaseHelper(Context context) {
            super(context, DB_NAME, null, 1);
            myContext = context;
            this.DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
            Log.e("Path 1", DB_PATH);
        }

        public void createDatabase() throws IOException {

            boolean dbExist = checkDataBase();
            if (dbExist) {

            } else {
                this.getReadableDatabase();
                try {
                    copyDatabase();
                } catch (IOException e) {
                    throw new Error("Error Copying Database");
                }
            }

        }

        private void copyDatabase() throws IOException {
            InputStream is;
            is = myContext.getAssets().open(DB_NAME);
            String outFileName = DB_PATH + DB_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte buffer[] = new byte[10];
            int length;
            while ((length = is.read(buffer)) > 0) {

                myOutput.write(buffer, 0, length);
     }
            myOutput.flush();
            myOutput.close();
            is.close();
 }
private boolean checkDataBase() {
            SQLiteDatabase checkDb = null;
            try {
                String myPath = DB_PATH + DB_NAME;
                checkDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
            } catch (SQLException e) {

            }
            if (checkDb != null) {
                checkDb.close();
            }
            return checkDb != null ? true : false;
        }
public void openDatabase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
            myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        }

        @Override
        public synchronized void close() {
            if (myDatabase != null) {
                myDatabase.close();
            }
            super.close();
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {

        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

            if (newVersion > oldVersion) {
                try {
                    copyDatabase();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public Cursor query(String table, String []columns, String selections, String []selectionArgs, String groupBy, String having, String orderBy){

            return query(table,columns,selections,selectionArgs,groupBy,having,orderBy);
        }

        public Cursor query(String sql){
            return query(sql);
        }

    }

MainActivity is Here:

package com.example.dell.externalfilestoragedatabasedemo;

import android.database.Cursor;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.dell.externalfilestoragedatabasedemo.constantsToUse.UsefulConstants;
import com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private Cursor cousor;
    String SQl="SELECT Topic FROM TopicTable";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.listView = (ListView) findViewById(R.id.listView);
        copyDatabase();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item index
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) listView.getItemAtPosition(position);

                switch (itemValue){

                    case "Education":
                        UsefulConstants.tableConstant=01;
                        SQl="SELECT Educational_Field FROM Education";
                        break;

                    case "Story":
                        UsefulConstants.tableConstant=02;
                        break;

                    case "Health":
                        UsefulConstants.tableConstant=03;
                        break;

                    case "Competitive":
                        UsefulConstants.tableConstant=11;
                        break;

                    case "Commerce":
                        UsefulConstants.tableConstant=12;
                        break;

                    case "Biology":
                        UsefulConstants.tableConstant=13;
                        break;

                    case "Art":
                        UsefulConstants.tableConstant=14;
                        break;

                    case "Technical ":
                        UsefulConstants.tableConstant=15;
                        SQl="SELECT Technologies FROM Technical";
                        break;

                }

                // Show Alert
                Toast.makeText(getApplicationContext(),
                        "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                        .show();

            }

        });

    }

    private void copyDatabase(){
    DatabaseHelper myDb= new DatabaseHelper(this);
    try {
        myDb.createDatabase();
        UsefulConstants.databaseHelper=myDb;
    } catch (IOException e) {
        throw new Error("Unable to Create Database");
    }
    try {
        myDb.openDatabase();
    }
    catch (SQLException e){
        throw e;
    }
    Toast.makeText(this,"Success",Toast.LENGTH_LONG).show();
    showListView();

}

    private void showListView() {

        Cursor cursor=UsefulConstants.databaseHelper.query(SQl);
        if (cursor != null) {
            Toast.makeText(this, "Done", Toast.LENGTH_LONG).show();
            cursor.moveToFirst();
            String[] data = new String[cursor.getCount()];
            int i = 0;
            for (; i < cursor.getCount(); i++) {
                data[i] = cursor.getString(0);
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, android.R.id.text1, data);

            // Assign adapter to ListView
            listView.setAdapter(adapter);
        } else if (cursor == null)
            Toast.makeText(this, Boolean.toString(cursor != null), Toast.LENGTH_LONG).show();

    }

}

It shows error :

 com.example.dell.externalfilestoragedatabasedemo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.dell.externalfilestoragedatabasedemo, PID: 12227
                                                                                java.lang.StackOverflowError: stack size 8MB
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.example.dell.externalfilestoragedatabasedemo.database.DatabaseHelper.query(DatabaseHelper.java:120)
                                                                                at com.examp

le.dell.externalfiles

Please help me to out of this

Body:
Problem in this part of code:

public Cursor query(String table, String []columns, String selections, String []selectionArgs, String groupBy, String having, String orderBy){
     return query(table,columns,selections,selectionArgs,groupBy,having,orderBy);
}

You return from query method the same method and you have infinite recursion. You should return something else


问:
why am i getting the attribute error?
The aim of my code is for the user to enter the sentence, ask for a position and then the whole thing to be read to one/two files, ie the positions and the words.

```<code>sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positionofword=[]
words= open("words.txt","w")
position= open("position.txt","w")
question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
    sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
    sentencetext=sentence.isalpha or sentence.isspace()
    while sentencetext==False: #if letters have not been entered
        print("Only letters are allowed") #error message
        sentence=input("Please enter a sentence").upper() #asks the question again
        sentencetext=sentence.isalpha #checks if letters have been entered this time

elif question=="N":
    print("The program will now close")

else:
    print("please enter a letter")

sentence_word = sentence.split(' ')
for (i, check) in enumerate(word): #orders the words
    print(sentence)

sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
    if (check == word):
        positionofword=print(str(("your word is in this position:", i+1)))
        positionofword=i+1
        break
else:
    print("This didn't work")

words.write(word + " ")
position.write(positionofword + " ")

words.close()
position.close()
</code>```

That's my code, however I am getting this error

```<code>position.write(positionofword + " ")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

Bear in mind that the word file is empty as well.

答:
The error is that the interpreter of python is reading the type of the interger first and then the + " " part. This produces an error as the interpreter is trying to use the integer add function which does not support the addition of a string.

You have to specifically tell the python interpreter that you want to use the string addition (concatenation) function.

```<code>position.write(str(positionofword) + " ")
</code>```

Title: why am i getting the attribute error?

Body:
The aim of my code is for the user to enter the sentence, ask for a position and then the whole thing to be read to one/two files, ie the positions and the words.

sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positionofword=[]
words= open("words.txt","w")
position= open("position.txt","w")
question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
    sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
    sentencetext=sentence.isalpha or sentence.isspace()
    while sentencetext==False: #if letters have not been entered
        print("Only letters are allowed") #error message
        sentence=input("Please enter a sentence").upper() #asks the question again
        sentencetext=sentence.isalpha #checks if letters have been entered this time

elif question=="N":
    print("The program will now close")

else:
    print("please enter a letter")

sentence_word = sentence.split(' ')
for (i, check) in enumerate(word): #orders the words
    print(sentence)

sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
    if (check == word):
        positionofword=print(str(("your word is in this position:", i+1)))
        positionofword=i+1
        break
else:
    print("This didn't work")

words.write(word + " ")
position.write(positionofword + " ")

words.close()
position.close()

That's my code, however I am getting this error

position.write(positionofword + " ")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Bear in mind that the word file is empty as well.

Body:
The error is that the interpreter of python is reading the type of the interger first and then the + " " part. This produces an error as the interpreter is trying to use the integer add function which does not support the addition of a string.

You have to specifically tell the python interpreter that you want to use the string addition (concatenation) function.

position.write(str(positionofword) + " ")


答:
You code fails at position.write(positionofword + " "), as positionofword is an integer and " " is a string, and python does not support adding integers to strings directly.

Use str() to convert positionofword to string:

```<code>position.write(str(positionofword) + " ")
</code>```

Title: why am i getting the attribute error?

Body:
You code fails at position.write(positionofword + " "), as positionofword is an integer and " " is a string, and python does not support adding integers to strings directly.

Use str() to convert positionofword to string:

position.write(str(positionofword) + " ")


问:
Scheme Function that takes n and list, and return list n
I tried many ways to solve my assignment but the problem is I guess I miss something or I used something in a wrong way :

my :
solution

```<code> (define (return l)
 (cond ((null? l) '())
 ( cond (!= (mod n (car l) 0) )
 ;; here will check if not equal 0 so it is not
 return then I will     remove it from the list
 ((eq? n (car l) )
(return (cdr l)) )
 (else (cons (car l) (n (cdr l))))
  )
 (return n (cdr l) ) ;;if not return then I will keep it in the list
  )
</code>```

答:
The standard way to solve this would be to use filter, as it already does what you want:

```<code>(define (divisibleByN n lst)
  (filter (lambda (e) (zero? (modulo e n))) lst))
</code>```

If that's not an acceptable solution, we can use the standard template for traversing a list and building an output list:

```<code>(define (divisibleByN n lst)
        ; base case: if the list is empty, return the empty list
  (cond ((null? lst) '())
        ; if the current number is divisible by n
        ((zero? (modulo (car lst) n))
        ; add it to output list and advance recursion
         (cons (car lst) (divisibleByN n (cdr lst))))
        ; otherwise just advance recursion
        (else (divisibleByN n (cdr lst)))))
</code>```

Either way, it works as expected:

```<code>(divisibleByN 3 '(5 9 27 14))
=> '(9 27)
(divisibleByN 4 '(15 6))
=> '()
(divisibleByN 7 '())
=> ()
(divisibleByN 5 '(40 40 40 3 10 50))
=> '(40 40 10 50)
</code>```

Body:
I tried many ways to solve my assignment but the problem is I guess I miss something or I used something in a wrong way :

my :
solution

 (define (return l)
 (cond ((null? l) '())
 ( cond (!= (mod n (car l) 0) )
 ;; here will check if not equal 0 so it is not
 return then I will     remove it from the list
 ((eq? n (car l) )
(return (cdr l)) )
 (else (cons (car l) (n (cdr l))))
  )
 (return n (cdr l) ) ;;if not return then I will keep it in the list
  )

Body:
The standard way to solve this would be to use filter, as it already does what you want:

(define (divisibleByN n lst)
  (filter (lambda (e) (zero? (modulo e n))) lst))

If that's not an acceptable solution, we can use the standard template for traversing a list and building an output list:

(define (divisibleByN n lst)
        ; base case: if the list is empty, return the empty list
  (cond ((null? lst) '())
        ; if the current number is divisible by n
        ((zero? (modulo (car lst) n))
        ; add it to output list and advance recursion
         (cons (car lst) (divisibleByN n (cdr lst))))
        ; otherwise just advance recursion
        (else (divisibleByN n (cdr lst)))))

Either way, it works as expected:

(divisibleByN 3 '(5 9 27 14))
=> '(9 27)
(divisibleByN 4 '(15 6))
=> '()
(divisibleByN 7 '())
=> ()
(divisibleByN 5 '(40 40 40 3 10 50))
=> '(40 40 10 50)


问:
Convert File URL to Path and send to file reader in javascript
I am using cordova camera plugin for capture the picture from gallery has below my code its working,Now i need to pass the URl to file reader,when i pass it to file reader it give me error Error in success callback: Camera1358190195 = TypeError: Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob' even for 'readAsBinarystring' not working need help below is my code.

```<code> //Cordova Camera Plugin

function PicfromGallery() {
var pictureSource = navigator.camera.PictureSourceType;
var destinationType = navigator.camera.DestinationType;
navigator.camera.getPicture(onSuccessEdituserProfileGallery, onFailEditProfileGallery, {
    quality: 50,
    sourceType: pictureSource.PHOTOLIBRARY,
    destinationType: destinationType.FILE_URI,
    targetWidth: 100,
    targetHeight: 100

});
}

function onSuccessEdituserProfileGallery(imageData) {
var smallImage
smallImage = document.getElementById('userProfileImage');
//EditUserProfileImageFilename(imageData);
smallImage.src = imageData;
var userPic = document.getElementById('EdituserProfileImage');
var file = new File(imageData);
OnFileImageEntry(file)
}

//File API
function OnFileImageEntry(file) {
var reader = new FileReader();
reader.onload = function (event) {
    var image = event.target.result;
    image.onload = function () {
       // need to get result
  }
  };
reader.readAsBinaryString(file);
 }
</code>```

答:
I found a solution in cordova-plugin-camera document.

Instead of creating a File object by new File(imageData), you may resolve the FileURI with window.resolveLocalFileSystemURL().

```<code>//Cordova Camera Plugin

function PicfromGallery() {
    var pictureSource = navigator.camera.PictureSourceType;
    var destinationType = navigator.camera.DestinationType;
    navigator.camera.getPicture(onSuccessEdituserProfileGallery, onFailEditProfileGallery, {
        quality: 50,
        sourceType: pictureSource.PHOTOLIBRARY,
        destinationType: destinationType.FILE_URI,
        targetWidth: 100,
        targetHeight: 100

    });
}

function onSuccessEdituserProfileGallery(imageData) {
    var smallImage;
    smallImage = document.getElementById('userProfileImage');
    smallImage.src = imageData;
    var userPic = document.getElementById('EdituserProfileImage');
    // var file = new File(imageData);
    OnFileImageEntry(imageData);  // Use the fileURI directly.
}

//File API
function OnFileImageEntry(file) {
    window.resolveLocalFileSystemURL(i, function (fileEntry) {
        fileEntry.file(function (file) {
            console.log('Now I have a file obj.');
            var reader = new FileReader();
            reader.onloadend = function (event) {
                var image = event.target.result;
                // Do something with the image
            };
            reader.readAsArrayBuffer(file);

        }, function (e) {
            console.log('Error getting file', e);
        });
    }, function (e) {
        console.log('Error resolving fs url', e);
    });
}
</code>```

BTW, FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft.

And Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation.

More info please read this: An answer of fileReader.readAsBinaryString to upload files.

Body:
I am using cordova camera plugin for capture the picture from gallery has below my code its working,Now i need to pass the URl to file reader,when i pass it to file reader it give me error Error in success callback: Camera1358190195 = TypeError: Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob' even for 'readAsBinarystring' not working need help below is my code.

 //Cordova Camera Plugin

function PicfromGallery() {
var pictureSource = navigator.camera.PictureSourceType;
var destinationType = navigator.camera.DestinationType;
navigator.camera.getPicture(onSuccessEdituserProfileGallery, onFailEditProfileGallery, {
    quality: 50,
    sourceType: pictureSource.PHOTOLIBRARY,
    destinationType: destinationType.FILE_URI,
    targetWidth: 100,
    targetHeight: 100

});
}

function onSuccessEdituserProfileGallery(imageData) {
var smallImage
smallImage = document.getElementById('userProfileImage');
//EditUserProfileImageFilename(imageData);
smallImage.src = imageData;
var userPic = document.getElementById('EdituserProfileImage');
var file = new File(imageData);
OnFileImageEntry(file)
}

//File API
function OnFileImageEntry(file) {
var reader = new FileReader();
reader.onload = function (event) {
    var image = event.target.result;
    image.onload = function () {
       // need to get result
  }
  };
reader.readAsBinaryString(file);
 }

Body:
I found a solution in cordova-plugin-camera document.

Instead of creating a File object by new File(imageData), you may resolve the FileURI with window.resolveLocalFileSystemURL().

//Cordova Camera Plugin

function PicfromGallery() {
    var pictureSource = navigator.camera.PictureSourceType;
    var destinationType = navigator.camera.DestinationType;
    navigator.camera.getPicture(onSuccessEdituserProfileGallery, onFailEditProfileGallery, {
        quality: 50,
        sourceType: pictureSource.PHOTOLIBRARY,
        destinationType: destinationType.FILE_URI,
        targetWidth: 100,
        targetHeight: 100

    });
}

function onSuccessEdituserProfileGallery(imageData) {
    var smallImage;
    smallImage = document.getElementById('userProfileImage');
    smallImage.src = imageData;
    var userPic = document.getElementById('EdituserProfileImage');
    // var file = new File(imageData);
    OnFileImageEntry(imageData);  // Use the fileURI directly.
}

//File API
function OnFileImageEntry(file) {
    window.resolveLocalFileSystemURL(i, function (fileEntry) {
        fileEntry.file(function (file) {
            console.log('Now I have a file obj.');
            var reader = new FileReader();
            reader.onloadend = function (event) {
                var image = event.target.result;
                // Do something with the image
            };
            reader.readAsArrayBuffer(file);

        }, function (e) {
            console.log('Error getting file', e);
        });
    }, function (e) {
        console.log('Error resolving fs url', e);
    });
}

BTW, FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft.

And Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation.

More info please read this: An answer of fileReader.readAsBinaryString to upload files.


问:
can i get httpOnly cookie work with vue-resource?
work on a full spa with vue, vue-router, vue-resource, etc.
sending request with vue-resource and server will return a response with a set-cookie header, but it is a httpOnly cookie, how could I make this cookie also work with the vue-resource request?

答:
To prevent cross-site scripting (XSS) attacks, HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs.

You may refer to here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies


问:
Can each application have its own separate Java SDK
While installing WebSphere application server (WAS), WebSphere Java SDK bundled with WAS is installed at path C:\Program Files\IBM\WebSphere\AppServer\java\bin

Similarly, after installing another product, example: IBM Security Directory Server [SDS] IBM Java SDK is installed at
C:\Program Files\IBM\ldap\V6.4\java\bin (This may be at different level depending on how it is bundled with specific software)

After installing WAS and SDS, value(s) in PATH environment variable is not updated with reference pointing to bin location of java installed with either of these two applications. However, both work with respective installed version of IBM Java.

Is it possible for an application to run if java is installed within its installation directory without any reference pointing to bin location of java in PATH environment variable?

In a default scenario third party java application runs only if it finds (Oracle) Java installed and has following value (C:\ProgramData\Oracle\Java\javapath;) in PATH environment variable.

Does Oracle java need to be installed to run a third-party java application? Or updating PATH environment variable pointing to bin location of java installed with any of these two application would work?

答:
Yes, it's possible and commonplace for a program to bundle Java and make use of it without adding it your systems PATH environment variable.

It's unwise to point some third-party software at a java bundled with some other application on anything but your own workstation in a pinch. You'll never remember the dependency, the java could be customized, etc.


问:
Pointing Visual Studio 2008 to the source code of a third-party DLL for debugging
I have a VS 2008 C++ project which uses a third-party library (Open Scene Graph).

When i start debugging the project, each time a function from this external library is called, the debugger just jumps over it, because (obviously) the debugger has no .cpp files where to look up the code. It only jumps into header files which are linked to my project because those files exist and their location is known. So, i can only see what's going on in those small inline functions, but not in the bigger functions whose implementation is in .cpp files which i don't have.

I need is to somehow step thru the source code of these third-party dlls/libs the same way I do with my own code.

I downloaded the the whole source code of that library and compiled it on my machine. Now i have the dlls and libs, and the .pdb files, and the .cpp files, too. But how exactly do I tell Visual Studio the locations of the .cpp files of the third-party library, so that it knows, that when i want to step into a function coming from a .dll or a .lib it opens the corresponding .cpp file (even though it's not in my project and is located is a completely different folder)?

Is this at all possible?

I tried copying the .libs, the .dlls (debug versions), .pdbs both to the locations which my Project uses and "Additional Library Directories" and to the project's folder but this must be not enough.

答: Add the dir with the PDB files to Tools -> Options -> Debugging -> Symbols.</p>

ContentLicense: CC BY-SA 2.5


问:
Firebase Auth - with Email and Password - Check user already registered
I want to check when a user attempts to signup with createUserWithEmailAndPassword() in Firebase user Authentication method, this user is already registered with my app.

答:
As a practice of @Frank's answer here is the code of using fetchProvidersForEmail()

```<code>private boolean checkAccountEmailExistInFirebase(String email) {
                FirebaseAuth mAuth = FirebaseAuth.getInstance();
                final boolean[] b = new boolean[1];
                mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
                    @Override
                    public void onComplete(@NonNull Task<ProviderQueryResult> task) {
                        b[0] = !task.getResult().getProviders().isEmpty();
                    }
                });
                return b[0];
            }
</code>```

Body:
As a practice of @Frank's answer here is the code of using fetchProvidersForEmail()

private boolean checkAccountEmailExistInFirebase(String email) {
                FirebaseAuth mAuth = FirebaseAuth.getInstance();
                final boolean[] b = new boolean[1];
                mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
                    @Override
                    public void onComplete(@NonNull Task<ProviderQueryResult> task) {
                        b[0] = !task.getResult().getProviders().isEmpty();
                    }
                });
                return b[0];
            }


问:
Download Image From Url not Working Well C#
I want to download an image from an URL.

My class:

```<code>public class MyWebClient : WebClient
{
    public TimeSpan Timeout { get; set; }

    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest request = base.GetWebRequest(uri);
        request.Timeout = (int)Timeout.TotalMilliseconds;

        ((HttpWebRequest)request).ReadWriteTimeout = (int)Timeout.TotalMilliseconds;

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

And my method:

```<code>public void DownloadImage(string _url, string filename)
{
    try
    {
        var timeout = TimeSpan.FromMinutes(5);
        using (var webClient = new MyWebClient { Timeout = timeout })
        {
            byte[] imageData = webClient.DownloadData(_url);
            File.WriteAllBytes(filename, imageData);
        }
    }
    catch (Exception ex)
    {
    }
}
</code>```

My test:

```<code>string url = "http://wallpaperswide.com/download/a_wooden_house_forest-wallpaper-1440x900.jpg";

DownloadImage(url, @"D:\test.jpg");
</code>```

The size of the downloaded file is wrong and I cannot open the image file. I used a PictureBox control to load the image from the URL, but it's not working either.

When I use a web browser control it works.

What is my problem?

答:
It looks like this particular website from which you are trying to download expects a User-Agent header to be specified, otherwise it just returns some html instead of the image. So you could trick it into thinking that it is a browser making the request and you will get the expected image back:

```<code>webClient.Headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
var imageData = webClient.DownloadData(_url);
</code>```

Body:
I want to download an image from an URL.

My class:

public class MyWebClient : WebClient
{
    public TimeSpan Timeout { get; set; }

    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest request = base.GetWebRequest(uri);
        request.Timeout = (int)Timeout.TotalMilliseconds;

        ((HttpWebRequest)request).ReadWriteTimeout = (int)Timeout.TotalMilliseconds;

        return request;
    }
}

And my method:

public void DownloadImage(string _url, string filename)
{
    try
    {
        var timeout = TimeSpan.FromMinutes(5);
        using (var webClient = new MyWebClient { Timeout = timeout })
        {
            byte[] imageData = webClient.DownloadData(_url);
            File.WriteAllBytes(filename, imageData);
        }
    }
    catch (Exception ex)
    {
    }
}

My test:

string url = "http://wallpaperswide.com/download/a_wooden_house_forest-wallpaper-1440x900.jpg";

DownloadImage(url, @"D:\test.jpg");

The size of the downloaded file is wrong and I cannot open the image file. I used a PictureBox control to load the image from the URL, but it's not working either.

When I use a web browser control it works.

What is my problem?

Body:
It looks like this particular website from which you are trying to download expects a User-Agent header to be specified, otherwise it just returns some html instead of the image. So you could trick it into thinking that it is a browser making the request and you will get the expected image back:

webClient.Headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
var imageData = webClient.DownloadData(_url);


问:
How to wait for user to click UILabel?
I want to make a while loop wait until a user clicks on a UILabel in a Swift Playground on Xcode. How can I do this?

Here's my loop

```<code>func gameLoop() {

    while(score >= 0) {

        let n = arc4random_uniform(3)

        if(n == 0) {
            opt1.text = rightStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 1) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = rightStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 2) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = rightStatements.randomElement()
        }
    }

}
</code>```

For example, I want to wait until the user either clicks opt1, opt2, or opt3 Then do something based on what the user clicks.

答:
Use Buttons instead of Labels and assign tag = 1, 2, and 3 for buttons. Create an IBAction function for the buttons and connect all the buttons to the same function.

Make variable 'n' as global.

```<code>var n = Int()

func nextAttempt() {

    if(score >= 0) {

        n = arc4random_uniform(3)

        if(n == 0) {
            opt1.text = rightStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 1) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = rightStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 2) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = rightStatements.randomElement()
        }
    }
   else
    {
      //Score < 0
      //Game Over
    }

 }

@IBAction func onButtonClick(_ sender: Any)
{
switch(sender.tag)
   {
    case 1:
      if (n==0)
       {
         //Right button tapped
         //Update score if you want
       }
      else
       {
         self.nextAttempt()
        }
  case 2:
     if (n==1)
      {
       //Right button tapped
       //Update score if you want
      }
     else
     {
       self.nextAttempt()
     }
  case 3:
    if (n==2)
    {
       //Right button tapped
       //Update score if you want
    }
    else
    {
      self.nextAttempt()
    }
  }
}
</code>```

Hope this helps you!!

Title: How to wait for user to click UILabel?

Body:
I want to make a while loop wait until a user clicks on a UILabel in a Swift Playground on Xcode. How can I do this?

Here's my loop

func gameLoop() {

    while(score >= 0) {

        let n = arc4random_uniform(3)

        if(n == 0) {
            opt1.text = rightStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 1) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = rightStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 2) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = rightStatements.randomElement()
        }
    }

}

For example, I want to wait until the user either clicks opt1, opt2, or opt3 Then do something based on what the user clicks.

Body:
Use Buttons instead of Labels and assign tag = 1, 2, and 3 for buttons. Create an IBAction function for the buttons and connect all the buttons to the same function.

Make variable 'n' as global.

var n = Int()

func nextAttempt() {

    if(score >= 0) {

        n = arc4random_uniform(3)

        if(n == 0) {
            opt1.text = rightStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 1) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = rightStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 2) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = rightStatements.randomElement()
        }
    }
   else
    {
      //Score < 0
      //Game Over
    }

 }

@IBAction func onButtonClick(_ sender: Any)
{
switch(sender.tag)
   {
    case 1:
      if (n==0)
       {
         //Right button tapped
         //Update score if you want
       }
      else
       {
         self.nextAttempt()
        }
  case 2:
     if (n==1)
      {
       //Right button tapped
       //Update score if you want
      }
     else
     {
       self.nextAttempt()
     }
  case 3:
    if (n==2)
    {
       //Right button tapped
       //Update score if you want
    }
    else
    {
      self.nextAttempt()
    }
  }
}

Hope this helps you!!


问:
No IP information in hostvars
My Playbook:

```<code>- hosts: master
  gather_facts: True
  become: True
  tasks:
    - set_fact: headnode={{ ansible_all_ipv4_addresses[0] }}

- hosts: slave
  become: True
  tasks:
    - debug: msg={{ hostvars.master }}
</code>```

And no fact headnode there. Am I missing something? Also, hostvars.master doesn't contain ['ansible_eth0'] So is all the documentation wrong?

This doesn't work also: hostvars['master ']['ansible_eth0']['ipv4']['address']

And this: hostvars[groups['master'][0]]['ansible_eth0']

http://docs.ansible.com/ansible/playbooks_variables.html#registered-variables

hostvars.master:

```<code>ok: [slave0] => {
    "msg": {
        "ansible_check_mode": false,
        "ansible_ssh_host": "xxx.westeurope.cloudapp.azure.com",
        "ansible_ssh_port": 22,
        "ansible_ssh_private_key_file": "/root/.ssh/id_rsa",
        "ansible_ssh_user": "vagrant",
        "ansible_version": {
            "full": "2.2.2.0",
            "major": 2,
            "minor": 2,
            "revision": 2,
            "string": "2.2.2.0"
        },
        "group_names": [
            "master"
        ],
        "groups": {
            "all": [
                "master",
                "slave0"
            ],
            "master": [
                "master"
            ],
            "slave": [
                "slave0"
            ],
            "ungrouped": []
        },
        "inventory_dir": "/xxx/.vagrant/provisioners/ansible/inventory",
        "inventory_file": null,
        "inventory_hostname": "master",
        "inventory_hostname_short": "master",
        "omit": "__omit_place_holder__fb9f90a73039d94f14c1a1f0af132f1c36b9fb4a",
        "playbook_dir": "/xxx/ansible"
    }
}
</code>```

答:
The - debug: msg={{ hostvars.master }} task shows only facts available from the inventory file. It does not contain the IP address nor quite a number of other facts that should be gathered from the remote machine by the regular setup module.

Now, as you seemingly run the playbook in Vagrant provisioning, it likely runs the playbook two times, first on master only, then on slave0 only. Vagrant by default passes a --limit argument to Ansible limiting the scope to the currently-provisioned machine only.

In result, when the playbook is being executed against slave0, the first play (set to run on hosts: master) is not executed and the facts from hosts belonging to the master group (in this case from the host also named master) are not gathered.

You can either change the scope of the provisioning for the slave0 machine in Vagrantfile by setting ansible.limit = 'all'.

Or you can run ansible-playbook afterwards pointing to the Vagrant-generated inventory file.

Title: No IP information in hostvars

Body:
My Playbook:

- hosts: master
  gather_facts: True
  become: True
  tasks:
    - set_fact: headnode={{ ansible_all_ipv4_addresses[0] }}

- hosts: slave
  become: True
  tasks:
    - debug: msg={{ hostvars.master }}

And no fact headnode there. Am I missing something? Also, hostvars.master doesn't contain ['ansible_eth0'] So is all the documentation wrong?

This doesn't work also: hostvars['master ']['ansible_eth0']['ipv4']['address']

And this: hostvars[groups['master'][0]]['ansible_eth0']

http://docs.ansible.com/ansible/playbooks_variables.html#registered-variables

hostvars.master:

ok: [slave0] => {
    "msg": {
        "ansible_check_mode": false,
        "ansible_ssh_host": "xxx.westeurope.cloudapp.azure.com",
        "ansible_ssh_port": 22,
        "ansible_ssh_private_key_file": "/root/.ssh/id_rsa",
        "ansible_ssh_user": "vagrant",
        "ansible_version": {
            "full": "2.2.2.0",
            "major": 2,
            "minor": 2,
            "revision": 2,
            "string": "2.2.2.0"
        },
        "group_names": [
            "master"
        ],
        "groups": {
            "all": [
                "master",
                "slave0"
            ],
            "master": [
                "master"
            ],
            "slave": [
                "slave0"
            ],
            "ungrouped": []
        },
        "inventory_dir": "/xxx/.vagrant/provisioners/ansible/inventory",
        "inventory_file": null,
        "inventory_hostname": "master",
        "inventory_hostname_short": "master",
        "omit": "__omit_place_holder__fb9f90a73039d94f14c1a1f0af132f1c36b9fb4a",
        "playbook_dir": "/xxx/ansible"
    }
}


问:
Custom ToolStripItem
I need to add a set of custom ToolStripItem (containing the additional property formReference) to a ToolStripPanel but they won't appear for some reason.

Code for adding the items:

```<code>foreach (Form form in Application.OpenForms)
if (form.Name != "MainForm")
{
    myToolStripItem mtsi = new myToolStripItem(form.Text, null, open_form);
    mtsi.formReference = form;
    tspTaskBar.Items.Add(mtsi);
}
</code>```

myToolStripItem:

```<code>public class myToolStripItem : ToolStripItem
{
    public object formReference { get; set; }

    public myToolStripItem(string text, System.Drawing.Image image, EventHandler onClick)
        : base(text,image,onClick) { }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
    }
}
</code>```

Can you please point me to what I'm doing wrong? Thank you.

答: I think the problem might be that ToolStripPanel is a panel for ToolStrips and a ToolStrip is the actual place where you put ToolStripItems.  Try putting a ToolStrip inside your ToolStripPanel and putting your custom ToolStripItem into that ToolStrip.

Title: Custom ToolStripItem

Body:
I need to add a set of custom ToolStripItem (containing the additional property formReference) to a ToolStripPanel but they won't appear for some reason.

Code for adding the items:

foreach (Form form in Application.OpenForms)
if (form.Name != "MainForm")
{
    myToolStripItem mtsi = new myToolStripItem(form.Text, null, open_form);
    mtsi.formReference = form;
    tspTaskBar.Items.Add(mtsi);
}

myToolStripItem:

public class myToolStripItem : ToolStripItem
{
    public object formReference { get; set; }

    public myToolStripItem(string text, System.Drawing.Image image, EventHandler onClick)
        : base(text,image,onClick) { }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
    }
}

Can you please point me to what I'm doing wrong? Thank you.


问:
PhantomJS unexpectedly exits on Selenium : WebDriverException with status code 127
I am using a global PhantomJS on my Mac OS X for multiple Javascript and Python selenium projects. For the first time, I set up a virtual environnement using virtualenv :

```<code>virtualenv Python3.5 Path/To/MyEnvironnement
</code>```

Then :

```<code>Path/To/MyEnvironnement
. bin/activate
which phantomjs
</code>```

... returns my global selenium : /Users/Me/.npm-packages/bin/phantomjs

But every time I call :

```<code>driver = webdriver.PhantomJS(executable_path=r'/Users/Me/.npm-packages/bin/phantomjs')
</code>```

I get this error :

```<code>Traceback (most recent call last):
File "/Path/To/MyEnvironnement/script/spider/crawl/Urls.py", line 194, in <module>
init_driver()
File "/Path/To/MyEnvironnement/script/spider/crawl/Urls.py", line 29, in init_driver
driver = webdriver.PhantomJS(executable_path=r'/Users/Me/.npm-packages/bin/phantomjs')
File "/Path/To/MyEnvironnement/lib/python3.5/site-packages/selenium/webdriver/phantomjs/webdriver.py", line 52, in __init__
self.service.start()
File "/Path/To/MyEnvironnement/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 86, in start
self.assert_process_still_running()
File "/Path/To/MyEnvironnement/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 99, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service /Users/Me/.npm-packages/bin/phantomjs unexpectedly exited. Status code was: 127
</code>```

It's been 24 hours since I first got this issue, and I read virtually all posts that could refer to it.

I tried, without success, to create a nodeenv inside my virtualenv : running phantomjs inside python virtualenv for selenium project

答:
I guess its too late, but for future reference I've solved this issue by:

```<code>sudo apt-get install libfontconfig
</code>```

The answer was found here:

Trouble connecting to phantomJs webdriver using python and selenium

Body:
I am using a global PhantomJS on my Mac OS X for multiple Javascript and Python selenium projects. For the first time, I set up a virtual environnement using virtualenv :

virtualenv Python3.5 Path/To/MyEnvironnement

Then :

Path/To/MyEnvironnement
. bin/activate
which phantomjs

... returns my global selenium : /Users/Me/.npm-packages/bin/phantomjs

But every time I call :

driver = webdriver.PhantomJS(executable_path=r'/Users/Me/.npm-packages/bin/phantomjs')

I get this error :

Traceback (most recent call last):
File "/Path/To/MyEnvironnement/script/spider/crawl/Urls.py", line 194, in <module>
init_driver()
File "/Path/To/MyEnvironnement/script/spider/crawl/Urls.py", line 29, in init_driver
driver = webdriver.PhantomJS(executable_path=r'/Users/Me/.npm-packages/bin/phantomjs')
File "/Path/To/MyEnvironnement/lib/python3.5/site-packages/selenium/webdriver/phantomjs/webdriver.py", line 52, in __init__
self.service.start()
File "/Path/To/MyEnvironnement/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 86, in start
self.assert_process_still_running()
File "/Path/To/MyEnvironnement/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 99, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service /Users/Me/.npm-packages/bin/phantomjs unexpectedly exited. Status code was: 127

It's been 24 hours since I first got this issue, and I read virtually all posts that could refer to it.

I tried, without success, to create a nodeenv inside my virtualenv : running phantomjs inside python virtualenv for selenium project

Body:
I guess its too late, but for future reference I've solved this issue by:

sudo apt-get install libfontconfig

The answer was found here:

Trouble connecting to phantomJs webdriver using python and selenium