问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
Let's talk about this problem in generalities first, then specifics.

In this problem what you want to do is select rows from table A depending on conditions in two (or for the general case, more than two) rows in table B.  In order to accomplish this, you need to do one of two things:

execute tests against different rows in table B

aggregate the rows of interest from table B into a single row which somehow contains the information you need to test the original rows from table B

This kind of problem is the big reason why, I think, you see people creating comma-delimited lists in VARCHAR fields instead of normalizing their databases correctly.

In your example, you want to select user rows based on the existence of rows matching two specific conditions in tags.

(1) Testing different rows.

There are three ways you can use technique (1) (testing different rows).  They are using EXISTS, using sub-queries, and using JOINs:

1A. Using EXISTs is (in my opinion, anyway) clear because it matches what you're trying to do — checking for existence of rows.  This is moderately scalable to more tags in terms of writing the SQL creation if you're generating dynamic SQL, you simple add an additional AND EXISTS clause for each tag (performance, of course, will suffer):

```<code>SELECT * FROM users WHERE
  EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag1') AND
  EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag2')
</code>```

I think this clearly expresses the intent of the query.

1B Using sub-queries is also pretty clear.  Because this technique does not involve correlated sub-queries some engines can optimize it better (it depends, in part, on the number of users with any given tag):

```<code>SELECT * FROM users WHERE
  id IN (SELECT user_id FROM tags WHERE name ='tag1') AND
  id IN (SELECT user_id FROM tags WHERE name ='tag2')
</code>```

This scales the same way that option 1A does.  It's also (to me, anyway) pretty clear.

1C Using JOINs involves INNER JOINing the tags table to the users table once for each tag.  It doesn't scale as well because it's harder (but still possible) to generate the dynamic SQL:

```<code>SELECT u.* FROM users u
     INNER JOIN tags t1 ON u.id = t1.user_id
     INNER JOIN tags t2 ON u.id = t2.user_id
  WHERE t1.name = 'tag1' AND t2.name = 'tag2'
</code>```

Personally, I feel this is considerably less clear than the other two options since it looks like the goal is to create a JOINed record set rather than filter the users table. Also, scalability suffers because you need to add INNER JOINs and change the WHERE clause. Note that this technique sort of straddles techniques 1 and 2 because it uses the JOINs to aggregate two rows from tags.

(2) Aggregating rows.

There are a two main ways of doing this, using COUNTs and using string processing:

2A Using COUNTs is much easier if your tags table is "protected" against having the same tag applied twice to the same user.  You can do this by making (user_id, name) the PRIMARY KEY in tags, or by creating a UNIQUE INDEX on those two columns.  If the rows are protected in that way you can do this:

```<code> SELECT users.id, users.user_name
   FROM users INNER JOIN tags ON users.id = tags.user_id
   WHERE tags.name IN ('tag1', 'tag2')
   GROUP BY users.id, users.user_name
   HAVING COUNT(*) = 2
</code>```

In this case you match the HAVING COUNT(*) = test value against the number of tags name in the IN clause.  This does not work if each tag can be applied to a user more than once because the count of 2 could be produced by two instances of 'tag1' and none of 'tag2' (and the row would qualify where it shouldn't) or two instances of 'tag1' plus one instance of 'tag2' would create a count of 3 (and the user would not qualify even though they should).

Note that this is the most scalable technique performance-wise since you can add additional tags and no additional queries or JOINs are needed.

If multiple tags are allowed you can perform an inner aggregation to remove the duplicates.  You can do this in the same query I showed above, but for simplicity sake I'm going to break the logic out into a separate view:

```<code> CREATE VIEW tags_dedup (user_id, name) AS
 SELECT DISTINCT user_id, name FROM tags
</code>```

and then you go back to the query above and substitute tags_dedup for tags.

2B Using String processing is database specific because there is no standard SQL aggregate function to produce string lists from multiple rows.  Some databases, however, offer extensions to do this.  In MySQL, you can use GROUP_CONCAT and FIND_IN_SET to do this:

```<code>SELECT user.id, users.user_name, GROUP_CONCAT(tags.name) as all_tags
  FROM users INNER JOIN tags ON users.id = tags.user_id
  GROUP BY users.id, users.user_name
  HAVING FIND_IN_SET('tag1', all_tags) > 0 AND
         FIND_IN_SET('tag2', all_tags) > 0
</code>```

Note, this is very inefficient and uses MySQL unique extensions.

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

Body:
Let's talk about this problem in generalities first, then specifics.

In this problem what you want to do is select rows from table A depending on conditions in two (or for the general case, more than two) rows in table B.  In order to accomplish this, you need to do one of two things:

execute tests against different rows in table B

aggregate the rows of interest from table B into a single row which somehow contains the information you need to test the original rows from table B

This kind of problem is the big reason why, I think, you see people creating comma-delimited lists in VARCHAR fields instead of normalizing their databases correctly.

In your example, you want to select user rows based on the existence of rows matching two specific conditions in tags.

(1) Testing different rows.

There are three ways you can use technique (1) (testing different rows).  They are using EXISTS, using sub-queries, and using JOINs:

1A. Using EXISTs is (in my opinion, anyway) clear because it matches what you're trying to do — checking for existence of rows.  This is moderately scalable to more tags in terms of writing the SQL creation if you're generating dynamic SQL, you simple add an additional AND EXISTS clause for each tag (performance, of course, will suffer):

SELECT * FROM users WHERE
  EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag1') AND
  EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag2')

I think this clearly expresses the intent of the query.

1B Using sub-queries is also pretty clear.  Because this technique does not involve correlated sub-queries some engines can optimize it better (it depends, in part, on the number of users with any given tag):

SELECT * FROM users WHERE
  id IN (SELECT user_id FROM tags WHERE name ='tag1') AND
  id IN (SELECT user_id FROM tags WHERE name ='tag2')

This scales the same way that option 1A does.  It's also (to me, anyway) pretty clear.

1C Using JOINs involves INNER JOINing the tags table to the users table once for each tag.  It doesn't scale as well because it's harder (but still possible) to generate the dynamic SQL:

SELECT u.* FROM users u
     INNER JOIN tags t1 ON u.id = t1.user_id
     INNER JOIN tags t2 ON u.id = t2.user_id
  WHERE t1.name = 'tag1' AND t2.name = 'tag2'

Personally, I feel this is considerably less clear than the other two options since it looks like the goal is to create a JOINed record set rather than filter the users table. Also, scalability suffers because you need to add INNER JOINs and change the WHERE clause. Note that this technique sort of straddles techniques 1 and 2 because it uses the JOINs to aggregate two rows from tags.

(2) Aggregating rows.

There are a two main ways of doing this, using COUNTs and using string processing:

2A Using COUNTs is much easier if your tags table is "protected" against having the same tag applied twice to the same user.  You can do this by making (user_id, name) the PRIMARY KEY in tags, or by creating a UNIQUE INDEX on those two columns.  If the rows are protected in that way you can do this:

 SELECT users.id, users.user_name
   FROM users INNER JOIN tags ON users.id = tags.user_id
   WHERE tags.name IN ('tag1', 'tag2')
   GROUP BY users.id, users.user_name
   HAVING COUNT(*) = 2

In this case you match the HAVING COUNT(*) = test value against the number of tags name in the IN clause.  This does not work if each tag can be applied to a user more than once because the count of 2 could be produced by two instances of 'tag1' and none of 'tag2' (and the row would qualify where it shouldn't) or two instances of 'tag1' plus one instance of 'tag2' would create a count of 3 (and the user would not qualify even though they should).

Note that this is the most scalable technique performance-wise since you can add additional tags and no additional queries or JOINs are needed.

If multiple tags are allowed you can perform an inner aggregation to remove the duplicates.  You can do this in the same query I showed above, but for simplicity sake I'm going to break the logic out into a separate view:

 CREATE VIEW tags_dedup (user_id, name) AS
 SELECT DISTINCT user_id, name FROM tags

and then you go back to the query above and substitute tags_dedup for tags.

2B Using String processing is database specific because there is no standard SQL aggregate function to produce string lists from multiple rows.  Some databases, however, offer extensions to do this.  In MySQL, you can use GROUP_CONCAT and FIND_IN_SET to do this:

SELECT user.id, users.user_name, GROUP_CONCAT(tags.name) as all_tags
  FROM users INNER JOIN tags ON users.id = tags.user_id
  GROUP BY users.id, users.user_name
  HAVING FIND_IN_SET('tag1', all_tags) > 0 AND
         FIND_IN_SET('tag2', all_tags) > 0

Note, this is very inefficient and uses MySQL unique extensions.


来源: stackexchange

问:
How to debug "MethodNotAllowedHttpException" in Symfony?
I created a backend for my site with an "add product" function but when I add it I do not create the product on the table and I have this error

I have this error:

```<code>Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
No message
</code>```

My form:

@extends('admin.layout.admin')

@section('content')

Aggiungi Prodotto

    {!! Form::open(['route'=>'product.create','method'=>'post', 'files'=>true]) !!}

    {{ Form::label('nome', 'Nome') }}
    {{ Form::text('nome', null, array('class'=> 'form-control')) }}

    {{ Form::label('descrizione', 'Descrizione') }}
    {{ Form::text('descrizione', null, array('class'=> 'form-control')) }}

    {{ Form::label('prezzo', 'Prezzo') }}
    {{ Form::text('prezzo', null, array('class'=> 'form-control')) }}

    {{ Form::label('category_id', 'Categoria') }}
    {{ Form::select('category_id',[1=>'Flauti'],null,['class'=> 'form-control','placeholder'=>'Seleziona Categoria']) }}

    {{ Form::label('image', 'Image') }}
    {{ Form::file('image',array('class'=> 'form-control')) }}

  {{ Form::submit('create', array('class'=>'btn btn-->default')) }}

  {!! Form::close() !!}

@endsection```
</div>
</div>
</p>

<p>My routes:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code><?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', 'frontcontroller@index');
Route::get('/index.html', 'frontcontroller@index');
Route::get('/checkout.html', 'frontcontroller@checkout');
Route::get('/furniture.html', 'frontcontroller@furniture');
Route::get('/login.html', 'frontcontroller@login');
Route::get('/products.html', 'frontcontroller@products');
Route::get('/register.html', 'frontcontroller@register');
Route::get('/single.html', 'frontcontroller@single');
Auth::routes();

Route::get('/logout', 'Auth\LoginController@logout')->name('home');;

Route::get('/home', 'HomeController@index')->name('home');

Route::group(['prefix' => 'admin' ,'middleware'=>'auth'], function () {
  Route::get('/', function () {
   return view('admin.index');
  })->name('admin.index');

Route::resource('product','ProductsController');
Route::resource('category','CategoriesController');

});</code>```

My controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;

class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories=Category::pluck('nome','id');
        return view('admin.product.create',compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $formInput=$request->except('image');
        //image upload
        $image=$request->image;
        if ($image){
            $imageName=$image->getClientOriginName();
            $image->move('image',$imageName);
            $formInput['image']=$imageName;
    }
        Product::create($formInput);
        return redirect()->route('admin.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

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

答:
Please change following line in your form

```<code>{!! Form::open(['route'=>'product.create','method'=>'post', 'files'=>true]) !!}
</code>```

to

```<code>{!! Form::open(['route'=>'product.store','method'=>'post', 'files'=>true]) !!}
</code>```

basically, create routes are to show forms when you use Resources. But when you want to submit the form you need to submit to .store or if it's an edit form then submit to .update route.

ContentLicense: CC BY-SA 3.0

Body:
I created a backend for my site with an "add product" function but when I add it I do not create the product on the table and I have this error

I have this error:

Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
No message

My form:

@extends('admin.layout.admin')

@section('content')

Aggiungi Prodotto

    {!! Form::open(['route'=>'product.create','method'=>'post', 'files'=>true]) !!}

    {{ Form::label('nome', 'Nome') }}
    {{ Form::text('nome', null, array('class'=> 'form-control')) }}

    {{ Form::label('descrizione', 'Descrizione') }}
    {{ Form::text('descrizione', null, array('class'=> 'form-control')) }}

    {{ Form::label('prezzo', 'Prezzo') }}
    {{ Form::text('prezzo', null, array('class'=> 'form-control')) }}

    {{ Form::label('category_id', 'Categoria') }}
    {{ Form::select('category_id',[1=>'Flauti'],null,['class'=> 'form-control','placeholder'=>'Seleziona Categoria']) }}

    {{ Form::label('image', 'Image') }}
    {{ Form::file('image',array('class'=> 'form-control')) }}

  {{ Form::submit('create', array('class'=>'btn btn-->default')) }}

  {!! Form::close() !!}

@endsection

My routes:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', 'frontcontroller@index');
Route::get('/index.html', 'frontcontroller@index');
Route::get('/checkout.html', 'frontcontroller@checkout');
Route::get('/furniture.html', 'frontcontroller@furniture');
Route::get('/login.html', 'frontcontroller@login');
Route::get('/products.html', 'frontcontroller@products');
Route::get('/register.html', 'frontcontroller@register');
Route::get('/single.html', 'frontcontroller@single');
Auth::routes();

Route::get('/logout', 'Auth\LoginController@logout')->name('home');;

Route::get('/home', 'HomeController@index')->name('home');

Route::group(['prefix' => 'admin' ,'middleware'=>'auth'], function () {
  Route::get('/', function () {
   return view('admin.index');
  })->name('admin.index');

Route::resource('product','ProductsController');
Route::resource('category','CategoriesController');

});

My controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;

class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories=Category::pluck('nome','id');
        return view('admin.product.create',compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $formInput=$request->except('image');
        //image upload
        $image=$request->image;
        if ($image){
            $imageName=$image->getClientOriginName();
            $image->move('image',$imageName);
            $formInput['image']=$imageName;
    }
        Product::create($formInput);
        return redirect()->route('admin.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

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

Body:
Please change following line in your form

{!! Form::open(['route'=>'product.create','method'=>'post', 'files'=>true]) !!}

to

{!! Form::open(['route'=>'product.store','method'=>'post', 'files'=>true]) !!}

basically, create routes are to show forms when you use Resources. But when you want to submit the form you need to submit to .store or if it's an edit form then submit to .update route.


问:
Netlogo: Syntax issue for setting neighbor values
I'm using Netlogo and I'd like to set up a scenario whereby my turtles cannot move to the previous patch, nor can they move to the previous-previous patch (i.e. patches an individual turtle occupied at t-1 and at t-2).

I've set things up as shown below. The idea is to set neighbors that have already been visited by the current turtle to have a patch_attractiveness of zero, so they can't be selected. I think I'm just struggling with the correct syntax. The line at issue is the one that starts with "set previously_visited_patches"

```<code>patches-own [patch_attractiveness]

turtles-own [previous2_patches]

to setup
  create-turtles 100  [
    set previous2_patches (list patch-here)
  ]
end

to go
  tick

  ask turtles [
    let previous_patchset patch-set previous2_patches
    let previously_visited_neighbors neighbors with [member? self previous_patchset]
    ask previously_visited_neighbours [
      set patch_attractiveness 0
    ]
    face max-one-of neighbors [patch_attractiveness]
    fd 1
  ]

  set previous2_patches lput patch-here previous2_patches
  if (ticks > 1) [
    set previous2_patches remove-item 0 previous2_patches
  ]

end
</code>```

The code as it stands seems to select the t-2 patch but not the t-1 patch as well. Anyone got any bright ideas? I'm assuming that "self" may not be the right call to make

Many thanks

答:
Okay, I think this does what you want.

```<code>patches-own [patch-attractiveness]

turtles-own [previous2-patches]

to setup
  clear-all
  create-turtles 100
  [ setxy random-xcor random-ycor
    set previous2-patches (list patch-here patch-here)
  ]
  ask patches [ set patch-attractiveness random 50 ]
  reset-ticks
end

to go
  ask turtles
  [ let candidates viable-neighbours neighbors previous2-patches
    if any? candidates
    [ face max-one-of candidates [patch-attractiveness]
      forward 1
      set previous2-patches (list patch-here item 0 previous2-patches)
    ]
  ]
end

to-report viable-neighbours [ set-of-patches delete-list ]
  let viable set-of-patches
  foreach delete-list
  [ x -> if member? x viable [ ask x [ set viable other viable ] ] ]
  report viable
end
</code>```

First, I changed the variable names to hyphens instead of underscore. Sorry, hyphens is sort of conventional in NetLogo and I didn't realise you'd used underscores until I got errors.

I did some simplifying. I scrapped your stuff about setting attractiveness to 0 due to comments. I also simplified the setup so that the starting list of excluded patches is simply two copies of the current patch (which means you don't need the if ticks > 1 test). I also created the new list from the current patch and the relevant item in the existing list - your lput and remove is more correct but since the list is only ever two items, this is easier to read. You should definitely retain the lput/remove structure if you may want to increase the memory of patches to exclude.

The important bit though is the new procedure. You pass it an agentset (in your case neighbors) and a list of agents to exclude (in your case the turtle variable previous2-patches) and it returns an agentset without the exclusions.It does this by running through the list and, if it's in the agentset, removing it with the other primitive.

Body:
I'm using Netlogo and I'd like to set up a scenario whereby my turtles cannot move to the previous patch, nor can they move to the previous-previous patch (i.e. patches an individual turtle occupied at t-1 and at t-2).

I've set things up as shown below. The idea is to set neighbors that have already been visited by the current turtle to have a patch_attractiveness of zero, so they can't be selected. I think I'm just struggling with the correct syntax. The line at issue is the one that starts with "set previously_visited_patches"

patches-own [patch_attractiveness]

turtles-own [previous2_patches]

to setup
  create-turtles 100  [
    set previous2_patches (list patch-here)
  ]
end

to go
  tick

  ask turtles [
    let previous_patchset patch-set previous2_patches
    let previously_visited_neighbors neighbors with [member? self previous_patchset]
    ask previously_visited_neighbours [
      set patch_attractiveness 0
    ]
    face max-one-of neighbors [patch_attractiveness]
    fd 1
  ]

  set previous2_patches lput patch-here previous2_patches
  if (ticks > 1) [
    set previous2_patches remove-item 0 previous2_patches
  ]

end

The code as it stands seems to select the t-2 patch but not the t-1 patch as well. Anyone got any bright ideas? I'm assuming that "self" may not be the right call to make

Many thanks

Body:
Okay, I think this does what you want.

patches-own [patch-attractiveness]

turtles-own [previous2-patches]

to setup
  clear-all
  create-turtles 100
  [ setxy random-xcor random-ycor
    set previous2-patches (list patch-here patch-here)
  ]
  ask patches [ set patch-attractiveness random 50 ]
  reset-ticks
end

to go
  ask turtles
  [ let candidates viable-neighbours neighbors previous2-patches
    if any? candidates
    [ face max-one-of candidates [patch-attractiveness]
      forward 1
      set previous2-patches (list patch-here item 0 previous2-patches)
    ]
  ]
end

to-report viable-neighbours [ set-of-patches delete-list ]
  let viable set-of-patches
  foreach delete-list
  [ x -> if member? x viable [ ask x [ set viable other viable ] ] ]
  report viable
end

First, I changed the variable names to hyphens instead of underscore. Sorry, hyphens is sort of conventional in NetLogo and I didn't realise you'd used underscores until I got errors.

I did some simplifying. I scrapped your stuff about setting attractiveness to 0 due to comments. I also simplified the setup so that the starting list of excluded patches is simply two copies of the current patch (which means you don't need the if ticks > 1 test). I also created the new list from the current patch and the relevant item in the existing list - your lput and remove is more correct but since the list is only ever two items, this is easier to read. You should definitely retain the lput/remove structure if you may want to increase the memory of patches to exclude.

The important bit though is the new procedure. You pass it an agentset (in your case neighbors) and a list of agents to exclude (in your case the turtle variable previous2-patches) and it returns an agentset without the exclusions.It does this by running through the list and, if it's in the agentset, removing it with the other primitive.


问:
Melt uneven data in columns and ignore NaNs using pandas
There must be an elegant way to do this but I have not found it yet. I have a large dataframe that looks something like this:

```<code>df
    Name    0           1           2        3      4
1   apple   2016 W1     NaN         NaN      NaN    NaN
2   orange  2016 W1     2017 W2     NaN      NaN    NaN
3   banana  2016 W2     2017 W3     NaN      NaN    NaN
4   pear    2016 W3     2016 W4     2016 W5  NaN    NaN
6   melon   2016 W2     2016 W4     2017 W5  2017 W6 2017 W7
</code>```

And I want to melt the data such that there are only two columns name and week. So the result should look like this:

```<code>df_result

    Name    week
    apple   2016 W1
    orange  2016 W1
    orange  2017 W2
    banana  2016 W2
    banana  2017 W3
    pear    2016 W3
    pear    2016 W4
    ... etc.
</code>```

What I'm stuck on is how to ignore the NaN values while being sure to not lose any values.

When I do pd.melt(df, id_vars=['Name']) I'm not sure if the outcome is what I want.

答:
Using stack

```<code>df.set_index('Name').stack().reset_index(1,drop = True)

Name
apple     2016 W1
orange    2016 W1
orange    2017 W2
banana    2016 W2
banana    2017 W3
pear      2016 W3
pear      2016 W4
pear      2016 W5
melon     2016 W2
melon     2016 W4
melon     2017 W5
melon     2017 W6
melon     2017 W7
dtype: object
</code>```

Or using melt with some cleaning

```<code>df.melt(id_vars='Name').sort_values('Name').dropna()
</code>```

Body:
There must be an elegant way to do this but I have not found it yet. I have a large dataframe that looks something like this:

df
    Name    0           1           2        3      4
1   apple   2016 W1     NaN         NaN      NaN    NaN
2   orange  2016 W1     2017 W2     NaN      NaN    NaN
3   banana  2016 W2     2017 W3     NaN      NaN    NaN
4   pear    2016 W3     2016 W4     2016 W5  NaN    NaN
6   melon   2016 W2     2016 W4     2017 W5  2017 W6 2017 W7

And I want to melt the data such that there are only two columns name and week. So the result should look like this:

df_result

    Name    week
    apple   2016 W1
    orange  2016 W1
    orange  2017 W2
    banana  2016 W2
    banana  2017 W3
    pear    2016 W3
    pear    2016 W4
    ... etc.

What I'm stuck on is how to ignore the NaN values while being sure to not lose any values.

When I do pd.melt(df, id_vars=['Name']) I'm not sure if the outcome is what I want.

Body:
Using stack

df.set_index('Name').stack().reset_index(1,drop = True)

Name
apple     2016 W1
orange    2016 W1
orange    2017 W2
banana    2016 W2
banana    2017 W3
pear      2016 W3
pear      2016 W4
pear      2016 W5
melon     2016 W2
melon     2016 W4
melon     2017 W5
melon     2017 W6
melon     2017 W7
dtype: object

Or using melt with some cleaning

df.melt(id_vars='Name').sort_values('Name').dropna()


问:
How to keep Outlook UI responsive in C# VSTO addin when making lots of CPU-intensive work on UI thread
I have the code which makes many calls to Outlook API in a loop. Outlook doesn't like access to its API from worker threads so I have to use main thread for that. The part of the code which makes network queries is perfectly fine with async/await so the UI does not freeze. But when the code reaches CPU-intensive part (calls to Outlook API), UI obviously freezes.

I inserted await Task.Delay(1) which executes after each 10ms elapses but since timer resolution is not so precise (15ms), it makes the code noticeably slower (although unblocks UI).

```<code>DateTime d1 = DateTime.Now;
int interval = 10;
foreach (SomeItem item in items)
{
    // Intense access to Outlook API...
    // ...

    DateTime d2 = DateTime.Now;
    if (d2.Subtract(d1).TotalMilliseconds > interval)
    {
        await Task.Delay(1);
        d1 = d2;
    }
}
</code>```

Using Task.Yield instead of Task.Delay(1) does not unblock UI (MSDN anyway doesn't recommend Task.Yield for this).

Increasing interval from 10ms to larger values (100ms) reduces performance loss to the minimum and makes UI somewhat responsive but not so smooth.

Maybe there is a better alternative which wouldn't imply any tradeoffs between UI smoothness and performance? Maybe like a good old Application.DoEvents but in a modern and recommended way?

答: There is no good way to do that using OOM alone. Extended MAPI is thread safe, but it is only accessible from C++ or Delphi. You can use Redemption (any language - I am its author) - its RDO family of objects is purely MAPI based and can be used from a secondary thread. Save Application.Session.MAPIOBJECT into a dedicated variable on the main thread (this way only that variable would have to be marshalled). On the secondary thread, create an instance of the RDOSession object (this way the MAPI system will be initialized on that thread) and set its MAPIOBJECT property to the variable saved on the main thread. This way the two will share the same MAPI session. You can then retrieve the folder using RDOSession.GetFolderFromID/GetDefaultFolder/etc. and process the items.

Body:
I have the code which makes many calls to Outlook API in a loop. Outlook doesn't like access to its API from worker threads so I have to use main thread for that. The part of the code which makes network queries is perfectly fine with async/await so the UI does not freeze. But when the code reaches CPU-intensive part (calls to Outlook API), UI obviously freezes.

I inserted await Task.Delay(1) which executes after each 10ms elapses but since timer resolution is not so precise (15ms), it makes the code noticeably slower (although unblocks UI).

DateTime d1 = DateTime.Now;
int interval = 10;
foreach (SomeItem item in items)
{
    // Intense access to Outlook API...
    // ...

    DateTime d2 = DateTime.Now;
    if (d2.Subtract(d1).TotalMilliseconds > interval)
    {
        await Task.Delay(1);
        d1 = d2;
    }
}

Using Task.Yield instead of Task.Delay(1) does not unblock UI (MSDN anyway doesn't recommend Task.Yield for this).

Increasing interval from 10ms to larger values (100ms) reduces performance loss to the minimum and makes UI somewhat responsive but not so smooth.

Maybe there is a better alternative which wouldn't imply any tradeoffs between UI smoothness and performance? Maybe like a good old Application.DoEvents but in a modern and recommended way?

ContentLicense: CC BY-SA 4.0


问:
jQuery time picker
I'm looking to fill a text input with a time that the user can choose in 15 minute intervals. I know there are a few plugins out there. I was wondering if there was any “industry standard” plugin, or strong objective reasons to prefer a particular one in common scenarios.</p>

答:
It's not jQuery ... but I have found that a dropdown, with a list of fifteen minute intervals of time, 8:00AM, 8:15AM, 8:30AM, and so on, is extremely easy for the user to interact with.

Not sure if you really need a jQuery way of doing this ... may be overkill. Just an opinion based on my personal experience with real users and developing business applications.

OwnerDisplayName: Bernardo

Title: jQuery time picker

OwnerDisplayName: MattRuma

ContentLicense: CC BY-SA 2.5


答:
Op1

```<code>df.melt('Name').dropna().drop('variable',1)
Out[62]:
      Name    value
0    apple  2016 W1
1   orange  2016 W1
2   banana  2016 W2
3     pear  2016 W3
4    melon  2016 W2
6   orange  2017 W2
7   banana  2017 W3
8     pear  2016 W4
9    melon  2016 W4
13    pear  2016 W5
14   melon  2017 W5
19   melon  2017 W6
24   melon  2017 W7
</code>```

Op2

```<code>df.set_index('Name').stack().reset_index().drop('level_1',1)
Out[66]:
      Name        0
0    apple  2016 W1
1   orange  2016 W1
2   orange  2017 W2
3   banana  2016 W2
4   banana  2017 W3
5     pear  2016 W3
6     pear  2016 W4
7     pear  2016 W5
8    melon  2016 W2
9    melon  2016 W4
10   melon  2017 W5
11   melon  2017 W6
12   melon  2017 W7
</code>```

Op3

```<code>pd.DataFrame({'Name':df.Name.tolist()*5,'Value':np.concatenate(df.iloc[:,1:].values)}).dropna()
Out[69]:
      Name    Value
0    apple  2016 W1
5    apple  2016 W1
6   orange  2017 W2
10   apple  2016 W2
11  orange  2017 W3
15   apple  2016 W3
16  orange  2016 W4
17  banana  2016 W5
20   apple  2016 W2
21  orange  2016 W4
22  banana  2017 W5
23    pear  2017 W6
24   melon  2017 W7
</code>```

Title: Melt uneven data in columns and ignore NaNs using pandas

Body:
Op1

df.melt('Name').dropna().drop('variable',1)
Out[62]:
      Name    value
0    apple  2016 W1
1   orange  2016 W1
2   banana  2016 W2
3     pear  2016 W3
4    melon  2016 W2
6   orange  2017 W2
7   banana  2017 W3
8     pear  2016 W4
9    melon  2016 W4
13    pear  2016 W5
14   melon  2017 W5
19   melon  2017 W6
24   melon  2017 W7

Op2

df.set_index('Name').stack().reset_index().drop('level_1',1)
Out[66]:
      Name        0
0    apple  2016 W1
1   orange  2016 W1
2   orange  2017 W2
3   banana  2016 W2
4   banana  2017 W3
5     pear  2016 W3
6     pear  2016 W4
7     pear  2016 W5
8    melon  2016 W2
9    melon  2016 W4
10   melon  2017 W5
11   melon  2017 W6
12   melon  2017 W7

Op3

pd.DataFrame({'Name':df.Name.tolist()*5,'Value':np.concatenate(df.iloc[:,1:].values)}).dropna()
Out[69]:
      Name    Value
0    apple  2016 W1
5    apple  2016 W1
6   orange  2017 W2
10   apple  2016 W2
11  orange  2017 W3
15   apple  2016 W3
16  orange  2016 W4
17  banana  2016 W5
20   apple  2016 W2
21  orange  2016 W4
22  banana  2017 W5
23    pear  2017 W6
24   melon  2017 W7


问:
rJava load error in RStudio/R after "upgrading" to OSX Yosemite
I recently "upgraded" from OSX Mountain Lion to Yosemite and from R 3.1.3 to 3.2. Immediately after the upgrade, when I opened R or RStudio I got a pop-up message saying that I needed to install Java 6. In addition, loading rJava or any package that depends on rJava (e.g., xlsx) caused RStudio to crash (R also crashed when I tried this by opening R.app directly).

After trying a few fixes found on Stack Overflow and elsewhere (more details below), I am at a point where loading rJava or any package that depends on rJava no longer causes R to crash, but results in the following error:

```<code>library(rJava)
Error : .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.2/Resources/library/rJava/libs/rJava.so':
  dlopen(/Library/Frameworks/R.framework/Versions/3.2/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib
  Referenced from: /Library/Frameworks/R.framework/Versions/3.2/Resources/library/rJava/libs/rJava.so
  Reason: image not found
Error: package or namespace load failed for ‘rJava’
</code>```

However, if I invoke R from the command line and then load rJava or any package that depends on rJava, it seems to work (or at least I don't get any error messages).

I've tried a number of different attempted fixes, some of them a few times, and can't quite remember exactly what I did in what order (didn't realize this would be such a morass and wasn't really keeping track), but here's the gist of it:

Added the following to my .bash_profile (per this SO answer):

export JAVA_HOME="/usr/libexec/java_home -v 1.8"

  export LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/server

Reconfigured java from the command line as follows:

sudo R CMD javareconf -n

Checked options("java.home") and discovered this was set to  NULL. I tried setting it to the following (per this SO question):

options("java.home"="/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre")

Installed the latest Java Development Kit and reinstalled rJava from source (can't remember where I found that one).

At some point while trying all of these, I was able to load rJava without crashing R, but instead got the error message posted above. In addition, when I quit RStudio, it would seem to close normally, but then an "RStudio quit unexpectedly" message would pop up, indicating that the program had crashed while trying to close.

I finally decided to install Java for OS X 2014-001 (Java 6), as I seemed to be running out of options. Now, when I opened R or RStudio the "This software needs Java 6" pop-up message no longer appeared. However, I was still getting the .onLoad failed in loadNamespace() for 'rJava' error message posted above.

In reviewing some of the posts I'd already looked at, I noticed another SO answer that I'd missed before, which recommended opening RStudio with the following command line code that gives RStudio the correct path to java:

LD_LIBRARY_PATH=$(/usr/libexec/java_home)/jre/lib/server: open -a RStudio

That opened an RStudio window and I was also able to load rJava and packages that depend on it without getting an error.

Lastly, I tried running R from the command line (which I hadn't done before). It turns out that on the command line, loading rJava or any package that depends on rJava works and does not throw any errors.

So, I can now get rJava to work if I open RStudio from the command line with the code that gives RStudio the java path (as noted above). However, I'd like to find a way to fix the underlying problem, whatever it may be, so that RStudio can be opened in the usual Mac way, without needing a command line kludge. I'm also concerned that having an old version of Java installed could cause problems down the road.

Does anyone have any ideas about how to diagnose and solve this issue?

答:
On macOS High Sierra (10.13.1) and Java Version 9 you have to use a slightly different JVM path (notice the missing jre folder in the path compared to the instructions for earlier Java versions):

```<code>sudo ln -f -s $(/usr/libexec/java_home)/lib/server/libjvm.dylib /usr/local/lib
</code>```

You also have to notify R about the JVM:

```<code>MY_R_VERSION=$(Rscript -e "cat(with(R.version, sprintf('%s.%s', major, substring(minor, 1, 1))))")
ln -s /usr/local/lib/libjvm.dylib /Library/Frameworks/R.framework/Versions/$MY_R_VERSION/Resources/lib/
</code>```

Body:
I recently "upgraded" from OSX Mountain Lion to Yosemite and from R 3.1.3 to 3.2. Immediately after the upgrade, when I opened R or RStudio I got a pop-up message saying that I needed to install Java 6. In addition, loading rJava or any package that depends on rJava (e.g., xlsx) caused RStudio to crash (R also crashed when I tried this by opening R.app directly).

After trying a few fixes found on Stack Overflow and elsewhere (more details below), I am at a point where loading rJava or any package that depends on rJava no longer causes R to crash, but results in the following error:

library(rJava)
Error : .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.2/Resources/library/rJava/libs/rJava.so':
  dlopen(/Library/Frameworks/R.framework/Versions/3.2/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib
  Referenced from: /Library/Frameworks/R.framework/Versions/3.2/Resources/library/rJava/libs/rJava.so
  Reason: image not found
Error: package or namespace load failed for ‘rJava’

However, if I invoke R from the command line and then load rJava or any package that depends on rJava, it seems to work (or at least I don't get any error messages).

I've tried a number of different attempted fixes, some of them a few times, and can't quite remember exactly what I did in what order (didn't realize this would be such a morass and wasn't really keeping track), but here's the gist of it:

Added the following to my .bash_profile (per this SO answer):

export JAVA_HOME="/usr/libexec/java_home -v 1.8"

  export LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/server

Reconfigured java from the command line as follows:

sudo R CMD javareconf -n

Checked options("java.home") and discovered this was set to  NULL. I tried setting it to the following (per this SO question):

options("java.home"="/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre")

Installed the latest Java Development Kit and reinstalled rJava from source (can't remember where I found that one).

At some point while trying all of these, I was able to load rJava without crashing R, but instead got the error message posted above. In addition, when I quit RStudio, it would seem to close normally, but then an "RStudio quit unexpectedly" message would pop up, indicating that the program had crashed while trying to close.

I finally decided to install Java for OS X 2014-001 (Java 6), as I seemed to be running out of options. Now, when I opened R or RStudio the "This software needs Java 6" pop-up message no longer appeared. However, I was still getting the .onLoad failed in loadNamespace() for 'rJava' error message posted above.

In reviewing some of the posts I'd already looked at, I noticed another SO answer that I'd missed before, which recommended opening RStudio with the following command line code that gives RStudio the correct path to java:

LD_LIBRARY_PATH=$(/usr/libexec/java_home)/jre/lib/server: open -a RStudio

That opened an RStudio window and I was also able to load rJava and packages that depend on it without getting an error.

Lastly, I tried running R from the command line (which I hadn't done before). It turns out that on the command line, loading rJava or any package that depends on rJava works and does not throw any errors.

So, I can now get rJava to work if I open RStudio from the command line with the code that gives RStudio the java path (as noted above). However, I'd like to find a way to fix the underlying problem, whatever it may be, so that RStudio can be opened in the usual Mac way, without needing a command line kludge. I'm also concerned that having an old version of Java installed could cause problems down the road.

Does anyone have any ideas about how to diagnose and solve this issue?

Body:
On macOS High Sierra (10.13.1) and Java Version 9 you have to use a slightly different JVM path (notice the missing jre folder in the path compared to the instructions for earlier Java versions):

sudo ln -f -s $(/usr/libexec/java_home)/lib/server/libjvm.dylib /usr/local/lib

You also have to notify R about the JVM:

MY_R_VERSION=$(Rscript -e "cat(with(R.version, sprintf('%s.%s', major, substring(minor, 1, 1))))")
ln -s /usr/local/lib/libjvm.dylib /Library/Frameworks/R.framework/Versions/$MY_R_VERSION/Resources/lib/


问:
WebGL2 FBO depth attachment values
I'm simply trying to render the depth values of my scene using WebGL2 like so:

```<code>//Texture
depthTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, depthTexture);

gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24,
                width, height, 0,
                gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);

gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

//FBO
fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
</code>```

Then I render it like so:

```<code>gl.bindFramebuffer(gl.FRAMEBUFFER, fb);

gl.useProgram(shaderProgram);

//Just a torus...
gl.bindVertexArray(vao);

gl.colorMask(false, false, false, false);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.DEPTH_BUFFER_BIT);
...
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);

//Then I draw a full screen quad that simply samples the depth texture
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
....
</code>```

It seems to work fine, however when sampling the attached depth texture I get what looks like linear depth...

The programs that I use to render into the FBO are very much basic

Vert:

```<code>#version 300 es

layout(location = 0) in vec3 position;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main() {

  gl_Position = projection * view * model * vec4(position, 1.);
}
</code>```

Frag:

```<code>#version 300 es
precision highp float;

layout(location = 0) out vec4 outColor;

void main() {
  outColor = vec4(1,0,0,1)
}
</code>```

I was expecting the depth buffer to be logarithmic, and even if I cannot say for sure that what I currently get is really linear or not, it doesn't look logarithmic either...
If it really is linear, and somehow this is what you are supposed to get from the depth attachment, I'm perfectly fine with it, since I'm probably going to need linear and not logarithmic depth, but currently I'm not sure if this is expected behavior, or I'm doing something wrong(probably the latter)

Cheers

答:
Thank you @LJ for the link.
I think I know what is actually happening. My previous conclusions were incorrect mostly because I did not understand what was going on.
What I was seeing was, as expected logarithmic depth, but since my near and far clipping planes were 1. and 1000. respectively, and the torus was relatively close to the near clipping plane, it was is that part of the 1/z curve where the values bunch up giving high precision. As soon as I increased the torus's depth, I saw the big precision loss. After linearizeing it using something like How to read depth texture attached to FBO in WebGL2 and using near and far clipping planes of 0.1 and 10(in order to have visual feedback since the torus is relatively small in depth) I could see the depth was linear.</p>

Title: WebGL2 FBO depth attachment values

Body:
I'm simply trying to render the depth values of my scene using WebGL2 like so:

//Texture
depthTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, depthTexture);

gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24,
                width, height, 0,
                gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);

gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

//FBO
fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);

Then I render it like so:

gl.bindFramebuffer(gl.FRAMEBUFFER, fb);

gl.useProgram(shaderProgram);

//Just a torus...
gl.bindVertexArray(vao);

gl.colorMask(false, false, false, false);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.DEPTH_BUFFER_BIT);
...
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);

//Then I draw a full screen quad that simply samples the depth texture
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
....

It seems to work fine, however when sampling the attached depth texture I get what looks like linear depth...

The programs that I use to render into the FBO are very much basic

Vert:

#version 300 es

layout(location = 0) in vec3 position;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main() {

  gl_Position = projection * view * model * vec4(position, 1.);
}

Frag:

#version 300 es
precision highp float;

layout(location = 0) out vec4 outColor;

void main() {
  outColor = vec4(1,0,0,1)
}

I was expecting the depth buffer to be logarithmic, and even if I cannot say for sure that what I currently get is really linear or not, it doesn't look logarithmic either...
If it really is linear, and somehow this is what you are supposed to get from the depth attachment, I'm perfectly fine with it, since I'm probably going to need linear and not logarithmic depth, but currently I'm not sure if this is expected behavior, or I'm doing something wrong(probably the latter)

Cheers


问:
Axis adding extra padding for large domains
Getting a strange situation in d3 axis generation. While creating a bottom x axis using d3.axisBottom() for ordinal domain values, adding extra padding in starting and ending point of ticks in the axis. Situation in which the d3.scaleBand() domain has more number of values in it.

I guess the tick generation getting shrink with some threshold number of domain items.

Ticks are equally distributed with a average number of items, Once it exceeds the limit it shrink with padding on first and last ticks.

Correct explanation for the above scenario will more appreciated.

var width = 400, height = 200;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var xAxisScale = d3.scaleBand()
 .domain([1,3,5,7,8,10,12,13,14,15,16,17,18,19,20,22,23,24,25,26,27,28,29,30,31,32,33,34,36,37,39,40,41,43,45,46,47,48,49,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,69,70,71,72,73,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,95,98,99,105,106,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,127,128,129,130,131,135,136,141,154])
    .rangeRound([10, width -10])
    .padding(0.1);

var xAxisScale1 = d3.scaleBand()
 .domain([1,3,5,7,8,10,12,13,14,15,16,17,18,19,20,22,23,24,25,26,27,28,29,30,31,32])
    .rangeRound([10, width -10])
    .padding(0.1);

var xAxis = d3.axisBottom(xAxisScale);
var xAxis1 = d3.axisBottom(xAxisScale1);

svg.append("g").attr("transform", "translate(0,20)").call(xAxis);
svg.append("g").attr("transform", "translate(0,60)").call(xAxis1);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

答:
The culprit here is rangeRound. This is the expected behaviour, and it is explained in the API:

If round is specified, enables or disables rounding accordingly. If rounding is enabled, the start and stop of each band will be integers. Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the shape-rendering “crispEdges” styles. Note that if the width of the domain is not a multiple of the cardinality of the range, there may be leftover unused space, even without padding! (emphasis mine)

So, the solution is simple: use range instead:

var width = 400,
  height = 200;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var xAxisScale = d3.scaleBand()
  .domain(d3.range(200))
  .range([10, width - 10])

var xAxisScale1 = d3.scaleBand()
  .domain(d3.range(20))
  .range([10, width - 10])

var xAxis = d3.axisBottom(xAxisScale);
var xAxis1 = d3.axisBottom(xAxisScale1);

svg.append("g").attr("transform", "translate(0,20)").call(xAxis);
svg.append("g").attr("transform", "translate(0,60)").call(xAxis1);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Body:
The culprit here is rangeRound. This is the expected behaviour, and it is explained in the API:

If round is specified, enables or disables rounding accordingly. If rounding is enabled, the start and stop of each band will be integers. Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the shape-rendering “crispEdges” styles. Note that if the width of the domain is not a multiple of the cardinality of the range, there may be leftover unused space, even without padding! (emphasis mine)

So, the solution is simple: use range instead:

var width = 400,
  height = 200;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var xAxisScale = d3.scaleBand()
  .domain(d3.range(200))
  .range([10, width - 10])

var xAxisScale1 = d3.scaleBand()
  .domain(d3.range(20))
  .range([10, width - 10])

var xAxis = d3.axisBottom(xAxisScale);
var xAxis1 = d3.axisBottom(xAxisScale1);

svg.append("g").attr("transform", "translate(0,20)").call(xAxis);
svg.append("g").attr("transform", "translate(0,60)").call(xAxis1);

<script src="https://d3js.org/d3.v4.min.js"></script>


问:
Null propagation operator, out parameters and false compiler errors?
Let's assume I have a class that has a property of type Dictionary<string,string>, that may be null.

This compiles but the call to TryGetValue() could throw at a NullRef exception at runtime:

```<code>MyClass c = ...;
string val;
if(c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val);
}
</code>```

So I'm adding a null-propagating operator to guard against nulls, but this doesn't compile:

```<code>MyClass c = ...;
string val;
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // use of unassigned local variable

}
</code>```

Is there an actual use case where val will be uninitialized inside the if block, or can the compiler simply not infer this (and why) ?

Update: The cleanest (?) way to workaround^H^H^H^H^H fix this is:

```<code>MyClass c = ...;
string val = null; //POW! initialized.
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // no more compiler error

}
</code>```

答:
Seems like you have run into a limitation of the compilers understanding of ?. and ?? which isn't too surprising, given that they aren't really fully incorporated in the language.

If you make your test explicit without the newer operators, the compiler will agree with you:

```<code>MyClass c = new MyClass();
string val;
if (c.PossiblyNullDictionary != null && c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val); // now okay
}
</code>```

Body:
Let's assume I have a class that has a property of type Dictionary<string,string>, that may be null.

This compiles but the call to TryGetValue() could throw at a NullRef exception at runtime:

MyClass c = ...;
string val;
if(c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val);
}

So I'm adding a null-propagating operator to guard against nulls, but this doesn't compile:

MyClass c = ...;
string val;
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // use of unassigned local variable

}

Is there an actual use case where val will be uninitialized inside the if block, or can the compiler simply not infer this (and why) ?

Update: The cleanest (?) way to workaround^H^H^H^H^H fix this is:

MyClass c = ...;
string val = null; //POW! initialized.
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // no more compiler error

}

Body:
Seems like you have run into a limitation of the compilers understanding of ?. and ?? which isn't too surprising, given that they aren't really fully incorporated in the language.

If you make your test explicit without the newer operators, the compiler will agree with you:

MyClass c = new MyClass();
string val;
if (c.PossiblyNullDictionary != null && c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val); // now okay
}


问:
Logger for Windows 10 UWP app
I couldn't found any loggers for windows 10 universal app, i have tried out log4net, Microsoft enterprise library, Nlog but none of them are supported in windows 10 Universal platform.

Can anyone suggest me good logger for the windows 10 UWP?

答:
If you would like to log to a file and take advantage of the Microsoft's lightweight DI framework you can use Serilog.

In Nuget Package Manager Console enter the following:

```<code>Install-Package Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.Logging
Install-Package Serilog.Extensions.Logging.File
</code>```

Set up dependency injection container at the composition root. In our case it is OnLaunched method in the App.xaml.cs file.

```<code>using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Windows.Storage;
...

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
     ...
    // Create IOC container and add logging feature to it.
    IServiceCollection services = new ServiceCollection();
    services.AddLogging();

    // Build provider to access the logging service.
    IServiceProvider provider = services.BuildServiceProvider();

    // UWP is very restrictive of where you can save files on the disk.
    // The preferred place to do that is app's local folder.
    StorageFolder folder = ApplicationData.Current.LocalFolder;
    string fullPath = $"{folder.Path}\\Logs\\App.log";

    // Tell the logging service to use Serilog.File extension.
    provider.GetService<ILoggerFactory>().AddFile(fullPath);
    ...
}
</code>```

Once set up, logging is very simple. Just inject the logger into your class.

```<code>using Microsoft.Extensions.Logging;

class MyClass
{
    readonly ILogger<MyClass> logger;

    public MyClass(ILogger<MyClass> logger)
    {
        this.logger = logger;
        logger.LogInformation("Hello from MyClass.");
    }
}
</code>```

Your log file should be created in:

C:\Users\yourUserName\AppData\Local\Packages\f15fdadf-faae-4f4a-8445-5feb195ff692_68newbw0j54vy\LocalState\Logs\App-20171206.log,

where f15fdadf-faae-4f4a-8445-5feb195ff692_68newbw0j54vy is the package name from the Package.appxmanifest file in my solution.

Please note that AppData folder is hidden in File Explorer by default.

And here is its content:

```<code>2017-12-06T17:06:33.1358005-06:00  [INF] Hello from MyClass. (25278b08)
</code>```

Title: Logger for Windows 10 UWP app

Body:
If you would like to log to a file and take advantage of the Microsoft's lightweight DI framework you can use Serilog.

In Nuget Package Manager Console enter the following:

Install-Package Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.Logging
Install-Package Serilog.Extensions.Logging.File

Set up dependency injection container at the composition root. In our case it is OnLaunched method in the App.xaml.cs file.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Windows.Storage;
...

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
     ...
    // Create IOC container and add logging feature to it.
    IServiceCollection services = new ServiceCollection();
    services.AddLogging();

    // Build provider to access the logging service.
    IServiceProvider provider = services.BuildServiceProvider();

    // UWP is very restrictive of where you can save files on the disk.
    // The preferred place to do that is app's local folder.
    StorageFolder folder = ApplicationData.Current.LocalFolder;
    string fullPath = $"{folder.Path}\\Logs\\App.log";

    // Tell the logging service to use Serilog.File extension.
    provider.GetService<ILoggerFactory>().AddFile(fullPath);
    ...
}

Once set up, logging is very simple. Just inject the logger into your class.

using Microsoft.Extensions.Logging;

class MyClass
{
    readonly ILogger<MyClass> logger;

    public MyClass(ILogger<MyClass> logger)
    {
        this.logger = logger;
        logger.LogInformation("Hello from MyClass.");
    }
}

Your log file should be created in:

C:\Users\yourUserName\AppData\Local\Packages\f15fdadf-faae-4f4a-8445-5feb195ff692_68newbw0j54vy\LocalState\Logs\App-20171206.log,

where f15fdadf-faae-4f4a-8445-5feb195ff692_68newbw0j54vy is the package name from the Package.appxmanifest file in my solution.

Please note that AppData folder is hidden in File Explorer by default.

And here is its content:

2017-12-06T17:06:33.1358005-06:00  [INF] Hello from MyClass. (25278b08)


问:
Is it possible to create directories under Android/data/data/your_package/ files
I would like to save some files in different directories under Android/data/data/my_app_package/files directory. I am able to obtain the path to the "files" directory by calling context.getExternalFilesDir(null), but can't create a directory under the path returned. Does anyone know why?

Thanks,

答:
```<code>File root = SoundApplication.getAppContext().getExternalFilesDir(null);
File soundDir = new File(root, "/sound-dir");
if (!soundDir.exists()) {
    boolean dir = soundDir.mkdirs();
    System.out.println("dir = " + dir);
}
</code>```

soundDir.mkdirs() returned true, but I don't see "sound-dir" in Android.data.mayPackage.files directory with Windows explorer.

Body:
File root = SoundApplication.getAppContext().getExternalFilesDir(null);
File soundDir = new File(root, "/sound-dir");
if (!soundDir.exists()) {
    boolean dir = soundDir.mkdirs();
    System.out.println("dir = " + dir);
}

soundDir.mkdirs() returned true, but I don't see "sound-dir" in Android.data.mayPackage.files directory with Windows explorer.


问:
Printing textdata from toString - Java
I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?

This is how my toString looks like:

```<code>@Override
public String toString() {
    return userNameGenerator + " -> " + "[" + personName + "]" ;
}
</code>```

Full code:

```<code>import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        catch (IOException ex) {
            System.out.println("An error has occured: " + ex.getMessage());
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++){
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++){
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String p: newStrSet) {
            System.out.printf("%s -> ", p);
            for (Codes2 s: personFile) {
                if (s.getUserNameGenerator().contains(p)) {
                    System.out.printf("%s, ", s.getPersonName());
                }
            }
            System.out.println();
        }
    }
}
</code>```

Java Class:

```<code>public class Codes2 implements Comparable<Codes2> {

    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }

    @Override
    public String toString() {
        return userNameGenerator + " -> " + "[" + personName + "]" ;
    }
}
</code>```

答:
Everything looks right in your code.

I think you should just call the method when you are trying to print it out:

```<code>for (Codes2 s: personFile) {
     if (s.getUserNameGenerator().contains(p)) {
         System.out.printf("%s, ", s.toString());
     }
}
</code>```

This follows the fact that the class that prints out the object is not so closely coupled with the class that hold the data.

Title: Printing textdata from toString - Java

Body:
I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?

This is how my toString looks like:

@Override
public String toString() {
    return userNameGenerator + " -> " + "[" + personName + "]" ;
}

Full code:

import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        catch (IOException ex) {
            System.out.println("An error has occured: " + ex.getMessage());
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++){
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++){
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String p: newStrSet) {
            System.out.printf("%s -> ", p);
            for (Codes2 s: personFile) {
                if (s.getUserNameGenerator().contains(p)) {
                    System.out.printf("%s, ", s.getPersonName());
                }
            }
            System.out.println();
        }
    }
}

Java Class:

public class Codes2 implements Comparable<Codes2> {

    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }

    @Override
    public String toString() {
        return userNameGenerator + " -> " + "[" + personName + "]" ;
    }
}

Body:
Everything looks right in your code.

I think you should just call the method when you are trying to print it out:

for (Codes2 s: personFile) {
     if (s.getUserNameGenerator().contains(p)) {
         System.out.printf("%s, ", s.toString());
     }
}

This follows the fact that the class that prints out the object is not so closely coupled with the class that hold the data.


问:
Prevent duplicate posts within foreach

Hello all, I'm currently working on a foreach loop that pulls images from a gallery from the backend of Wordpress. The gallery is working fine and as expected, however, I would like to prevent duplicate photos from appearing.

```<code><?php if () $query->have_posts() ):
  $thumbs = [];
?>
<?php
    foreach( $query->posts as $gallery ):
      $images = get_field('gallery_images', $gallery->ID);
      if( $images ):
        foreach( $images as $image ):
          $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
          $img_id[] = $image['ID'];
          $thumbs[] = $cropped_img;
?>
</code>```

Unrelated HTML to the Problem

```<code><?php endforeach; endif; endforeach; ?>
<?php foreach($thumbs as $thumbnail): ?>
  <div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
<?php endforeach; ?>
</code>```

Here is essentially what I'm trying to work out. I've thought to add two variables for the image ID so that they aren't duplicated in the first block of code. So that first if/foreach state looks like:

```<code><?php if( $images ):
  foreach( $images as $image ):
    $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
    $img_id[] = $image['ID'];
    $do_not_duplicate[] = $image['ID'];
    $thumbs[] = $cropped_img;
?>
</code>```

Followed by the followed foreach for the thumbnails

```<code><?php foreach($thumbs as $thumbnail): ?>
    <?php foreach($img_id as $img): ?>
      <?php if ($img == $do_not_duplicate) : ?>
      //do nothing
      <?php else : ?>
      <div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
      <?php endif; ?>
<?php endforeach; endforeach; ?>
</code>```

The problem I'm experiencing with this is I'm getting 22 images outputed 23 times because there are 22 images being pulled(with 1 duplicate). Essentially I'm trying to accomplish 22 images with no duplicates.

Any insight would be greatly appreciated, thank you in advance.

答:
Simply edit your php code like that:

```<code>$thumbs[$image['ID']] = $cropped_img;
</code>```

It will be an associative array in which the images are stored with ids as keys, so if an doubled image is pushed to array, it will just override the old one

Title: Prevent duplicate posts within foreach

Body:
Hello all, I'm currently working on a foreach loop that pulls images from a gallery from the backend of Wordpress. The gallery is working fine and as expected, however, I would like to prevent duplicate photos from appearing.

<?php if () $query->have_posts() ):
  $thumbs = [];
?>
<?php
    foreach( $query->posts as $gallery ):
      $images = get_field('gallery_images', $gallery->ID);
      if( $images ):
        foreach( $images as $image ):
          $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
          $img_id[] = $image['ID'];
          $thumbs[] = $cropped_img;
?>

Unrelated HTML to the Problem

<?php endforeach; endif; endforeach; ?>
<?php foreach($thumbs as $thumbnail): ?>

<img src="<?= $thumbnail; ?>">

<?php endforeach; ?>

Here is essentially what I'm trying to work out. I've thought to add two variables for the image ID so that they aren't duplicated in the first block of code. So that first if/foreach state looks like:

<?php if( $images ):
  foreach( $images as $image ):
    $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
    $img_id[] = $image['ID'];
    $do_not_duplicate[] = $image['ID'];
    $thumbs[] = $cropped_img;
?>

Followed by the followed foreach for the thumbnails

<?php foreach($thumbs as $thumbnail): ?>
    <?php foreach($img_id as $img): ?>
      <?php if ($img == $do_not_duplicate) : ?>
      //do nothing
      <?php else : ?>

<img src="<?= $thumbnail; ?>">

      <?php endif; ?>
<?php endforeach; endforeach; ?>

The problem I'm experiencing with this is I'm getting 22 images outputed 23 times because there are 22 images being pulled(with 1 duplicate). Essentially I'm trying to accomplish 22 images with no duplicates.

Any insight would be greatly appreciated, thank you in advance.

Body:
Simply edit your php code like that:

$thumbs[$image['ID']] = $cropped_img;

It will be an associative array in which the images are stored with ids as keys, so if an doubled image is pushed to array, it will just override the old one


问:
Problem with access to Mongodb on Amazon EC2
i've got another question for you.
I have Amazon EC2 instance with mondodb installed.
It works great except one thing - i can't access (connect to) it from outside (my PC).
I think the problem with Security Groups. It's some sort of default firewall.
Does anyone know how to configure EC2 instance to have access to mongodb?
Thanks in advance.</p>

答:
You need to add a security group exception for the port 27017 if you are using default config for you to access it from outside. For security group configuration, please check the amazon EC2 documentation. And if you are using a different port on Mongo, change the security group port accordingly.

--Sai


问:
How to customize marker colors and shapes in scatter plot?
I have a data set with 9 columns. 7 features are used for feature selection and one of them for the classification.
I used tsne library for feature selection in order to see how much my data could be classified.The result from tsne is shown in picture.

However, I want to visualize my data in another way. I would like to set a color for each observation based on the column f1 (id). for example :

```<code>f1(id) f2 f3 ... f9(class label)
1      66 77 ... A
1      44 88 ... A
2      33 55 ... B
2      77 88 ..  B
</code>```

colors come from f1 and shapes come from f9
. I do not know how to do it! I would appreciate for your comments or give me some references to learn more about visualization part.

this is my code:

```<code>plt.scatter(visualize_x, visualize_y, c= y,marker='^', cmap=plt.cm.get_cmap("jet", 10))
</code>```

答:
Is this the type of thing you're after?

```<code>from matplotlib import pyplot as plt

#generate a list of markers and another of colors
markers = ["." , "," , "o" , "v" , "^" , "<", ">"]
colors = ['r','g','b','c','m', 'y', 'k']

#make a sample dataset
x = np.arange(0,10)  #test x values.. every feature gets the same x values but you can generalize this
y = [s*x for s in np.arange(7)] #generate 7 arrays of y values

for i in range(7): #for each of the 7 features
    mi = markers[i] #marker for ith feature
    xi = x #x array for ith feature .. here is where you would generalize      different x for every feature
    yi = y[i] #y array for ith feature
    ci = colors[i] #color for ith feature
    plt.scatter(xi,yi,marker=mi, color=ci)
plt.show()
</code>```

Body:
I have a data set with 9 columns. 7 features are used for feature selection and one of them for the classification.
I used tsne library for feature selection in order to see how much my data could be classified.The result from tsne is shown in picture.

However, I want to visualize my data in another way. I would like to set a color for each observation based on the column f1 (id). for example :

f1(id) f2 f3 ... f9(class label)
1      66 77 ... A
1      44 88 ... A
2      33 55 ... B
2      77 88 ..  B

colors come from f1 and shapes come from f9
. I do not know how to do it! I would appreciate for your comments or give me some references to learn more about visualization part.

this is my code:

plt.scatter(visualize_x, visualize_y, c= y,marker='^', cmap=plt.cm.get_cmap("jet", 10))

Body:
Is this the type of thing you're after?

from matplotlib import pyplot as plt

#generate a list of markers and another of colors
markers = ["." , "," , "o" , "v" , "^" , "<", ">"]
colors = ['r','g','b','c','m', 'y', 'k']

#make a sample dataset
x = np.arange(0,10)  #test x values.. every feature gets the same x values but you can generalize this
y = [s*x for s in np.arange(7)] #generate 7 arrays of y values

for i in range(7): #for each of the 7 features
    mi = markers[i] #marker for ith feature
    xi = x #x array for ith feature .. here is where you would generalize      different x for every feature
    yi = y[i] #y array for ith feature
    ci = colors[i] #color for ith feature
    plt.scatter(xi,yi,marker=mi, color=ci)
plt.show()


问:
Bulk collect into array and error handling in DBMS_OUTPUT
I am copying data from table A to table B. In table A I have four columns for countries (EN, ES, RU, UK). The column per country is a separate row in table B. In addition, each row in table B must be duplicated and receive the next sequence number.

Table A - my cursor

```<code>+---------+---------+---------+---------+---------+
| Company |   EN    |   ES    |   RU    |   UK    |
+---------+---------+---------+---------+---------+
| Intel   | 123 345 | 453 343 | 444 101 | 110 232 |
+---------+---------+---------+---------+---------+
</code>```

Table B

```<code>+---------+---------+-----+
| Company | Country | SEQ |
+---------+---------+-----+
| Intel   | 123 345 |   0 |
| Intel   | 123 345 |   1 |
| Intel   | 453 343 |   0 |
| Intel   | 453 343 |   1 |
| INTEL   | 444 101 |   0 |
| INTEL   | 444 101 |   1 |
| INTEL   | 110 232 |   0 |
| INTEL   | 110 232 |   1 |
+---------+---------+-----+
</code>```

In table A I have 1,000,000 rows.

In Table B, I should have 1,000,000 (rows) x 4 (country) x 2 (seq) = 8,000,000.

I prepared the procedure for inserting data.

```<code>BEGIN

OPEN my_cursor;
    LOOP
        EXIT WHEN my_cursor%notfound;
        FETCH my_cursor BULK COLLECT INTO TAB LIMIT 500;

        FOR y in 0..1 LOOP

                FORALL x IN TAB.first..TAB.last
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."EN", y);

                FORALL x IN TAB.first..TAB.last
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."ES", y);

                FORALL x IN TAB.first..TAB.last
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."RU", y);

                FORALL x IN TAB.first..TAB.last
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."UK", y);

        END LOOP;

        COMMIT;
    END LOOP;
CLOSE my_cursor;

END;
</code>```

In the case of a DML error in table B, I have to return the value of variables from array (tab) together with the error code in DBMS_OUTPUT
for example:

```<code>DBMS_OUTPUT.PUT_LINE(tab(x)."company" || ' ' || tab(x)."UK" || SQLERRM);
</code>```

Is it possible to handle such errors? How can I implement such a solution?
.

答:
You can achieve your goal by using FOR ALL ... SAVE EXCEPTIONS instruction.
This will give you the following :

```<code>DECLARE
    ln_error_count NUMBER;
    ln_line_error  NUMBER;
BEGIN

    OPEN my_cursor;
    LOOP
        EXIT WHEN my_cursor%notfound;
        FETCH my_cursor BULK COLLECT INTO TAB LIMIT 500;

        FOR y in 0..1 LOOP

            BEGIN
                FORALL x IN TAB.first..TAB.last SAVE EXCEPTIONS
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."EN", y);
            EXCEPTION
                WHEN ex_dml_errors THEN
                    ln_error_count := SQL%BULK_EXCEPTIONS.count;
                    FOR i IN 1 .. ln_error_count LOOP
                        ln_line_error := SQL%BULK_EXCEPTIONS(i).error_index;
                        DBMS_OUTPUT.PUT_LINE(tab(ln_line_error)."company" || ' ' || tab(ln_line_error)."EN" || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
                    END LOOP;
            END;

            BEGIN
                FORALL x IN TAB.first..TAB.last SAVE EXCEPTIONS
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."ES", y);
            EXCEPTION
                WHEN ex_dml_errors THEN
                    ln_error_count := SQL%BULK_EXCEPTIONS.count;
                    FOR i IN 1 .. ln_error_count LOOP
                        ln_line_error := SQL%BULK_EXCEPTIONS(i).error_index;
                        DBMS_OUTPUT.PUT_LINE(tab(ln_line_error)."company" || ' ' || tab(ln_line_error)."ES" || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
                    END LOOP;
                END;

            BEGIN
                FORALL x IN TAB.first..TAB.last SAVE EXCEPTIONS
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."RU", y);
            EXCEPTION
                WHEN ex_dml_errors THEN
                    ln_error_count := SQL%BULK_EXCEPTIONS.count;
                    FOR i IN 1 .. ln_error_count LOOP
                        ln_line_error := SQL%BULK_EXCEPTIONS(i).error_index;
                        DBMS_OUTPUT.PUT_LINE(tab(ln_line_error)."company" || ' ' || tab(ln_line_error)."RU" || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
                    END LOOP;
            END;

            BEGIN
                FORALL x IN TAB.first..TAB.last SAVE EXCEPTIONS
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."UK", y);
            EXCEPTION
                WHEN ex_dml_errors THEN
                    ln_error_count := SQL%BULK_EXCEPTIONS.count;
                    FOR i IN 1 .. ln_error_count LOOP
                        ln_line_error := SQL%BULK_EXCEPTIONS(i).error_index;
                        DBMS_OUTPUT.PUT_LINE(tab(ln_line_error)."company" || ' ' || tab(ln_line_error)."UK" || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
                    END LOOP;
            END;
        END LOOP;

        COMMIT;
    END LOOP;
    CLOSE my_cursor;

END;
</code>```

Body:
I am copying data from table A to table B. In table A I have four columns for countries (EN, ES, RU, UK). The column per country is a separate row in table B. In addition, each row in table B must be duplicated and receive the next sequence number.

Table A - my cursor

+---------+---------+---------+---------+---------+
| Company |   EN    |   ES    |   RU    |   UK    |
+---------+---------+---------+---------+---------+
| Intel   | 123 345 | 453 343 | 444 101 | 110 232 |
+---------+---------+---------+---------+---------+

Table B

+---------+---------+-----+
| Company | Country | SEQ |
+---------+---------+-----+
| Intel   | 123 345 |   0 |
| Intel   | 123 345 |   1 |
| Intel   | 453 343 |   0 |
| Intel   | 453 343 |   1 |
| INTEL   | 444 101 |   0 |
| INTEL   | 444 101 |   1 |
| INTEL   | 110 232 |   0 |
| INTEL   | 110 232 |   1 |
+---------+---------+-----+

In table A I have 1,000,000 rows.

In Table B, I should have 1,000,000 (rows) x 4 (country) x 2 (seq) = 8,000,000.

I prepared the procedure for inserting data.

BEGIN

OPEN my_cursor;
    LOOP
        EXIT WHEN my_cursor%notfound;
        FETCH my_cursor BULK COLLECT INTO TAB LIMIT 500;

        FOR y in 0..1 LOOP

                FORALL x IN TAB.first..TAB.last
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."EN", y);

                FORALL x IN TAB.first..TAB.last
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."ES", y);

                FORALL x IN TAB.first..TAB.last
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."RU", y);

                FORALL x IN TAB.first..TAB.last
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."UK", y);

        END LOOP;

        COMMIT;
    END LOOP;
CLOSE my_cursor;

END;

In the case of a DML error in table B, I have to return the value of variables from array (tab) together with the error code in DBMS_OUTPUT
for example:

DBMS_OUTPUT.PUT_LINE(tab(x)."company" || ' ' || tab(x)."UK" || SQLERRM);

Is it possible to handle such errors? How can I implement such a solution?
.

Body:
You can achieve your goal by using FOR ALL ... SAVE EXCEPTIONS instruction.
This will give you the following :

DECLARE
    ln_error_count NUMBER;
    ln_line_error  NUMBER;
BEGIN

    OPEN my_cursor;
    LOOP
        EXIT WHEN my_cursor%notfound;
        FETCH my_cursor BULK COLLECT INTO TAB LIMIT 500;

        FOR y in 0..1 LOOP

            BEGIN
                FORALL x IN TAB.first..TAB.last SAVE EXCEPTIONS
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."EN", y);
            EXCEPTION
                WHEN ex_dml_errors THEN
                    ln_error_count := SQL%BULK_EXCEPTIONS.count;
                    FOR i IN 1 .. ln_error_count LOOP
                        ln_line_error := SQL%BULK_EXCEPTIONS(i).error_index;
                        DBMS_OUTPUT.PUT_LINE(tab(ln_line_error)."company" || ' ' || tab(ln_line_error)."EN" || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
                    END LOOP;
            END;

            BEGIN
                FORALL x IN TAB.first..TAB.last SAVE EXCEPTIONS
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."ES", y);
            EXCEPTION
                WHEN ex_dml_errors THEN
                    ln_error_count := SQL%BULK_EXCEPTIONS.count;
                    FOR i IN 1 .. ln_error_count LOOP
                        ln_line_error := SQL%BULK_EXCEPTIONS(i).error_index;
                        DBMS_OUTPUT.PUT_LINE(tab(ln_line_error)."company" || ' ' || tab(ln_line_error)."ES" || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
                    END LOOP;
                END;

            BEGIN
                FORALL x IN TAB.first..TAB.last SAVE EXCEPTIONS
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."RU", y);
            EXCEPTION
                WHEN ex_dml_errors THEN
                    ln_error_count := SQL%BULK_EXCEPTIONS.count;
                    FOR i IN 1 .. ln_error_count LOOP
                        ln_line_error := SQL%BULK_EXCEPTIONS(i).error_index;
                        DBMS_OUTPUT.PUT_LINE(tab(ln_line_error)."company" || ' ' || tab(ln_line_error)."RU" || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
                    END LOOP;
            END;

            BEGIN
                FORALL x IN TAB.first..TAB.last SAVE EXCEPTIONS
                    INSERT INTO table_B ("company","country","seq") VALUES (tab(x)."company", tab(x)."UK", y);
            EXCEPTION
                WHEN ex_dml_errors THEN
                    ln_error_count := SQL%BULK_EXCEPTIONS.count;
                    FOR i IN 1 .. ln_error_count LOOP
                        ln_line_error := SQL%BULK_EXCEPTIONS(i).error_index;
                        DBMS_OUTPUT.PUT_LINE(tab(ln_line_error)."company" || ' ' || tab(ln_line_error)."UK" || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
                    END LOOP;
            END;
        END LOOP;

        COMMIT;
    END LOOP;
    CLOSE my_cursor;

END;


问:
how to get the html5 time input to display 00:00 instead of 12:00 in the input field?
the original input field display is hh:mm am/pm, I got some CSS codes that turned the display into hh:mm:ss, but it won't display 00:--:-- even if the input value is 00:--:--, instead it displays 12:--:--. is there a way to fix this? perhaps by CSS or JS?

edit: is there another way to have a similar styled input field that takes input in the form of hh:mm:ss into "hh:mm:ss"?

答:
If you are using -

```<code><input type="time" name="time" />
</code>```

Then Chrome may not display it in 24 hour format but other browsers may.

Body:
If you are using -

<input type="time" name="time" />

Then Chrome may not display it in 24 hour format but other browsers may.


问:
How center the text between the limits of the picture
I'm doing a tool to help in a game. The original game looks like this:

I was able to do the elixir number on the purple drop on the top-left. The transparent label to show the Level. (still need to work with the right colors based in card rarity).

But cant make the label center on the bottom and if possible looks like inside the border instead of above the whole picture.

I was trying following this question CSS center text (horizontally and vertically) inside a div block but haven't be able to make it work.

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header-content {
  position: absolute;
  bottom: 0;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div></code>```

答:
Not too sure, but looks like you are just missing coordonates and text-align.

update example for #header-content:

```<code>  bottom: 30px;
  left:24px;
  right:24px;
  text-align:center;
</code>```

and eventually

```<code>  border-radius:0 0 10px 10px;
  text-shadow:1px 1px  white;
</code>```

Demo below:

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(218, 21, 225);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header-content {
  position: absolute;
  bottom: 30px;
  left:24px;
  right:24px;
  text-align:center;
  border-radius:0 0 10px 10px;
  text-shadow:2px 2px  black, -1px -1px black;;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background:  rgba(218, 21, 225,0.5);
  /* padding:10px;
  width: 100%; */
  line-height: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div></code>```

Body:
I'm doing a tool to help in a game. The original game looks like this:

I was able to do the elixir number on the purple drop on the top-left. The transparent label to show the Level. (still need to work with the right colors based in card rarity).

But cant make the label center on the bottom and if possible looks like inside the border instead of above the whole picture.

I was trying following this question CSS center text (horizontally and vertically) inside a div block but haven't be able to make it work.

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header-content {
  position: absolute;
  bottom: 0;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
}

   4
   Level 2

Body:
Not too sure, but looks like you are just missing coordonates and text-align.

update example for #header-content:

  bottom: 30px;
  left:24px;
  right:24px;
  text-align:center;

and eventually

  border-radius:0 0 10px 10px;
  text-shadow:1px 1px  white;

Demo below:

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(218, 21, 225);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header-content {
  position: absolute;
  bottom: 30px;
  left:24px;
  right:24px;
  text-align:center;
  border-radius:0 0 10px 10px;
  text-shadow:2px 2px  black, -1px -1px black;;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background:  rgba(218, 21, 225,0.5);
  /* padding:10px;
  width: 100%; */
  line-height: 40px;
}

<div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div>


问:
LDA analysis error: object not found
I am trying to make a LDA analysis in R to some data. The code is below:

The data is defines as follows:

```<code>mydata=matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30), ncol=5, dimnames=list(c("ex1","ex2","ex3","ex4","ex5","ex6"),c("class","a","b","c","d")))
</code>```

This is the result for "mydata":

```<code>class  a  b  c  d
ex1     1  7 13 19 25
ex2     2  8 14 20 26
ex3     3  9 15 21 27
ex4     4 10 16 22 28
ex5     5 11 17 23 29
ex6     6 12 18 24 30
</code>```

Now, I try to make a LDA analysis using this code:

```<code>mydata.lda<-lda(class ~ mydata.a + mydata.b + mydata.c + mydata.d)
</code>```

This is the error code I get:

```<code>Error in eval(expr, envir, enclos) : object 'mydata.a' not found
Calls: lda ... eval -> model.frame -> model.frame.default -> eval -> eval
</code>```

Why it is not working? Should I change something?

答:
You need to use mydata$a, not mydata.a. You could also just do (untested)</p>

```<code>mydata.lda <- lda(class~a+b+c+d, data = mydata)
</code>```

Title: LDA analysis error: object not found

Body:
I am trying to make a LDA analysis in R to some data. The code is below:

The data is defines as follows:

mydata=matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30), ncol=5, dimnames=list(c("ex1","ex2","ex3","ex4","ex5","ex6"),c("class","a","b","c","d")))

This is the result for "mydata":

class  a  b  c  d
ex1     1  7 13 19 25
ex2     2  8 14 20 26
ex3     3  9 15 21 27
ex4     4 10 16 22 28
ex5     5 11 17 23 29
ex6     6 12 18 24 30

Now, I try to make a LDA analysis using this code:

mydata.lda<-lda(class ~ mydata.a + mydata.b + mydata.c + mydata.d)

This is the error code I get:

Error in eval(expr, envir, enclos) : object 'mydata.a' not found
Calls: lda ... eval -> model.frame -> model.frame.default -> eval -> eval

Why it is not working? Should I change something?

Body:
You need to use mydata$a, not mydata.a. You could also just do (untested)

mydata.lda <- lda(class~a+b+c+d, data = mydata)


问:
Azure IoT Hubs: offline storage of messages
Is there any functionality within the Azure IoT device SDKs to ensure that a message is sent to the hub from a device in the event of a loss of connectivity and subsequent termination and restart (after connectivity is restored) of the application sending the message?

I am struggling to find anything about this in the documentation; I have found this question, however it has not been updated in nearly 2 years and I suspect (hope) things have moved on since then.

The application will be WPF, running on Windows 10 Professional if that makes any difference.

答: This blog has a section on the reliability features in the SDKs.  We will have more documentation on this soon.  You may also want to implement some heat beat mechanism so devices can auto-reboot.</p>