问:
cursor initialization error: column value is always -1 in content providers
This is the error I am getting
    FATAL EXCEPTION: main

```<code>Process: com.example.yaamu.survey_contentprovider, PID: 17250

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yaamu.survey_contentprovider/com.example.yaamu.survey_contentprovider.Database_Activitry}: java.lang.IllegalStateException: Couldn't read row 3, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                Caused by: java.lang.IllegalStateException: Couldn't read row 3, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                                at android.database.CursorWindow.nativeGetString(Native Method)
                                                                                at android.database.CursorWindow.getString(CursorWindow.java:438)
                                                                                at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
                                                                                at android.database.CursorWrapper.getString(CursorWrapper.java:137)
                                                                                at com.example.yaamu.survey_contentprovider.Database_Activitry.onCreate(Database_Activitry.java:33)
                                                                                at android.app.Activity.performCreate(Activity.java:6679)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

This is the attribute set
      /**************DATABASE TABLE
      COLUMNS*****************************************/

```<code> public static final String TABLE_DATABASE = "database_table";
public static final String COLUMN_DB_QUEST_ID = "question_question_id";
public static final String COLUMN_DB_SURVEYID = " survey_id";
public static final String COLUMN_QUESTION = " question_ques";
public static final String COLUMN_TYPE_OF_ANSWER = "type_of_answer";
public static final String COLUMN_IS_VALIDATION = "is_validation";
public static final String COLUMN_ANSWER_TYPE_FILTER = "answer_type_filter";
public static final String COLUMN_IS_REQUIRED = "is_required";
public static final String COLUMN_IS_SHUFFLE = "is_shuffle";
public static final String COLUMN_LINEAR_MIN_VALUE = "linear_min_value";
public static final String COLUMN_LINEAR_MAX_VALUE = "linear_max_value";
public static final String COLUMN_LINEAR_MIN_LABEL = "linear_min_label";
public static final String COLUMN_LINEAR_MAX_LABEL = "linear_max_label";
public static final String COLUMN_RATING_VALUE = "rating_value";
/**********************************************************************************************/
</code>```

And the table is created.

```<code>  private static final String DATABASE_TABLE_CREATE = " create table "
        + TABLE_DATABASE + "("
        + COLUMN_DB_QUEST_ID + " integer primary key autoincrement, "
        + COLUMN_DB_SURVEYID + " integer not null, "
        + COLUMN_QUESTION + " text not null, "
        + COLUMN_TYPE_OF_ANSWER + " text not null, "
        + COLUMN_IS_VALIDATION + " boolean, "
        + COLUMN_ANSWER_TYPE_FILTER + " text, "
        + COLUMN_IS_REQUIRED + " boolean not null,"
        + COLUMN_IS_SHUFFLE + " boolean, "
        + COLUMN_LINEAR_MIN_VALUE + " integer, "
        + COLUMN_LINEAR_MAX_VALUE + " integer, "
        + COLUMN_LINEAR_MIN_LABEL + " text,"
        + COLUMN_LINEAR_MAX_LABEL + " text, "
        + COLUMN_RATING_VALUE + " integer );";
</code>```

The values are been added. It is shown in toast message but I am not able to retrieve the values

I have used another activity to retrieve the values

```<code>   Cursor c=getContentResolver().query(SurveyContentProvider.CONTENT_URI3, null, null, null, SurveyContentProvider.COLUMN_DB_QUEST_ID);
    if(c!=null & c.getCount()>0)
    {
        c.moveToFirst();
        while(c.moveToNext()){
            text1.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_DB_QUEST_ID)));
            text2.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_DB_SURVEYID)));
            text3.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_QUESTION)));
            text4.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_TYPE_OF_ANSWER)));
            text5.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_IS_VALIDATION)));
            text6.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_ANSWER_TYPE_FILTER)));
            text7.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_IS_REQUIRED)));
            text8.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_IS_SHUFFLE)));
            text9.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_LINEAR_MIN_VALUE)));
            text10.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_LINEAR_MAX_VALUE)));
            text11.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_LINEAR_MIN_LABEL)));
            text12.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_LINEAR_MAX_LABEL)));
            text13.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_RATING_VALUE)));
        }
    }
</code>```

THANK YOU

答:
It was just because of an space which was initialized while defining the column attributes COLUMN_DB_SURVEYID and COLUMN_QUESTION.
Thanks for your kind replies!</p>

Body:
This is the error I am getting
    FATAL EXCEPTION: main

Process: com.example.yaamu.survey_contentprovider, PID: 17250

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yaamu.survey_contentprovider/com.example.yaamu.survey_contentprovider.Database_Activitry}: java.lang.IllegalStateException: Couldn't read row 3, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                Caused by: java.lang.IllegalStateException: Couldn't read row 3, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                                at android.database.CursorWindow.nativeGetString(Native Method)
                                                                                at android.database.CursorWindow.getString(CursorWindow.java:438)
                                                                                at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
                                                                                at android.database.CursorWrapper.getString(CursorWrapper.java:137)
                                                                                at com.example.yaamu.survey_contentprovider.Database_Activitry.onCreate(Database_Activitry.java:33)
                                                                                at android.app.Activity.performCreate(Activity.java:6679)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

This is the attribute set
      /**************DATABASE TABLE
      COLUMNS*****************************************/

 public static final String TABLE_DATABASE = "database_table";
public static final String COLUMN_DB_QUEST_ID = "question_question_id";
public static final String COLUMN_DB_SURVEYID = " survey_id";
public static final String COLUMN_QUESTION = " question_ques";
public static final String COLUMN_TYPE_OF_ANSWER = "type_of_answer";
public static final String COLUMN_IS_VALIDATION = "is_validation";
public static final String COLUMN_ANSWER_TYPE_FILTER = "answer_type_filter";
public static final String COLUMN_IS_REQUIRED = "is_required";
public static final String COLUMN_IS_SHUFFLE = "is_shuffle";
public static final String COLUMN_LINEAR_MIN_VALUE = "linear_min_value";
public static final String COLUMN_LINEAR_MAX_VALUE = "linear_max_value";
public static final String COLUMN_LINEAR_MIN_LABEL = "linear_min_label";
public static final String COLUMN_LINEAR_MAX_LABEL = "linear_max_label";
public static final String COLUMN_RATING_VALUE = "rating_value";
/**********************************************************************************************/

And the table is created.

  private static final String DATABASE_TABLE_CREATE = " create table "
        + TABLE_DATABASE + "("
        + COLUMN_DB_QUEST_ID + " integer primary key autoincrement, "
        + COLUMN_DB_SURVEYID + " integer not null, "
        + COLUMN_QUESTION + " text not null, "
        + COLUMN_TYPE_OF_ANSWER + " text not null, "
        + COLUMN_IS_VALIDATION + " boolean, "
        + COLUMN_ANSWER_TYPE_FILTER + " text, "
        + COLUMN_IS_REQUIRED + " boolean not null,"
        + COLUMN_IS_SHUFFLE + " boolean, "
        + COLUMN_LINEAR_MIN_VALUE + " integer, "
        + COLUMN_LINEAR_MAX_VALUE + " integer, "
        + COLUMN_LINEAR_MIN_LABEL + " text,"
        + COLUMN_LINEAR_MAX_LABEL + " text, "
        + COLUMN_RATING_VALUE + " integer );";

The values are been added. It is shown in toast message but I am not able to retrieve the values

I have used another activity to retrieve the values

   Cursor c=getContentResolver().query(SurveyContentProvider.CONTENT_URI3, null, null, null, SurveyContentProvider.COLUMN_DB_QUEST_ID);
    if(c!=null & c.getCount()>0)
    {
        c.moveToFirst();
        while(c.moveToNext()){
            text1.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_DB_QUEST_ID)));
            text2.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_DB_SURVEYID)));
            text3.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_QUESTION)));
            text4.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_TYPE_OF_ANSWER)));
            text5.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_IS_VALIDATION)));
            text6.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_ANSWER_TYPE_FILTER)));
            text7.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_IS_REQUIRED)));
            text8.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_IS_SHUFFLE)));
            text9.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_LINEAR_MIN_VALUE)));
            text10.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_LINEAR_MAX_VALUE)));
            text11.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_LINEAR_MIN_LABEL)));
            text12.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_LINEAR_MAX_LABEL)));
            text13.setText(c.getString(c.getColumnIndex(SurveyContentProvider.COLUMN_RATING_VALUE)));
        }
    }

THANK YOU


来源: stackexchange

问:
Tuple and List to formatted string in python
In Python3.4 I have a tuple

```<code>t = ('A', 'B', 'C')
</code>```

and a list

```<code>l = ['P', 'Q', 'R']
</code>```

and I need to convert the tuple to a string formatted as "(#A;#B;#C)" and the list to a string formatted as "(@P; @Q; @R)". The obvious way is to traverse using a for loop and string manipulation.

Is there a way to do it without running the loop?

Thanks!

答:
If not using a loop is the case, another approach can be to convert them to string and use replace method of string, as follows

```<code>str(t).replace("', '", ";#").replace("('", "(#").replace("')", ")")

str(l).replace("', '", '; @').replace("['", "(@").replace("']", ")")
</code>```

If there are only three elements, you can replace them individually as well.

ContentLicense: CC BY-SA 3.0

Body:
In Python3.4 I have a tuple

t = ('A', 'B', 'C')

and a list

l = ['P', 'Q', 'R']

and I need to convert the tuple to a string formatted as "(#A;#B;#C)" and the list to a string formatted as "(@P; @Q; @R)". The obvious way is to traverse using a for loop and string manipulation.

Is there a way to do it without running the loop?

Thanks!

Body:
If not using a loop is the case, another approach can be to convert them to string and use replace method of string, as follows

str(t).replace("', '", ";#").replace("('", "(#").replace("')", ")")

str(l).replace("', '", '; @').replace("['", "(@").replace("']", ")")

If there are only three elements, you can replace them individually as well.


问:
AngularJS : How to send files via websocket?
I am new to websocket and I have been assigned an existing working chat module which, for now, just sends messages to other users. I have been asked to integrate feature where a user can send "attachments" to each other. FYI, I came across this link which says few point but I need more clarity.

My questions:

What is the server-side requirement there for its implementation?

Can someone provide a little elaborated answer? More codes rather than words are highly appreciated.

Do I need to use use ng-file-upload for the same, DEMO

Any relevant link for this question

UPDATE 1:

I tried implementing below code:

```<code>var input = document.querySelector('input[type=file]');

function readFile(event) {
    var ws_msg =  {content: event.target.result };
    // Here I call the ws.send method
    send_chat_message($scope.sender, $scope.receiver , ws_msg );
}

function changeFile() {
    var file = input.files[0];
    var reader = new FileReader();
    reader.addEventListener('load', readFile);
    reader.readAsText(file);
}

input.addEventListener('change', changeFile);
</code>```

Selecting a file automatically tries to send it over ws but for some weird reason, the WS connection is getting closed immediately.

答:
I have tried below sample code. I have used https://github.com/websockets/ws for web-socket server. and in HTML/jS I have modified code like below works fine. Steps are below. (Hope you have node installed).

Create a folder and do a npm install --save ws

Create a server.js file and add below code.

```<code>        const WebSocket = require('ws');

        const wss = new WebSocket.Server({ port: 8080 });

        wss.on('connection', function connection(ws) {
          ws.on('message', function incoming(message) {
            console.log('received: %s', message);
          });

          ws.send('something');
        });
</code>```

run node server using node server.js, your websocket server is up on localhost:8080

In your browser js change code as below (you are using angular do the change accordingly later as per your requirement)

```<code>            var input = document.querySelector('input[type=file]');
        var socket = new WebSocket('ws://localhost:8080');

            socket.addEventListener('open', function (event) {
                socket.send('Hello Server!');
            });

        function readFile(event) {
            var ws_msg =  {content: event.target.result };
            socket.send(ws_msg);
            // Here I call the ws.send method
            //send_chat_message($scope.sender, $scope.receiver , ws_msg );
        }

        function changeFile() {
            var file = input.files[0];
            var reader = new FileReader();
            reader.addEventListener('load', readFile);
            reader.readAsText(file);
        }

        input.addEventListener('change', changeFile);
</code>```

load your JS/HTML and upload a file you should see to console logs in your node server console.

UPDATE:

you can update your node js server code:

```<code>            const WebSocket = require('ws');
            const fs = require('fs');

            const wss = new WebSocket.Server({ port: 8080 });

            wss.on('connection', function connection(ws) {
              ws.on('message', function incoming(message) {
                let data =  new Buffer(message);
                    fs.writeFile('new.png', data, 'binary', function (err) {
                        if (err) {
                            console.log("error")
                        }
                        else {
                            console.log("done")
                        }
                    });
              });
</code>```

Reference: Create image from ArrayBuffer in Nodejs

```<code>              ws.send('something');
            });
</code>```

And client(browser side js) code as:

```<code>            var input = document.querySelector('input[type=file]');
            var socket = new WebSocket('ws://localhost:8080');

                socket.addEventListener('open', function (event) {
                    socket.send('Hello Server!');
                });

            function readFile(e) {
                //var ws_msg =  {content: event.target.result };
                 var rawData = e.target.result;
                 socket.send(rawData);
                // Here I call the ws.send method
                //send_chat_message($scope.sender, $scope.receiver , ws_msg );
            }

            function changeFile() {
                var file = input.files[0];
                var reader = new FileReader();
                reader.addEventListener('load', readFile);
                reader.readAsArrayBuffer(file);
            }

            input.addEventListener('change', changeFile);
</code>```

Body:
I am new to websocket and I have been assigned an existing working chat module which, for now, just sends messages to other users. I have been asked to integrate feature where a user can send "attachments" to each other. FYI, I came across this link which says few point but I need more clarity.

My questions:

What is the server-side requirement there for its implementation?

Can someone provide a little elaborated answer? More codes rather than words are highly appreciated.

Do I need to use use ng-file-upload for the same, DEMO

Any relevant link for this question

UPDATE 1:

I tried implementing below code:

var input = document.querySelector('input[type=file]');

function readFile(event) {
    var ws_msg =  {content: event.target.result };
    // Here I call the ws.send method
    send_chat_message($scope.sender, $scope.receiver , ws_msg );
}

function changeFile() {
    var file = input.files[0];
    var reader = new FileReader();
    reader.addEventListener('load', readFile);
    reader.readAsText(file);
}

input.addEventListener('change', changeFile);

Selecting a file automatically tries to send it over ws but for some weird reason, the WS connection is getting closed immediately.

Body:
I have tried below sample code. I have used https://github.com/websockets/ws for web-socket server. and in HTML/jS I have modified code like below works fine. Steps are below. (Hope you have node installed).

Create a folder and do a npm install --save ws

Create a server.js file and add below code.

        const WebSocket = require('ws');

        const wss = new WebSocket.Server({ port: 8080 });

        wss.on('connection', function connection(ws) {
          ws.on('message', function incoming(message) {
            console.log('received: %s', message);
          });

          ws.send('something');
        });

run node server using node server.js, your websocket server is up on localhost:8080

In your browser js change code as below (you are using angular do the change accordingly later as per your requirement)

            var input = document.querySelector('input[type=file]');
        var socket = new WebSocket('ws://localhost:8080');

            socket.addEventListener('open', function (event) {
                socket.send('Hello Server!');
            });

        function readFile(event) {
            var ws_msg =  {content: event.target.result };
            socket.send(ws_msg);
            // Here I call the ws.send method
            //send_chat_message($scope.sender, $scope.receiver , ws_msg );
        }

        function changeFile() {
            var file = input.files[0];
            var reader = new FileReader();
            reader.addEventListener('load', readFile);
            reader.readAsText(file);
        }

        input.addEventListener('change', changeFile);

load your JS/HTML and upload a file you should see to console logs in your node server console.

UPDATE:

you can update your node js server code:

            const WebSocket = require('ws');
            const fs = require('fs');

            const wss = new WebSocket.Server({ port: 8080 });

            wss.on('connection', function connection(ws) {
              ws.on('message', function incoming(message) {
                let data =  new Buffer(message);
                    fs.writeFile('new.png', data, 'binary', function (err) {
                        if (err) {
                            console.log("error")
                        }
                        else {
                            console.log("done")
                        }
                    });
              });

Reference: Create image from ArrayBuffer in Nodejs

              ws.send('something');
            });

And client(browser side js) code as:

            var input = document.querySelector('input[type=file]');
            var socket = new WebSocket('ws://localhost:8080');

                socket.addEventListener('open', function (event) {
                    socket.send('Hello Server!');
                });

            function readFile(e) {
                //var ws_msg =  {content: event.target.result };
                 var rawData = e.target.result;
                 socket.send(rawData);
                // Here I call the ws.send method
                //send_chat_message($scope.sender, $scope.receiver , ws_msg );
            }

            function changeFile() {
                var file = input.files[0];
                var reader = new FileReader();
                reader.addEventListener('load', readFile);
                reader.readAsArrayBuffer(file);
            }

            input.addEventListener('change', changeFile);


问:
Group 2d array by column value and concatenate values within each group
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.

```<code>$new_arr = [
    [
        'name' => 'Jambi Selatan',
        'code' => '36139',
        'code_name' => '36139 - Jambi Selatan'
    ],
    [
        'name' => 'Jambi Selatan',
        'code' => '36137',
        'code_name' => '36137 - Jambi Selatan'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36129',
        'code_name' => '36129 - Bagan Pete'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36127',
        'code_name' => '36127 - Bagan Pete'
    ]
];
</code>```

I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.

```<code>Array (
    [0] => Array
        (
            [name] => Jambi Selatan
            [code] => 36139, 36137
            [code_name] => 36139, 36139 - Jambi Selatan
        )

    [1] => Array
        (
            [name] => Bagan Pete
            [code] => 36127, 36129
            [code_name] => 36127, 36129 - Bagan Pete
        )
)
</code>```

I try this method, but not fix at 'code_name'

```<code>$out = array();
foreach ($new_arr as $key => $value){
    if (array_key_exists($value['name'], $out)){
        $out[$value['name']]['code'] .= ', '.$value['code'];
    } else {
        $out[$value['name']] = array(
            'name' => $value['name'],
            'code' => $value['code'],
            'code_name' => $value['code'] . ' - ' . $value['name']
        );
    }
}
$out = array_values($out);
</code>```

print_r($out);

答:
You have to check duplicate name by in_array and update exist array value .If not exist insert that value to $out array .

```<code>$out = array();
foreach($new_arr as $k=>$v) {
    //empty array state
    if(count($out) == 0) {
        $out[] = $v;
        continue;
    }
    foreach ($out as $key => $value) {
        if(in_array($v["name"],$value)) {
            $out[$key]["code"] .= ",".$v["code"];
            //for the code_name output as OP described
            $nn = explode("-", $value["code_name"]);
            $l = count($nn) - 1;
            unset($nn[$l]);
            $out[$key]["code_name"] = implode($nn).",".$v["code_name"];
            break;
        } else {
            if((count($out)-1) == $key) {
                $out[] = $v;
            }
        }
    }
}
var_dump($out);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.

$new_arr = [
    [
        'name' => 'Jambi Selatan',
        'code' => '36139',
        'code_name' => '36139 - Jambi Selatan'
    ],
    [
        'name' => 'Jambi Selatan',
        'code' => '36137',
        'code_name' => '36137 - Jambi Selatan'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36129',
        'code_name' => '36129 - Bagan Pete'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36127',
        'code_name' => '36127 - Bagan Pete'
    ]
];

I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.

Array (
    [0] => Array
        (
            [name] => Jambi Selatan
            [code] => 36139, 36137
            [code_name] => 36139, 36139 - Jambi Selatan
        )

    [1] => Array
        (
            [name] => Bagan Pete
            [code] => 36127, 36129
            [code_name] => 36127, 36129 - Bagan Pete
        )
)

I try this method, but not fix at 'code_name'

$out = array();
foreach ($new_arr as $key => $value){
    if (array_key_exists($value['name'], $out)){
        $out[$value['name']]['code'] .= ', '.$value['code'];
    } else {
        $out[$value['name']] = array(
            'name' => $value['name'],
            'code' => $value['code'],
            'code_name' => $value['code'] . ' - ' . $value['name']
        );
    }
}
$out = array_values($out);

print_r($out);

Body:
You have to check duplicate name by in_array and update exist array value .If not exist insert that value to $out array .

$out = array();
foreach($new_arr as $k=>$v) {
    //empty array state
    if(count($out) == 0) {
        $out[] = $v;
        continue;
    }
    foreach ($out as $key => $value) {
        if(in_array($v["name"],$value)) {
            $out[$key]["code"] .= ",".$v["code"];
            //for the code_name output as OP described
            $nn = explode("-", $value["code_name"]);
            $l = count($nn) - 1;
            unset($nn[$l]);
            $out[$key]["code_name"] = implode($nn).",".$v["code_name"];
            break;
        } else {
            if((count($out)-1) == $key) {
                $out[] = $v;
            }
        }
    }
}
var_dump($out);


问:
backpack for laravel get last id
I'm using laravel's backpack CRUD and
 I have a pivot table called equipment_parameter where i'm trying to save the last id from the parent equipment table.
 how do i get the last equipment ID to save it in Equipment_parameter pivot table ?

```<code>    public function store(StoreRequest $request)
{
    $response= parent::storeCrud();

    // $id = $response->lastInsertId(); <-- doesn't work

    $user = EquipoParametro::create([
        'equipo_id' => Input::get("equipo_id"), <-- this works sometimes)
        'parametro_id' => Input::get("parametros")
    ]);

    return $response;
}
</code>```

Equipment model

```<code>   public function parametros(){

   return $this->belongsToMany('App\Parametro','equipo_parametro','equipo_id','parametro_id')->withTimestamps();
}
</code>```

答:
If you're looking for the ID of the entry you've just inserted, I should be able to use $this->crud->entry->id:

```<code>public function store(StoreRequest $request)
{
    $response= parent::storeCrud();

    $id = $this->crud->entry->id; // <-- SHOULD WORK

    $user = EquipoParametro::create([
        'equipo_id' => $id,
        'parametro_id' => Input::get("parametros")
    ]);

    return $response;
}
</code>```

Title: backpack for laravel get last id

Body:
I'm using laravel's backpack CRUD and
 I have a pivot table called equipment_parameter where i'm trying to save the last id from the parent equipment table.
 how do i get the last equipment ID to save it in Equipment_parameter pivot table ?

    public function store(StoreRequest $request)
{
    $response= parent::storeCrud();

    // $id = $response->lastInsertId(); <-- doesn't work

    $user = EquipoParametro::create([
        'equipo_id' => Input::get("equipo_id"), <-- this works sometimes)
        'parametro_id' => Input::get("parametros")
    ]);

    return $response;
}

Equipment model

   public function parametros(){

   return $this->belongsToMany('App\Parametro','equipo_parametro','equipo_id','parametro_id')->withTimestamps();
}

Body:
If you're looking for the ID of the entry you've just inserted, I should be able to use $this->crud->entry->id:

public function store(StoreRequest $request)
{
    $response= parent::storeCrud();

    $id = $this->crud->entry->id; // <-- SHOULD WORK

    $user = EquipoParametro::create([
        'equipo_id' => $id,
        'parametro_id' => Input::get("parametros")
    ]);

    return $response;
}


问:
Box with multiple borders
I am trying to code and style a box which will contain a post. My problem is with multiple borders (i guess), trying to find the best way to code this, i prefer semantic HTML5 and CSS3, but if there is no other way, i can do "old style" with 3 divs (top, center, bottom) with css background: url..., can anyone give me some lights please?

If you please check the following url, you can check what i need to accomplish.

http://dl.dropbox.com/u/3696224/postBox.jpg

If you notice it has:

one border around all the box with a dark gray (#cccccc); (border)

a small space between that border and other light gray (#f7f7f7), almost white;

and only then the content with a white background;

Any suggestions? Very sorry for English grammar, thanks in advance.

Regards

PS - I almost forgot, i don't know is if needed or not, but the all around the box i have a box-shadow (i know how to do this part)

答:
You only need 2 different
 elements; one for each border that you want.

HTML

```<code><div class="outer">
    <div class="inner">
        CONTENT
    </div>
</div>
</code>```

CSS

```<code>/* colors sampled from image linked in OP */

.outer {
    border: 1px solid #C8C8C8;
    box-shadow: 3px 3px 4px #000;
}

.inner {
    background-color: #FFF;
    border: 5px solid #F8F8F8;
    color: #595959;
    padding: 50px;
    text-align: center;
}
</code>```

z0mg demo →

ContentLicense: CC BY-SA 2.5

Title: Box with multiple borders

Body:
You only need 2 different <div> elements; one for each border that you want.

HTML

<div class="outer">
    <div class="inner">
        CONTENT
    </div>
</div>

CSS

/* colors sampled from image linked in OP */

.outer {
    border: 1px solid #C8C8C8;
    box-shadow: 3px 3px 4px #000;
}

.inner {
    background-color: #FFF;
    border: 5px solid #F8F8F8;
    color: #595959;
    padding: 50px;
    text-align: center;
}

z0mg demo →


问:
Passing data through Angular2 router
I have a component where I select a set of image objects. I want to pass these selected images to my new route, CreateAlbum. The data it nested and wouldn't be suitable to pass as URL parameters.

Is there any easy way to achieve this?

Here's my code to navigate to the route

```<code>  public gotoCreateAlbum(): void {
    this.router.navigate([('/create-album')])
  }
</code>```

My selected data sits in this variable

```<code>@Input() selectedPhotos: IPhoto[];
</code>```

and this is my routing module

```<code>const routes: Routes = [
  { path: 'photos',  component: PhotosComponent},
  { path: 'photos/:filter', component: PhotosComponent},
  { path: 'create-album', component: CreateAlbumComponent}
];
</code>```

Basically I want to perform the same operations as if the CreateAlbum component was a child to my current component in which case I would have used @Input()

答:
```<code>this.router.navigate(['path', { flag: "1"}]);
</code>```

Title: Passing data through Angular2 router

Body:
I have a component where I select a set of image objects. I want to pass these selected images to my new route, CreateAlbum. The data it nested and wouldn't be suitable to pass as URL parameters.

Is there any easy way to achieve this?

Here's my code to navigate to the route

  public gotoCreateAlbum(): void {
    this.router.navigate([('/create-album')])
  }

My selected data sits in this variable

@Input() selectedPhotos: IPhoto[];

and this is my routing module

const routes: Routes = [
  { path: 'photos',  component: PhotosComponent},
  { path: 'photos/:filter', component: PhotosComponent},
  { path: 'create-album', component: CreateAlbumComponent}
];

Basically I want to perform the same operations as if the CreateAlbum component was a child to my current component in which case I would have used @Input()


问:
How to load heavy data?
I am getting 5000 list of user and their details from server and am trying to show those records . Records are displayed but am seeing continues loading.. and after loading am not able to do anything. Is there any solution to load 5000 records without loading and crashing? </p>

答:
The problem with loading 5000 records isn't (only) that you're receiving a lot of data, but that Angular has to process all that in the digest cycle. I'll bet that if you do a profiling in the browser, you'll find most of the CPU time is spend in the digest loop.

To avoid that you have to only allow a limited number of DOM elements on the page at a time. As suggested, one way of doing this is using paging.

Another way, where you still load your 5000 records, is to use a concept called virtual repeat/scroll, where you have a directive that only shows the elements that can fit in your viewport (i.e. on the users screen) and then whenever the user scrolls, the directive adds more elements below, while removing elements that goes out of view. This can be done seamless and can have a huge impact on performance.

Virtual repeat/scroll can be a difficult task to create on your own, but fortunately there are several different implementations available. I have experience with Angular Virtual Scroll ngRepeat directive but there are others out there that work just as well.

Title: How to load heavy data?


问:
Automate mysql table entry
I want to insert mysql data table values from a excel file , in php.I googled a lot for it and none of them worked .
The excel table is like this:
The excel file which i want to upload it to mysql</p>

答:
I would suggest save the file in csv format and upload using "Load data infile"

check the mysql documentation here

```<code>CREATE TABLE sample
(
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
   rollno INT,
   admnno INT,
   name varchar(50),
   dob Date,
   classid INT,
   guardian varchar(50),
   contactno INT
);

LOAD DATA INFILE '/tmp/sample.csv'
INTO TABLE sample
   FIELDS TERMINATED BY ','
   OPTIONALLY ENCLOSED BY '"'
LINES  TERMINATED BY '\n'
</code>```

Title: Automate mysql table entry

Body:
I would suggest save the file in csv format and upload using "Load data infile"

check the mysql documentation here

CREATE TABLE sample
(
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
   rollno INT,
   admnno INT,
   name varchar(50),
   dob Date,
   classid INT,
   guardian varchar(50),
   contactno INT
);

LOAD DATA INFILE '/tmp/sample.csv'
INTO TABLE sample
   FIELDS TERMINATED BY ','
   OPTIONALLY ENCLOSED BY '"'
LINES  TERMINATED BY '\n'


问:
Deleting xib files causes "NSInternalInconsistencyException, reason: 'Could not load NIB in bundle: "
When I deleted xib files for my view controllers, I got this error: "Could not load NIB in bundle...with name 'LibraryViewController'". I referenced this question.

Things I have already done:

Deleted app from simulator

Deleted derived data

Cleaned build folder

Restarted my computer

Attempted to clean the contents of /var/folders. However, I could not delete the folders 8k, gf, and zz inside /var/folders because they are required by Mac OS.

Is there any way I can delete my unused xib files without crashing my app?

Update:

```<code> override func viewDidLoad() {
      libraryTable.register(UINib(nibName: "categoriesTableViewCell", bundle: nil), forCellReuseIdentifier: "categoriesTableViewCell")
 }

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0  {
        let cell = tableView.dequeueReusableCell(withIdentifier: "categoriesTableViewCell", for: indexPath) as! categoriesTableViewCell
        return cell
    } else {
        let cell = songTableViewCell()
        return cell
    }
}
</code>```

答:
Replace the code where you register the cell (you now want created in code rather than the .xib/storyboard), as follows:

```<code>libraryTable.register(UITableViewCell.self, forCellReuseIdentifier: "categoriesTableViewCell")
</code>```

The line you show above registers the nib, so when it's time to create a cell you've told it its in a certain nib file.  The replacement line creates a default cell programmatically, which means you need to make any modifications to it using swift code rather than the GUI approach which InterfaceBuilder provides. It is very straightforward.

Body:
When I deleted xib files for my view controllers, I got this error: "Could not load NIB in bundle...with name 'LibraryViewController'". I referenced this question.

Things I have already done:

Deleted app from simulator

Deleted derived data

Cleaned build folder

Restarted my computer

Attempted to clean the contents of /var/folders. However, I could not delete the folders 8k, gf, and zz inside /var/folders because they are required by Mac OS.

Is there any way I can delete my unused xib files without crashing my app?

Update:

 override func viewDidLoad() {
      libraryTable.register(UINib(nibName: "categoriesTableViewCell", bundle: nil), forCellReuseIdentifier: "categoriesTableViewCell")
 }

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0  {
        let cell = tableView.dequeueReusableCell(withIdentifier: "categoriesTableViewCell", for: indexPath) as! categoriesTableViewCell
        return cell
    } else {
        let cell = songTableViewCell()
        return cell
    }
}

Body:
Replace the code where you register the cell (you now want created in code rather than the .xib/storyboard), as follows:

libraryTable.register(UITableViewCell.self, forCellReuseIdentifier: "categoriesTableViewCell")

The line you show above registers the nib, so when it's time to create a cell you've told it its in a certain nib file.  The replacement line creates a default cell programmatically, which means you need to make any modifications to it using swift code rather than the GUI approach which InterfaceBuilder provides. It is very straightforward.


问:
Can't load page in Spring MVC
I want to add a page in my spring MVC. I can call the index file but I can't click on the link in index.jsp to show page product.jsp. Its error message is "The requested resource is not available".

Below is my controller code:

```<code>@RequestMapping({"/", "/index"})
public String index(ModelMap model, HttpSession session, Principal principal) throws Exception {
    return "index";
}

@RequestMapping({"/product"})
public String product(ModelMap model, HttpSession session, Principal principal) throws Exception {
    return "product";
}
</code>```

this index.jsp

```<code><div class="row">
   <div class="col-sm-4 menu-img-pad">
       <ul class="multi-column-dropdown">
          <li><a href="../product.jsp">Joggers</a></li>
          <li><a href="../product.jsp">Foot Ball</a></li>
          <li><a href="../product.jsp">Cricket</a></li>
       </ul>
   </div>
</div>
</code>```

答:
You need to define a ViewResolver in order to let spring how to find your views.

Have a look here. In your case an InternalResourceViewResolver would work.

An then -- in order to call your handler -- your link should look point to /product as you defined the path in your @RequestMapping method

Title: Can't load page in Spring MVC

Body:
I want to add a page in my spring MVC. I can call the index file but I can't click on the link in index.jsp to show page product.jsp. Its error message is "The requested resource is not available".

Below is my controller code:

@RequestMapping({"/", "/index"})
public String index(ModelMap model, HttpSession session, Principal principal) throws Exception {
    return "index";
}

@RequestMapping({"/product"})
public String product(ModelMap model, HttpSession session, Principal principal) throws Exception {
    return "product";
}

this index.jsp

Joggers

Foot Ball

Cricket


问:
Array of two types
I have two arrays :

```<code>Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)
</code>```

How to combine both as:

```<code>Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)
</code>```

Thanks -
Haan

答:
I think you may want to try:
$secondArray[i]['day'] = $firstArray[i]; </p>

Title: Array of two types

Body:
I have two arrays :

Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)

How to combine both as:

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)

Thanks -
Haan


问:
Android layouts for different screen sizes
I am struggling for layouts for an Android app. I have defined different layouts for different screen sizes and the current layout directory structure is something like this:

layout

layout-land

layout-small

layout-xlarge

layout-xlarge-land

Problem

The main layout directory files are being displayed for 3.7 to 7.0 which is a very broad range. And text overlap on small screens and if I adjust on small; it becomes very tiny on the large screen.

According to me, the layout small files should be rendered for smaller screens but those files are only rendered for android wear devices.

layout-xlarge seems to work for Nexus 9 to Nexus 10

I want to know, how can I define the different layout for 3.7-5.0 and 5.0-7.0 screen sizes.

答: you should try dp in your layout-height/layout-width/textsize as it is independent of screen sizes.</p>


问:
How to send Push Notification from device when the receiver device is not in foreground state using FCM in android?
I have created a one to one chat using FCM. I have stuck at one point, I want to send push notification when the device is not in foreground state. I am new to this can anyone suggest me how can I proceed.
Thankyou</p>

答:
You can try this bellow code in MyFirebaseMessagingService class:</p>

```<code> if (remoteMessage.getData() != null && remoteMessage.getData().size() > 0) {
            Log.d("TAGRK", "Message data payload: " + remoteMessage.getData());

            message = "" + remoteMessage.getData().get(Config.MESSAGE_KEY);//MESSAGE_KEY is your key for message in your json.(eg. "message")
            title = "" + remoteMessage.getData().get(Config.TITLE_KEY);//TITLE_KEY is your key for title in your json..(eg. "title")
            //send pushnoification method
        } else if (remoteMessage.getNotification() != null) {
            Log.d("TAGRK", "Message Notification Body: " + remoteMessage.getNotification().getBody());
            message = "" + remoteMessage.getNotification().getBody();
            title = "" + remoteMessage.getNotification().getTitle();
             //send pushnoification method
        }
</code>```

Body:
You can try this bellow code in MyFirebaseMessagingService class:

 if (remoteMessage.getData() != null && remoteMessage.getData().size() > 0) {
            Log.d("TAGRK", "Message data payload: " + remoteMessage.getData());

            message = "" + remoteMessage.getData().get(Config.MESSAGE_KEY);//MESSAGE_KEY is your key for message in your json.(eg. "message")
            title = "" + remoteMessage.getData().get(Config.TITLE_KEY);//TITLE_KEY is your key for title in your json..(eg. "title")
            //send pushnoification method
        } else if (remoteMessage.getNotification() != null) {
            Log.d("TAGRK", "Message Notification Body: " + remoteMessage.getNotification().getBody());
            message = "" + remoteMessage.getNotification().getBody();
            title = "" + remoteMessage.getNotification().getTitle();
             //send pushnoification method
        }


问:
How to customize Acrylic brush
I want to paint Stack Panel surface using Acrylic brush.

```<code><StackPanel Background="{ThemeResource SystemControlAcrylicElementBrush}"></StackPanel>
</code>```

It works for me but there is a problem when I want to change Tint color and opacity. There is a following code to change it:

```<code><ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
    <AcrylicBrush x:Key="MyAcrylicBrush"
        BackgroundSource="HostBackdrop"
        TintColor="#FFFF0000"
        TintOpacity="0.8"
        FallbackColor="#FF7F0000"/>
</ResourceDictionary>
</code>```

I don't know where should I place it and rename brush for this?

```<code> <StackPanel Background="{ThemeResource **MyAcrylicBrush**}"></StackPanel>
</code>```

Thanks for help.
P.S. You need Windows Insider SDK and system build 16190 or higher

答:
Method 1:

Add ResourceDictionary.ThemeDictionaries in Application.Resources

In App.xaml

```<code><Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Default">
                <AcrylicBrush x:Key="MyAcrylicBrush" BackgroundSource="HostBackdrop" TintColor="#FFFF0000" TintOpacity="0.8" FallbackColor="#FF7F0000"/>
            </ResourceDictionary>

            <ResourceDictionary x:Key="HighContrast">
                <SolidColorBrush x:Key="MyAcrylicBrush" Color="{ThemeResource SystemColorWindowColor}"/>
            </ResourceDictionary>

            <ResourceDictionary x:Key="Light">
                <AcrylicBrush x:Key="MyAcrylicBrush" BackgroundSource="HostBackdrop" TintColor="#FFFF0000" TintOpacity="0.8" FallbackColor="#FFFF7F7F"/>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Application.Resources>
</code>```

Method 2:

As @jsmyth886 answered

Add a separate ResourceDictionary file and place your ResourceDictionary.ThemeDictionaries code

```<code><ResourceDictionary.ThemeDictionaries>
    <ResourceDictionary x:Key="Default">
        <AcrylicBrush x:Key="MyAcrylicBrush" BackgroundSource="HostBackdrop" TintColor="#FFFF0000" TintOpacity="0.8" FallbackColor="#FF7F0000"/>
    </ResourceDictionary>

    <ResourceDictionary x:Key="HighContrast">
        <SolidColorBrush x:Key="MyAcrylicBrush" Color="{ThemeResource SystemColorWindowColor}"/>
    </ResourceDictionary>

    <ResourceDictionary x:Key="Light">
        <AcrylicBrush x:Key="MyAcrylicBrush" BackgroundSource="HostBackdrop" TintColor="#FFFF0000" TintOpacity="0.8" FallbackColor="#FFFF7F7F"/>
    </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</code>```

You MergedDictionaries in App.xaml to Merged your ResourceDictionary file

```<code><Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
</code>```

For more Info: ResourceDictionary and XAML resource references, XAML for Windows 10 Controls - Styling

Title: How to customize Acrylic brush

Body:
I want to paint Stack Panel surface using Acrylic brush.

<StackPanel Background="{ThemeResource SystemControlAcrylicElementBrush}"></StackPanel>

It works for me but there is a problem when I want to change Tint color and opacity. There is a following code to change it:

<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
    <AcrylicBrush x:Key="MyAcrylicBrush"
        BackgroundSource="HostBackdrop"
        TintColor="#FFFF0000"
        TintOpacity="0.8"
        FallbackColor="#FF7F0000"/>
</ResourceDictionary>

I don't know where should I place it and rename brush for this?

 <StackPanel Background="{ThemeResource **MyAcrylicBrush**}"></StackPanel>

Thanks for help.
P.S. You need Windows Insider SDK and system build 16190 or higher

Body:
Method 1:

Add ResourceDictionary.ThemeDictionaries in Application.Resources

In App.xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Default">
                <AcrylicBrush x:Key="MyAcrylicBrush" BackgroundSource="HostBackdrop" TintColor="#FFFF0000" TintOpacity="0.8" FallbackColor="#FF7F0000"/>
            </ResourceDictionary>

            <ResourceDictionary x:Key="HighContrast">
                <SolidColorBrush x:Key="MyAcrylicBrush" Color="{ThemeResource SystemColorWindowColor}"/>
            </ResourceDictionary>

            <ResourceDictionary x:Key="Light">
                <AcrylicBrush x:Key="MyAcrylicBrush" BackgroundSource="HostBackdrop" TintColor="#FFFF0000" TintOpacity="0.8" FallbackColor="#FFFF7F7F"/>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Application.Resources>

Method 2:

As @jsmyth886 answered

Add a separate ResourceDictionary file and place your ResourceDictionary.ThemeDictionaries code

<ResourceDictionary.ThemeDictionaries>
    <ResourceDictionary x:Key="Default">
        <AcrylicBrush x:Key="MyAcrylicBrush" BackgroundSource="HostBackdrop" TintColor="#FFFF0000" TintOpacity="0.8" FallbackColor="#FF7F0000"/>
    </ResourceDictionary>

    <ResourceDictionary x:Key="HighContrast">
        <SolidColorBrush x:Key="MyAcrylicBrush" Color="{ThemeResource SystemColorWindowColor}"/>
    </ResourceDictionary>

    <ResourceDictionary x:Key="Light">
        <AcrylicBrush x:Key="MyAcrylicBrush" BackgroundSource="HostBackdrop" TintColor="#FFFF0000" TintOpacity="0.8" FallbackColor="#FFFF7F7F"/>
    </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>

You MergedDictionaries in App.xaml to Merged your ResourceDictionary file

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

For more Info: ResourceDictionary and XAML resource references, XAML for Windows 10 Controls - Styling


问:
How to Align a div in Center When Contents added Dynamically
Please have a look at this Image.

Here I was use the Bootstrap for aligning the divs. And created only one div. The Contents are added in this div dynamically from the admin side. then it will loop the div. That's Working fine.

But here you can see only 6 Contents are available. So 2 Divs are aligned in the left. I need these div should align in the middle of the Page. If the Contents are 7 or 5 the Second row Contents should be in the Middle. How to align these Divs Middle. Please Help me to Solve this Problem.

Here Is My Code..

{{ service['name'] }}

{{ str_limit(service['description'], 100) }}

                Read More

Thank you in Advance.

答: You can use bootstrap to set an offset for each div dynamically depending on your div's desired position or set the margin of the divs to auto. See this post for a detailed explanation.</p>


问:
Scrollify function not being found even when script is imported
So I'm trying to use Scrollify, which is a jQuery plugin for scroll snapping. I have jQuery imported no problem, but no matter how I import the plugin itself, I get the error:

```<code>Uncaught TypeError: $.scrollify is not a function
</code>```

I have the plugin script loading after jQuery itself loads, and the configuration code after both of those load, even to the point where I put the plugin's script tag and configuration code at the very end of the page before .

I've tried hosting the plugin script locally, and I tried using a CDN. Both gave the same issue.

I've had these sort of issues with other scripts and they always were due to the loading order, but I'm stumped here. Any help?

答:
Try to use it this way</p>

```<code>jQuery(document).ready(function($) {

    $.scrollify({
       ...
    });

});
</code>```

Body:
So I'm trying to use Scrollify, which is a jQuery plugin for scroll snapping. I have jQuery imported no problem, but no matter how I import the plugin itself, I get the error:

Uncaught TypeError: $.scrollify is not a function

I have the plugin script loading after jQuery itself loads, and the configuration code after both of those load, even to the point where I put the plugin's script tag and configuration code at the very end of the page before .

I've tried hosting the plugin script locally, and I tried using a CDN. Both gave the same issue.

I've had these sort of issues with other scripts and they always were due to the loading order, but I'm stumped here. Any help?

Body:
Try to use it this way

jQuery(document).ready(function($) {

    $.scrollify({
       ...
    });

});


问:
How to get Json object values inside array in angular using ng-repeat
I have a array of JSON objects like below:

```<code> todoList:
      [ { todo: 'dummy1', id: 595b9c2bb4b9992a4041d6e3 },
      { todo: 'dummy2', id: 595e4ffc62e38e3844f8d43a },
      { todo: 'dummy3', id: 595e4fff62e38e3844f8d43b },
      { todo: 'dummy4', id: 595f00c1d18df61840ad1ba3 } ]
</code>```

I want to use the todo field in my view using ng-repeat like below

```<code><div ng-repeat ="todo in todoList">
  <label>
     {{ todo }}
   </label>
 </div>
</code>```

Can you please tell me the way in which I can access only todo field from the todo List?

答:
Use {{todo.todo}}

```<code><div ng-repeat ="todo in todoList">
  <label>
     {{ todo.todo}}
   </label>
 </div>
</code>```

DEMO

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope, $http) {
 $scope.todoList=
      [ { todo: 'dummy1', id: "595b9c2bb4b9992a4041d6e3" },
      { todo: 'dummy2', id: "595e4ffc62e38e3844f8d43a" },
      { todo: 'dummy3', id: "595e4fff62e38e3844f8d43b" },
      { todo: 'dummy4', id: "595f00c1d18df61840ad1ba3" } ];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <div ng-app="myApp" ng-controller="AppCtrl">
 <div ng-repeat ="todo in todoList">
  <label>
     {{ todo.todo }}
   </label>
 </div>
  </div>
</body>

</html></code>```

Body:
I have a array of JSON objects like below:

 todoList:
      [ { todo: 'dummy1', id: 595b9c2bb4b9992a4041d6e3 },
      { todo: 'dummy2', id: 595e4ffc62e38e3844f8d43a },
      { todo: 'dummy3', id: 595e4fff62e38e3844f8d43b },
      { todo: 'dummy4', id: 595f00c1d18df61840ad1ba3 } ]

I want to use the todo field in my view using ng-repeat like below

     {{ todo }}

Can you please tell me the way in which I can access only todo field from the todo List?

Body:
Use {{todo.todo}}

<div ng-repeat ="todo in todoList">
  <label>
     {{ todo.todo}}
   </label>
 </div>

DEMO

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope, $http) {
 $scope.todoList=
      [ { todo: 'dummy1', id: "595b9c2bb4b9992a4041d6e3" },
      { todo: 'dummy2', id: "595e4ffc62e38e3844f8d43a" },
      { todo: 'dummy3', id: "595e4fff62e38e3844f8d43b" },
      { todo: 'dummy4', id: "595f00c1d18df61840ad1ba3" } ];
});

<!DOCTYPE html>
<html>
<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <div ng-app="myApp" ng-controller="AppCtrl">
 <div ng-repeat ="todo in todoList">
  <label>
     {{ todo.todo }}
   </label>
 </div>
  </div>
</body>

</html>


问:
How to create a control-flow graph with Soot?
For a while I have been struggling with creating a control-flow graph with Soot and I kinda got lost in its tutorials. Rather than using Soot as an Eclipse plugin, I have been trying to use Soot as a library or API.

What I want to do is, I have a bunch of Java projects and I want to create/generate a control-flow graph of these projects. I also saw that there is a feature in Soot that I can generate control-flow graphs in "DOT" format, which is quite acceptable for me as well.

Any guide or sample of code that shows how to create/generate a control-flow graph with Soot would be great!

答:
You can create a method-local CFG by just creating a new ExceptionalUnitGraph, passing it the method's SootBody. The Soot Tutorial in the wiki shows you how to do that.

To get an inter-procedural CFG, i.e., an ICFG, you can use the Soot extension Heros:
https://github.com/Sable/heros/blob/develop/src/heros/InterproceduralCFG.java


问:
Check all $_POST Variable at once
instead of checking all my post variables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like</p>

```<code>if(!isset(ALL $_POST)){
echo "one of your fields is not completed.";
}
</code>```

答:
Can't be done like the way you're thinking (as PHP has no way of knowing what values there should be).

But you could it like this:

```<code><?php
  $POSTvaluesToCheck = array('write', 'here', 'all', 'the', 'values', 'that', 'are', 'mandatory', 'to', 'exist');

  foreach($POSTvaluesToCheck as $key) {
    if(!isset($_POST[$key]) {
      echo $key . ' not set correctly!';
    }
  }
?>
</code>```

Title: Check all $_POST Variable at once

Body:
instead of checking all my post variables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like

if(!isset(ALL $_POST)){
echo "one of your fields is not completed.";
}

Body:
Can't be done like the way you're thinking (as PHP has no way of knowing what values there should be).

But you could it like this:

<?php
  $POSTvaluesToCheck = array('write', 'here', 'all', 'the', 'values', 'that', 'are', 'mandatory', 'to', 'exist');

  foreach($POSTvaluesToCheck as $key) {
    if(!isset($_POST[$key]) {
      echo $key . ' not set correctly!';
    }
  }
?>


问:
Having troubles pushing into an array which is a property of an object
I have this array called "players" which stores all the players, each element of this array contains each individual player stored as an object, and this player object contains a property called "time" which in it of itself is an array. When ever I try to push an integer into this time array, I get a "time.push() is not a function" error.

```<code>players[data.num].time.push(uptime());
</code>```

what I am attempting here is array[index].array.push()

This array is undefined and is declared like this.time = [];
The player objects were made by constructor function as well.

Here are the other arrays I mentioned before;

```<code>var players = [];
players.push(new Player(0,0,true));
</code>```

Player() is a constructor function that contains this.time = [];

Any help is appreciated.

答:
Very stupid mistake.

```<code>this.time = [];
</code>```

and just a few lines later...

```<code>this.time = 0;
</code>```

I created the former this.time = 0; for animation, I forgot about it when making this array and as you know, you cannot push into and int variable.

Sorry for causing all the trouble...

Body:
I have this array called "players" which stores all the players, each element of this array contains each individual player stored as an object, and this player object contains a property called "time" which in it of itself is an array. When ever I try to push an integer into this time array, I get a "time.push() is not a function" error.

players[data.num].time.push(uptime());

what I am attempting here is array[index].array.push()

This array is undefined and is declared like this.time = [];
The player objects were made by constructor function as well.

Here are the other arrays I mentioned before;

var players = [];
players.push(new Player(0,0,true));

Player() is a constructor function that contains this.time = [];

Any help is appreciated.

Body:
Very stupid mistake.

this.time = [];

and just a few lines later...

this.time = 0;

I created the former this.time = 0; for animation, I forgot about it when making this array and as you know, you cannot push into and int variable.

Sorry for causing all the trouble...


答:
You can use

```<code><div ng-repeat ="todo in todoList">
  <label>
     {{ todo.todo }}
   </label>
  <label>
     {{ todo.id}}
   </label>
 </div>
</code>```

If you want to debug, You can use json filter to print json object.

```<code><div ng-repeat ="todo in todoList">
  <label>
     {{ todo|json}}
   </label>
 </div>
</code>```

Title: How to get Json object values inside array in angular using ng-repeat

Body:
You can use

<div ng-repeat ="todo in todoList">
  <label>
     {{ todo.todo }}
   </label>
  <label>
     {{ todo.id}}
   </label>
 </div>

If you want to debug, You can use json filter to print json object.

<div ng-repeat ="todo in todoList">
  <label>
     {{ todo|json}}
   </label>
 </div>


问:
Coded UI test - how to programmatically set a Select Option
I'm writing some coded UI tests to automate testing of some webpages. I've chosen to write the code by hand rather than record a manual testing session.

I can modify controls on the page, for example an input box:

```<code>var edit = new HtmlEdit(browser);
edit.SearchProperties.Add(HtmlEdit.PropertyNames.Id, id);
edit.Text = value;
</code>```

or click on a button:

```<code>var btn = new HtmlInputButton(browser);
btn.SearchProperties.Add(HtmlInputButton.PropertyNames.ValueAttribute, "Enter");
Mouse.Click(btn);
</code>```

I can't work out how to set the value of a dropdown, e.g.

```<code>var select = new HtmlControl(browser);
select.SearchProperties.Add(HtmlControl.PropertyNames.Id, "Country");
select.????
</code>```

the ValueAttribute is read only.

Any ideas?

答:
Use an HtmlComboBox instead. HtmlControl is generic and has limited properties.

```<code>HtmlComboBox combox = new HtmlComboBox(browser);
combox.SearchProperties.Add(HtmlControl.PropertyNames.Id, "Country");

//Select by Index
combox.SelectedIndex = 0;
//Select by ITem
combox.SelectedItem = "India";
</code>```

Body:
I'm writing some coded UI tests to automate testing of some webpages. I've chosen to write the code by hand rather than record a manual testing session.

I can modify controls on the page, for example an input box:

var edit = new HtmlEdit(browser);
edit.SearchProperties.Add(HtmlEdit.PropertyNames.Id, id);
edit.Text = value;

or click on a button:

var btn = new HtmlInputButton(browser);
btn.SearchProperties.Add(HtmlInputButton.PropertyNames.ValueAttribute, "Enter");
Mouse.Click(btn);

I can't work out how to set the value of a dropdown, e.g.

var select = new HtmlControl(browser);
select.SearchProperties.Add(HtmlControl.PropertyNames.Id, "Country");
select.????

the ValueAttribute is read only.

Any ideas?

Body:
Use an HtmlComboBox instead. HtmlControl is generic and has limited properties.

HtmlComboBox combox = new HtmlComboBox(browser);
combox.SearchProperties.Add(HtmlControl.PropertyNames.Id, "Country");

//Select by Index
combox.SelectedIndex = 0;
//Select by ITem
combox.SelectedItem = "India";


问:
How to P/Invoke getaddrinfo in Linux using Mono
I'm having problems with the structs and linked list when trying to use getaddrinfo from libc like this:

```<code>[DllImport("libc.so.6")]
private static extern int getaddrinfo(string node, string service,
                       addrinfo hints,
                       addrinfo res);
</code>```

How can I make the missing addrinfo (and sockaddr inside addrinfo). addrinfo is a linked list by the way. I'm guessing I have to [MarshalAs] but I have no idea how to do that.

If you are thinking of suggesting Dns.GetHostEntry, take a look at this post. It's the reson why I plan to invoke getaddrinfo from libc.

答:
Answering my own question.

The short answer is “Don’t do it!” :-)

The reason is that getaddrinfo creates a linked list on the heap (the res pointer) and that needs to be freed.

It can be done however, with a disposable wrapper (adapter pattern), but it’s most likely to cause the same issues as Dns.GetHostEntry as described in the post linked in the question.

Body:
I'm having problems with the structs and linked list when trying to use getaddrinfo from libc like this:

[DllImport("libc.so.6")]
private static extern int getaddrinfo(string node, string service,
                       addrinfo hints,
                       addrinfo res);

How can I make the missing addrinfo (and sockaddr inside addrinfo). addrinfo is a linked list by the way. I'm guessing I have to [MarshalAs] but I have no idea how to do that.

If you are thinking of suggesting Dns.GetHostEntry, take a look at this post. It's the reson why I plan to invoke getaddrinfo from libc.


问:
jQuery form serializeObject
I have a form with fields and a list of another object with items. But with jQuery $("form").serializeObject(), it is not creating the right object like here:

```<code>var functionViewModel = new Object();
functionViewModel.Id = 1;
functionViewModel.Name = "F-I-001";
functionViewModel.Localised = [];
functionViewModel.Localised.push({

  LocalisedId: '1|1',
  Subject: "F-N-001"
});

functionViewModel.CategoryViewModel = new Object();
functionViewModel.CategoryViewModel.CategoryInGroup = [];
functionViewModel.CategoryViewModel.CategoryInGroup.push({
  Id: '1'
})
</code>```

Any ideas?

答:
Before sending data to server you need to stringify() the object. At the server you need to parse() it.

Use JSON.stringify() to convert object to string. Use

JSON.parse() to convert JSON object from string.

var functionViewModel = new Object();
functionViewModel.Id = 1;
functionViewModel.Name = "F-I-001";
functionViewModel.Localised = [];
functionViewModel.Localised.push({

  LocalisedId: '1|1',
  Subject: "F-N-001"
});

functionViewModel.CategoryViewModel = new Object();
functionViewModel.CategoryViewModel.CategoryInGroup = [];
functionViewModel.CategoryViewModel.CategoryInGroup.push({
  Id: '1'
})

var str = JSON.stringify(functionViewModel)
var obj = JSON.parse(str);
console.log(str);
console.log(obj);```
</div>
</div>
</p>

<p>To send it to server. Use </p>

```$.post(
  url: url, //Url of your server
  data: JSON.stringify(obj), //data you want to send to server
  function(data, status) {
    alert("Success");
});
```

As pointed by Heena, you can use param()

You need to serialize/convert the object to a string before submitting it. You can use $.param() for this.

$('#form').val($.param(functionViewModel));

Title: jQuery form serializeObject

Body:
I have a form with fields and a list of another object with items. But with jQuery $("form").serializeObject(), it is not creating the right object like here:

var functionViewModel = new Object();
functionViewModel.Id = 1;
functionViewModel.Name = "F-I-001";
functionViewModel.Localised = [];
functionViewModel.Localised.push({

  LocalisedId: '1|1',
  Subject: "F-N-001"
});

functionViewModel.CategoryViewModel = new Object();
functionViewModel.CategoryViewModel.CategoryInGroup = [];
functionViewModel.CategoryViewModel.CategoryInGroup.push({
  Id: '1'
})

Any ideas?

Body:
Before sending data to server you need to stringify() the object. At the server you need to parse() it.

Use JSON.stringify() to convert object to string. Use

JSON.parse() to convert JSON object from string.

var functionViewModel = new Object();
functionViewModel.Id = 1;
functionViewModel.Name = "F-I-001";
functionViewModel.Localised = [];
functionViewModel.Localised.push({

  LocalisedId: '1|1',
  Subject: "F-N-001"
});

functionViewModel.CategoryViewModel = new Object();
functionViewModel.CategoryViewModel.CategoryInGroup = [];
functionViewModel.CategoryViewModel.CategoryInGroup.push({
  Id: '1'
})

var str = JSON.stringify(functionViewModel)
var obj = JSON.parse(str);
console.log(str);
console.log(obj);

To send it to server. Use

$.post(
  url: url, //Url of your server
  data: JSON.stringify(obj), //data you want to send to server
  function(data, status) {
    alert("Success");
});

As pointed by Heena, you can use param()

You need to serialize/convert the object to a string before submitting it. You can use $.param() for this.

$('#form').val($.param(functionViewModel));


问:
AnnotationAwareAspectJAutoProxyCreator is only available on Java 1.5 and higher
I have a project that is runing on eclipse but when i make "java -jar" it gives this error:

```<code> Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [Beans.xml]; nested
 java.lang.IllegalStateException: AnnotationAwareAspectJAutoProxyCreator is only available on Java 1.5 and higher
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:420)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:113)
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:80)
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
        at pt.myCompany.myProduct.integrator.Integrator.init(Integrator.java:27)
        at pt.myCompany.myProduct.integrator.jobs.RequstSentToProvider.execute(RequstSentToProvider.java:24)
        at pt.myCompany.integrador.jobSchedule.RunRequstSentToProvider.main(RunRequstSentToProvider.java:10)
Caused by: java.lang.IllegalStateException: AnnotationAwareAspectJAutoProxyCreator is only available on Java 1.5 and higher
        at org.springframework.aop.config.AopConfigUtils.getAspectJAnnotationAutoProxyCreatorClassIfPossible(AopConfigUtils.java:134)
        at org.springframework.aop.config.AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(AopConfigUtils.java:99)
        at org.springframework.aop.config.AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(AopNamespaceUtils.java:71)
        at org.springframework.aop.config.AspectJAutoProxyBeanDefinitionParser.parse(AspectJAutoProxyBeanDefinitionParser.java:41)
        at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:69)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1297)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1287)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
        ... 16 more
</code>```

When I make "java -version" the output is:

```<code>java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
</code>```

What am I doing wrong?

答: I also got exact same error. What I noticed that when I set JAVA_HOME system variable to JDK version 1.8 I got the error mentioned by Jp Felgueiras and by switching to JDK version 1.7 my code works, so looks like there is some issue with old version of spring code, and this may well be because of the code is spring core org.springframework.core.JdkVersion.java, this code deals with JDK version 1.4(default), 1.5, 1.6 and 1.7. This means if your java version is not 1.5, 1.6 or 1.7 then it will be treated as 1.4 so you get the error suggesting to user java version of 1.5 or higher. Hope this will help anyone stumble upon this question </p>

Body:
I have a project that is runing on eclipse but when i make "java -jar" it gives this error:

 Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [Beans.xml]; nested
 java.lang.IllegalStateException: AnnotationAwareAspectJAutoProxyCreator is only available on Java 1.5 and higher
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:420)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:113)
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:80)
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
        at pt.myCompany.myProduct.integrator.Integrator.init(Integrator.java:27)
        at pt.myCompany.myProduct.integrator.jobs.RequstSentToProvider.execute(RequstSentToProvider.java:24)
        at pt.myCompany.integrador.jobSchedule.RunRequstSentToProvider.main(RunRequstSentToProvider.java:10)
Caused by: java.lang.IllegalStateException: AnnotationAwareAspectJAutoProxyCreator is only available on Java 1.5 and higher
        at org.springframework.aop.config.AopConfigUtils.getAspectJAnnotationAutoProxyCreatorClassIfPossible(AopConfigUtils.java:134)
        at org.springframework.aop.config.AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(AopConfigUtils.java:99)
        at org.springframework.aop.config.AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(AopNamespaceUtils.java:71)
        at org.springframework.aop.config.AspectJAutoProxyBeanDefinitionParser.parse(AspectJAutoProxyBeanDefinitionParser.java:41)
        at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:69)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1297)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1287)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
        ... 16 more

When I make "java -version" the output is:

java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)

What am I doing wrong?


问:
Function kepps after return ( Recursion C)
This is my code:

```<code>int Binary (int* arr, unsigned int size, int num)
{

    if (0 == size)
    {
        return -1;
    }
    if (1 == size)
    {
        if (arr[0] == num)
        {
            return 0;
        }
        return -1;
    }

    size/= 2;
    if (num == arr[size])
    {
        return size;
    }
    else
    {
        if (num < arr[size])
        {
            Binary (arr, size, num);
        }
        else
        {
            Binary (&arr[size+1], size, num);
        }
    }

    return -1;
}
</code>```

It doesn't work.
When I debug it (trying to search a number that appears in an array), I see that it goes into the line of 'return size', which it should do (side question- is there a way to put line numbers in the code..) but then it keeps going to the last line and returns -1.
How come I have a return and it doesn't go out of the function?
I first tried not to put any return in the end because I am not supposed to reach to the end, but the compiler says "control reaches end of non-void function" so I added the last return, but obviously it is not the right thing to do..

Thanks

答:
Replaced recursive call to:

```<code>  return Binary (arr, size, num);
//^^^^^^
</code>```

Currently, you are just calling the function and ignoring the return value.

but then it keeps going to the last line and returns -1.

It is actually the parent going into return -1

Body:
This is my code:

int Binary (int* arr, unsigned int size, int num)
{

    if (0 == size)
    {
        return -1;
    }
    if (1 == size)
    {
        if (arr[0] == num)
        {
            return 0;
        }
        return -1;
    }

    size/= 2;
    if (num == arr[size])
    {
        return size;
    }
    else
    {
        if (num < arr[size])
        {
            Binary (arr, size, num);
        }
        else
        {
            Binary (&arr[size+1], size, num);
        }
    }

    return -1;
}

It doesn't work.
When I debug it (trying to search a number that appears in an array), I see that it goes into the line of 'return size', which it should do (side question- is there a way to put line numbers in the code..) but then it keeps going to the last line and returns -1.
How come I have a return and it doesn't go out of the function?
I first tried not to put any return in the end because I am not supposed to reach to the end, but the compiler says "control reaches end of non-void function" so I added the last return, but obviously it is not the right thing to do..

Thanks

Body:
Replaced recursive call to:

  return Binary (arr, size, num);
//^^^^^^

Currently, you are just calling the function and ignoring the return value.

but then it keeps going to the last line and returns -1.

It is actually the parent going into return -1


问:
Valgrind memory leak with linked lists
When I run my program with valgrind I notice I only have a small memory leak (2 blocks) when I implement this function. This removes the node and when the list is printed out the node no longer appears.

```<code>car *removeCar(car *head, char *targetModel) {

car *temp=head;
car *temp2=head->next;

if(strcmp(temp->model,targetModel)==0) {
    return head;
}

while(temp2!=NULL) {
    if(strcmp(temp2->model,targetModel)==0) {

        temp->next=temp2->next;
        free(temp2);

        return head;
    }

    temp=temp->next;
    temp2=temp2->next;
}

return head;
}
</code>```

Here is my free function. It has been freeing the memory just fine until I choose to call the removeCar function.

```<code>void freeMem(car *head) {/*Function frees all memory allocated to linked lists*/

car *current=NULL;

while((current=head)!=NULL) {
    head=head->next;
    free(current->model);
    free(current->color);
    free(current);
}
}
</code>```

Any suggestions would be greatly appreciated.

答:
With linked lists I used to add an extra indirection, so I don't need the extra handling when dealing with the head of the list.</p>

```<code>car *removeCar(car *head, char *targetModel)
{
    car * * ppNode = &head;
    while (*ppNode)
    {
        car* pCurrent = *ppNode;
        if(strcmp(pCurrent->model,targetModel)==0)
        {
           //replace the reference to pCurrent by its successor
           *ppNode = pCurrent->next;
           free(pCurrent->model);
           free(pCurrent->color);
           free(pCurrent);
           break;
        }
        ppNode = &pCurrent->next;
    }
    return head; //possibly changed
}
</code>```

Title: Valgrind memory leak with linked lists

Body:
When I run my program with valgrind I notice I only have a small memory leak (2 blocks) when I implement this function. This removes the node and when the list is printed out the node no longer appears.

car *removeCar(car *head, char *targetModel) {

car *temp=head;
car *temp2=head->next;

if(strcmp(temp->model,targetModel)==0) {
    return head;
}

while(temp2!=NULL) {
    if(strcmp(temp2->model,targetModel)==0) {

        temp->next=temp2->next;
        free(temp2);

        return head;
    }

    temp=temp->next;
    temp2=temp2->next;
}

return head;
}

Here is my free function. It has been freeing the memory just fine until I choose to call the removeCar function.

void freeMem(car *head) {/*Function frees all memory allocated to linked lists*/

car *current=NULL;

while((current=head)!=NULL) {
    head=head->next;
    free(current->model);
    free(current->color);
    free(current);
}
}

Any suggestions would be greatly appreciated.

Body:
With linked lists I used to add an extra indirection, so I don't need the extra handling when dealing with the head of the list.

car *removeCar(car *head, char *targetModel)
{
    car * * ppNode = &head;
    while (*ppNode)
    {
        car* pCurrent = *ppNode;
        if(strcmp(pCurrent->model,targetModel)==0)
        {
           //replace the reference to pCurrent by its successor
           *ppNode = pCurrent->next;
           free(pCurrent->model);
           free(pCurrent->color);
           free(pCurrent);
           break;
        }
        ppNode = &pCurrent->next;
    }
    return head; //possibly changed
}


答:
Here todo become one object from todoList object, then you can access property from that, like todo.todo and todo.id</p>

```<code><div ng-repeat ="todo in todoList">
 <label>
  {{ todo.todo }}
 </label>
</div>
</code>```

Body:
I have a array of JSON objects like below:

 todoList:
      [ { todo: 'dummy1', id: 595b9c2bb4b9992a4041d6e3 },
      { todo: 'dummy2', id: 595e4ffc62e38e3844f8d43a },
      { todo: 'dummy3', id: 595e4fff62e38e3844f8d43b },
      { todo: 'dummy4', id: 595f00c1d18df61840ad1ba3 } ]

I want to use the todo field in my view using ng-repeat like below

     {{ todo }}

Can you please tell me the way in which I can access only todo field from the todo List?

Body:
Here todo become one object from todoList object, then you can access property from that, like todo.todo and todo.id

<div ng-repeat ="todo in todoList">
 <label>
  {{ todo.todo }}
 </label>
</div>


问:
Vue.js - can not add date/timepicker to the html element rendered by vue.js
I have a Vue.js component where there are groups of text fields ( group of a text field labelled "Start" and another text field labelled "To") bound to a Vue array ( s.timespans) .

What I want is, when I add another group of text field by adding element to the ( s.timespans ) array, all the textfields get date/timepicker. But unfortunately, now only the first group of field gets the date/timepicker and the other groups don't. What is the right way of doing this?

Thanks in advance.

```<code><template id="settings">
<div v-for="(k,slot) in s.timespans" class="row mb5">
            <div class="col-sm-5">
                <label><?php _e( 'From', 'smps' ); ?></label>
                <input type="text" class="datepicker form-control" v-model="slot.from">
            </div>
            <div class="col-sm-5">
                <label><?php _e( 'To', 'smps' ); ?></label>
                <input type="text" class="datepicker form-control" v-model="slot.to">
            </div>
            <div class="col-sm-2">
                <a href="javascript:" class="btn btn-default pull-right btn-xs br0" @click="remove_timeslot(k)"><i class="fa fa-remove"></i></a>
            </div>
        </div>

<template>
</code>```

The Vue js code

```<code>Vue.component( 'settings', {
        template : '#settings',
        data : function () {
            return {
                s : {
                    timespans : [
                        {from : '', to : ''}
                    ]
                }
            }
        },
        methods : {
            add_timeslot : function () {
                Vue.set(this.s.timespans,this.s.timespans.length,{from:'',to:''});
                $('.datepicker').datetimepicker();
            },
            remove_timeslot : function (k) {
                this.s.timespans.splice(k,1);
            },

        },

    });
</code>```

答:
Try this then the DOM will be finished rendering, not before nextTick:

```<code>        add_timeslot : function () {
            Vue.set(this.s.timespans,this.s.timespans.length,{from:'',to:''});
            this.$nextTick(function () {
              $('.datepicker').datetimepicker();
            });
        },
</code>```

when the function in nextTick is executed, the DOM Element will be rendered.

Body:
I have a Vue.js component where there are groups of text fields ( group of a text field labelled "Start" and another text field labelled "To") bound to a Vue array ( s.timespans) .

What I want is, when I add another group of text field by adding element to the ( s.timespans ) array, all the textfields get date/timepicker. But unfortunately, now only the first group of field gets the date/timepicker and the other groups don't. What is the right way of doing this?

Thanks in advance.

<template id="settings">

                <?php _e( 'From', 'smps' ); ?>
                <input type="text" class="datepicker form-control" v-model="slot.from">

                <?php _e( 'To', 'smps' ); ?>
                <input type="text" class="datepicker form-control" v-model="slot.to">

<template>

The Vue js code

Vue.component( 'settings', {
        template : '#settings',
        data : function () {
            return {
                s : {
                    timespans : [
                        {from : '', to : ''}
                    ]
                }
            }
        },
        methods : {
            add_timeslot : function () {
                Vue.set(this.s.timespans,this.s.timespans.length,{from:'',to:''});
                $('.datepicker').datetimepicker();
            },
            remove_timeslot : function (k) {
                this.s.timespans.splice(k,1);
            },

        },

    });

Body:
Try this then the DOM will be finished rendering, not before nextTick:

        add_timeslot : function () {
            Vue.set(this.s.timespans,this.s.timespans.length,{from:'',to:''});
            this.$nextTick(function () {
              $('.datepicker').datetimepicker();
            });
        },

when the function in nextTick is executed, the DOM Element will be rendered.


问:
how do I add and commit a png screenshot image to a local repo?
I see repos in github that just have a screenshot added. Not a screenshot inside an md file, the png is it's own file in the repo. I want to know how to get the screenshot png into the local repo and commit it to be pushed to github without using the gui. </p>

答:
You should get screenshot via some tool (press "PrtScn" button for Monitor screenshot >> open paint >> paste >> save as 'screenshot.jpg')

copy this file in your Git repo

add filr "git add screenshot.jpg"

commit "git commit"

push "git push"

DONE :)


问:
How to insert data in nested div
I want to insert data in paragraph which is in nested div. plz guide me how to insert data in this paragraph through selenium web driver. Code is given below.</p>

```<code><div class="modal-body">
    <div class="row">
        <div class="col-xs-12 m-t-md">
            <div class="note-editing-area">
                <div class="note-editor note-frame panel panel-default">
                    <p> I want to insert text in this paragraph </p>
                </div>
            </div>
        </div>
    </div>
</div
</code>```

答: i have found the solution for access an element which exist in multiple div we can identified it with class driver.findElement(By.xpath("//div[contains(@class,' ')]")) you can use ur element class name in ' class name' –

Title: How to insert data in nested div

Body:
I want to insert data in paragraph which is in nested div. plz guide me how to insert data in this paragraph through selenium web driver. Code is given below.

 I want to insert text in this paragraph

</div


问:
Check or uncheck all radio inputs by id on radio yes/no selection
My issue is that i cannot edit the form code output so would like to target radio ids to check or uncheck depending on if a different radio button is selected. Would this is be possible? - i can add a function call on the  tag or use jquery - but i cannot edit the form code itself like adding onclick events.

Pseudo code would be:

```<code>If #unsubYes is checked Then
uncheck #option1Yes + #option2Yes AND
check #option1No + #option2No

If #unsubNo is checked Then
uncheck #option1No + #option2No AND
check #option1Yes + #option2Yes
</code>```

Link to JS fiddle html

Any help appreciated.

Cheers,
Chris

答:
Yes of course is possible.
You could do something similar like this</p>

```<code>document.querySelector('#unsubYes').addEventListener('change', function() {
    if (this.checked) {
        // do something if is checked
    } else {
        // do other thins
    }
});
</code>```

Body:
My issue is that i cannot edit the form code output so would like to target radio ids to check or uncheck depending on if a different radio button is selected. Would this is be possible? - i can add a function call on the  tag or use jquery - but i cannot edit the form code itself like adding onclick events.

Pseudo code would be:

If #unsubYes is checked Then
uncheck #option1Yes + #option2Yes AND
check #option1No + #option2No

If #unsubNo is checked Then
uncheck #option1No + #option2No AND
check #option1Yes + #option2Yes

Link to JS fiddle html

Any help appreciated.

Cheers,
Chris

Body:
Yes of course is possible.
You could do something similar like this

document.querySelector('#unsubYes').addEventListener('change', function() {
    if (this.checked) {
        // do something if is checked
    } else {
        // do other thins
    }
});