问:
Basic authentication when downloading file over https
I want to download a file from the internet (over https) using WinForms in C#

```<code>private void Button1_Click(object sender, EventArgs e)
{
    string url = textBox1.Text;
    string user = "user";
    string pwd = "pwd";
    CredentialCache mycache = new CredentialCache();
    if (!string.IsNullOrEmpty(url))
    {
        Thread thread = new Thread(() =>
        {
            //Uri uri = new Uri(url);
            mycache.Add(new Uri(url), "Basic", new NetworkCredential(user, pwd));
            client.Credentials = mycache;
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.Buffer = true;
            response.AddHeader("Content-Disposition","attachment;filename=\"" + "a.zip" + "\"");
            byte[] data = client.DownloadData(url);
            response.BinaryWrite(data);
            response.End();
        });
        thread.Start();
    }
}
</code>```

When I start to download this line:
HttpResponse response = HttpContext.Current.Response; threw an exception

'HttpContext.Current.Response' threw an exception of type 'System.NullReferenceException'`.

Can anyone help me solve this problem?

答:
You're thinking of WebForms (classic ASP.NET). WinForms would not have an HttpContext available as it assumes you are in a web context (which you are not). Some options are HttpClient, WebClient, or HttpWebRequest.

You question in and of itself isn't a duplicate of https://stackoverflow.com/a/14628308/120753 but it provides you a solution to do what you need.

Body:
I want to download a file from the internet (over https) using WinForms in C#

private void Button1_Click(object sender, EventArgs e)
{
    string url = textBox1.Text;
    string user = "user";
    string pwd = "pwd";
    CredentialCache mycache = new CredentialCache();
    if (!string.IsNullOrEmpty(url))
    {
        Thread thread = new Thread(() =>
        {
            //Uri uri = new Uri(url);
            mycache.Add(new Uri(url), "Basic", new NetworkCredential(user, pwd));
            client.Credentials = mycache;
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.Buffer = true;
            response.AddHeader("Content-Disposition","attachment;filename=\"" + "a.zip" + "\"");
            byte[] data = client.DownloadData(url);
            response.BinaryWrite(data);
            response.End();
        });
        thread.Start();
    }
}

When I start to download this line:
HttpResponse response = HttpContext.Current.Response; threw an exception

'HttpContext.Current.Response' threw an exception of type 'System.NullReferenceException'`.

Can anyone help me solve this problem?


来源: stackexchange

问:
Changing class state from an imported function in ReactJS
I am trying to change the state of a class from an imported named component so I only need to write the code once. Is this even possible?

I have 3 files ( Login, ForgotPassword, Register ). On ALL of these files I am listening for an "onChange" event on the input fields that all do the same thing as show below:

onChange method:

```<code>onChange = (e) => {
    this.setState(() => ({ errors: {} }));

    let fields = this.state.fields;
    fields[e.target.name] = e.target.value;
    this.setState(() => {
        return {
            fields
        }
    });
};
</code>```

I'd really like to import this as a named method along with some others that are working already:

```<code>import { onFocus, onBlur, onChange } from './Utils/Input';
</code>```

The issue is (as seen above in the onChange code), that I need to update the class state from this method.

Is this at all possible? I am very new to React, so I might be going about this in the completely wrong way.

Thank you in advance!

答:
Use the method by binding the context to it from inside the class like this

onChange.bind(this)

ContentLicense: CC BY-SA 4.0

Body:
I am trying to change the state of a class from an imported named component so I only need to write the code once. Is this even possible?

I have 3 files ( Login, ForgotPassword, Register ). On ALL of these files I am listening for an "onChange" event on the input fields that all do the same thing as show below:

onChange method:

onChange = (e) => {
    this.setState(() => ({ errors: {} }));

    let fields = this.state.fields;
    fields[e.target.name] = e.target.value;
    this.setState(() => {
        return {
            fields
        }
    });
};

I'd really like to import this as a named method along with some others that are working already:

import { onFocus, onBlur, onChange } from './Utils/Input';

The issue is (as seen above in the onChange code), that I need to update the class state from this method.

Is this at all possible? I am very new to React, so I might be going about this in the completely wrong way.

Thank you in advance!


问:
How to retrieve the data sent to database after sent by using notification
/* Am trying to retrieve a notifications after i provide a meeting to the members, the way to retrieveenter code here it comes with undefined index id

I have tried to use json_encode then use json_decode during retrieving but nothing works (am not having much skills in using json) */

/* controller
     */

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
use App\Meeting;
use App\Meeting_agenda;
use App\Meeting_minute;
use App\Notifications\MeetingNotify;
use App\User;

class MeetingsController extends Controller
{
    public function store(Request $request, Meeting $meet)
    {
        $meeting=new Meeting();
        $meeting->meeting_title=$request->meeting_title;
        $meeting->meeting_venue=$request->meeting_venue;
        $meeting->meeting_date=$request->meeting_date;
        $meeting->meeting_type_id=$request->meeting_type_id;
        $meeting->save();

        foreach($request->input('name') as $agenda) {
            $agendas= new Meeting_agenda();
            $agendas->meeting_id=$meeting->id;
            $agendas->name=$agenda;
            $agendas->save();

        }
        $meet=Meeting::where('id',$meeting->id)->get();

                 $users=User::all();
                json_encode(Notification::send($users, new
        MeetingNotify($meet))) ;

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

/* My notification class */

```<code><?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class MeetingNotify extends Notification
{
    use Queueable;
    protected $meet;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($meet)
    {
        $this->meet=$meet;

    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        // return ['mail'];
        return ['database'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */

     public function toDatabase($notifiable)
    {
        return [
            'meet'=>$this->meet,
            // 'user'=>auth()->user()
        ];
    }

     public function toArray($notifiable)
    {
        return [
        // 'meet'=>$this->meet,
        ];
    }

}
</code>```

/* My returning view blade */

```<code><a href="#">
    @if((count(auth()->user()->unreadNotifications)>0))
      @foreach(auth()->user()
         ->unreadNotifications as $notification)
             <div class="dropdown-item"
               onclick="markAsReadNotification()">
                 @include('includes.notifications.'.snake_case(class_basename($notification->type)))

    </div>
     @endforeach
       @else
        <p>  No notifications!</p>
          @endif
            </a>
</code>```

/* includes.notifications.meeting_notify.blade.php */

```<code><a href="/Posts/{{$notification->data['meet']['id']}}">
    {{json_decode($notification->data['meet']['id'])}}
    </a>
</code>```

/* Data that goes to the database */

```<code>{"meet":[{"id":43,"meeting_title":"ordinary","meeting_type_id":2,"meeting_venue":"sdsd","meeting_date":"2019-5-30","minute":null,"created_at":"2019-05-29 15:53:58","updated_at":"2019-05-29 15:53:58"}]}
</code>```

/* I expected to get the meeting shown in my include blade so as to redirect each user there

Below is the error */

```<code>    ErrorException (E_ERROR)
    Undefined index: id (View: C

:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php)
    Previous exceptions
    Undefined index: id (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (0)
    Undefined index: id (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (0)
    Undefined index: id (0)
</code>```

答:
Your problem is that you are using get() when you should be using first(). get() returns a collection of items while first() will return a single resource.

Your code should look like:

```<code>$meet=Meeting::where('id',$meeting->id)->first();
</code>```

Everything will be working fine after that change

Body:
/* Am trying to retrieve a notifications after i provide a meeting to the members, the way to retrieveenter code here it comes with undefined index id

I have tried to use json_encode then use json_decode during retrieving but nothing works (am not having much skills in using json) */

/* controller
     */

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
use App\Meeting;
use App\Meeting_agenda;
use App\Meeting_minute;
use App\Notifications\MeetingNotify;
use App\User;

class MeetingsController extends Controller
{
    public function store(Request $request, Meeting $meet)
    {
        $meeting=new Meeting();
        $meeting->meeting_title=$request->meeting_title;
        $meeting->meeting_venue=$request->meeting_venue;
        $meeting->meeting_date=$request->meeting_date;
        $meeting->meeting_type_id=$request->meeting_type_id;
        $meeting->save();

        foreach($request->input('name') as $agenda) {
            $agendas= new Meeting_agenda();
            $agendas->meeting_id=$meeting->id;
            $agendas->name=$agenda;
            $agendas->save();

        }
        $meet=Meeting::where('id',$meeting->id)->get();

                 $users=User::all();
                json_encode(Notification::send($users, new
        MeetingNotify($meet))) ;

        return redirect('/meetings');
    }
}

/* My notification class */

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class MeetingNotify extends Notification
{
    use Queueable;
    protected $meet;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($meet)
    {
        $this->meet=$meet;

    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        // return ['mail'];
        return ['database'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */

     public function toDatabase($notifiable)
    {
        return [
            'meet'=>$this->meet,
            // 'user'=>auth()->user()
        ];
    }

     public function toArray($notifiable)
    {
        return [
        // 'meet'=>$this->meet,
        ];
    }

}

/* My returning view blade */

    @if((count(auth()->user()->unreadNotifications)>0))
      @foreach(auth()->user()
         ->unreadNotifications as $notification)

                 @include('includes.notifications.'.snake_case(class_basename($notification->type)))

     @endforeach
       @else

  No notifications!

          @endif

/* includes.notifications.meeting_notify.blade.php */

data['meet']['id']}}">
    {{json_decode($notification->data['meet']['id'])}}

/* Data that goes to the database */

{"meet":[{"id":43,"meeting_title":"ordinary","meeting_type_id":2,"meeting_venue":"sdsd","meeting_date":"2019-5-30","minute":null,"created_at":"2019-05-29 15:53:58","updated_at":"2019-05-29 15:53:58"}]}

/* I expected to get the meeting shown in my include blade so as to redirect each user there

Below is the error */

    ErrorException (E_ERROR)
    Undefined index: id (View: C

:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php)
    Previous exceptions
    Undefined index: id (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (0)
    Undefined index: id (View: C:\xampp\htdocs\BoardMeetingSytem\resources\views\includes\notifications\meeting_notify.blade.php) (0)
    Undefined index: id (0)

Body:
Your problem is that you are using get() when you should be using first(). get() returns a collection of items while first() will return a single resource.

Your code should look like:

$meet=Meeting::where('id',$meeting->id)->first();

Everything will be working fine after that change


问:
How do I remove border bottom of input field?
Can anyone tell me how do I remove border-bottom of the input field when I start writing?

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
  border-left: 2px solid #e0e6e8;
  border-right: 2px solid #e0e6e8;
  border-top: 2px solid #e0e6e8;
  border-bottom: 0px;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input"></code>```

答:
You didn't defined any margin-bottom style.

The input looks "tall" because your font size is 14px and the input height is 35px.

So maybe, just low the height, put some padding and add an event listener.

document.getElementById("location").addEventListener("keyup", function(){
  if (this.value != '') {
    this.style.borderBottomWidth = "0px"
  } else {
    this.style.borderBottomWidth = "2px"
  }
},false)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border: 2px solid #e0e6e8;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: solid 2px #25c16f;
}</code>```

<input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">```
</div>
</div>
</p>

<p>Also, pure CSS proposition, add a <code>required</code> attribute to input and check the new CSS :</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>.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-style: solid;
  border-color: #e0e6e8;
  border-width: 2px 2px 0 2px;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-color: #25c16f;
}

.car-list-input:invalid {
  border-width:2px;
}</code>```

<input type="text" required placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">```

Body:
Can anyone tell me how do I remove border-bottom of the input field when I start writing?

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
  border-left: 2px solid #e0e6e8;
  border-right: 2px solid #e0e6e8;
  border-top: 2px solid #e0e6e8;
  border-bottom: 0px;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: 0px;
}

<input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">

Body:
You didn't defined any margin-bottom style.

The input looks "tall" because your font size is 14px and the input height is 35px.

So maybe, just low the height, put some padding and add an event listener.

document.getElementById("location").addEventListener("keyup", function(){
  if (this.value != '') {
    this.style.borderBottomWidth = "0px"
  } else {
    this.style.borderBottomWidth = "2px"
  }
},false)

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border: 2px solid #e0e6e8;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-bottom: solid 2px #25c16f;
}

<input type="text" placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">

Also, pure CSS proposition, add a required attribute to input and check the new CSS :

.car-list-input {
  font-family: 'Source Sans Pro', sans-serif;
  border-style: solid;
  border-color: #e0e6e8;
  border-width: 2px 2px 0 2px;
  border-radius: 3px;
  font-size: 14px;
  font-weight: 400 !important;
  height: 35px;
  position: relative;
}

.car-list-input:focus {
  border-color: #25c16f;
  outline: 0;
  box-shadow: none;
  border-color: #25c16f;
}

.car-list-input:invalid {
  border-width:2px;
}

<input type="text" required placeholder="Enter the location of your vehicle" id="location" onchange="locationApproved()" autocomplete="off" class="form-control car-list-input">


问:
Copy value of above row in 1st column for rows matching pattern
Suppose I have a | separated text file like this:

```<code>123|col 2 row 1|col 3 row 1
xxx|col 2 row 2|col 3 row 2
xxx|col 2 row 3|col 3 row 3
789|col 2 row 4|col 3 row 4
xxx|col 2 row 5|col 3 row 5
xxx|col 2 row 6|col 3 row 6
</code>```

Using sed or awk how to get this:

```<code>123|col 2 row 1|col 3 row 1
123|col 2 row 2|col 3 row 2
123|col 2 row 3|col 3 row 3
789|col 2 row 4|col 3 row 4
789|col 2 row 5|col 3 row 5
789|col 2 row 6|col 3 row 6
</code>```

If value of column 1 is 'xxx' it should be replaced with value in above row.

答:
```<code>$ awk 'BEGIN{FS=OFS="|"} {if ($1=="xxx") $1=p; else p=$1} 1' file
123|col 2 row 1|col 3 row 1
123|col 2 row 2|col 3 row 2
123|col 2 row 3|col 3 row 3
789|col 2 row 4|col 3 row 4
789|col 2 row 5|col 3 row 5
789|col 2 row 6|col 3 row 6
</code>```

Body:
Suppose I have a | separated text file like this:

123|col 2 row 1|col 3 row 1
xxx|col 2 row 2|col 3 row 2
xxx|col 2 row 3|col 3 row 3
789|col 2 row 4|col 3 row 4
xxx|col 2 row 5|col 3 row 5
xxx|col 2 row 6|col 3 row 6

Using sed or awk how to get this:

123|col 2 row 1|col 3 row 1
123|col 2 row 2|col 3 row 2
123|col 2 row 3|col 3 row 3
789|col 2 row 4|col 3 row 4
789|col 2 row 5|col 3 row 5
789|col 2 row 6|col 3 row 6

If value of column 1 is 'xxx' it should be replaced with value in above row.


问:
Error: Schema validation failed with the following errors: Data path "" should NOT have additional properties(project)
After migrating application from angular 5 to 6, on running ng serve the following errors pop up.

Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
  Error: Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
      at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/src/workspace/workspace.js:210:42)
      at MergeMapSubscriber._tryNext (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:65:27)
      at MergeMapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:55:18)
      at MergeMapSubscriber.Subscriber.next (/home/training/Attinad_Projects/TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MergeMapSubscriber.notifyNext (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:84:26)
      at InnerSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:25:21)
      at InnerSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/map.js:52:26)
      at MapSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at SwitchMapSubscriber.notifyNext (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:77:26)

I assume that the error is with .angular.json file which I re-named from .angular-cli.json .

My .angular.json file is as follows :

```<code>{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "project": {
        "name": "mediaweb"
    },
    "apps": [{
            "root": "src",
            "outDir": "dist/browser",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.ts",
            "polyfills": "polyfills.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.app.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss",
                "../node_modules/owl.carousel/dist/assets/owl.carousel.css",
                "../node_modules/owl.carousel/dist/assets/owl.theme.default.css",
                "../node_modules/video.js/dist/video-js.css"
            ],
            "scripts": [
                "../node_modules/jquery/dist/jquery.js",
                "../node_modules/owl.carousel/dist/owl.carousel.js",
                "../node_modules/video.js/dist/ie8/videojs-ie8.js",
                "../node_modules/video.js/dist/video.js"
            ],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        },
        {
            "platform": "server",
            "root": "src",
            "outDir": "dist/server",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.server.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.server.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss"
            ],
            "scripts": [],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        }
    ],
    "e2e": {
        "protractor": {
            "config": "./protractor.conf.js"
        }
    },
    "lint": [{
            "project": "src/tsconfig.app.json",
            "exclude": ["**/node_modules/**", "**/UI/**"]
        },
        {
            "project": "src/tsconfig.spec.json",
            "exclude": "**/node_modules/**"
        },
        {
            "project": "e2e/tsconfig.e2e.json",
            "exclude": "**/node_modules/**"
        }
    ],
    "test": {
        "karma": {
            "config": "./karma.conf.js"
        }
    },
    "defaults": {
        "styleExt": "scss",
        "component": {}
    }
}
</code>```

Should I re-structure the json file, if so how?.

Any help would be great.

答:
Change package.json from:

```<code>"@angular-devkit/build-angular": "^0.13.5",
</code>```

to:

```<code>"@angular-devkit/build-angular": "^0.12.1",
</code>```

Body:
After migrating application from angular 5 to 6, on running ng serve the following errors pop up.

Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
  Error: Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
      at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/src/workspace/workspace.js:210:42)
      at MergeMapSubscriber._tryNext (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:65:27)
      at MergeMapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:55:18)
      at MergeMapSubscriber.Subscriber.next (/home/training/Attinad_Projects/TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MergeMapSubscriber.notifyNext (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:84:26)
      at InnerSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:25:21)
      at InnerSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/map.js:52:26)
      at MapSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at SwitchMapSubscriber.notifyNext (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:77:26)

I assume that the error is with .angular.json file which I re-named from .angular-cli.json .

My .angular.json file is as follows :

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "project": {
        "name": "mediaweb"
    },
    "apps": [{
            "root": "src",
            "outDir": "dist/browser",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.ts",
            "polyfills": "polyfills.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.app.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss",
                "../node_modules/owl.carousel/dist/assets/owl.carousel.css",
                "../node_modules/owl.carousel/dist/assets/owl.theme.default.css",
                "../node_modules/video.js/dist/video-js.css"
            ],
            "scripts": [
                "../node_modules/jquery/dist/jquery.js",
                "../node_modules/owl.carousel/dist/owl.carousel.js",
                "../node_modules/video.js/dist/ie8/videojs-ie8.js",
                "../node_modules/video.js/dist/video.js"
            ],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        },
        {
            "platform": "server",
            "root": "src",
            "outDir": "dist/server",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.server.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.server.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss"
            ],
            "scripts": [],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        }
    ],
    "e2e": {
        "protractor": {
            "config": "./protractor.conf.js"
        }
    },
    "lint": [{
            "project": "src/tsconfig.app.json",
            "exclude": ["**/node_modules/**", "**/UI/**"]
        },
        {
            "project": "src/tsconfig.spec.json",
            "exclude": "**/node_modules/**"
        },
        {
            "project": "e2e/tsconfig.e2e.json",
            "exclude": "**/node_modules/**"
        }
    ],
    "test": {
        "karma": {
            "config": "./karma.conf.js"
        }
    },
    "defaults": {
        "styleExt": "scss",
        "component": {}
    }
}

Should I re-structure the json file, if so how?.

Any help would be great.

Body:
Change package.json from:

"@angular-devkit/build-angular": "^0.13.5",

to:

"@angular-devkit/build-angular": "^0.12.1",


问:
Why using Gunicorn with GEvent could increate the query time to Redis/Database?
In actual production load (web app) with an Redis server (v4.x) when using gunicorn with worker_class gevent the query time increases by 3. Database access also got worse (but not so much, only 50%). I'm trying to figure out why this would happen. Any ideas? The app is very IO Bound, with lots of database queries and redis accesses for every single request, which should be the perfect scenario for gevent.

Moving from SYNC to GEVENT (~11 A.M)

Would the monkey patching to the socket decrease performance somehow? I tried to fine tuning worker_connections without success, even the extremely low level of just 2 (almost sync again), give me the same bad results. Am I missing some gotcha for how gevent and it's pseudothreads work?

Disclaimer: I'm using NewRelic to monitor the performance and redis-py/django/mysql. I tried some tweaks like using the BlockingConnectionPool for Redis, but my Database access performance also decreased so Redis is not the only problem. The worker size is 5 (CPUs * 2 + 1). I also had tons of GreenletExit/ConnectionError[redis] at random times, which was minimized by moving worker_connections from 2k (default) to 10.

答:
Example of a redis connection after monkeypatching.  </p>

```<code>_rconn = None
def redisconn():
    global _rconn
    if _rconn is None:
        try:
            _rconn = redis.StrictRedis(host=redisconfig['host'], port=redisconfig['port'], db=redisconfig['db'])
        except:
            traceback.print_exc()
            _rconn = None
    return _rconn

class RedisCache(object):
    def __init__(self):
        #in case of a lost connection lets sit and wait till it's online
        global _rconn
        if not _rconn:
            while not _rconn:
                try:
                    redisconn()
                except:
                    print('Attempting Connection To Redis...')
                    gsleep(1)
        self.r = _rconn
        self.rpool = self.r.connection_pool

    def get(self, key):
        return self.r.get(key)

    def set(self, key, meta, expire=86400, nx=True):
        return self.r.set(key, json.loads(meta), ex=expire, nx=nx)

    def connections(self):
        return self.rpool._created_connections

    def inuse(self):
        return self.rpool._in_use_connections
</code>```

Body:
Example of a redis connection after monkeypatching.

_rconn = None
def redisconn():
    global _rconn
    if _rconn is None:
        try:
            _rconn = redis.StrictRedis(host=redisconfig['host'], port=redisconfig['port'], db=redisconfig['db'])
        except:
            traceback.print_exc()
            _rconn = None
    return _rconn

class RedisCache(object):
    def __init__(self):
        #in case of a lost connection lets sit and wait till it's online
        global _rconn
        if not _rconn:
            while not _rconn:
                try:
                    redisconn()
                except:
                    print('Attempting Connection To Redis...')
                    gsleep(1)
        self.r = _rconn
        self.rpool = self.r.connection_pool

    def get(self, key):
        return self.r.get(key)

    def set(self, key, meta, expire=86400, nx=True):
        return self.r.set(key, json.loads(meta), ex=expire, nx=nx)

    def connections(self):
        return self.rpool._created_connections

    def inuse(self):
        return self.rpool._in_use_connections


问:
Is there a way to skip error "filename is not found" and move to the next file
Is there a way to skip error "filename is not found" and move to the next file?

```<code>Sub CopyDataAndMoveDown()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        Call MoveBelow
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

Sub MoveBelow ()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        ' At this point when the macro meet again a empty cell
        ' it should keep moving from the same counted X
        ' but start the paste operation from 24 rows below.
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub
</code>```

So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.

--------Below the old question.

I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?

```<code>Sub HaeReseptiTiedot()

Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String

myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value

Application.ScreenUpdating = False

Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
</code>```

答:
You could work around this by creating a second Sub that opens the file and handles the error if the file doesn't exist. That way you are still able to catch other Errors in the main Sub without going to next. Example:</p>

```<code>Sub MainSub()

    myFile1 = "C:\Temp\New1.xlsx"
    myFile2 = "C:\Temp\New2.xlsx"
    CheckAndOpen (myFile1)
    CheckAndOpen (myFile2)

End Sub

Sub CheckAndOpen(myFileName As String)

    On Error Resume Next
    Workbooks.Open Filename:=myFileName
    Debug.Print Err.Number, myFileName

End Sub
</code>```

Body:
Is there a way to skip error "filename is not found" and move to the next file?

Sub CopyDataAndMoveDown()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        Call MoveBelow
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

Sub MoveBelow ()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        ' At this point when the macro meet again a empty cell
        ' it should keep moving from the same counted X
        ' but start the paste operation from 24 rows below.
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.

--------Below the old question.

I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?

Sub HaeReseptiTiedot()

Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String

myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value

Application.ScreenUpdating = False

Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Body:
You could work around this by creating a second Sub that opens the file and handles the error if the file doesn't exist. That way you are still able to catch other Errors in the main Sub without going to next. Example:

Sub MainSub()

    myFile1 = "C:\Temp\New1.xlsx"
    myFile2 = "C:\Temp\New2.xlsx"
    CheckAndOpen (myFile1)
    CheckAndOpen (myFile2)

End Sub

Sub CheckAndOpen(myFileName As String)

    On Error Resume Next
    Workbooks.Open Filename:=myFileName
    Debug.Print Err.Number, myFileName

End Sub


问:
Org.Hibernate.AnnotationException: No Identifier Specified For Entity I don't have a id in my table
I'm working with a table in a database and that table don't have a primary key or a proper column whith a unique value who can act as a primary key, I don't have permissions to alter that table.

What should I do? I tried putting a @id annotation in a random column and it worked, but I don't know if this is going to bring any trouble later on. what can I do?

My class

```<code>@Entity
@Table(name="my_table")
public class TheTable {
@Column (name="name", nullable=false)
    private String name;

    @Id <--- I just put this id in this random column but this column should not be a id column
    @Column (name="anyfield", nullable=false)
    private String anyfield;
}
</code>```

答:
Use @Embeddable annotation instead of @Entity if your class mapping is used as readOnly mapping and does not have PK or @EmbeddedKey

```<code>//@Entity
@Embeddable
@Table(name = "my_table")
public class MyTable implements Serializable {

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working with a table in a database and that table don't have a primary key or a proper column whith a unique value who can act as a primary key, I don't have permissions to alter that table.

What should I do? I tried putting a @id annotation in a random column and it worked, but I don't know if this is going to bring any trouble later on. what can I do?

My class

@Entity
@Table(name="my_table")
public class TheTable {
@Column (name="name", nullable=false)
    private String name;

    @Id <--- I just put this id in this random column but this column should not be a id column
    @Column (name="anyfield", nullable=false)
    private String anyfield;
}

Body:
Use @Embeddable annotation instead of @Entity if your class mapping is used as readOnly mapping and does not have PK or @EmbeddedKey

//@Entity
@Embeddable
@Table(name = "my_table")
public class MyTable implements Serializable {

}


问:
Difference between events and delegates and its respective applications
I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate.

Would you explain to me the differences and when to use which?  What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.

答:
Events are marked as such in the metadata.  This allows things like the Windows Forms or ASP.NET designers to distinguish events from mere properties of delegate type, and provide appropriate support for them (specifically showing them on the Events tab of the Properties window).

Another difference from a property of delegate type is that users can only add and remove event handlers, whereas with a property of delegate type they can set the value:

```<code>someObj.SomeCallback = MyCallback;  // okay, replaces any existing callback
someObj.SomeEvent = MyHandler;  // not okay, must use += instead
</code>```

This helps to isolate event subscribers: I can add my handler to an event, and you can add your handler to the same event, and you won't accidentally overwrite my handler.

OwnerDisplayName: Sasha

LastEditorDisplayName: RoBorg

Body:
Events are marked as such in the metadata.  This allows things like the Windows Forms or ASP.NET designers to distinguish events from mere properties of delegate type, and provide appropriate support for them (specifically showing them on the Events tab of the Properties window).

Another difference from a property of delegate type is that users can only add and remove event handlers, whereas with a property of delegate type they can set the value:

someObj.SomeCallback = MyCallback;  // okay, replaces any existing callback
someObj.SomeEvent = MyHandler;  // not okay, must use += instead

This helps to isolate event subscribers: I can add my handler to an event, and you can add your handler to the same event, and you won't accidentally overwrite my handler.

OwnerDisplayName: itowlson

ContentLicense: CC BY-SA 2.5


问:
Evaluating JavaScript into WKWebView to fetch the Video URL doesn't work
So I'm trying to get the video source URL by evaluating javascript into WKWebView. Tried to search through many different posts but none of them got me what I want. I'm trying to download videos from Dailymotion.com , which I've opened in my WKWebView. Now in my WKWebView's delegate methods I am passing the current URL of Webview for evaluation of JavaScript so that I get the video URL.

```<code>

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)
    {
        print("wkwebview")
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)
    {
        print("wkwebview")
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        //print("wkwebview")
        //print(navigationAction.request.url?.absoluteString as Any)

        webView.evaluateJavaScript("document.getElementsByTagName('video')")
        {
            (result, error) in
            guard error == nil else
            {
                print(error!)
                return
            }
             print(String(describing: result))
        }

       //loadURL(site: (webView.url?.absoluteString)!)

        decisionHandler(.allow)
    }

</code>```

The error I've been getting is Error Domain=WKErrorDomain Code=5 "JavaScript execution returned a result of an unsupported type" UserInfo={NSLocalizedDescription=JavaScript execution returned a result of an unsupported type}

答:
Swift can't interpret javascript objects - in this case you're returning an array of element objects with the tag 'video'.

However, Swift can receive String values fine. Assuming your video element has the url as a 'src' attribute, you can just use document.getElementsByTagName('video')[0].getAttribute('src') in place of your current JS call to get the source url as a string.

.getElementsByTagName returns an array. You'll need to grab the right index if you have multiple video elements, or just grab the first (like I did above).

Alternatively:
document.getElementsByTagName('video')[0].src

Body:
So I'm trying to get the video source URL by evaluating javascript into WKWebView. Tried to search through many different posts but none of them got me what I want. I'm trying to download videos from Dailymotion.com , which I've opened in my WKWebView. Now in my WKWebView's delegate methods I am passing the current URL of Webview for evaluation of JavaScript so that I get the video URL.

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)
    {
        print("wkwebview")
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)
    {
        print("wkwebview")
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        //print("wkwebview")
        //print(navigationAction.request.url?.absoluteString as Any)

        webView.evaluateJavaScript("document.getElementsByTagName('video')")
        {
            (result, error) in
            guard error == nil else
            {
                print(error!)
                return
            }
             print(String(describing: result))
        }

       //loadURL(site: (webView.url?.absoluteString)!)

        decisionHandler(.allow)
    }

The error I've been getting is Error Domain=WKErrorDomain Code=5 "JavaScript execution returned a result of an unsupported type" UserInfo={NSLocalizedDescription=JavaScript execution returned a result of an unsupported type}


问:
R: weighted inverse document frequency (tfidf) similarity between strings
I want to be able to find similarity between two strings, weighting each token (word) with its inverse document frequency (those frequencies are not taken from those strings).

Using quanteda I can create a dfm_tfidf with inverted frequency weights, but do not know how to proceed after that.

Sample data :

ss = c(
        "ibm madrid limited research",
        "madrid limited research",
        "limited research",
        "research"
    )
counts = list(ibm = 1, madrid = 2, limited = 3, research = 4)
cor = corpus(long_list_of_strings)  ## the documents where we take words from
df = dfm(cor, tolower = T, verbose = T)
dfi = dfm_tfidf(df)
```

<p>The goal is to find a function <code>similarity</code> that will make:</p>

<pre class="lang-r prettyprint-override"><code>res = similarity(dfi, "ibm limited", similarity_scheme = "simple matching")
</code>```

with res in the form (random numbers for the example):

```<code>"ibm madrid limited research"  0.445
"madrid limited research" 0.2
"limited research" 0.76
"research" 0.45
</code>```

Ideally would be to apply to those frequencies a function like :

```<code>sim = sum(Wc) / sqrt(sum(Wi)*sum(Wj))
</code>```

where:
Wc are the weights of words common to the two strings.

Wi and Wj are the weights of words in string1 and string2.

答:
I had problems with the quanteda and qdap packages, so I built my own code to get a dataframe with individual words and frequency count. The code could be improved of course, but I think it shows how to do it.

```<code>library(RecordLinkage)
library(stringr)
library(dplyr)

searchstring = c(
  "ibm madrid limited research",
  "madrid limited research",
  "limited research",
  "research"
)

cleanInput <- function(x) {
  x <- tolower(x)
  x <- removePunctuation(x)
  x <- stripWhitespace(x)
  x <- gsub("-", "", x)
  x <- gsub(" ?(f|ht)tp(s?)://(.*)[.][a-z]+", "", x)
  x <- gsub("[[:digit:]]+", "", x)
}

searchstring <- cleanInput(searchstring)
splitted <- str_split(searchstring, " ", simplify = TRUE)
df <- as.data.frame(as.vector(splitted))
df <- df[df$`as.vector(splitted)` != "", , drop = FALSE]
colnames(df)[1] <- "string"
result <- df %>%
  group_by(string) %>%
  summarise(n = n())
result$string <- as.character(result$string)
</code>```

I first clean up the strings and then build a data.frame with it.

After I received my data.frame, where exists a function called jarowinkler from the RecordLinkage package to measure similarity between two strings. It is vectorized and fast :-)

```<code>> jarowinkler(result$string, "ibm limited")
[1] 0.0000000 0.8303030 0.8311688 0.3383838 0.0000000
</code>```

I hope this is what you desired :-)

Body:
I want to be able to find similarity between two strings, weighting each token (word) with its inverse document frequency (those frequencies are not taken from those strings).

Using quanteda I can create a dfm_tfidf with inverted frequency weights, but do not know how to proceed after that.

Sample data :

ss = c(
        "ibm madrid limited research",
        "madrid limited research",
        "limited research",
        "research"
    )
counts = list(ibm = 1, madrid = 2, limited = 3, research = 4)
cor = corpus(long_list_of_strings)  ## the documents where we take words from
df = dfm(cor, tolower = T, verbose = T)
dfi = dfm_tfidf(df)

The goal is to find a function similarity that will make:

res = similarity(dfi, "ibm limited", similarity_scheme = "simple matching")

with res in the form (random numbers for the example):

"ibm madrid limited research"  0.445
"madrid limited research" 0.2
"limited research" 0.76
"research" 0.45

Ideally would be to apply to those frequencies a function like :

sim = sum(Wc) / sqrt(sum(Wi)*sum(Wj))

where:
Wc are the weights of words common to the two strings.

Wi and Wj are the weights of words in string1 and string2.

Body:
I had problems with the quanteda and qdap packages, so I built my own code to get a dataframe with individual words and frequency count. The code could be improved of course, but I think it shows how to do it.

library(RecordLinkage)
library(stringr)
library(dplyr)

searchstring = c(
  "ibm madrid limited research",
  "madrid limited research",
  "limited research",
  "research"
)

cleanInput <- function(x) {
  x <- tolower(x)
  x <- removePunctuation(x)
  x <- stripWhitespace(x)
  x <- gsub("-", "", x)
  x <- gsub(" ?(f|ht)tp(s?)://(.*)[.][a-z]+", "", x)
  x <- gsub("[[:digit:]]+", "", x)
}

searchstring <- cleanInput(searchstring)
splitted <- str_split(searchstring, " ", simplify = TRUE)
df <- as.data.frame(as.vector(splitted))
df <- df[df$`as.vector(splitted)` != "", , drop = FALSE]
colnames(df)[1] <- "string"
result <- df %>%
  group_by(string) %>%
  summarise(n = n())
result$string <- as.character(result$string)

I first clean up the strings and then build a data.frame with it.

After I received my data.frame, where exists a function called jarowinkler from the RecordLinkage package to measure similarity between two strings. It is vectorized and fast :-)

> jarowinkler(result$string, "ibm limited")
[1] 0.0000000 0.8303030 0.8311688 0.3383838 0.0000000

I hope this is what you desired :-)


问:
get length of strings split into parts
I want to get the length of silted strings in number or stringlist view

```<code>String s= "Aan.Gabriel.Gymkhana";
String[] parts = s.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
String part3

String s= "Aan.Gabriel.Gymkhana";
String[] parts = s.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
String part3
</code>```

as list

```<code>1 Aan
2 Gabrie
3 Gymkhana
</code>```

the length of list will be 3

答:
I'm having a hard time figuring out what you want, but I think that s.split("\\.").length should get you the correct solution.

If you just need the length, then you don't need to turn it into a list.

If you want to turn it into a list, @Micheal's answer was correct.

List<String> list = Arrays.asList(parts);
```

Title: get length of strings split into parts

Body:
I want to get the length of silted strings in number or stringlist view

String s= "Aan.Gabriel.Gymkhana";
String[] parts = s.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
String part3

String s= "Aan.Gabriel.Gymkhana";
String[] parts = s.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
String part3

as list

1 Aan
2 Gabrie
3 Gymkhana

the length of list will be 3


问:
Can you run Kubernetes nodes on multiple clouds as part of one cluster?
Is it possible to run a single Kubernetes cluster that includes nodes that are spread across multiple clouds? For example, could you have some nodes running in AWS and some in Azure, and all be a part of the same cluster?

This question was asked in 2015 but I'm not sure if that answer is still accurate.

答:
Assuming that you can reach a low latency between the machines then it should not be a problem. There are many reasons to do this but also many to not do it (security, latency, networking problems). I did not attempt to do this yet so if there is someone who has experience in this topic I will gladly welcome some more insights.
There is an interesting whitepapers and report about multi cloud deployments here. You would have to also look at cluster federation described in the Kubernetes official docs and the tool used for it Kubefed. There is another source in medium article from 2017 with approach to do this using Juju and Kubefed.

I am going to actually try this this week or in the beggining of next. So I will comeback with some more information.

You can find some information about similar scenario here.


问:
How to use python language server for vscode in specific path?
I'm using ArchLinux and want to use Python Language Server with vscode to write python codes.

As I search in aur, I found microsoft-python-language-server which download and build the language server with dotnet.
The package gives me an executable file at /usr/bin/mspyls.

However, when I open vscode, it still downloads a new language server automatically for me at
.vscode/extensions/ms-python.python-2019.5.17059/languageServer.0.2.86/Microsoft.Python.LanguageServer.
And there are not any config for me to specify the path to language server.

Are there any possible solution to use my own mspyls but not the one vscode downloaded?

答: No, the Python extension for VS Code doesn't allow you to choose your own copy of the language server to use due to compatibility requirements (e.g. changes in the LSP, other extensions like IntelliCode that need to plug into the language server, etc.).</p>


问:
jQuery Select by Name and ID
I have a table like so:

```<code>    <table>
        <tr>
            <td>
                <input type="radio" name="Sample1" id="Sample1" value="1" />
                <input type="radio" name="Sample1" id="Sample2" value="1" />
            </td>
            <td>
                <input type="radio" name="Sample2" id="Sample1" value="1" />
                <input type="radio" name="Sample2" id="Sample2" value="1" />
            </td>
            etc....
        </tr>
    </table>
</code>```

I want to be able to select a specific radio button by name and id. E.G., select the radio button with the name Sample2 and id Sample1. I tried doing this:

```<code>    $('[id="Sample1"][name="Sample2"]').checked = true;
</code>```

But no luck... How should I be doing this?

答:
```<code> $('#Sample1[name="Sample2"]').attr('checked','checked');
</code>```

but elements can only have one id so maybe you want class instead of id

```<code>  $('.Sample1[name="Sample2"]').attr('checked','checked');
</code>```

then your html

```<code><table>
    <tr>
        <td>
            <input type="radio" name="Sample1" class="Sample" value="1" />
            <input type="radio" name="Sample1" class="Sample" value="1" />
        </td>
        <td>
            <input type="radio" name="Sample2" class="Sample1" value="1" />
            <input type="radio" name="Sample2" class="Sample2" value="1" />
        </td>
    </tr>
</table>
</code>```

EDIT

made some changes here is a working demo

Title: jQuery Select by Name and ID

Body:
I have a table like so:

                <input type="radio" name="Sample1" id="Sample1" value="1" />
                <input type="radio" name="Sample1" id="Sample2" value="1" />

                <input type="radio" name="Sample2" id="Sample1" value="1" />
                <input type="radio" name="Sample2" id="Sample2" value="1" />

            etc....

I want to be able to select a specific radio button by name and id. E.G., select the radio button with the name Sample2 and id Sample1. I tried doing this:

    $('[id="Sample1"][name="Sample2"]').checked = true;

But no luck... How should I be doing this?

Body:
 $('#Sample1[name="Sample2"]').attr('checked','checked');

but elements can only have one id so maybe you want class instead of id

  $('.Sample1[name="Sample2"]').attr('checked','checked');

then your html

<table>
    <tr>
        <td>
            <input type="radio" name="Sample1" class="Sample" value="1" />
            <input type="radio" name="Sample1" class="Sample" value="1" />
        </td>
        <td>
            <input type="radio" name="Sample2" class="Sample1" value="1" />
            <input type="radio" name="Sample2" class="Sample2" value="1" />
        </td>
    </tr>
</table>

EDIT

made some changes here is a working demo


问:
How would you analyse a file too big for memory?
Recently I was asked this question in a live coding interview round by the recruiter. I was not sure how to do this with code.

I thought of splitting the file into multiple files and then read those chunks through multiple threads.

But I was not able to implement the same.

Any help with the implementation or some other approach will be appreciated !

答:
This is a broad topic but usually these types of problems are solved using buffer.

The size of the buffer is what your memory can hold and you can read data from file and load it in buffer to perform the task and then empty the buffer and load the next chunk and so on.

For example, if you want to sort some data which is too big for memory, we use method known as external sorting.

Mostly, relational database uses this external sort method sort the data when we use order by clause in our query. For deeper details on this, there is a wonderful lecture of which video link is pasted below.

https://www.youtube.com/watch?v=YjFI9CJy6x0&t=3506s

I hope it helps you in understanding.


问:
Powershell module initialization
Does PowerShell call any initialization code when a module is loaded?

I am looking for something like a Perl BEGIN block, or a constructor.

Both NEW-MODULE and IMPORT-MODULE will return a PSCustomObject. I am trying to encapsulate a custom object in a module to avoid lengthy code in scripts. One method that tests well in open code is:

```<code>$m = new-module -scriptblock {
New-Object PSCustomObject |
    Add-Member NoteProperty -name person -value Frodo -passthru |
    Add-Member ScriptMethod Who { $this.person }  -passthru |
    Add-Member ScriptMethod Mod {
        param($x)
        $this.person = $x
        } -passthru
} -ascustomobject -returnresult
</code>```

Ideally I would like to drop this code into a module and use something like:

```<code>$MyObj = Import-Module -Name ".\MyPackage" -AsCustomObject
</code>```

and have MyObj be a handle to an object the same as the first snippet provides.

Suggestions appreciated.

答:
Using Modules you can export both innate properties and functions, and don't need to run them through add-member or do much acrobatics.  Note however that it has some issues if you don't want to export all properties and methods, and while you can initialize properties to an initial value, you CAN'T call an internal function during initialization without doing some akward acrobatics.

But I think what you really want to do is use Classes which are now available in Powershell 5 (they weren't when you posted).  I've provided examples of each.
 Sysops has a decent tutorial on the new classes in 4 parts

Here's the older way before powershell 5.0

```<code># powershell 3.0 and above (I think)
$m = new-module -ascustomobject -scriptblock `
    {
    $person = "Frodo"
    function Who
        ()
        {return $this.person}
    function Rename
        ($name)
        {$this.person = $name}
    Export-ModuleMember -Function * -Variable *
    }

write-host "direct property access: $($m.person)"
write-host "method call: $($m.who())"
$m.Rename("Shelob")
write-host "change test: $($m.who())"
</code>```

Also you can replicate multiple objects from a template like this:

```<code># powershell 3.0 and above (I think)
$template = `
    {
    $person = "Frodo"
    function Who
        ()
        {return $this.person}
    function Rename
        ($name)
        {$this.person = $name}
    Export-ModuleMember -Function * -Variable *
    }

$me = new-module -ascustomobject -scriptblock $template; $me.Rename("Shelob")
$you = new-module -ascustomobject -scriptblock $template

"Me: $($me.Who())"
"You: $($you.Who())"
</code>```

And in powershell 5 you have actual classes (mostly)

```<code>#requires -version 5
Class Person
    {
    hidden [String] $name #not actually private

    [string] Who ()
        {return $this.name}

    [void] Rename ([string] $name)
        {$this.name = $name}

    # constructors are weird though, you don't specify return type OR explicitly return value.
    Person ([String]$name)
        {$this.name = $name}
    <#
    # The above constructor code is secretly converted to this
    [Person] New ([string]$name) #note the added return type and renamed to New
        {
        $this.name = $name
        return $this #note that we are returning ourself, you can exploit this to create chained constructors like [person]::New("gandalf").withWizardLevel("White") but I haven't done so here
        }
    #>

    }
$me = [Person]::new("Shelob")
$you = [Person]::new("Frodo")

# $me|gm        # Note that Name doesn't show here
# $me.name      # But we can still access it...
# $me|gm -Force # Note that Name DOES show here

"`n"
"Me: $($me.who())"
"You: $($you.who())"
$you.Rename("Dinner")
"You after we meet: $($you.who())"
</code>```

Title: Powershell module initialization

Body:
Does PowerShell call any initialization code when a module is loaded?

I am looking for something like a Perl BEGIN block, or a constructor.

Both NEW-MODULE and IMPORT-MODULE will return a PSCustomObject. I am trying to encapsulate a custom object in a module to avoid lengthy code in scripts. One method that tests well in open code is:

$m = new-module -scriptblock {
New-Object PSCustomObject |
    Add-Member NoteProperty -name person -value Frodo -passthru |
    Add-Member ScriptMethod Who { $this.person }  -passthru |
    Add-Member ScriptMethod Mod {
        param($x)
        $this.person = $x
        } -passthru
} -ascustomobject -returnresult

Ideally I would like to drop this code into a module and use something like:

$MyObj = Import-Module -Name ".\MyPackage" -AsCustomObject

and have MyObj be a handle to an object the same as the first snippet provides.

Suggestions appreciated.

Body:
Using Modules you can export both innate properties and functions, and don't need to run them through add-member or do much acrobatics.  Note however that it has some issues if you don't want to export all properties and methods, and while you can initialize properties to an initial value, you CAN'T call an internal function during initialization without doing some akward acrobatics.

But I think what you really want to do is use Classes which are now available in Powershell 5 (they weren't when you posted).  I've provided examples of each.
 Sysops has a decent tutorial on the new classes in 4 parts

Here's the older way before powershell 5.0

# powershell 3.0 and above (I think)
$m = new-module -ascustomobject -scriptblock `
    {
    $person = "Frodo"
    function Who
        ()
        {return $this.person}
    function Rename
        ($name)
        {$this.person = $name}
    Export-ModuleMember -Function * -Variable *
    }

write-host "direct property access: $($m.person)"
write-host "method call: $($m.who())"
$m.Rename("Shelob")
write-host "change test: $($m.who())"

Also you can replicate multiple objects from a template like this:

# powershell 3.0 and above (I think)
$template = `
    {
    $person = "Frodo"
    function Who
        ()
        {return $this.person}
    function Rename
        ($name)
        {$this.person = $name}
    Export-ModuleMember -Function * -Variable *
    }

$me = new-module -ascustomobject -scriptblock $template; $me.Rename("Shelob")
$you = new-module -ascustomobject -scriptblock $template

"Me: $($me.Who())"
"You: $($you.Who())"

And in powershell 5 you have actual classes (mostly)

#requires -version 5
Class Person
    {
    hidden [String] $name #not actually private

    [string] Who ()
        {return $this.name}

    [void] Rename ([string] $name)
        {$this.name = $name}

    # constructors are weird though, you don't specify return type OR explicitly return value.
    Person ([String]$name)
        {$this.name = $name}
    <#
    # The above constructor code is secretly converted to this
    [Person] New ([string]$name) #note the added return type and renamed to New
        {
        $this.name = $name
        return $this #note that we are returning ourself, you can exploit this to create chained constructors like [person]::New("gandalf").withWizardLevel("White") but I haven't done so here
        }
    #>

    }
$me = [Person]::new("Shelob")
$you = [Person]::new("Frodo")

# $me|gm        # Note that Name doesn't show here
# $me.name      # But we can still access it...
# $me|gm -Force # Note that Name DOES show here

"`n"
"Me: $($me.who())"
"You: $($you.who())"
$you.Rename("Dinner")
"You after we meet: $($you.who())"


问:
Unable to get data from JSONDecoder ,that's right, I made up the structure?
I have such a structure, I took a piece to get the data. Here's my code.Why can't I get data from the Api?Can anyone help and example write in the answer.It seems like all are correct.  I will be very grateful.

```<code>[{
    "id": 142636,
    "apiId": 353056,
    "shortName": "K. McKenzie-Lyle",
    "firstName": "Kai",
    "middleName": null,
    "lastName": "McKenzie-Lyle",
    "imageFileName": null,
    "height": 195,
    "weight": 86,
    "birthDate": "1997-11-30T00:00:00",
    "contractExpiration": null,
    "onLoanSquadTillDate": null,
    "oldApiId": 344534,
    "age": 22,
    "birthAreaId": 80,
    "passportAreaId": 110,
    "footName": "Right",
    "male": true,
    "currentSquadId": 20401,
    "parentSquadId": 46,
    "nationalSquadId": 31885,

    }]
</code>```

My code struct tried decode and "id" , etc.

```<code>struct PlayerRoster:Codable {
    let id: String?
    let apiId:String?
    let shortName: String?
    let firstName: String?
    let middleName:String?
    let lastName:String?
    let imageFileName:String?
    let height:Double?
    let weight:Double?

}
</code>```

My load url api adress.

```<code>func loadingApi(){
            let urlData = "https://apidev.transferroom.com/api/values"

            guard let url = URL(string: urlData) else { return }

            let task = URLSession.shared.dataTask(with: url) { (data,response,error) in

                guard let data = data else { return }
                guard error == nil else {return}

                    do {
                        let decoder = JSONDecoder()

                        //using the array to put values
                      let player = try decoder.decode(PlayerRoster.self, from: data)
                      self.updatedPlauers = player

                    } catch let error as NSError {
                        print("Failed to load: \(error.localizedDescription)")
                    }
                }

            task.resume()

        }
    }
</code>```

答:
You need

```<code>let player = try decoder.decode([PlayerRoster].self, from: data)
</code>```

the root of your json is an array indicated by [] , doing this would help knowing the problem

```<code>} catch {
   print("Failed to decode : \(error)")
 }
</code>```

plus

```<code>let id: Int?
let apiId:Int?
</code>```

Body:
I have such a structure, I took a piece to get the data. Here's my code.Why can't I get data from the Api?Can anyone help and example write in the answer.It seems like all are correct.  I will be very grateful.

[{
    "id": 142636,
    "apiId": 353056,
    "shortName": "K. McKenzie-Lyle",
    "firstName": "Kai",
    "middleName": null,
    "lastName": "McKenzie-Lyle",
    "imageFileName": null,
    "height": 195,
    "weight": 86,
    "birthDate": "1997-11-30T00:00:00",
    "contractExpiration": null,
    "onLoanSquadTillDate": null,
    "oldApiId": 344534,
    "age": 22,
    "birthAreaId": 80,
    "passportAreaId": 110,
    "footName": "Right",
    "male": true,
    "currentSquadId": 20401,
    "parentSquadId": 46,
    "nationalSquadId": 31885,

    }]

My code struct tried decode and "id" , etc.

struct PlayerRoster:Codable {
    let id: String?
    let apiId:String?
    let shortName: String?
    let firstName: String?
    let middleName:String?
    let lastName:String?
    let imageFileName:String?
    let height:Double?
    let weight:Double?

}

My load url api adress.

func loadingApi(){
            let urlData = "https://apidev.transferroom.com/api/values"

            guard let url = URL(string: urlData) else { return }

            let task = URLSession.shared.dataTask(with: url) { (data,response,error) in

                guard let data = data else { return }
                guard error == nil else {return}

                    do {
                        let decoder = JSONDecoder()

                        //using the array to put values
                      let player = try decoder.decode(PlayerRoster.self, from: data)
                      self.updatedPlauers = player

                    } catch let error as NSError {
                        print("Failed to load: \(error.localizedDescription)")
                    }
                }

            task.resume()

        }
    }

Body:
You need

let player = try decoder.decode([PlayerRoster].self, from: data)

the root of your json is an array indicated by [] , doing this would help knowing the problem

} catch {
   print("Failed to decode : \(error)")
 }

plus

let id: Int?
let apiId:Int?


问:
how to access the current index in array_reduce?
Having read this SO post, In PHP I am aware that you can get the index under iteration with array_map as such:

```<code>array_map(function($item, $index) { ... }, $items, array_keys($items));
</code>```

How can I get the an $index available to me when I use array_reduce? I have tried:

```<code>array_reduce($items, array_keys($items), function($acc, $item, $index) { ... }, array());

array_reduce($items, function($acc, $item, $index) { ... }, array(), array_keys($items));
</code>```

But I still can't seem to get $index in an array_reduce. Has anyone successfully done this before?

EDIT

Here's some context as to why I am asking this question.

I do not want to use foreach because I would have to mutate an array outside of the foreach in order to create my collection. I would prefer to avoid mutation.

Other languages allow one to use reduce and get access to the current index like in JavaScript and Ruby. I was hoping to get the same feature in PHP. Oh well! Looks like I'm going to have to use a foreach to create my array while also having the current index under iteration.

答:
I just had same issue. It's pretty simple to solve.

```<code>$i = 0;
$p = array_reduce($array, function($output, $item) use (&$i) {
   // use $i
   // do something with $item and/or $output
   $i++; // increment $i
   return $output;
}, $initial);
</code>```

&$i pass $i as reference and grants it will be updated.

Body:
Having read this SO post, In PHP I am aware that you can get the index under iteration with array_map as such:

array_map(function($item, $index) { ... }, $items, array_keys($items));

How can I get the an $index available to me when I use array_reduce? I have tried:

array_reduce($items, array_keys($items), function($acc, $item, $index) { ... }, array());

array_reduce($items, function($acc, $item, $index) { ... }, array(), array_keys($items));

But I still can't seem to get $index in an array_reduce. Has anyone successfully done this before?

EDIT

Here's some context as to why I am asking this question.

I do not want to use foreach because I would have to mutate an array outside of the foreach in order to create my collection. I would prefer to avoid mutation.

Other languages allow one to use reduce and get access to the current index like in JavaScript and Ruby. I was hoping to get the same feature in PHP. Oh well! Looks like I'm going to have to use a foreach to create my array while also having the current index under iteration.

Body:
I just had same issue. It's pretty simple to solve.

$i = 0;
$p = array_reduce($array, function($output, $item) use (&$i) {
   // use $i
   // do something with $item and/or $output
   $i++; // increment $i
   return $output;
}, $initial);

&$i pass $i as reference and grants it will be updated.


问:
Clear multiple select jquery-select2
I am trying to create a reset button for jquery-select2 multiple select. I have no idea why my solution doesn't work.

Html:

```<code><select id="workload-selector" class="js-source-states-2" multiple="multiple" style="width: 100%">
  <option value="haha">haha</option>
  <option value="haha2">haha2</option>
  <option value="haha3">haha3</option>
</select>

<button id="reset">
Reset
</button>
</code>```

Javascript:

```<code>$("#workload-selector").select2();
$("#reset").click(function(){
  $("#workload-selector option:selected").removeAttr("selected");
});
</code>```

I made it on jsFiddle:
https://jsfiddle.net/DTcHh/41975/

答:
I have done just that, there it goes a sample of my elaboration</p>

```<code>$("#reset").click(function(){
  $("#workload-selector").val(null).trigger('change');
});
</code>```

Title: Clear multiple select jquery-select2

Body:
I am trying to create a reset button for jquery-select2 multiple select. I have no idea why my solution doesn't work.

Html:

<select id="workload-selector" class="js-source-states-2" multiple="multiple" style="width: 100%">
  <option value="haha">haha</option>
  <option value="haha2">haha2</option>
  <option value="haha3">haha3</option>
</select>

<button id="reset">
Reset
</button>

Javascript:

$("#workload-selector").select2();
$("#reset").click(function(){
  $("#workload-selector option:selected").removeAttr("selected");
});

I made it on jsFiddle:
https://jsfiddle.net/DTcHh/41975/

Body:
I have done just that, there it goes a sample of my elaboration

$("#reset").click(function(){
  $("#workload-selector").val(null).trigger('change');
});


问:
Simple javascript counter that can be paused and resumed after web page has been closed
I need to create a very simple Javascript-based counter, which counts currency (so two decimal places) and increases in value by 0.18 every minute. The idea is to represent "live" estimated savings by the company's new solar panels, and this counter will be started and stopped by an employee every day, to continue the next day.

I found a fiddle by somebody else for a start/resume counter: http://jsfiddle.net/f9X6J/
HTML:

```<code><span id="hour"></span>
<span id="min"></span>
<span id="sec"></span>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
</code>```

Javascript:

```<code>  var Clock = {
  totalSeconds: 1000,

  start: function () {
    var self = this;

    this.interval = setInterval(function () {
      self.totalSeconds += 1;

      $("#hour").text(Math.floor(self.totalSeconds / 3600));
      $("#min").text(Math.floor(self.totalSeconds / 60 % 60));
      $("#sec").text(parseInt(self.totalSeconds % 60));
    }, 1000);
  },

  pause: function () {
    clearInterval(this.interval);
    delete this.interval;
  },

  resume: function () {
    if (!this.interval) this.start();
  }
};

Clock.start();

$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
</code>```

This is great so far, but I please need the following:

It must not calculate time, but rather money.

It must be saved to the server in case the computer shuts off.

Thanks!

答:
For the sake of beginners in 2019. The answer to the two questions are,

1) Keep a counter outside the clock object and keep adding 1 to it every second the clock is active. This will give the total number of seconds the clock has been active. This can be then converted to total savings at any point.

2) Don't jump on to server side stuff just yet. Try to store the total with localStorage which persists even if the computer is switched off until browsing data is cleared in the browser. This will avoid lot of added complexity. An example for storing values locally and reading from them is below.

```<code><html>
  <head></head>
  <body>
    <div id="counter"></div>
  </body>
  <script>
    var counter;
    if( localStorage.getItem("counter") == null) {
      counter = 0;
      localStorage.setItem("counter", counter);
    } else {
      counter = localStorage.getItem("counter");
    }
    document.getElementById('counter').textContent = counter;
    setInterval(function(){
      counter = parseInt(counter)+1;
      localStorage.setItem("counter", counter);
      document.getElementById('counter').textContent = counter;
    },1000);
  </script>
</html>
</code>```

Hope this provides a right direction.

Body:
I need to create a very simple Javascript-based counter, which counts currency (so two decimal places) and increases in value by 0.18 every minute. The idea is to represent "live" estimated savings by the company's new solar panels, and this counter will be started and stopped by an employee every day, to continue the next day.

I found a fiddle by somebody else for a start/resume counter: http://jsfiddle.net/f9X6J/
HTML:

<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">

Javascript:

  var Clock = {
  totalSeconds: 1000,

  start: function () {
    var self = this;

    this.interval = setInterval(function () {
      self.totalSeconds += 1;

      $("#hour").text(Math.floor(self.totalSeconds / 3600));
      $("#min").text(Math.floor(self.totalSeconds / 60 % 60));
      $("#sec").text(parseInt(self.totalSeconds % 60));
    }, 1000);
  },

  pause: function () {
    clearInterval(this.interval);
    delete this.interval;
  },

  resume: function () {
    if (!this.interval) this.start();
  }
};

Clock.start();

$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });

This is great so far, but I please need the following:

It must not calculate time, but rather money.

It must be saved to the server in case the computer shuts off.

Thanks!

Body:
For the sake of beginners in 2019. The answer to the two questions are,

1) Keep a counter outside the clock object and keep adding 1 to it every second the clock is active. This will give the total number of seconds the clock has been active. This can be then converted to total savings at any point.

2) Don't jump on to server side stuff just yet. Try to store the total with localStorage which persists even if the computer is switched off until browsing data is cleared in the browser. This will avoid lot of added complexity. An example for storing values locally and reading from them is below.

<html>
  <head></head>
  <body>
    <div id="counter"></div>
  </body>
  <script>
    var counter;
    if( localStorage.getItem("counter") == null) {
      counter = 0;
      localStorage.setItem("counter", counter);
    } else {
      counter = localStorage.getItem("counter");
    }
    document.getElementById('counter').textContent = counter;
    setInterval(function(){
      counter = parseInt(counter)+1;
      localStorage.setItem("counter", counter);
      document.getElementById('counter').textContent = counter;
    },1000);
  </script>
</html>

Hope this provides a right direction.


问:
AJV return only one error although there is multiple
I'm trying to use AJV with the below code, when I validate an object with multiple errors, AJV throws only one error at a time.

const schema = {
    type: 'object',
    properties: {
      name: {type: 'string', minLength: 1, maxLength: 1},
      sku: { type: 'string', minLength: 1, maxLength: 200},
    },
    required: ['name', 'sku']
  }

  const ajv = require('ajv');
  const validator = new ajv();

  const valid = validator.validate(schema, {});

  if (!valid) {
    console.log(validator.errors);
  }```
</div>
</div>

That code should produce two errors, as name and SKU is required, but it returns only one error, check the below output:</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-js lang-js prettyprint-override"><code>[ { keyword: 'required',
    dataPath: '',
    schemaPath: '#/required',
    params: { missingProperty: 'name' },
    message: 'should have required property \'name\'' } ]</code>```

答:
You need to set the configuration for that.

If you have get all the errors in once then you have to set this object param when creating an object of ajv {allErrors: true}

here is updated the code.

```<code>const schema = {
    type: 'object',
    properties: {
        name: {type: 'string', minLength: 1, maxLength: 1},
        sku: { type: 'string', minLength: 1, maxLength: 200},
    },
    required: ['name', 'sku']
}

const ajv = require('ajv');
const validator = new ajv({allErrors:true});

const valid = validator.validate(schema, {});

if (!valid) {
  console.log(validator.errors);
}
</code>```

Please also check this link for more configuration params. Link https://github.com/epoberezkin/ajv#options

Body:
I'm trying to use AJV with the below code, when I validate an object with multiple errors, AJV throws only one error at a time.

const schema = {
    type: 'object',
    properties: {
      name: {type: 'string', minLength: 1, maxLength: 1},
      sku: { type: 'string', minLength: 1, maxLength: 200},
    },
    required: ['name', 'sku']
  }

  const ajv = require('ajv');
  const validator = new ajv();

  const valid = validator.validate(schema, {});

  if (!valid) {
    console.log(validator.errors);
  }

That code should produce two errors, as name and SKU is required, but it returns only one error, check the below output:

[ { keyword: 'required',
    dataPath: '',
    schemaPath: '#/required',
    params: { missingProperty: 'name' },
    message: 'should have required property \'name\'' } ]

Body:
You need to set the configuration for that.

If you have get all the errors in once then you have to set this object param when creating an object of ajv {allErrors: true}

here is updated the code.

const schema = {
    type: 'object',
    properties: {
        name: {type: 'string', minLength: 1, maxLength: 1},
        sku: { type: 'string', minLength: 1, maxLength: 200},
    },
    required: ['name', 'sku']
}

const ajv = require('ajv');
const validator = new ajv({allErrors:true});

const valid = validator.validate(schema, {});

if (!valid) {
  console.log(validator.errors);
}

Please also check this link for more configuration params. Link https://github.com/epoberezkin/ajv#options


问:
vba scraping nested (?) tab/button
I've been trying to scrape an intranet site at work longer than I'm willing to admit. The program is Agile (a common manufacturing tool) which uses IE so the address doesn't change while navigating. The tab/button/menu I want to select is inside a tab_wrapper which I am not able to get to with my skill set.

The furthest I can drill down is...

```<code>idoc.getElementById("rightPaneContent").getElementsByTagName("Form")(0)
</code>```

...but it doesn't show a complete result for DIV, LI or A.

The menu drop down I'm trying to select is actually redundant, but the menu bar uses HREF javascript without class or ID which I also tried to execute without any luck, so I turned my attention to the drop down menu with ID's.

```<code>Private Sub btnSearch_Click()

    Dim page, srch As String

    srch = Me.txtSearch
    page = "http://xxagile.xxxxxx.com/Agile/" & _
           "PLMServlet?module=LoginHandler&opcode=forwardToMainMenu#"

    Dim ie As InternetExplorer: Set ie = New InternetExplorerMedium

        With ie
        .Visible = True
        .Navigate page
        End With

        Do Until ie.ReadyState = 4: DoEvents: Loop

    Dim iDoc As HTMLDocument: Set iDoc = ie.Document

        With iDoc
        .getElementById("toggle_search_menu").Click        ' select menu
        .getElementById("cls_901").Click                   ' select ITEM from menu
        .getElementById("quicksearch_string").Value = srch ' enter string
        .getElementById("top_simpleSearch").Click          ' click search button
        End With

        Do Until ie.ReadyState = 4: DoEvents: Loop

    'iDoc.getElementById("rightMenuImg").Click ' error 91
    'iDoc.getElementById("rightScrollMenu").Click ' error 91

    With ie
    '.Stop
    '.Quit
    End With

    Set ie = Nothing: Set iDoc = Nothing

End Sub
</code>```

The outerHTML is about 1600+ lines so I shortened it to this...

```<code><div id="rightpanecontent">

<form name="MainForm" method="POST" action="PCMServlet" enctype="application/x-www-form-urlencoded" onsubmit="return false;" target="_self">

<!--************************************
    TAB VIEW
*************************************-->
<div id="tabsview_wrapper">
<div id="tabsandcontrols"> <!-- wrapper for tabs, dms, and tab actions -->

    <!--************************************
        TABS
    *************************************-->
<div id="leftScroll" style="display: none; left: 129px; top: 174px;">
<div id="rightScroll" style="display: none; left: 528px; top: 174px;">
<img id="rightScrollImg" src="/Agile/static/6dbe07cad9d304865dea9dfd18d4cb59/images/icn_action_tabscroll_right_enabled.png" onmousedown="scrollButtonPressed(event, 'right')" onmouseup="hideShowScrollButtons()" oncontextmenu="return false" style="cursor: pointer;">
</div>

<div id="rightScrollMenu" style="display: block; left: 891px; top: 142px;">
<img id="rightMenuImg" src="/Agile/static/8913d52dc8a2aeaaa1ea83e36663943d/images/icn_action_tabmenu.png" onclick="showTabsMenu(this, '21', event)" ondblclick="showTabsMenu(this, '21', event)" style="cursor: pointer;">
</div>
</code>```

I have attempted a slew of coding variations.  Fire, click, nesting, focus, etc and I'm at my end.

agile screen capture

答:
Eureka moment...</p>

```<code>    Dim sJS As String
    sJS = "javascript:displayObject" & _
           "('ItemHandler', '10000', '394341431', '12','', '0');"

        Call iDoc.parentWindow.execScript(sJS)
</code>```

Title: vba scraping nested (?) tab/button

Body:
I've been trying to scrape an intranet site at work longer than I'm willing to admit. The program is Agile (a common manufacturing tool) which uses IE so the address doesn't change while navigating. The tab/button/menu I want to select is inside a tab_wrapper which I am not able to get to with my skill set.

The furthest I can drill down is...

idoc.getElementById("rightPaneContent").getElementsByTagName("Form")(0)

...but it doesn't show a complete result for DIV, LI or A.

The menu drop down I'm trying to select is actually redundant, but the menu bar uses HREF javascript without class or ID which I also tried to execute without any luck, so I turned my attention to the drop down menu with ID's.

Private Sub btnSearch_Click()

    Dim page, srch As String

    srch = Me.txtSearch
    page = "http://xxagile.xxxxxx.com/Agile/" & _
           "PLMServlet?module=LoginHandler&opcode=forwardToMainMenu#"

    Dim ie As InternetExplorer: Set ie = New InternetExplorerMedium

        With ie
        .Visible = True
        .Navigate page
        End With

        Do Until ie.ReadyState = 4: DoEvents: Loop

    Dim iDoc As HTMLDocument: Set iDoc = ie.Document

        With iDoc
        .getElementById("toggle_search_menu").Click        ' select menu
        .getElementById("cls_901").Click                   ' select ITEM from menu
        .getElementById("quicksearch_string").Value = srch ' enter string
        .getElementById("top_simpleSearch").Click          ' click search button
        End With

        Do Until ie.ReadyState = 4: DoEvents: Loop

    'iDoc.getElementById("rightMenuImg").Click ' error 91
    'iDoc.getElementById("rightScrollMenu").Click ' error 91

    With ie
    '.Stop
    '.Quit
    End With

    Set ie = Nothing: Set iDoc = Nothing

End Sub

The outerHTML is about 1600+ lines so I shortened it to this...

<form name="MainForm" method="POST" action="PCMServlet" enctype="application/x-www-form-urlencoded" onsubmit="return false;" target="_self">

I have attempted a slew of coding variations.  Fire, click, nesting, focus, etc and I'm at my end.

agile screen capture

Body:
Eureka moment...

    Dim sJS As String
    sJS = "javascript:displayObject" & _
           "('ItemHandler', '10000', '394341431', '12','', '0');"

        Call iDoc.parentWindow.execScript(sJS)


问:
What's the best way to rank models in rails
Let's say I have Posts and Comments for a blog app using Rails and MySQL.

I want to rank Posts by number of comments.  (Note: not just sort, but get their actual 1st,2nd,3rd rank).

Also, given a post, I want to be able to get it's rank without loading all Posts into Rails and searching through them.

e.g. "This post is ranked #372 by number of comments"

Finally, if two posts have the same number of comments, they should have the same rank - so ties are ok.

I've seem some clever solutions to this in MySQL, such as this post:
How do I Handle Ties When Ranking Results in MySQL?

I'm wondering if there is a simpler solution by normalizing some of the data in an additional field on the posts table.

Has anyone seen a good approach for this?

答:
Thinking more about this, I think there are few different ways you can go about adding this functionality.

You can either add Redis to the mix and use its sorted set functionality ala the top score example in this post, http://jimneath.org/2011/03/24/using-redis-with-ruby-on-rails.html

This would probably be the best design, in my opinion. You divorce the analysis part from the data gathering part and you use redis what it's best at.

Another way is to create a PostRanking model that records the post_id and the comment count. You can put a default scope on this to sort by number of comments in descending order and query it easily.


问:
Get timezone of area with country code in Java
I have to pass a message (jms) with timezone info like (America/Los_Angeles) but I have only country name and code. If it possible get timezone info with Java code. Somewhere I read this:

```<code>System.out.println(TimeZone.getTimeZone("US"));
</code>```

But its giving output as

```<code>sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
</code>```

I am expecting List of "America/Los_Angeles", ...

答: The builtin Java classes don't offer this, but ICU's TimeZone class does, and TimeZone.getAvailableIDs("US") provides the correct answer.

Body:
I have to pass a message (jms) with timezone info like (America/Los_Angeles) but I have only country name and code. If it possible get timezone info with Java code. Somewhere I read this:

System.out.println(TimeZone.getTimeZone("US"));

But its giving output as

sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]

I am expecting List of "America/Los_Angeles", ...