问:
Laravel redirect to home when I surf the backend panel
I have a problem with laravel 5.4

Laravel redirect to /home when I surf the backend panel or I create new category or edit category.

I did composer dump-autoload and php artisan cache:clear but It is redirect to /home again.

.env

```<code> BROADCAST_DRIVER=log
 CACHE_DRIVER=file
 SESSION_DRIVER=array
 QUEUE_DRIVER=sync
</code>```

config/session.php

```<code>return [

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "array"
|
*/

'driver' => env('SESSION_DRIVER', 'file'),

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => 1,

'expire_on_close' => false,

/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/

'encrypt' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/

'files' => storage_path('framework/sessions'),

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

'connection' => null,

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc" or "memcached" session drivers, you may specify a
| cache store that should be used for these sessions. This value must
| correspond with one of the application's configured cache stores.
|
*/

'store' => null,

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => [2, 100],

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/

'cookie' => 'laravel_session',

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/

'domain' => env('SESSION_DOMAIN', null),

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => env('SESSION_SECURE_COOKIE', false),

/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/

'http_only' => true,

 ];
</code>```

routes.php

```<code>    Route::group(['middleware' => 'auth', 'prefix' => 'backend', 'as' => 'backend.'], function () {

        Route::get('/', 'Backend\DashboardController@index');
        Route::get('/dashboard', 'Backend\DashboardController@index');

        Route::resource('/category', 'Backend\CategoryController');

        Route::resource('/blog', 'Backend\BlogController');

    });
</code>```

CategoryController.php

```<code><?php

    namespace App\Http\Controllers\Backend;

    use App\Repositories\CategoryRepository as CategoryRepo;
    use League\Flysystem\Exception;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use App\Entity\Category;

    class CategoryController extends Controller
    {
        protected $category;

        public function __construct(CategoryRepo $categoryRepo)
        {
            $this->category = $categoryRepo;
        }

        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
            $this->data["categories"] = $this->category->paginate(10);
            return view('backend.category.index', $this->data);
        }

        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function create()
        {
            return view('backend.category.create');
        }

        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request $request
         * @return \Illuminate\Http\Response
         */
        public function store(Request $request)
        {
            $Result = $request->except(["path_info"]);

            $row = $this->category->create($Result);
            flash('Kayıt eklenmiştir', 'success');

            return redirect(route("backend.category.index"));
        }

        /**
         * Display the specified resource.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function show($id)
        {
            $this->data["result"] = $this->category->find($id);
            return view('backend.category.show', $this->data);
        }

        /**
         * Show the form for editing the specified resource.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function edit($id)
        {
            $this->data["result"] = $this->category->find($id);
            return view('backend.category.edit', $this->data);
        }

        /**
         * Update the specified resource in storage.
         *
         * @param  \Illuminate\Http\Request $request
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function update(Request $request, $id)
        {
            $PagesUpdate = $request->except(["path_info"]);
            $Pages = $this->category->find($id);
            $Pages->update($PagesUpdate);
            flash('Kayıt güncellenmiştir', 'info');

            return redirect(route("backend.category.index"));
        }

        /**
         * Remove the specified resource from storage.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function destroy($id)
        {

            try {
                $this->category->delete($id);
                flash('Kayıt silinmiştir', 'danger');
                return redirect(route("backend.category.index"));
            } catch (Exception $ex) {
                throw new Exception($ex);
            }

        }
    }
</code>```

答:
You should do something like this when you store the data: </p>

```<code>public function store(Request $request)
{
    $Result = $request->except(["path_info"]);

    $row = $this->category->create($Result);
    flash('Kayıt eklenmiştir', 'success');

    return redirect('/dashboard');
}
</code>```

<p>When you update them redirect back at the same page: </p>

```<code>    public function update(Request $request, $id)
    {
        $PagesUpdate = $request->except(["path_info"]);
        $Pages = $this->category->find($id);
        $Pages->update($PagesUpdate);
        flash('Kayıt güncellenmiştir', 'info');

        return back();
             //or
        return redirect ('/');
    }
</code>```

Body:
I have a problem with laravel 5.4

Laravel redirect to /home when I surf the backend panel or I create new category or edit category.

I did composer dump-autoload and php artisan cache:clear but It is redirect to /home again.

.env

 BROADCAST_DRIVER=log
 CACHE_DRIVER=file
 SESSION_DRIVER=array
 QUEUE_DRIVER=sync

config/session.php

return [

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "array"
|
*/

'driver' => env('SESSION_DRIVER', 'file'),

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => 1,

'expire_on_close' => false,

/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/

'encrypt' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/

'files' => storage_path('framework/sessions'),

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

'connection' => null,

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc" or "memcached" session drivers, you may specify a
| cache store that should be used for these sessions. This value must
| correspond with one of the application's configured cache stores.
|
*/

'store' => null,

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => [2, 100],

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/

'cookie' => 'laravel_session',

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/

'domain' => env('SESSION_DOMAIN', null),

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => env('SESSION_SECURE_COOKIE', false),

/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/

'http_only' => true,

 ];

routes.php

    Route::group(['middleware' => 'auth', 'prefix' => 'backend', 'as' => 'backend.'], function () {

        Route::get('/', 'Backend\DashboardController@index');
        Route::get('/dashboard', 'Backend\DashboardController@index');

        Route::resource('/category', 'Backend\CategoryController');

        Route::resource('/blog', 'Backend\BlogController');

    });

CategoryController.php

<?php

    namespace App\Http\Controllers\Backend;

    use App\Repositories\CategoryRepository as CategoryRepo;
    use League\Flysystem\Exception;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use App\Entity\Category;

    class CategoryController extends Controller
    {
        protected $category;

        public function __construct(CategoryRepo $categoryRepo)
        {
            $this->category = $categoryRepo;
        }

        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
            $this->data["categories"] = $this->category->paginate(10);
            return view('backend.category.index', $this->data);
        }

        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function create()
        {
            return view('backend.category.create');
        }

        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request $request
         * @return \Illuminate\Http\Response
         */
        public function store(Request $request)
        {
            $Result = $request->except(["path_info"]);

            $row = $this->category->create($Result);
            flash('Kayıt eklenmiştir', 'success');

            return redirect(route("backend.category.index"));
        }

        /**
         * Display the specified resource.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function show($id)
        {
            $this->data["result"] = $this->category->find($id);
            return view('backend.category.show', $this->data);
        }

        /**
         * Show the form for editing the specified resource.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function edit($id)
        {
            $this->data["result"] = $this->category->find($id);
            return view('backend.category.edit', $this->data);
        }

        /**
         * Update the specified resource in storage.
         *
         * @param  \Illuminate\Http\Request $request
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function update(Request $request, $id)
        {
            $PagesUpdate = $request->except(["path_info"]);
            $Pages = $this->category->find($id);
            $Pages->update($PagesUpdate);
            flash('Kayıt güncellenmiştir', 'info');

            return redirect(route("backend.category.index"));
        }

        /**
         * Remove the specified resource from storage.
         *
         * @param  int $id
         * @return \Illuminate\Http\Response
         */
        public function destroy($id)
        {

            try {
                $this->category->delete($id);
                flash('Kayıt silinmiştir', 'danger');
                return redirect(route("backend.category.index"));
            } catch (Exception $ex) {
                throw new Exception($ex);
            }

        }
    }

Body:
You should do something like this when you store the data:

public function store(Request $request)
{
    $Result = $request->except(["path_info"]);

    $row = $this->category->create($Result);
    flash('Kayıt eklenmiştir', 'success');

    return redirect('/dashboard');
}

When you update them redirect back at the same page:

    public function update(Request $request, $id)
    {
        $PagesUpdate = $request->except(["path_info"]);
        $Pages = $this->category->find($id);
        $Pages->update($PagesUpdate);
        flash('Kayıt güncellenmiştir', 'info');

        return back();
             //or
        return redirect ('/');
    }


来源: stackexchange

问:
Regular expression to match any word followed by a literal string
So I have the following:

```<code>^[a-zA-Z]+\b(myword+-)\b*
</code>```

which I thought would match

^ start of string

[a-zA-Z] any alpha character

+ of one or more characters

\b followed by a word break

(myword+-) followed by myword which could include one or more special characters

\b followed by a word break

\* followed by anything at all

One: it does not work - it does not match anything

Two: any special characters included in {myword+-) throws an error

I could escape the special characters, but I don't know in advance what they might be, so I would have to escape all the possibilites, or perhaps I could just escape every character in {\m\y\w\o\r\d\\+\\-)

Edited to add:

Sorry, I knew I should have given more information

I have a series of strings to seach through in the form:

extra android-sdk and more that is of no interest

extra android-ndk and more that is of no interest

extra anjuta-extra and more that is of no interest

community c++-gtk-utils and more that is of no interest

and I have a list of items to search for in the strings:

android-sdk

android-ndk

extra

c++-gtk-utils

The item should only match if the second word in the string is an exact match to the item, so:

android-sdk will match the first string

android-ndk will match the second string

extra wuill NOT match the third string

c++-gtk-utils will match the fourth string

So (myword+-) is the item I am searching for "which could include one or more special characters"

Thanks for the help

Andrew

答:
Strong recommendation: if you want to match literal strings, don't use regular expressions.

If we have this sample data:

```<code>set strings {
    {extra android-sdk and more that is of no interest}
    {extra android-ndk and more that is of no interest}
    {extra anjuta-extra and more that is of no interest}
    {community c++-gtk-utils and more that is of no interest}
}

set search_strings {
    android-sdk
    android-ndk
    extra
    c++-gtk-utils
}
</code>```

Then, to find matches in the 2nd word of each string, we'll just use the eq string equality operator

```<code>foreach string $strings {
    foreach search $search_strings {
        if {[lindex [split $string] 1] eq $search} {
            puts "$search matches $string"
        }
    }
}
</code>```

outputs

```<code>android-sdk matches extra android-sdk and more that is of no interest
android-ndk matches extra android-ndk and more that is of no interest
c++-gtk-utils matches community c++-gtk-utils and more that is of no interest
</code>```

If you insist on regular expression matching, you can escape any special characters to take away their usual regex meaning. Here, we'll take the brute force approach: any non-word chars will get escaped, so that the pattern may look like ^\S+\s+c\+\+\-gtk\-utils

```<code>foreach string $strings {
    foreach search $search_strings {
        set pattern "^\\S+\\s+[regsub -all {\W} $search {\\&}]"
        if {[regexp $pattern $string]} {
            puts "$search matches $string"
        }
    }
}
</code>```

I was hoping to be able to  make a portion of a regular expression to be a literal string, like

```<code>set pattern "^\\S+\\s+(***=$string)"
set pattern "^\\S+\\s+((?q)$string)"
</code>```

but both failed.

Tcl regular expressions are documented at
https://www.tcl.tk/man/tcl8.6/TclCmd/re_syntax.htm

Also note your pattern ^[a-zA-Z]+\b(myword+-)\b* does not provide for any whitespace between the first and second words.

ContentLicense: CC BY-SA 3.0

Body:
So I have the following:

^[a-zA-Z]+\b(myword+-)\b*

which I thought would match

^ start of string

[a-zA-Z] any alpha character

+ of one or more characters

\b followed by a word break

(myword+-) followed by myword which could include one or more special characters

\b followed by a word break

\* followed by anything at all

One: it does not work - it does not match anything

Two: any special characters included in {myword+-) throws an error

I could escape the special characters, but I don't know in advance what they might be, so I would have to escape all the possibilites, or perhaps I could just escape every character in {\m\y\w\o\r\d\\+\\-)

Edited to add:

Sorry, I knew I should have given more information

I have a series of strings to seach through in the form:

extra android-sdk and more that is of no interest

extra android-ndk and more that is of no interest

extra anjuta-extra and more that is of no interest

community c++-gtk-utils and more that is of no interest

and I have a list of items to search for in the strings:

android-sdk

android-ndk

extra

c++-gtk-utils

The item should only match if the second word in the string is an exact match to the item, so:

android-sdk will match the first string

android-ndk will match the second string

extra wuill NOT match the third string

c++-gtk-utils will match the fourth string

So (myword+-) is the item I am searching for "which could include one or more special characters"

Thanks for the help

Andrew

Body:
Strong recommendation: if you want to match literal strings, don't use regular expressions.

If we have this sample data:

set strings {
    {extra android-sdk and more that is of no interest}
    {extra android-ndk and more that is of no interest}
    {extra anjuta-extra and more that is of no interest}
    {community c++-gtk-utils and more that is of no interest}
}

set search_strings {
    android-sdk
    android-ndk
    extra
    c++-gtk-utils
}

Then, to find matches in the 2nd word of each string, we'll just use the eq string equality operator

foreach string $strings {
    foreach search $search_strings {
        if {[lindex [split $string] 1] eq $search} {
            puts "$search matches $string"
        }
    }
}

outputs

android-sdk matches extra android-sdk and more that is of no interest
android-ndk matches extra android-ndk and more that is of no interest
c++-gtk-utils matches community c++-gtk-utils and more that is of no interest

If you insist on regular expression matching, you can escape any special characters to take away their usual regex meaning. Here, we'll take the brute force approach: any non-word chars will get escaped, so that the pattern may look like ^\S+\s+c\+\+\-gtk\-utils

foreach string $strings {
    foreach search $search_strings {
        set pattern "^\\S+\\s+[regsub -all {\W} $search {\\&}]"
        if {[regexp $pattern $string]} {
            puts "$search matches $string"
        }
    }
}

I was hoping to be able to  make a portion of a regular expression to be a literal string, like

set pattern "^\\S+\\s+(***=$string)"
set pattern "^\\S+\\s+((?q)$string)"

but both failed.

Tcl regular expressions are documented at
https://www.tcl.tk/man/tcl8.6/TclCmd/re_syntax.htm

Also note your pattern ^[a-zA-Z]+\b(myword+-)\b* does not provide for any whitespace between the first and second words.


问:
Why '$' can be omitted within let construct
The $ sign can be omitted within the let and (( ... )) constructs.

Why is that so, given that $ is mandatory when using if or while?

答:
Arithmetic expressions deal only with integers, not strings. So if a string appears in an expression, the only sensible way to interpret it is as a variable to expand (recursively, as necessary) until you get an integer.

In other contexts, strings are allowed, so the only way to differentiate between the string foo and the value of the variable foo is to have an explicit syntax for parameter expansion (foo is a string, $foo produces the value of the parameter foo).

The root of all this is that shells do not pass variables to functions or commands; you effectively just expand macros and pass the resulting values.


问:
How to label duplicate groups in pandas?
I have a DataFrame:

```<code>>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar
</code>```

I need to find all the duplicate groups and label them with sequential dgroup_id's:

```<code>>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2
</code>```

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

```<code>import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))
</code>```

This leads to:

```<code>>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0
</code>```

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

答:
Use duplicated to identify where dups are.  Use where to replace singletons with ''.  Use categorical to factorize.

```<code>dups = df.A.duplicated(keep=False)
df.assign(dgroup_id=df.A.where(dups, '').astype('category').cat.codes)

     A  dgroup_id
0  foo          2
1  bar          1
2  foo          2
3  baz          0
4  foo          2
5  bar          1
</code>```

If you insist on the zeros being ''

```<code>dups = df.A.duplicated(keep=False)
df.assign(
    dgroup_id=df.A.where(dups, '').astype('category').cat.codes.replace(0, ''))

     A dgroup_id
0  foo         2
1  bar         1
2  foo         2
3  baz
4  foo         2
5  bar         1
</code>```

Body:
I have a DataFrame:

>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar

I need to find all the duplicate groups and label them with sequential dgroup_id's:

>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))

This leads to:

>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

Body:
Use duplicated to identify where dups are.  Use where to replace singletons with ''.  Use categorical to factorize.

dups = df.A.duplicated(keep=False)
df.assign(dgroup_id=df.A.where(dups, '').astype('category').cat.codes)

     A  dgroup_id
0  foo          2
1  bar          1
2  foo          2
3  baz          0
4  foo          2
5  bar          1

If you insist on the zeros being ''

dups = df.A.duplicated(keep=False)
df.assign(
    dgroup_id=df.A.where(dups, '').astype('category').cat.codes.replace(0, ''))

     A dgroup_id
0  foo         2
1  bar         1
2  foo         2
3  baz
4  foo         2
5  bar         1


问:
How to do correct inner join over this query?
```<code>SELECT p.product_id, p.quantity, p.price, pd.name, pd.description
FROM product AS p
INNER JOIN product_description AS pd ON p.product_id = pd.product_id
WHERE p.product_id = 1 AND pd.landuage_id = 5
</code>```

In this query, only one condition exists, p.product_id in this case, but the other condition pd.landuage_id does not exist. I want the request to be executed, whether it exists. How to do it ?

答:
It's possible duplicate, but right answer is:</p>

```<code>SELECT p.product_id, p.quantity, p.price, pd.name, pd.description
FROM product p
LEFT JOIN product_description pd ON p.product_id = pd.product_id AND pd.language_id = 5
WHERE p.product_id = 1;
</code>```

Body:
SELECT p.product_id, p.quantity, p.price, pd.name, pd.description
FROM product AS p
INNER JOIN product_description AS pd ON p.product_id = pd.product_id
WHERE p.product_id = 1 AND pd.landuage_id = 5

In this query, only one condition exists, p.product_id in this case, but the other condition pd.landuage_id does not exist. I want the request to be executed, whether it exists. How to do it ?

Body:
It's possible duplicate, but right answer is:

SELECT p.product_id, p.quantity, p.price, pd.name, pd.description
FROM product p
LEFT JOIN product_description pd ON p.product_id = pd.product_id AND pd.language_id = 5
WHERE p.product_id = 1;


问:
How to use single word as JSON data in android?
I am trying to extract the JSON data which is just a single word. I have used JSON Array when it was a long list of a set of data but this time it just a word like - done or failed.

My Code is -

```<code>JSONObject jsonObject = new JSONObject(s);
//JSONArray jsonArray = jsonObject.getJSONArray("contacted");
loggingTest = jsonObject.getString("??"); // what to put here (??) as
//there is just a single word.
</code>```

It may be very easy to get it but I feels I am missing something. Thanks for your help in advance.

答:
URL just gives a word like - done that's it not even " or : { nothing

Then simply use the String variable s , don't convert it into json

plus you can put this JSONObject jsonObject = new JSONObject(s); in try-catch to recognize that respose is simply a valid json or not , if not it will throw an exception

```<code>try{
    // exception will be thrown in case of invalid json
    JSONObject jsonObject = new JSONObject(s);
 }
  catch(JSONException e){
  // s containing a single word so use it as it is
}
</code>```

Body:
I am trying to extract the JSON data which is just a single word. I have used JSON Array when it was a long list of a set of data but this time it just a word like - done or failed.

My Code is -

JSONObject jsonObject = new JSONObject(s);
//JSONArray jsonArray = jsonObject.getJSONArray("contacted");
loggingTest = jsonObject.getString("??"); // what to put here (??) as
//there is just a single word.

It may be very easy to get it but I feels I am missing something. Thanks for your help in advance.

Body:
URL just gives a word like - done that's it not even " or : { nothing

Then simply use the String variable s , don't convert it into json

plus you can put this JSONObject jsonObject = new JSONObject(s); in try-catch to recognize that respose is simply a valid json or not , if not it will throw an exception

try{
    // exception will be thrown in case of invalid json
    JSONObject jsonObject = new JSONObject(s);
 }
  catch(JSONException e){
  // s containing a single word so use it as it is
}


问:
Pass selected UIImage image anto another view?
I want to pass selected UIImage into another viewControllerwithout using segue.

I have UICollectionViewCell ,so when I click on particular cell, selected image will show on another viewController.

答:
You can use delegates to send data between classes:

First create a delegate:

```<code>@protocol ImageSelectDelegate <NSObject>
@required
-(void)selectedImage:(UIImage *)image;
@end
</code>```

and  implement this protocol in the class you want to send your image :

```<code>@interface CollectionDetailViewController()< ImageSelectDelegate >
</code>```

and in the collection controller, create a property for the delegate :

```<code>@property (nonatomic, retain) id< ImageSelectDelegate > imageSelectDelegate;
</code>```

and in the didSelect method, just do:

```<code>[self.imageSelectDelegate selectedImage:imageTosend];
</code>```

In the other class, you can obtain the image in this method:

```<code>-(void) selectedImage:(UIImage *)image{
    self.image = image;

}
</code>```

Make sure your imageSelectDelegate is not nil, else this won't work

Body:
You can use delegates to send data between classes:

First create a delegate:

@protocol ImageSelectDelegate <NSObject>
@required
-(void)selectedImage:(UIImage *)image;
@end

and  implement this protocol in the class you want to send your image :

@interface CollectionDetailViewController()< ImageSelectDelegate >

and in the collection controller, create a property for the delegate :

@property (nonatomic, retain) id< ImageSelectDelegate > imageSelectDelegate;

and in the didSelect method, just do:

[self.imageSelectDelegate selectedImage:imageTosend];

In the other class, you can obtain the image in this method:

-(void) selectedImage:(UIImage *)image{
    self.image = image;

}

Make sure your imageSelectDelegate is not nil, else this won't work


问:
How can I add font awesome icons into Custom Post Type UI Menu Icon area?
I want to add font awesome icons into Custom Post Type UI Menu Icon area but I couldn't add. How can I do any idea, guys? Thank you.

答:
if you can paste these files into the functions.php and style.css and know the custom post type class looking at the body class given by wordpress

To use Font Awesome for a WordPress Custom Post Type, you’ll need to write a little CSS: just target a CPT menu item (inspect the WordPress admin sidebar to find the correct CSS ID) like this:

```<code>#adminmenu #menu-posts-custom_post_type_name .wp-menu-image:before {
 content: "\f135"; //find this by clicking on the individual icon on Font
 Awesome's site.
font-family: 'FontAwesome' !important;
 font-size: 18px !important;
}
</code>```

Next, add those styles to the WordPress admin by using the admin_head hook:

```<code>function namespaced_admin_styles_function() {

  echo '<link href="/link/to/admin-styles.css"  rel="stylesheet">';
}

add_action('admin_head', 'namespaced_admin_styles_function');
</code>```

…and you’re off and running! Well, not quite. You still need to add the Font Awesome stylesheet to both the WordPress admin and the front-end of your site. Fortunately, you can kill two birds with one stone this way:

```<code>function FontAwesome_icons() {
echo '<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"  rel="stylesheet">';
}

add_action('admin_head', 'FontAwesome_icons');
add_action('wp_head', 'FontAwesome_icons');
</code>```

Refrence from:https://cnpagency.com/blog/3-ways-to-use-icon-fonts-in-your-wordpress-theme-admin/

Body:
if you can paste these files into the functions.php and style.css and know the custom post type class looking at the body class given by wordpress

To use Font Awesome for a WordPress Custom Post Type, you’ll need to write a little CSS: just target a CPT menu item (inspect the WordPress admin sidebar to find the correct CSS ID) like this:

#adminmenu #menu-posts-custom_post_type_name .wp-menu-image:before {
 content: "\f135"; //find this by clicking on the individual icon on Font
 Awesome's site.
font-family: 'FontAwesome' !important;
 font-size: 18px !important;
}

Next, add those styles to the WordPress admin by using the admin_head hook:

function namespaced_admin_styles_function() {

  echo '<link href="/link/to/admin-styles.css"  rel="stylesheet">';
}

add_action('admin_head', 'namespaced_admin_styles_function');

…and you’re off and running! Well, not quite. You still need to add the Font Awesome stylesheet to both the WordPress admin and the front-end of your site. Fortunately, you can kill two birds with one stone this way:

function FontAwesome_icons() {
echo '<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"  rel="stylesheet">';
}

add_action('admin_head', 'FontAwesome_icons');
add_action('wp_head', 'FontAwesome_icons');

Refrence from:https://cnpagency.com/blog/3-ways-to-use-icon-fonts-in-your-wordpress-theme-admin/


问:
Is this possible to write Win32 .dll files by C#.NET?
Is this possible to write Win32 .dll files by C#.NET ?
If yes, where i can find some tutorials?
If no, so what's your suggestion to write Win32 .DLLs?

Thanks.

答:
Of course you can create DLL Files in C#.

All you need is to choose Class Library in your Project Type when you create a new Project in Visual Studio.

Here is a tutorial : http://www.c-sharpcorner.com/uploadfile/mahesh/dll12222005064058am/dll.aspx

ContentLicense: CC BY-SA 2.5


问:
How can I convince AWS CLI sync to exclude any file matching a directory pattern?
The use case is I want to exclude certain data from going up to S3. The files could be anywhere within the file hierarchy, but if they are contained anywhere below a directory named foobar I don't want them copied over.

For example:

```<code>/my-data/20150806-1600/foobar/blah.csv  # Exclude
/my-data/20150806-1600/dingbat/blah.csv # Include
/my-data/clients/foobar/README.txt      # Exclude

$ /usr/local/bin/aws --version
aws-cli/1.11.117 Python/2.7.6 Linux/3.13.0-92-generic botocore/1.5.80
</code>```

Alas ...

```<code>/usr/local/bin/aws s3 sync /my-data/ s3://my-bucket/my-data/ --exclude '*/foobar/*' --exclude '*/foobaz/*' --delete
</code>```

The files still upload. I have tried changing the exclude pattern(s) to foobar/* and *foobar* but in every case, files matching a parent directory with foobar in the path still get uploaded.

答:
For me, it only seemed to work by excluding *foobar* or *foorbar/*. It would not work by excluding */foobar/*:

```<code>$ ls -lR stack
total 8
drwxr-xr-x  3 user  wheel  102  8 Jul 23:25 foobar
-rw-r--r--  1 user  wheel    5  8 Jul 23:25 level1

stack/foobar:
total 8
-rw-r--r--  1 user  wheel  5  8 Jul 23:25 level2

$ aws s3 sync stack/ s3://my-bucket --exclude '*foobar*'
upload: stack/level1 to s3://my-bucket/level1
</code>```

Body:
The use case is I want to exclude certain data from going up to S3. The files could be anywhere within the file hierarchy, but if they are contained anywhere below a directory named foobar I don't want them copied over.

For example:

/my-data/20150806-1600/foobar/blah.csv  # Exclude
/my-data/20150806-1600/dingbat/blah.csv # Include
/my-data/clients/foobar/README.txt      # Exclude

$ /usr/local/bin/aws --version
aws-cli/1.11.117 Python/2.7.6 Linux/3.13.0-92-generic botocore/1.5.80

Alas ...

/usr/local/bin/aws s3 sync /my-data/ s3://my-bucket/my-data/ --exclude '*/foobar/*' --exclude '*/foobaz/*' --delete

The files still upload. I have tried changing the exclude pattern(s) to foobar/* and *foobar* but in every case, files matching a parent directory with foobar in the path still get uploaded.

Body:
For me, it only seemed to work by excluding *foobar* or *foorbar/*. It would not work by excluding */foobar/*:

$ ls -lR stack
total 8
drwxr-xr-x  3 user  wheel  102  8 Jul 23:25 foobar
-rw-r--r--  1 user  wheel    5  8 Jul 23:25 level1

stack/foobar:
total 8
-rw-r--r--  1 user  wheel  5  8 Jul 23:25 level2

$ aws s3 sync stack/ s3://my-bucket --exclude '*foobar*'
upload: stack/level1 to s3://my-bucket/level1


问:
delete elements from a data frame w.r.t columns of another data frame
I have a data frame say df1 with MULTILEVEL INDEX:

```<code>       A     B     C      D
 0  0    0     1     2      3
         4     5     6      7
 1  2    8     9     10     11
    3    2     3     4      5
</code>```

and I have another data frame with 2 common columns in df2 also with MULTILEVEL INDEX

```<code>          X     B     C      Y
 0   0    0     0     7      3
     1    4     5     6      7
 1   2    8     2     3     11
     3    2     3     4      5
</code>```

I need to remove the rows from df1 where the values of column B and C are the same as in df2, so I should be getting something like this:

```<code>       A     B     C      D
  0  0    0     1     2      3
  0  2    8     9     10     11
</code>```

I have tried to do this by getting the index of the common elements and then remove them via a list, but they are all messed up and are in multi-level form.

答:
You could make MultiIndexes out of the B and C columns, and then call the index's isin method:

```<code>idx1 = pd.MultiIndex.from_arrays([df1['B'],df1['C']])
idx2 = pd.MultiIndex.from_arrays([df2['B'],df2['C']])
mask = idx1.isin(idx2)
result = df1.loc[~mask]
</code>```

For example,

```<code>import pandas as pd
df1 = pd.DataFrame({'A': [0, 4, 8, 2], 'B': [1, 5, 9, 3], 'C': [2, 6, 10, 4], 'D': [3, 7, 11, 5], 'P': [0, 0, 1, 1], 'Q': [0, 0, 2, 3]})
df1 = df1.set_index(list('PQ'))
df1.index.names = [None,None]

df2 = pd.DataFrame({'B': [0, 5, 2, 3], 'C': [7, 6, 3, 4], 'P': [0, 0, 1, 1], 'Q': [0, 1, 2, 3], 'X': [0, 4, 8, 2], 'Y': [3, 7, 11, 5]})
df2 = df2.set_index(list('PQ'))
df2.index.names = [None,None]

idx1 = pd.MultiIndex.from_arrays([df1['B'],df1['C']])
idx2 = pd.MultiIndex.from_arrays([df2['B'],df2['C']])
mask = idx1.isin(idx2)
result = df1.loc[~mask]
print(result)
</code>```

yields

```<code>     A  B   C   D
0 0  0  1   2   3
1 2  8  9  10  11
</code>```

Body:
I have a data frame say df1 with MULTILEVEL INDEX:

       A     B     C      D
 0  0    0     1     2      3
         4     5     6      7
 1  2    8     9     10     11
    3    2     3     4      5

and I have another data frame with 2 common columns in df2 also with MULTILEVEL INDEX

          X     B     C      Y
 0   0    0     0     7      3
     1    4     5     6      7
 1   2    8     2     3     11
     3    2     3     4      5

I need to remove the rows from df1 where the values of column B and C are the same as in df2, so I should be getting something like this:

       A     B     C      D
  0  0    0     1     2      3
  0  2    8     9     10     11

I have tried to do this by getting the index of the common elements and then remove them via a list, but they are all messed up and are in multi-level form.

Body:
You could make MultiIndexes out of the B and C columns, and then call the index's isin method:

idx1 = pd.MultiIndex.from_arrays([df1['B'],df1['C']])
idx2 = pd.MultiIndex.from_arrays([df2['B'],df2['C']])
mask = idx1.isin(idx2)
result = df1.loc[~mask]

For example,

import pandas as pd
df1 = pd.DataFrame({'A': [0, 4, 8, 2], 'B': [1, 5, 9, 3], 'C': [2, 6, 10, 4], 'D': [3, 7, 11, 5], 'P': [0, 0, 1, 1], 'Q': [0, 0, 2, 3]})
df1 = df1.set_index(list('PQ'))
df1.index.names = [None,None]

df2 = pd.DataFrame({'B': [0, 5, 2, 3], 'C': [7, 6, 3, 4], 'P': [0, 0, 1, 1], 'Q': [0, 1, 2, 3], 'X': [0, 4, 8, 2], 'Y': [3, 7, 11, 5]})
df2 = df2.set_index(list('PQ'))
df2.index.names = [None,None]

idx1 = pd.MultiIndex.from_arrays([df1['B'],df1['C']])
idx2 = pd.MultiIndex.from_arrays([df2['B'],df2['C']])
mask = idx1.isin(idx2)
result = df1.loc[~mask]
print(result)

yields

     A  B   C   D
0 0  0  1   2   3
1 2  8  9  10  11


问:
What I should use font icons or sprite images?
What I should use font icons or sprite images for better performance? What will
be load faster and light weighted?</p>

答:
there are two crucial points where I feel icon fonts can have an advantage:

Overall file size

Internet Explorer support

When you have a set of icons that you’d like to use on a given project, the larger the set of icons, the more likely an icon font will have a smaller overall file footprint.

Talking about performances, during a recent test I made on a set of about 30 icons, the icon fonts can reach a boost of about 240% compared to sprite images.
Also, icon fonts work as far back as IE6.

On the other hand, vector icons are resizable up and down without losing quality, extra sharp on retina displays. It can also support multi-color icons.

I recommend this post for any further reference.

Hope this could help,
L.


问:
copy database row with all dependency with others Tables
Hi all I have below mentioned Tables and every Table ID is auto incremented in DB (I can't change this property).

```<code>    Box_Table
Id  Name    Cost
 1  Box1    100
 2  Box2    175

    Fruit_Table
Id  Name    Cost
1   Apple   100
2   Orange  75
3   Bannana 25

    Box_Fruit_Table
Id  Box_Id  Fruit_Id
1      1      2
2      1      3
3      2      1
4      2      2
</code>```

I am trying to duplicate ROW of Table Box_Table.

I am trying this in WPF using DataSet by adding one Row to the DataSet and copying
the content of duplicating ROW except ID and doing commiting. After getting duplicated ID
have to update the Box_Fruit_Table.

Problem I am facing is:
As ID is autoincrement in DB, only after commit I will get the generated ID.
Because of this I am not able to update the BOX_FRUIT_TABLE for duplicated ROW.

答:
do following steps

1- Save in the parent table 'Box_Table'

2- Get the latest id generated

3- Update the Box_Fruit_Table with this new id.

Body:
Hi all I have below mentioned Tables and every Table ID is auto incremented in DB (I can't change this property).

    Box_Table
Id  Name    Cost
 1  Box1    100
 2  Box2    175

    Fruit_Table
Id  Name    Cost
1   Apple   100
2   Orange  75
3   Bannana 25

    Box_Fruit_Table
Id  Box_Id  Fruit_Id
1      1      2
2      1      3
3      2      1
4      2      2

I am trying to duplicate ROW of Table Box_Table.

I am trying this in WPF using DataSet by adding one Row to the DataSet and copying
the content of duplicating ROW except ID and doing commiting. After getting duplicated ID
have to update the Box_Fruit_Table.

Problem I am facing is:
As ID is autoincrement in DB, only after commit I will get the generated ID.
Because of this I am not able to update the BOX_FRUIT_TABLE for duplicated ROW.


问:
How do I convert a SOAP to JSON?
I have a soap file that i am trying to convert to JSON. I have realised that I can use simplexml_load_string without namespaces as below

```<code>$xml = simplexml_load_string($soap_string);
$json = json_encode($xml);
header('Content-Type: application/json');
echo $json;
</code>```

My response xml below has namespaces and therefore throws errors when i try using simplexml_load_string.

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
        <soapenv:Body>
            <res:ResultMsg xmlns:res="http://api-v1.gen.mm.vodafone.com/mminterface/result">
                <![CDATA[
                <?xml version="1.0" encoding="UTF-8"?>
                <Result xmlns="http://api-v1.gen.mm.vodafone.com/mminterface/result">
                   <ResultType>0</ResultType>
                   <ResultCode>0</ResultCode>
                   <ResultDesc>The service request has been accepted successfully.</ResultDesc>
                   <OriginatorConversationID>555010_jYJlV0MP3y</OriginatorConversationID>
                   <ConversationID>20170705_00007d59ab9111033601</ConversationID>
                   <TransactionID>LG51195MWH</TransactionID>
                   <ResultParameters>
                      <ResultParameter>
                         <Key>TransactionAmount</Key>
                         <Value>100</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>TransactionReceipt</Key>
                         <Value>LG51195MWH</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>B2CRecipientIsRegisteredCustomer</Key>
                         <Value>Y</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>B2CChargesPaidAccountAvailableFunds</Key>
                         <Value>-55.00</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>ReceiverPartyPublicName</Key>
                         <Value>254713171292 - test test</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>TransactionCompletedDateTime</Key>
                         <Value>05.07.2017 08:27:38</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>B2CUtilityAccountAvailableFunds</Key>
                         <Value>32526.00</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>B2CWorkingAccountAvailableFunds</Key>
                         <Value>541703.00</Value>
                      </ResultParameter>
                   </ResultParameters>
                   <ReferenceData>
                      <ReferenceItem>
                         <Key>QueueTimeoutURL</Key>
                         <Value>https://localhost:443/pay/timeout.php</Value>
                      </ReferenceItem>
                   </ReferenceData>
                </Result>
                ]]>
            </res:ResultMsg>
    </soapenv:Body>
    </soapenv:Envelope>
</code>```

How do I take out the envelope parts from the soap response above so that I can remain with only the xml part that I can easily store in variable and covert it to json using simplexml_load_string?

答:
The json can not be parsed because your xml file contains "xml
  namespace". With Regex you can parse the json by selecting the
  "Result" tag (Basic way).

If you can test it, you can edit the regex pattern you need.

```<code><?php
header('Content-type: application/json');
$soap_string = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <res:ResultMsg xmlns:res="http://api-v1.gen.mm.vodafone.com/mminterface/result">
            <![CDATA[
            <?xml version="1.0" encoding="UTF-8"?>
            <Result xmlns="http://api-v1.gen.mm.vodafone.com/mminterface/result">
               <ResultType>0</ResultType>
               <ResultCode>0</ResultCode>
               <ResultDesc>The service request has been accepted successfully.</ResultDesc>
               <OriginatorConversationID>555010_jYJlV0MP3y</OriginatorConversationID>
               <ConversationID>20170705_00007d59ab9111033601</ConversationID>
               <TransactionID>LG51195MWH</TransactionID>
               <ResultParameters>
                  <ResultParameter>
                     <Key>TransactionAmount</Key>
                     <Value>100</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>TransactionReceipt</Key>
                     <Value>LG51195MWH</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>B2CRecipientIsRegisteredCustomer</Key>
                     <Value>Y</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>B2CChargesPaidAccountAvailableFunds</Key>
                     <Value>-55.00</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>ReceiverPartyPublicName</Key>
                     <Value>254713171292 - test test</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>TransactionCompletedDateTime</Key>
                     <Value>05.07.2017 08:27:38</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>B2CUtilityAccountAvailableFunds</Key>
                     <Value>32526.00</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>B2CWorkingAccountAvailableFunds</Key>
                     <Value>541703.00</Value>
                  </ResultParameter>
               </ResultParameters>
               <ReferenceData>
                  <ReferenceItem>
                     <Key>QueueTimeoutURL</Key>
                     <Value>https://localhost:443/pay/timeout.php</Value>
                  </ReferenceItem>
               </ReferenceData>
            </Result>
            ]]>
        </res:ResultMsg>
</soapenv:Body>
</soapenv:Envelope>';

//file_get_contents("http://localhost:24563/soap_string.xml"); // test xml url :) remove this comment
$pattern = "(<Result(.+)>[\s\S]*?<\/Result>)";
preg_match_all($pattern, $soap_string, $matches);

$xml = simplexml_load_string($matches[0][0]);
echo json_encode($xml);
?>
</code>```

Title: How do I convert a SOAP to JSON?

Body:
I have a soap file that i am trying to convert to JSON. I have realised that I can use simplexml_load_string without namespaces as below

$xml = simplexml_load_string($soap_string);
$json = json_encode($xml);
header('Content-Type: application/json');
echo $json;

My response xml below has namespaces and therefore throws errors when i try using simplexml_load_string.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
        <soapenv:Body>
            <res:ResultMsg xmlns:res="http://api-v1.gen.mm.vodafone.com/mminterface/result">
                <![CDATA[
                <?xml version="1.0" encoding="UTF-8"?>
                <Result xmlns="http://api-v1.gen.mm.vodafone.com/mminterface/result">
                   <ResultType>0</ResultType>
                   <ResultCode>0</ResultCode>
                   <ResultDesc>The service request has been accepted successfully.</ResultDesc>
                   <OriginatorConversationID>555010_jYJlV0MP3y</OriginatorConversationID>
                   <ConversationID>20170705_00007d59ab9111033601</ConversationID>
                   <TransactionID>LG51195MWH</TransactionID>
                   <ResultParameters>
                      <ResultParameter>
                         <Key>TransactionAmount</Key>
                         <Value>100</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>TransactionReceipt</Key>
                         <Value>LG51195MWH</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>B2CRecipientIsRegisteredCustomer</Key>
                         <Value>Y</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>B2CChargesPaidAccountAvailableFunds</Key>
                         <Value>-55.00</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>ReceiverPartyPublicName</Key>
                         <Value>254713171292 - test test</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>TransactionCompletedDateTime</Key>
                         <Value>05.07.2017 08:27:38</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>B2CUtilityAccountAvailableFunds</Key>
                         <Value>32526.00</Value>
                      </ResultParameter>
                      <ResultParameter>
                         <Key>B2CWorkingAccountAvailableFunds</Key>
                         <Value>541703.00</Value>
                      </ResultParameter>
                   </ResultParameters>
                   <ReferenceData>
                      <ReferenceItem>
                         <Key>QueueTimeoutURL</Key>
                         <Value>https://localhost:443/pay/timeout.php</Value>
                      </ReferenceItem>
                   </ReferenceData>
                </Result>
                ]]>
            </res:ResultMsg>
    </soapenv:Body>
    </soapenv:Envelope>

How do I take out the envelope parts from the soap response above so that I can remain with only the xml part that I can easily store in variable and covert it to json using simplexml_load_string?

Body:
The json can not be parsed because your xml file contains "xml
  namespace". With Regex you can parse the json by selecting the
  "Result" tag (Basic way).

If you can test it, you can edit the regex pattern you need.

<?php
header('Content-type: application/json');
$soap_string = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <res:ResultMsg xmlns:res="http://api-v1.gen.mm.vodafone.com/mminterface/result">
            <![CDATA[
            <?xml version="1.0" encoding="UTF-8"?>
            <Result xmlns="http://api-v1.gen.mm.vodafone.com/mminterface/result">
               <ResultType>0</ResultType>
               <ResultCode>0</ResultCode>
               <ResultDesc>The service request has been accepted successfully.</ResultDesc>
               <OriginatorConversationID>555010_jYJlV0MP3y</OriginatorConversationID>
               <ConversationID>20170705_00007d59ab9111033601</ConversationID>
               <TransactionID>LG51195MWH</TransactionID>
               <ResultParameters>
                  <ResultParameter>
                     <Key>TransactionAmount</Key>
                     <Value>100</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>TransactionReceipt</Key>
                     <Value>LG51195MWH</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>B2CRecipientIsRegisteredCustomer</Key>
                     <Value>Y</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>B2CChargesPaidAccountAvailableFunds</Key>
                     <Value>-55.00</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>ReceiverPartyPublicName</Key>
                     <Value>254713171292 - test test</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>TransactionCompletedDateTime</Key>
                     <Value>05.07.2017 08:27:38</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>B2CUtilityAccountAvailableFunds</Key>
                     <Value>32526.00</Value>
                  </ResultParameter>
                  <ResultParameter>
                     <Key>B2CWorkingAccountAvailableFunds</Key>
                     <Value>541703.00</Value>
                  </ResultParameter>
               </ResultParameters>
               <ReferenceData>
                  <ReferenceItem>
                     <Key>QueueTimeoutURL</Key>
                     <Value>https://localhost:443/pay/timeout.php</Value>
                  </ReferenceItem>
               </ReferenceData>
            </Result>
            ]]>
        </res:ResultMsg>
</soapenv:Body>
</soapenv:Envelope>';

//file_get_contents("http://localhost:24563/soap_string.xml"); // test xml url :) remove this comment
$pattern = "(<Result(.+)>[\s\S]*?<\/Result>)";
preg_match_all($pattern, $soap_string, $matches);

$xml = simplexml_load_string($matches[0][0]);
echo json_encode($xml);
?>


问:
store Arabic letters into character array matlab
I am trying to make an array of Arabic letters, loop on it and write the letters in text file. The problem is matlab can't recognize it, it gives '?' instead of the letters. I am using matlab 2016a.

```<code>% slCharacterEncoding()
fid = fopen('nv.txt', 'w+', 'n', 'UTF-8');
words = ['ا','ل','ل','ه',' ', 'و'];
for i=1:length(words)
    w=words(1,i);
    fprintf(fid,'%s',w);
end
fclose(fid);
</code>```

The weird thing is that it works when i enter the words array from the command and comment it's line from the code.

答:
One workaround would be to use uint16 to get their 16-bit integer value in the command window i.e.

```<code>>> words = ['ا','ل','ل','ه',' ', 'و'];
>> uint16(words)

ans =

   1575   1604   1604   1607     32   1608
</code>```

Now substitute words = char([1575 1604 1604 1607 32 1608]); in your m-file.

Body:
I am trying to make an array of Arabic letters, loop on it and write the letters in text file. The problem is matlab can't recognize it, it gives '?' instead of the letters. I am using matlab 2016a.

% slCharacterEncoding()
fid = fopen('nv.txt', 'w+', 'n', 'UTF-8');
words = ['ا','ل','ل','ه',' ', 'و'];
for i=1:length(words)
    w=words(1,i);
    fprintf(fid,'%s',w);
end
fclose(fid);

The weird thing is that it works when i enter the words array from the command and comment it's line from the code.

Body:
One workaround would be to use uint16 to get their 16-bit integer value in the command window i.e.

>> words = ['ا','ل','ل','ه',' ', 'و'];
>> uint16(words)

ans =

   1575   1604   1604   1607     32   1608

Now substitute words = char([1575 1604 1604 1607 32 1608]); in your m-file.


问:
Conflict: Multiple assets emit to the same filename
I'm a webpack rookie who wants to learn all about it.
I came across a conflict when running my webpack telling me:

ERROR in chunk html [entry]  app.js  Conflict: Multiple assets emit to
the same filename app.js

What should I do to avoid the conflict?

This is my webpack.config.js:

module.exports = {
  context: __dirname + "/app",

  entry: {
    'javascript': "./js/app.js",
    'html': "./index.html",
  },
  output: {
    path: __dirname + "/dist",
    filename: "app.js",
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ["babel-loader"]
      },
      {
        test: /\.html$/,
        loader: "file-loader?name=[name].[ext]",
      }
    ]
  }
};```

答:
I had the same problem, and I found these in the documents.

If your configuration creates more than a single “chunk” (as with multiple entry points or when using plugins like CommonsChunkPlugin), you should use substitutions to ensure that each file has a unique name.

[name] is replaced by the name of the chunk.

[hash] is replaced by the hash of the compilation.

[chunkhash] is replaced by the hash of the chunk.

```<code> output: {
    path:__dirname+'/dist/js',

    //replace filename:'app.js'
    filename:'[name].js'
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I had the same problem, and I found these in the documents.

If your configuration creates more than a single “chunk” (as with multiple entry points or when using plugins like CommonsChunkPlugin), you should use substitutions to ensure that each file has a unique name.

[name] is replaced by the name of the chunk.

[hash] is replaced by the hash of the compilation.

[chunkhash] is replaced by the hash of the chunk.

 output: {
    path:__dirname+'/dist/js',

    //replace filename:'app.js'
    filename:'[name].js'
}


问:
Get Any/All Active JFrames in Java Application?
Is there a way from within a Java application to list all of the currently open/active (I'm not sure the terminology here) JFrames that are visible on screen? Thanks for your help.

答:
Frame.getFrames() will do your work.

From oracle Doc:

Returns an array of all Frames created by this application. If called
  from an applet, the array includes only the Frames accessible by that
  applet.

A simple example:

```<code>//all frames to a array
Frame[] allFrames = Frame.getFrames();

//Iterate through the allFrames array
for(Frame fr : allFrames){
    //uncomment the below line to see frames names and properties/atr.
    //System.out.println(fr);

    //to get specific frame name
    String specificFrameName = fr.getClass().getName();

    //if found frame that I want I can close or any you want
    //GUIS.CheckForCustomer is my specific frame name that I want to close.
    if(specificFrameName.equals("GUIS.CheckForCustomer")){
        //close the frame
        fr.dispose();
    }
}
</code>```

Also you can use Window.getWindows() as others mentioned.

Body:
Frame.getFrames() will do your work.

From oracle Doc:

Returns an array of all Frames created by this application. If called
  from an applet, the array includes only the Frames accessible by that
  applet.

A simple example:

//all frames to a array
Frame[] allFrames = Frame.getFrames();

//Iterate through the allFrames array
for(Frame fr : allFrames){
    //uncomment the below line to see frames names and properties/atr.
    //System.out.println(fr);

    //to get specific frame name
    String specificFrameName = fr.getClass().getName();

    //if found frame that I want I can close or any you want
    //GUIS.CheckForCustomer is my specific frame name that I want to close.
    if(specificFrameName.equals("GUIS.CheckForCustomer")){
        //close the frame
        fr.dispose();
    }
}

Also you can use Window.getWindows() as others mentioned.


问:
Add item at beginning of array on completion
Almost finished (finally) building a simple to do list.

I'm trying to improve what I've done so far.

One big issue is if say you add a task for e.g. 'Task 1' and then 'Task 2' naturally the array will hold them in that order.

The problem with that is if you 'complete' say Task 2 and then 'uncomplete' it goes back to the top of the list.

But I'm using local storage to save my data so even though it goes to the top of the list on the front end when you refresh it doesn't stay there because in the array it is in position 2.

I'm aware of the 'unshift' method but not sure how to use it here in my completed/uncompleted task methods.

Essentially I want my tasks that go from complete back to uncomplete to be priority and go to the top of the uncompleted task list and thus save that order in my local storage array.

https://jsfiddle.net/1uopkysn/

Thanks

JS

```<code>// To do list

var storeToDos = [];

// Cache DOM
var addToDo = document.getElementById('add-to-do');
var taskHolder = document.getElementById('task-holder');
var uncompleteTasks = document.getElementById('uncompleted-tasks');
var completedTasks = document.getElementById('completed-tasks');

// Bind events
var bindEvents = function(listItem, checkboxEventHandler) {
  // Delete
  var deleteToDo = listItem.querySelector('.delete-to-do');
  deleteToDo.addEventListener('click', deleteTask);
  // Edit
  listItem.querySelector('.edit-to-do').addEventListener('click', editTask);
  listItem.querySelector('.edit-holder').addEventListener('keyup', editTaskEnter);
  // Checkbox
  var checkbox = listItem.querySelector('input.edit-to-do');
  checkbox.onchange = checkboxEventHandler;
}

// Create list item
var createListItem = function() {
  var listItem = document.createElement('li');
  var deleteToDo = document.createElement('div');
  deleteToDo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" stroke="#FFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M7.1 7.1l9.8 9.8M7.1 16.9l9.8-9.8"/></svg>';
  deleteToDo.classList.add('delete-to-do');
  var editToDo = document.createElement('div');
  editToDo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" stroke="#FFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M16 3l5 5L8 21H3v-5z"/></svg>';
  editToDo.classList.add('edit-to-do');
  var toDoStatus = document.createElement('input');
  toDoStatus.type = 'checkbox';
  toDoStatus.classList.add('edit-to-do');
  var editHolder = document.createElement('input');
  editHolder.type = 'text';
  editHolder.classList.add('edit-holder');

  listItem.appendChild(deleteToDo);
  listItem.appendChild(editToDo);
  listItem.appendChild(toDoStatus);
  listItem.appendChild(editHolder);

  return listItem;
}

// Add task
var addTask = function(e) {
  var listItem = createListItem();
  var taskHolderValue = taskHolder.value;
  if(taskHolderValue) {
    var taskHolderElement = document.createElement('label');
    taskHolderElement.classList.add('to-do-item');
    listItem.insertBefore(taskHolderElement, listItem.childNodes[0]);
    var storeToDosObj = {
      value: '',
      id: null,
      completed: false
    }
    storeToDosObj.value = taskHolderValue;
    var listId = storeToDosObj.id = Date.now();
    listItem.id = listId;
    uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
    var storedToDos = localStorage.getItem('todos');
    if(storedToDos) {
      var storedToDosArr = JSON.parse(localStorage.todos);
      storedToDosArr.push(storeToDosObj);
      localStorage.setItem('todos', JSON.stringify(storedToDosArr));
    } else {
      console.log(storeToDos);
      storeToDos.push(storeToDosObj);
      localStorage.setItem('todos', JSON.stringify(storeToDos));
    }
    taskHolderElement.innerHTML = taskHolderValue;
    bindEvents(listItem, taskCompleted);
    taskHolder.value = '';
  } else {
    alert("You didn't add a to a to do!");
  }
}

var addTaskEnter = function(e) {
  var key = 'which' in e ? e.which : e.keyCode;
  if(key === 13) {
    addTask();
  }
}

// Delete task
var deleteTask = function() {
  var listItem = this.parentNode;
  var parentItem = listItem.parentNode;
  var getToDos = JSON.parse(localStorage.getItem('todos'));
  for(var b=0; b<getToDos.length; b++) {
    if(getToDos[b].id == listItem.id) {
      getToDos.splice(b, 1);
      localStorage.setItem('todos', JSON.stringify(getToDos));
    }
  }
  parentItem.removeChild(listItem);
}

// Edit task
var editTask = function() {
  var defaultValue = this.parentNode.querySelector('label').innerHTML;
  var listItem = this.parentNode;
  var listParent = this.parentNode;
  var editedValue = listParent.querySelector('input.edit-holder').value;
  if(listItem.classList.contains('editing') && editedValue) {
    listParent.querySelector('label').innerHTML = editedValue;
    var storedLocalStorage = JSON.parse(localStorage.todos);
    for(var d=0; d<storedLocalStorage.length; d++) {
      if(storedLocalStorage[d].id == listItem.id) {
        storedLocalStorage[d].value = editedValue;
        localStorage.setItem('todos', JSON.stringify(storedLocalStorage));
      }
    }
  }
  listItem.classList.toggle('editing');
  listParent.querySelector('input.edit-holder').value = '';
}

// Edit task enter
var editTaskEnter = function(e) {
  var key = 'which' in e ? e.which : e.keyCode;
  if(key === 13) {
    editTask.call(this);
  }
}

// Task completed
var taskCompleted = function() {
  var listItem = this.parentNode;

  var storedCompletion = JSON.parse(localStorage.getItem('todos'));
  if(storedCompletion) {
    if(listItem.classList.contains('editing')) {

    }
    for(var e=0; e<storedCompletion.length; e++) {
      if(storedCompletion[e].id == listItem.id) {
        if(storedCompletion[e].completed === true) {
          this.parentNode.classList.add('completed');
          uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
          this.parentNode.classList.remove('completed');
          bindEvents(listItem, taskCompleted);
          storedCompletion[e].completed = false;
        } else {
          completedTasks.insertBefore(listItem, completedTasks.childNodes[0]);
          this.parentNode.classList.add('completed');
          bindEvents(listItem, taskUncompleted);
          storedCompletion[e].completed = true;
        }
        localStorage.setItem('todos', JSON.stringify(storedCompletion));
      }
    }
  }
}

// Task uncompleted
var taskUncompleted = function() {
  var listItem = this.parentNode;
  uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
  this.parentNode.classList.remove('completed');
  bindEvents(listItem, taskCompleted);

  if(localStorage) {
    var storedCompletion = JSON.parse(localStorage.getItem('todos'));
  }

  for(var f=0; f<storedCompletion.length; f++) {
    if(storedCompletion[f].id == listItem.id) {
      storedCompletion[f].completed = false;
      localStorage.setItem('todos', JSON.stringify(storedCompletion));
    }
  }
}

// Add task
addToDo.addEventListener("click", addTask);
taskHolder.addEventListener("keyup", addTaskEnter);

// Loop over complete tasks
for(i=0; i<completedTasks.length; i++) {
  var listItem = completedTasks[i];
  uncompleteTasks.appendChild(listItem);
  bindEvents(listItem, completedTasks);
}

// Render local storage
var getToDos = JSON.parse(localStorage.getItem('todos'));
console.log(getToDos);
if(getToDos) {
  for(i=0; i<getToDos.length; i++) {
    var listItem = createListItem();
    listItem.id = getToDos[i].id;
    var storedListItem = document.createElement('label');
    storedListItem.innerHTML = getToDos[i].value;
    listItem.insertBefore(storedListItem, listItem.childNodes[0]);
    if(getToDos[i].completed === true) {
      listItem.querySelector('input').checked = true;
      completedTasks.appendChild(listItem);
      listItem.classList.add('completed');
    } else {
      uncompleteTasks.appendChild(listItem);
    }
    bindEvents(listItem, taskCompleted)
  }
}
</code>```

答:
How about updating the stored array when you change something in memory?
So each time you make a change to your view, you update the "model", thus the JSON array and save it again. </p>

Body:
Almost finished (finally) building a simple to do list.

I'm trying to improve what I've done so far.

One big issue is if say you add a task for e.g. 'Task 1' and then 'Task 2' naturally the array will hold them in that order.

The problem with that is if you 'complete' say Task 2 and then 'uncomplete' it goes back to the top of the list.

But I'm using local storage to save my data so even though it goes to the top of the list on the front end when you refresh it doesn't stay there because in the array it is in position 2.

I'm aware of the 'unshift' method but not sure how to use it here in my completed/uncompleted task methods.

Essentially I want my tasks that go from complete back to uncomplete to be priority and go to the top of the uncompleted task list and thus save that order in my local storage array.

https://jsfiddle.net/1uopkysn/

Thanks

JS

// To do list

var storeToDos = [];

// Cache DOM
var addToDo = document.getElementById('add-to-do');
var taskHolder = document.getElementById('task-holder');
var uncompleteTasks = document.getElementById('uncompleted-tasks');
var completedTasks = document.getElementById('completed-tasks');

// Bind events
var bindEvents = function(listItem, checkboxEventHandler) {
  // Delete
  var deleteToDo = listItem.querySelector('.delete-to-do');
  deleteToDo.addEventListener('click', deleteTask);
  // Edit
  listItem.querySelector('.edit-to-do').addEventListener('click', editTask);
  listItem.querySelector('.edit-holder').addEventListener('keyup', editTaskEnter);
  // Checkbox
  var checkbox = listItem.querySelector('input.edit-to-do');
  checkbox.onchange = checkboxEventHandler;
}

// Create list item
var createListItem = function() {
  var listItem = document.createElement('li');
  var deleteToDo = document.createElement('div');
  deleteToDo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" stroke="#FFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M7.1 7.1l9.8 9.8M7.1 16.9l9.8-9.8"/></svg>';
  deleteToDo.classList.add('delete-to-do');
  var editToDo = document.createElement('div');
  editToDo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" stroke="#FFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M16 3l5 5L8 21H3v-5z"/></svg>';
  editToDo.classList.add('edit-to-do');
  var toDoStatus = document.createElement('input');
  toDoStatus.type = 'checkbox';
  toDoStatus.classList.add('edit-to-do');
  var editHolder = document.createElement('input');
  editHolder.type = 'text';
  editHolder.classList.add('edit-holder');

  listItem.appendChild(deleteToDo);
  listItem.appendChild(editToDo);
  listItem.appendChild(toDoStatus);
  listItem.appendChild(editHolder);

  return listItem;
}

// Add task
var addTask = function(e) {
  var listItem = createListItem();
  var taskHolderValue = taskHolder.value;
  if(taskHolderValue) {
    var taskHolderElement = document.createElement('label');
    taskHolderElement.classList.add('to-do-item');
    listItem.insertBefore(taskHolderElement, listItem.childNodes[0]);
    var storeToDosObj = {
      value: '',
      id: null,
      completed: false
    }
    storeToDosObj.value = taskHolderValue;
    var listId = storeToDosObj.id = Date.now();
    listItem.id = listId;
    uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
    var storedToDos = localStorage.getItem('todos');
    if(storedToDos) {
      var storedToDosArr = JSON.parse(localStorage.todos);
      storedToDosArr.push(storeToDosObj);
      localStorage.setItem('todos', JSON.stringify(storedToDosArr));
    } else {
      console.log(storeToDos);
      storeToDos.push(storeToDosObj);
      localStorage.setItem('todos', JSON.stringify(storeToDos));
    }
    taskHolderElement.innerHTML = taskHolderValue;
    bindEvents(listItem, taskCompleted);
    taskHolder.value = '';
  } else {
    alert("You didn't add a to a to do!");
  }
}

var addTaskEnter = function(e) {
  var key = 'which' in e ? e.which : e.keyCode;
  if(key === 13) {
    addTask();
  }
}

// Delete task
var deleteTask = function() {
  var listItem = this.parentNode;
  var parentItem = listItem.parentNode;
  var getToDos = JSON.parse(localStorage.getItem('todos'));
  for(var b=0; b<getToDos.length; b++) {
    if(getToDos[b].id == listItem.id) {
      getToDos.splice(b, 1);
      localStorage.setItem('todos', JSON.stringify(getToDos));
    }
  }
  parentItem.removeChild(listItem);
}

// Edit task
var editTask = function() {
  var defaultValue = this.parentNode.querySelector('label').innerHTML;
  var listItem = this.parentNode;
  var listParent = this.parentNode;
  var editedValue = listParent.querySelector('input.edit-holder').value;
  if(listItem.classList.contains('editing') && editedValue) {
    listParent.querySelector('label').innerHTML = editedValue;
    var storedLocalStorage = JSON.parse(localStorage.todos);
    for(var d=0; d<storedLocalStorage.length; d++) {
      if(storedLocalStorage[d].id == listItem.id) {
        storedLocalStorage[d].value = editedValue;
        localStorage.setItem('todos', JSON.stringify(storedLocalStorage));
      }
    }
  }
  listItem.classList.toggle('editing');
  listParent.querySelector('input.edit-holder').value = '';
}

// Edit task enter
var editTaskEnter = function(e) {
  var key = 'which' in e ? e.which : e.keyCode;
  if(key === 13) {
    editTask.call(this);
  }
}

// Task completed
var taskCompleted = function() {
  var listItem = this.parentNode;

  var storedCompletion = JSON.parse(localStorage.getItem('todos'));
  if(storedCompletion) {
    if(listItem.classList.contains('editing')) {

    }
    for(var e=0; e<storedCompletion.length; e++) {
      if(storedCompletion[e].id == listItem.id) {
        if(storedCompletion[e].completed === true) {
          this.parentNode.classList.add('completed');
          uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
          this.parentNode.classList.remove('completed');
          bindEvents(listItem, taskCompleted);
          storedCompletion[e].completed = false;
        } else {
          completedTasks.insertBefore(listItem, completedTasks.childNodes[0]);
          this.parentNode.classList.add('completed');
          bindEvents(listItem, taskUncompleted);
          storedCompletion[e].completed = true;
        }
        localStorage.setItem('todos', JSON.stringify(storedCompletion));
      }
    }
  }
}

// Task uncompleted
var taskUncompleted = function() {
  var listItem = this.parentNode;
  uncompleteTasks.insertBefore(listItem, uncompleteTasks.childNodes[0]);
  this.parentNode.classList.remove('completed');
  bindEvents(listItem, taskCompleted);

  if(localStorage) {
    var storedCompletion = JSON.parse(localStorage.getItem('todos'));
  }

  for(var f=0; f<storedCompletion.length; f++) {
    if(storedCompletion[f].id == listItem.id) {
      storedCompletion[f].completed = false;
      localStorage.setItem('todos', JSON.stringify(storedCompletion));
    }
  }
}

// Add task
addToDo.addEventListener("click", addTask);
taskHolder.addEventListener("keyup", addTaskEnter);

// Loop over complete tasks
for(i=0; i<completedTasks.length; i++) {
  var listItem = completedTasks[i];
  uncompleteTasks.appendChild(listItem);
  bindEvents(listItem, completedTasks);
}

// Render local storage
var getToDos = JSON.parse(localStorage.getItem('todos'));
console.log(getToDos);
if(getToDos) {
  for(i=0; i<getToDos.length; i++) {
    var listItem = createListItem();
    listItem.id = getToDos[i].id;
    var storedListItem = document.createElement('label');
    storedListItem.innerHTML = getToDos[i].value;
    listItem.insertBefore(storedListItem, listItem.childNodes[0]);
    if(getToDos[i].completed === true) {
      listItem.querySelector('input').checked = true;
      completedTasks.appendChild(listItem);
      listItem.classList.add('completed');
    } else {
      uncompleteTasks.appendChild(listItem);
    }
    bindEvents(listItem, taskCompleted)
  }
}


问:
Creating dynamic array name in python numpy
There are already several similar questions on SO, for example How do I create a variable number of variables?. But I think my question is bit different one.

I want to create dynamic array names. MATLAB (and Octave) has built in data structure cell array that can do the job. For example code creates A{1} to A{10} variables dynamically. var1 is 'dynamic input' to program.

```<code>var1=10;
for j=1:1:var1
  A{j} = {}; %creating empty cell
end
%resizing empty cells using a loop, arrays can be of different size
</code>```

As answered in the first question, python has dictionary to do this task. However, I am working with huge amount of data stored in form of arrays, and need to use numpy array as they are faster than python built in lists. Any suggestions?

Update:
I want to create variable size arrays afterwards.

答:
Ok so from what I understand you want to create several arrays of different sizes, so the final datastructure is not rectangular. Numpy-arrays have to be rectangular, so you cannot just use them.
What you can do is to create a list of numpy-arrays. A list is just a datastructure that holds a sequence of arbitrary objects, so it does not care if its elements are arrays of the same size.

If you want to translate your code 1:1, do something like this:

```<code>import numpy as np

var1=10;
a = []
for j in range(var1):
    # you cant use a[j] in python because the j-th element does not exist yet, so use .append instead to add an element to the end
    a.append(np.array(0))
end
</code>```

Now you have a list of 10 empty numpy arrays and you can loop through them to resize them or add data etc.

An easier method to get the above is this, its just different syntax:

```<code>import numpy as np

var1 = 10
a = [np.array(0) for i in range(var1)]
</code>```

To change, resize, add data just loop through the list:

```<code>for arr in a:
    # arr is the numpy array
    arr.resize(...)
</code>```

Body:
There are already several similar questions on SO, for example How do I create a variable number of variables?. But I think my question is bit different one.

I want to create dynamic array names. MATLAB (and Octave) has built in data structure cell array that can do the job. For example code creates A{1} to A{10} variables dynamically. var1 is 'dynamic input' to program.

var1=10;
for j=1:1:var1
  A{j} = {}; %creating empty cell
end
%resizing empty cells using a loop, arrays can be of different size

As answered in the first question, python has dictionary to do this task. However, I am working with huge amount of data stored in form of arrays, and need to use numpy array as they are faster than python built in lists. Any suggestions?

Update:
I want to create variable size arrays afterwards.

Body:
Ok so from what I understand you want to create several arrays of different sizes, so the final datastructure is not rectangular. Numpy-arrays have to be rectangular, so you cannot just use them.
What you can do is to create a list of numpy-arrays. A list is just a datastructure that holds a sequence of arbitrary objects, so it does not care if its elements are arrays of the same size.

If you want to translate your code 1:1, do something like this:

import numpy as np

var1=10;
a = []
for j in range(var1):
    # you cant use a[j] in python because the j-th element does not exist yet, so use .append instead to add an element to the end
    a.append(np.array(0))
end

Now you have a list of 10 empty numpy arrays and you can loop through them to resize them or add data etc.

An easier method to get the above is this, its just different syntax:

import numpy as np

var1 = 10
a = [np.array(0) for i in range(var1)]

To change, resize, add data just loop through the list:

for arr in a:
    # arr is the numpy array
    arr.resize(...)


问:
fpga: choosing c++ to program fpga
I keep hearing mostly from electrical engineers that C is used for fpga work.

What about C++? Are there any disadvantages to using C++? I would think that the parallelism desired when programming for hardware would be better served by C++ more than C, no?

Also what do I use after that to make compatible c++ with the hardware?

答:
What you are referring to is "behavioral synthesis", a compilation technique that allows to take sequential code as input (C, SystemC, C++) and generate automatically a FSM+Datapath pair in VHDL or Verilog, that can then be synthesized using regular Xilinx or Altera synthesizers.

To date, there are many "behavioral synthesizers" :

CatapultC from Mentor Graphics allows you to use a big subset of C and also C++

Cynthesizer from Forte Design System (systemC based) [edit 2015: now Cadence]

for FPGA, ImpulseC seems quite mature

[edit 2015] for Xilinx FPGA : Vivado-HLS

Hope this helps

Title: fpga: choosing c++ to program fpga


问:
remove spaces in every where in the string python
I have below string

```<code> a = " Get a Pen"
</code>```

Code:

```<code> if a.lower().strip() == "get a pen"
     print "removed white spaces"
</code>```

need help to achieve remove all spaces in the string

```<code> if a.lower.().strip() =="getapen" # which is the easiest way remove all spaces
      print "remove all spaces in the string"
</code>```

答:
As @ChristianDean pointed out, do</p>

```<code>if a.lower().replace(' ', '') == 'getapen':
    print "remove all spaces in the string"
</code>```

Body:
I have below string

 a = " Get a Pen"

Code:

 if a.lower().strip() == "get a pen"
     print "removed white spaces"

need help to achieve remove all spaces in the string

 if a.lower.().strip() =="getapen" # which is the easiest way remove all spaces
      print "remove all spaces in the string"

Body:
As @ChristianDean pointed out, do

if a.lower().replace(' ', '') == 'getapen':
    print "remove all spaces in the string"


问:
Social Login of facebook not working in ASP.Net MVC 5 project
I am going through a tutorial to implement facebook social log in my sample web site. Below are the steps I did.

Pointed my localhost application to https and allowed fake SSL in VS.

Created a web app in facebook developer web site and noted down the secret key and id.

Added my application localhost URL in the URL section of the dashboard in facebook

I added key and id in the starup.Auth.cs file in my ASP.Net MVC-5 project .

Behavour: Now when I run my application from local host (https) and click Register then I see the facebook sign in button. Also when I click that button a facebook pop up comes with "Sample App" wants to access your facebook data. So far so good. But as I say YES to it nothing happens after that. I get redirected to the log in page. and the URL is https://localhost:44393/Account/Login#_=_

Expected Behaviour: For the tutorial that I am following after doing above steps one message comes on tutors screen as "Facebook has authenticated.... Enter you email to continue". Something like this. Can some one please guide me here why I am not getting same message and why I am not able to use social log in. I have tried to follow all the steps.

Expected Screenshot from tutorial

Is there any other steps I need to do in facebook developer dashboard?

EDIT 1 :

In the facebook developer dashboard for my app in the Facbook Login Tab->Settings : I see below message.

EDIT 2: I debugged and found that returnURL is null when I click on facebook log in button.

```<code>   [AllowAnonymous]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                return RedirectToAction("Login");
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
</code>```

答:
Simply update the Windows.Owin.Security.Facebook to latest version(3.1.0)
further in facebook application update the "Valid OAuth redirect URIs" to "http://localhost:xxxx/signin-facebook" (in my case) every thing works...

OR

Please see the link ExternalLoginConfirmation returns null after facebook succesful login

Body:
I am going through a tutorial to implement facebook social log in my sample web site. Below are the steps I did.

Pointed my localhost application to https and allowed fake SSL in VS.

Created a web app in facebook developer web site and noted down the secret key and id.

Added my application localhost URL in the URL section of the dashboard in facebook

I added key and id in the starup.Auth.cs file in my ASP.Net MVC-5 project .

Behavour: Now when I run my application from local host (https) and click Register then I see the facebook sign in button. Also when I click that button a facebook pop up comes with "Sample App" wants to access your facebook data. So far so good. But as I say YES to it nothing happens after that. I get redirected to the log in page. and the URL is https://localhost:44393/Account/Login#_=_

Expected Behaviour: For the tutorial that I am following after doing above steps one message comes on tutors screen as "Facebook has authenticated.... Enter you email to continue". Something like this. Can some one please guide me here why I am not getting same message and why I am not able to use social log in. I have tried to follow all the steps.

Expected Screenshot from tutorial

Is there any other steps I need to do in facebook developer dashboard?

EDIT 1 :

In the facebook developer dashboard for my app in the Facbook Login Tab->Settings : I see below message.

EDIT 2: I debugged and found that returnURL is null when I click on facebook log in button.

   [AllowAnonymous]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                return RedirectToAction("Login");
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);


问:
Select count, inner joins and where statements
This is erp.orders:

```<code>userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01
</code>```

This is prod.referral_order_delivered

```<code>user_id
1
2
</code>```

This request :

```<code>select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"
</code>```

will give me this result:

```<code>userId  count
1       2
2       1
</code>```

This is not the result I want. Among the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered, I want to count how many times they appear in the table erp.orders IN TOTAL.
In my current request, I only count from 2017-06-07 to 2017-07-07.

The result I want is :

```<code>userId  count
1       2
2       4
</code>```

See how userId 3 and 4 are excluded. This is really important. Could you modify my request, please?

答:
Use a having clause instead of a where clause:

```<code>select o."userId", count(o."userId")
from erp.orders o inner join
     prod.referral_order_delivered rod
     on o."userId"::uuid = rod.user_id::uuid
group by o."userId"
having sum( (o."paidAt"::date >= '2017-06-07' and o."paidAt"::date <= '2017-07-07')::int) > 0;
</code>```

Body:
This is erp.orders:

userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01

This is prod.referral_order_delivered

user_id
1
2

This request :

select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"

will give me this result:

userId  count
1       2
2       1

This is not the result I want. Among the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered, I want to count how many times they appear in the table erp.orders IN TOTAL.
In my current request, I only count from 2017-06-07 to 2017-07-07.

The result I want is :

userId  count
1       2
2       4

See how userId 3 and 4 are excluded. This is really important. Could you modify my request, please?

Body:
Use a having clause instead of a where clause:

select o."userId", count(o."userId")
from erp.orders o inner join
     prod.referral_order_delivered rod
     on o."userId"::uuid = rod.user_id::uuid
group by o."userId"
having sum( (o."paidAt"::date >= '2017-06-07' and o."paidAt"::date <= '2017-07-07')::int) > 0;