问:
Lifecycle of BuiltinHandlerActivator and application requests with Rebus
I have questions regarding lifecycles of various Rebus’s object related to application requests for Publisher and Subscriber:

Please see below:

Publisher

1 Must the code below be initialised once and only once for the lifetime of the app?

For example, instance of BuiltinHandlerActivator below is initialised once, and used throughout the lifecycle of the app?

```<code>using (var activator = new BuiltinHandlerActivator())
{
    Log.Logger = new LoggerConfiguration()
        .WriteTo.ColoredConsole()
        .ReadFrom.Configuration(SerilogConfiguration)
        .Enrich.WithProperty("App Name", "Rebus Publisher")
        .CreateLogger();

    Configure.With(activator)
        .Logging(l =>
        {
            l.Serilog(Log.Logger);
        })
        .Transport(t => t.UseAzureServiceBus(Consts.ServiceBusConnectionString, Consts.Publisher))
        .Options(o =>
        {
            o.Decorate<IErrorHandler>(c => new MyErrorHandler(c.Get<IErrorHandler>()));

            o.SimpleRetryStrategy(maxDeliveryAttempts: 1, errorQueueAddress: "poison");
        })
        .Start();
</code>```

2 Can multiple threads call and use activator below concurrently?

For example, if multiple requests are coming in, Azure Function runtime creates multiple instance of Function below, each of which process the requests.

```<code>activator.Bus.Publish("test").Wait();
</code>```

Subscriber1

Similar questions apply to the publisher above

1 Must the code below be initialised once and only once for the lifetime of the app?
For example, instance of BuiltinHandlerActivator below is initialised once, and used throughout the lifecycle of the app?

```<code>using (var activator = new BuiltinHandlerActivator())
{
    activator.Register(() => new Handler(MessageContext.Current));

    Configure.With(activator)
        .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn))
        .Transport(t => t.UseAzureServiceBus(Consts.ServiceBusConnectionString, Consts.Subscriber1))
        .Routing(r => r.TypeBased().MapAssemblyOf<string>(Consts.Publisher))
        .Options(o =>
        {
            //consumer only
            o.SimpleRetryStrategy(maxDeliveryAttempts: 2, errorQueueAddress: "poison");
            //consumer only
            o.SetNumberOfWorkers(7);
            o.SetMaxParallelism(10);
        }).Start();
</code>```

2 Can multiple threads call and use activator below concurrently?

For example, if multiple requests are coming in, Azure Function runtime creates multiple instance of Function below, each of which process the requests.

Please note that both SetNumberOfWorkers and SetMaxParallelism are used for Subscriber1.

```<code>activator.Bus.Subscribe<string>().Wait();
</code>```

答:
The bus instance is fully re-entrant and thus safe to use across threads.

Generally, you should create the bus instance only once, and then either

dispose the bus instance, or

dispose the BuiltinHandlerActivator, or

dispose the IoC container you're using to hold on to your bus instance

when the application shuts down.

If you're in an Azure Function, you should use a "one-way client", which is just another word for a bus instance that is not capable of receiving messages – it's only capable of sending/publishing. You can read about the two bus modes here: Different bus modes

You can read more about instance policy and thread safety here: Thread safety and instance policies.

Body:
I have questions regarding lifecycles of various Rebus’s object related to application requests for Publisher and Subscriber:

Please see below:

Publisher

1 Must the code below be initialised once and only once for the lifetime of the app?

For example, instance of BuiltinHandlerActivator below is initialised once, and used throughout the lifecycle of the app?

using (var activator = new BuiltinHandlerActivator())
{
    Log.Logger = new LoggerConfiguration()
        .WriteTo.ColoredConsole()
        .ReadFrom.Configuration(SerilogConfiguration)
        .Enrich.WithProperty("App Name", "Rebus Publisher")
        .CreateLogger();

    Configure.With(activator)
        .Logging(l =>
        {
            l.Serilog(Log.Logger);
        })
        .Transport(t => t.UseAzureServiceBus(Consts.ServiceBusConnectionString, Consts.Publisher))
        .Options(o =>
        {
            o.Decorate<IErrorHandler>(c => new MyErrorHandler(c.Get<IErrorHandler>()));

            o.SimpleRetryStrategy(maxDeliveryAttempts: 1, errorQueueAddress: "poison");
        })
        .Start();

2 Can multiple threads call and use activator below concurrently?

For example, if multiple requests are coming in, Azure Function runtime creates multiple instance of Function below, each of which process the requests.

activator.Bus.Publish("test").Wait();

Subscriber1

Similar questions apply to the publisher above

1 Must the code below be initialised once and only once for the lifetime of the app?
For example, instance of BuiltinHandlerActivator below is initialised once, and used throughout the lifecycle of the app?

using (var activator = new BuiltinHandlerActivator())
{
    activator.Register(() => new Handler(MessageContext.Current));

    Configure.With(activator)
        .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn))
        .Transport(t => t.UseAzureServiceBus(Consts.ServiceBusConnectionString, Consts.Subscriber1))
        .Routing(r => r.TypeBased().MapAssemblyOf<string>(Consts.Publisher))
        .Options(o =>
        {
            //consumer only
            o.SimpleRetryStrategy(maxDeliveryAttempts: 2, errorQueueAddress: "poison");
            //consumer only
            o.SetNumberOfWorkers(7);
            o.SetMaxParallelism(10);
        }).Start();

2 Can multiple threads call and use activator below concurrently?

For example, if multiple requests are coming in, Azure Function runtime creates multiple instance of Function below, each of which process the requests.

Please note that both SetNumberOfWorkers and SetMaxParallelism are used for Subscriber1.

activator.Bus.Subscribe<string>().Wait();


来源: stackexchange

问:
sum after subtracting first element of particular column with all the elements of another column and repeat with 2 element and so on in R programming
I would like to sum post subtracting all elements of datestamp-1 with 1st element of datestamp-2, and repeat the same for 2nd element of datestamp-2 and so on in R

```<code>datestamp1 datestamp2 load_percent
2019-05-28 2019-05-25 0.01883
2019-05-29 2019-05-26 0.72340
</code>```

Expected result is as mentioned below.

```<code>datestamp1 datestamp2 weighted_index
2019-05-28 2019-05-25 2.95
2019-05-29 2019-05-26 2.20
</code>```

Logic being

```<code>1. 2019-05-28 - 2019-05-25 = 3 * 0.01 = 0.056
2. 2019-05-29 - 2019-05-25 = 4 * 0.72 = 2.893
</code>```

sum of 0.056 and 2.893 is 2.95

similarly

```<code>3. 2019-05-28 - 2019-05-26 = 2 * 0.01 = 0.037
4. 2019-05-29 - 2019-05-26 = 3 * 0.72 = 2.170
</code>```

and sum of 0.037 and 2.170 is 2.20

答:
Using sapply you can do

```<code>df$weighted_index <- sapply(df$datestamp2, function(x)
                            sum((df$datestamp1 - x) * df$load_percent))

df
#  datestamp1 datestamp2 load_percent weighted_index
#1 2019-05-28 2019-05-25      0.01883        2.95009
#2 2019-05-29 2019-05-26      0.72340        2.20786
</code>```

Make sure that your columns datestamp1 and datestamp2 are of Date class. If they are not first convert them to date and then use the above code.

```<code> df[1:2] <- lapply(df[1:2], as.Date)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to sum post subtracting all elements of datestamp-1 with 1st element of datestamp-2, and repeat the same for 2nd element of datestamp-2 and so on in R

datestamp1 datestamp2 load_percent
2019-05-28 2019-05-25 0.01883
2019-05-29 2019-05-26 0.72340

Expected result is as mentioned below.

datestamp1 datestamp2 weighted_index
2019-05-28 2019-05-25 2.95
2019-05-29 2019-05-26 2.20

Logic being

1. 2019-05-28 - 2019-05-25 = 3 * 0.01 = 0.056
2. 2019-05-29 - 2019-05-25 = 4 * 0.72 = 2.893

sum of 0.056 and 2.893 is 2.95

similarly

3. 2019-05-28 - 2019-05-26 = 2 * 0.01 = 0.037
4. 2019-05-29 - 2019-05-26 = 3 * 0.72 = 2.170

and sum of 0.037 and 2.170 is 2.20

Body:
Using sapply you can do

df$weighted_index <- sapply(df$datestamp2, function(x)
                            sum((df$datestamp1 - x) * df$load_percent))

df
#  datestamp1 datestamp2 load_percent weighted_index
#1 2019-05-28 2019-05-25      0.01883        2.95009
#2 2019-05-29 2019-05-26      0.72340        2.20786

Make sure that your columns datestamp1 and datestamp2 are of Date class. If they are not first convert them to date and then use the above code.

 df[1:2] <- lapply(df[1:2], as.Date)


问:
How do I checkout a branch added after a Github clone?
I have cloned a Github repository with the "--recursive" qualifier.  I then checked out the latest branch in that repository.

Later, the author of the repository added a new branch.  When I attempted to checkout that new branch with git checkout branch-name, git reported that the branch-name was unknown.

Is there a way to get the new branch-name without again cloning the repository?

答:
First fetch from your remote $ git fetch origin

You could list all branches with command git branch -a

And then, checkout required branch.

```<code>$ git fetch origin
$ git checkout --track origin/new_branch_1
</code>```

Body:
First fetch from your remote $ git fetch origin

You could list all branches with command git branch -a

And then, checkout required branch.

$ git fetch origin
$ git checkout --track origin/new_branch_1


问:
How to create notifyIcon without Form?
I added notifyIcon to the container and set Visible = true option, but no icon appeared.</p>

```<code>private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
            this.SuspendLayout();
            //
            // notifyIcon1
            //
            this.notifyIcon1.Text = "Manager";
            this.notifyIcon1.Visible = true;
            //
            // Form1
            //
            this.ClientSize = new System.Drawing.Size(0, 0);
            this.ShowInTaskbar = false;
            this.Visible = false;

        }
</code>```

答:
I believe you need to add a few more events for this to work, Hope this helps</p>

```<code>public Form2()
    {
        InitializeComponent();
        notifyIcon1.Icon = SystemIcons.Asterisk;
        notifyIcon1.DoubleClick += new EventHandler(notifyIcon1_DoubleClick);// to bring it back
        this.Resize += new EventHandler(Form2_Resize);// to move it to tray
    }

    void notifyIcon1_DoubleClick(object sender, EventArgs e)
    {
        Show();
        this.BringToFront();
        this.WindowState = FormWindowState.Normal;
    }

    void Form2_Resize(object sender, EventArgs e)
    {
        if (this.WindowState ==FormWindowState.Minimized)
            Hide();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to create notifyIcon without Form?

Body:
I added notifyIcon to the container and set Visible = true option, but no icon appeared.

private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
            this.SuspendLayout();
            //
            // notifyIcon1
            //
            this.notifyIcon1.Text = "Manager";
            this.notifyIcon1.Visible = true;
            //
            // Form1
            //
            this.ClientSize = new System.Drawing.Size(0, 0);
            this.ShowInTaskbar = false;
            this.Visible = false;

        }

Body:
I believe you need to add a few more events for this to work, Hope this helps

public Form2()
    {
        InitializeComponent();
        notifyIcon1.Icon = SystemIcons.Asterisk;
        notifyIcon1.DoubleClick += new EventHandler(notifyIcon1_DoubleClick);// to bring it back
        this.Resize += new EventHandler(Form2_Resize);// to move it to tray
    }

    void notifyIcon1_DoubleClick(object sender, EventArgs e)
    {
        Show();
        this.BringToFront();
        this.WindowState = FormWindowState.Normal;
    }

    void Form2_Resize(object sender, EventArgs e)
    {
        if (this.WindowState ==FormWindowState.Minimized)
            Hide();
    }


问:
JS clone objects using spread operator and change one field
Say I have an object: {a: 'A', b: 'B', c: 'C'} and I want to create a new object from it that would have the same values except I want to set c: 'D'.

What is the syntax for that?
I tried something like:

{c: 'D', ...rest} = {...foo}

But it is not a valid syntax.

答:
You would write your code like this:

var obj1 = {a: 'A', b: 'B', c: 'C'}
var obj2 = {...obj1, c: 'D'}
console.log(obj2)```
</div>
</div>
</p>

<p>Writing <code>...obj1</code> will fill <code>obj2</code> with <code>obj1</code>'s contents, and writing <code>c: 'D'</code> will overwrite <code>c: 'c'</code>.</p>

<blockquote>
  <p>Note, ordering is important, as maheer mentioned, because the object will be written in order, from each property, which can mess up ordering of keys, and setting incorrect values:</p>
</blockquote>

<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>var obj = {a: 'A', b: 'B', c: 'C'}
var ex1 = {...obj, c: 'D'}
var ex2 = {c: 'D', ...obj}
var ex3 = {c: 'D', ...obj, c: 'E'}

console.log('Example 1:', ex1)
console.log('Example 2:', ex2)
console.log('Example 3:', ex3)</code>```

Body:
You would write your code like this:

var obj1 = {a: 'A', b: 'B', c: 'C'}
var obj2 = {...obj1, c: 'D'}
console.log(obj2)

Writing ...obj1 will fill obj2 with obj1's contents, and writing c: 'D' will overwrite c: 'c'.

Note, ordering is important, as maheer mentioned, because the object will be written in order, from each property, which can mess up ordering of keys, and setting incorrect values:

var obj = {a: 'A', b: 'B', c: 'C'}
var ex1 = {...obj, c: 'D'}
var ex2 = {c: 'D', ...obj}
var ex3 = {c: 'D', ...obj, c: 'E'}

console.log('Example 1:', ex1)
console.log('Example 2:', ex2)
console.log('Example 3:', ex3)


问:
How to use meta tags with dynamic value in react js?
Can anyone help me regarding how to use meta tags with dynamic value in react js?

Please see the image for my requirement,

I am using the extra metatag html tag here(because react require wrap complete html inside the single tag else it raise error). I can also use div/p any html tag, but is this right way to render the react component? having extra html tag than inside that meta tags. Will this work for SEO?

Please suggested me any other good way to use meta tags manually.

答:
There Is a Package Named React-Helmet available it helps to take control over Your Head tags on each route.
Helmet takes plain HTML tags and outputs plain HTML tags. It’s dead simple, and React beginner friendly.

```<code><Helmet>
     <title>{context.StoreName}</title>
     <meta name="theme-color" content={`${context.ThemeColor}`}/>
</Helmet>
</code>```

reference - https://codeburst.io/how-to-control-head-tags-in-react-seo-friendly-8264e1194880

Body:
There Is a Package Named React-Helmet available it helps to take control over Your Head tags on each route.
Helmet takes plain HTML tags and outputs plain HTML tags. It’s dead simple, and React beginner friendly.

<Helmet>
     <title>{context.StoreName}</title>
     <meta name="theme-color" content={`${context.ThemeColor}`}/>
</Helmet>

reference - https://codeburst.io/how-to-control-head-tags-in-react-seo-friendly-8264e1194880


问:
use params in devise signup form
My user visits an item show view and then is send to the signup-page (I use devise). On the signup page, I have the params (item_id) of the item he visited on the previous page. I want this item_id to be saved when the user makes his sign_up (like user.item_id). Here is how I tried to do it:

```<code><input value="#{params[:item_id]}" type="hidden" name="user[item_id]" id="user_item_id">
</code>```

When the user is saved, the item_id remains empty. What am I missing here?
Here is what I put into my controller:

```<code>def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:item_id])
end
</code>```

答:
Here is how I fixed it:

class RegistrationsController < Devise::RegistrationsController
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:item_id])
  end
end
```

Title: use params in devise signup form

Body:
My user visits an item show view and then is send to the signup-page (I use devise). On the signup page, I have the params (item_id) of the item he visited on the previous page. I want this item_id to be saved when the user makes his sign_up (like user.item_id). Here is how I tried to do it:

<input value="#{params[:item_id]}" type="hidden" name="user[item_id]" id="user_item_id">

When the user is saved, the item_id remains empty. What am I missing here?
Here is what I put into my controller:

def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:item_id])
end


答:
You spread syntax on right hand side.

Note: Use Spread Operator first then set the new property. For example {c:'D',...foo} will not work.

let foo = {a: 'A', b: 'B', c: 'C'};
let res = {...foo, c:'D'};
console.log(res)```

Title: JS clone objects using spread operator and change one field

Body:
Say I have an object: {a: 'A', b: 'B', c: 'C'} and I want to create a new object from it that would have the same values except I want to set c: 'D'.

What is the syntax for that?
I tried something like:

{c: 'D', ...rest} = {...foo}

But it is not a valid syntax.


问:
PDFKit, nodeJS merging two PDF files
does anyone have experience with PDFKit with NodeJS. Specifically, I'm trying to merge 2 PDF documents into 1, but I can't seem seem to get the content of the two PDFs properly with formatting inside the merged one.

Here's what I do:

```<code>var PDFDocument = require('pdfkit');
var fs = require('fs');

var doc = new PDFDocument();
var fileName = 'test.pdf';
doc.pipe(fs.createWriteStream(fileName));

var file1 = '1.pdf';
var file2 = '2.pdf';

var stream1 = fs.createReadStream(file1);
doc.text(stream1);

doc.addPage();
var stream2 = fs.createReadStream(file2);
doc.text(stream2);

doc.end();
</code>```

The output, that being test.pdf, should consist of a single pdf containing the contents of the 2 pdfs with the same formatting, but I'm only getting test.pdf with 2 pages, each consisting of a single line of "[Object object]". I can't seem to find how to redirect the content of the stream inside the doc.text() function.

Any idea on what I do wrong, how should I fix it?

答:
It is not possible to merge two PDF documents with pdfkit!

You can use pdftk Server for that purpose. The program offers a command line interface, which could merge two pdfs with the following command:

```<code>pdftk 1.pdf 2.pdf cat output merged.pdf
</code>```

Title: PDFKit, nodeJS merging two PDF files

Body:
does anyone have experience with PDFKit with NodeJS. Specifically, I'm trying to merge 2 PDF documents into 1, but I can't seem seem to get the content of the two PDFs properly with formatting inside the merged one.

Here's what I do:

var PDFDocument = require('pdfkit');
var fs = require('fs');

var doc = new PDFDocument();
var fileName = 'test.pdf';
doc.pipe(fs.createWriteStream(fileName));

var file1 = '1.pdf';
var file2 = '2.pdf';

var stream1 = fs.createReadStream(file1);
doc.text(stream1);

doc.addPage();
var stream2 = fs.createReadStream(file2);
doc.text(stream2);

doc.end();

The output, that being test.pdf, should consist of a single pdf containing the contents of the 2 pdfs with the same formatting, but I'm only getting test.pdf with 2 pages, each consisting of a single line of "[Object object]". I can't seem to find how to redirect the content of the stream inside the doc.text() function.

Any idea on what I do wrong, how should I fix it?

Body:
It is not possible to merge two PDF documents with pdfkit!

You can use pdftk Server for that purpose. The program offers a command line interface, which could merge two pdfs with the following command:

pdftk 1.pdf 2.pdf cat output merged.pdf


问:
Why is `'\t\n ' == false` in JavaScript?
In JavaScript...

```<code>'\t\n ' == false // true
</code>```

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

答:
```<code>whitespace == false; // true
</code>```

Type coercion, love it or hate it.

Digging into the ES5 spec atm. There really isn't any other good way apart from reading what someone else dug out of the ES5 spec.

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

new Number(false) == " "; // true

Booleans get converted to 0 or 1. The reason this is the case is that whitespace == 0

And if you really want to know about new Number(" ") then read this 9.3.1 in the ES5 spec.

The important line is :

The MV of StringNumericLiteral ::: StrWhiteSpace is 0.

Body:
In JavaScript...

'\t\n ' == false // true

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

Body:
whitespace == false; // true

Type coercion, love it or hate it.

Digging into the ES5 spec atm. There really isn't any other good way apart from reading what someone else dug out of the ES5 spec.

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

new Number(false) == " "; // true

Booleans get converted to 0 or 1. The reason this is the case is that whitespace == 0

And if you really want to know about new Number(" ") then read this 9.3.1 in the ES5 spec.

The important line is :

The MV of StringNumericLiteral ::: StrWhiteSpace is 0.


答:
Use the spread operator and put your property you wanna change after it

let foo = {a : "Other A", b : "OtherB", c : "OtherC"}
let obj = {a: 'A', b: 'B', c: 'C'}
    obj = {...foo, c : 'D'};

    console.log(obj);```


问:
ExecStartPost script an infinite loop script - Is it possible to do?
I am tweaking snmpd systemd service and I want to execute a script in ExecStartPost. This will be an infinite loop script.

This script is an implementation of agentx ..

I have tried running in a normal manner with and without & , but after sometime the systemd service is timing out..

it is timing out expecting a exit status from the script is what is believe.

Is there any way to run the script in background without the systemd snmp service timing out ?

```<code>[Unit]
Description=Simple Network Management Protocol (SNMP) Daemon.
After=syslog.target network.target
[Service]
Type=notify
Environment=OPTIONS="-LS0-6d"
EnvironmentFile=-/etc/sysconfig/snmpd
ExecStart=/usr/sbin/snmpd $OPTIONS -f
ExecStartPost=/usr/bin/python /usr/local/bin/pyagent.py
ExecReload=/bin/kill -HUP $MAINPID
[Install]
WantedBy=multi-user.target
</code>```

答:
From reading the documentation, I believe you want to keep your & but add - prefix to skip result checking:

```<code>ExecStartPost=-/usr/bin/python /usr/local/bin/pyagent.py &
</code>```

Body:
I am tweaking snmpd systemd service and I want to execute a script in ExecStartPost. This will be an infinite loop script.

This script is an implementation of agentx ..

I have tried running in a normal manner with and without & , but after sometime the systemd service is timing out..

it is timing out expecting a exit status from the script is what is believe.

Is there any way to run the script in background without the systemd snmp service timing out ?

[Unit]
Description=Simple Network Management Protocol (SNMP) Daemon.
After=syslog.target network.target
[Service]
Type=notify
Environment=OPTIONS="-LS0-6d"
EnvironmentFile=-/etc/sysconfig/snmpd
ExecStart=/usr/sbin/snmpd $OPTIONS -f
ExecStartPost=/usr/bin/python /usr/local/bin/pyagent.py
ExecReload=/bin/kill -HUP $MAINPID
[Install]
WantedBy=multi-user.target

Body:
From reading the documentation, I believe you want to keep your & but add - prefix to skip result checking:

ExecStartPost=-/usr/bin/python /usr/local/bin/pyagent.py &


问:
Is it possible to reference IdentityModel library in a project .Net framework 4.5?
When I try to install the nuget package for IdentityModel for my .NET Framework 4.5 console application, I get the error:

```<code>Could not install package 'IdentityModel 3.10.10'. You are trying to install
this package into a project that targets '.NETFramework,Version=v4.5', but the
package does not contain any assembly references or content files that are
compatible with that framework. For more information, contact the package author.
</code>```

But it does work in my ASP.NET Web Application, which targets .NET Core 2.1.

Is it possible to use this library in a console application, or am I forced to use a web application?

答:
IdentityModel requires minimum .NETFramework 4.5.2 or NetStandard 2.0

https://www.nuget.org/packages/identitymodel/

Please see below
https://learn.microsoft.com/en-us/dotnet/standard/net-standard

Body:
When I try to install the nuget package for IdentityModel for my .NET Framework 4.5 console application, I get the error:

Could not install package 'IdentityModel 3.10.10'. You are trying to install
this package into a project that targets '.NETFramework,Version=v4.5', but the
package does not contain any assembly references or content files that are
compatible with that framework. For more information, contact the package author.

But it does work in my ASP.NET Web Application, which targets .NET Core 2.1.

Is it possible to use this library in a console application, or am I forced to use a web application?


问:
Nodejs: how to check if spawn is successfull?
I am spawing a command from my express script, but I need to distinguish between error and success. I was looking for a child.on('success'...) function, but it doesn't exist.

This piece of code (of course) doesn't work.

```<code>app.get(myID+'/test/', function(req, res){
        var child = spawn('lbg');
        child.on('error', function(err) {
                console.log('Failed to start child process.');
                res.status(404).send("Cannot send test command");
                return;
        });
        res.json({statusMessage: "OK", statusCode: "200"});

 });
</code>```

In other words, I need to fire the correct response only, not both!

答:
```<code>app.get(myID+'/test/', function(req, res){
        var child = spawn('lbg');
        child.on('close', code => {
          if (code === 0) {
             res.json({statusMessage: "OK", statusCode: "200"});
          } else {
             res.status(404).send("Cannot send test command");
          }
        }).on('error', err => res.status(404).send(err)) ;
});
</code>```

Body:
I am spawing a command from my express script, but I need to distinguish between error and success. I was looking for a child.on('success'...) function, but it doesn't exist.

This piece of code (of course) doesn't work.

app.get(myID+'/test/', function(req, res){
        var child = spawn('lbg');
        child.on('error', function(err) {
                console.log('Failed to start child process.');
                res.status(404).send("Cannot send test command");
                return;
        });
        res.json({statusMessage: "OK", statusCode: "200"});

 });

In other words, I need to fire the correct response only, not both!


问:
How to use label class in datatable with an accented database?
I have a problem adding Label class to a datatable column. My database (SQL server) have accents (mostly "é") which prevent using the jquery code to work properly.

The words without accents work fine. i tried everything with the ones with accents with no luck, they are only shown in the default color. i even tried different accent neutralise codes with no result.

```<code>function removeAccents ( data ) {
    return data
        .replace( /έ/g, 'ε' )
        .replace( /[ύϋΰ]/g, 'υ' )
        .replace( /ό/g, 'ο' )
        .replace( /ώ/g, 'ω' )
        .replace( /ά/g, 'α' )
        .replace( /[ίϊΐ]/g, 'ι' )
        .replace( /ή/g, 'η' )
        .replace( /\n/g, ' ' )
        .replace( /á/g, 'a' )
        .replace( /é/g, 'e' )
        .replace( /í/g, 'i' )
        .replace( /ó/g, 'o' )
        .replace( /ú/g, 'u' )
        .replace( /ê/g, 'e' )
        .replace( /î/g, 'i' )
        .replace( /ô/g, 'o' )
        .replace( /è/g, 'e' )
        .replace( /ï/g, 'i' )
        .replace( /ü/g, 'u' )
        .replace( /ã/g, 'a' )
        .replace( /õ/g, 'o' )
        .replace( /ç/g, 'c' )
        .replace( /ì/g, 'i' );
}

var searchType = jQuery.fn.DataTable.ext.type.search;

searchType.html = function ( data ) {
    return ! data ?
        '' :
        typeof data === 'string' ?
            removeAccents( data.replace( /<.*?>/g, '' ) ) :
            data;
};

var dataTable = $('.table').dataTable({
                                    scrollX: true,
                  dom: 'Bfrtip',
                  buttons: {
                        dom: {
                            button: {
                                className: 'btn btn-default'
                            }
                        },
                        buttons: [
                              {extend: 'colvis'},
                              {extend: 'copy'},
                              {extend: 'csv'},
                              {extend: 'print'}
                        ]},
                                    columnDefs: [
                                        {
                                            'data' : 'id_statut',
                                            "targets": 12,
                                            render: function (data, type, row, meta) {
                                                if (type === 'display') {
                                                    var label = 'label-default';
                                    if (data == "A Valider SH") {
                                                    label = 'label-warning';
                                                    }
                                                if (data == "A Valider RI") {
                                                    label = 'label-warning';
                                                }
                                                if (data == "A planifier") {
                                                    label = 'bg-purple';
                                                }
                                                if (data == "A traiter") {
                                                    label = 'bg-brown';
                                                }
                                                if (data == "En cours de traitement") {
                                                    label = 'label-info';
                                                }
                                                if (data == 'Manque Information' ) {
                                                    label = 'bg-teal';
                                                }
                                                if (data == "A Valider" ) {
                                                    label = 'bg-pink';
                                                }
                                                if (data == "Manque Information RI" ) {
                                                    label = 'bg-violet';
                                                }
                                                if (data === 'Traité' ) {
                                                    label = 'bg-violet';
                                                }
                                        return '<span class="label ' + label + '">' + data + '</span>';
                                            }
                                            return data;
                                        }
                                    }
                                ]
                                });
</code>```

The actual result:

what i'm trying to achieve:

http://demo.interface.club/limitless/demo/bs4/Template/layout_1/LTR/default/full/datatable_basic.html

答:
Solved it by adding data.substr(x,y) to the words with accents</p>

```<code>$(document).ready(function(){
$("input[type=submit]").button();
$('.table').dataTable({
              scrollX: true,
              dom: 'lBfrtip',
              buttons: {
                    dom: {
                        button: {
                            className: 'btn btn-default'
                        }
                    },
                    buttons: [
                            {extend: 'colvis'},
                            {extend: 'copy'},
                            'excel',
                            {
                            extend: 'pdf',
                            orientation: 'landscape',
                            exportOptions: {
                            columns: 'thead th:not(.noExport)'
                            }
                            },
                            {
                            extend: 'print',
                            exportOptions: {
                            columns: 'thead th:not(.noExport)'
                            }
                            }
                            ]},
                                columnDefs: [
                        {
                        'data' : 'id',
                        "targets": 1,
                        render: function (data, type, row, meta) {

                                            if (type === 'display') {
                                                var label = 'label-default';
                                            if (data == "A valider") {
                                                label = 'bg-orange';
                                                }
                                            if (data == "Encours") {
                                                label = 'label-info';
                                            }
                                            if (data.substr(0,5) == "Annul") {
                                                label = 'bg-danger';
                                            }
                                            if (data.substr(0,6) == "Affect") {
                                                label = 'bg-green';
                                            }
                                            if (data.substr(0,2) == "Cl") {
                                                label = 'bg-brown';
                                            }
                                            if (data.substr(0,5) == 'Trait' ) {
                                                label = 'bg-success';
                                            }
                                            if (data == "Traitement en cours" ) {
                                                label = 'bg-primary';
                                            }
                                            if (data.substr(0,5) == "Achev" ) {
                                                label = 'bg-teal';
                                            }
                                            if (data.substr(0,8) == "Actions " ) {
                                                label = 'bg-pink';
                                            }
                                            if (data.substr(0,12) == "Actions Valid" ) {
                                                label = 'bg-indigo-400';
                                            }
                                            if (data.substr(0,6) == "Clotur" ) {
                                                label = 'bg-slate';
                                            }
                                    return '<span class="label ' + label + '">' + data + '</span>';
                                        }
                                        return data;
                                    }
                                }
                            ]
                            });
</code>```

Body:
I have a problem adding Label class to a datatable column. My database (SQL server) have accents (mostly "é") which prevent using the jquery code to work properly.

The words without accents work fine. i tried everything with the ones with accents with no luck, they are only shown in the default color. i even tried different accent neutralise codes with no result.

function removeAccents ( data ) {
    return data
        .replace( /έ/g, 'ε' )
        .replace( /[ύϋΰ]/g, 'υ' )
        .replace( /ό/g, 'ο' )
        .replace( /ώ/g, 'ω' )
        .replace( /ά/g, 'α' )
        .replace( /[ίϊΐ]/g, 'ι' )
        .replace( /ή/g, 'η' )
        .replace( /\n/g, ' ' )
        .replace( /á/g, 'a' )
        .replace( /é/g, 'e' )
        .replace( /í/g, 'i' )
        .replace( /ó/g, 'o' )
        .replace( /ú/g, 'u' )
        .replace( /ê/g, 'e' )
        .replace( /î/g, 'i' )
        .replace( /ô/g, 'o' )
        .replace( /è/g, 'e' )
        .replace( /ï/g, 'i' )
        .replace( /ü/g, 'u' )
        .replace( /ã/g, 'a' )
        .replace( /õ/g, 'o' )
        .replace( /ç/g, 'c' )
        .replace( /ì/g, 'i' );
}

var searchType = jQuery.fn.DataTable.ext.type.search;

searchType.html = function ( data ) {
    return ! data ?
        '' :
        typeof data === 'string' ?
            removeAccents( data.replace( /<.*?>/g, '' ) ) :
            data;
};

var dataTable = $('.table').dataTable({
                                    scrollX: true,
                  dom: 'Bfrtip',
                  buttons: {
                        dom: {
                            button: {
                                className: 'btn btn-default'
                            }
                        },
                        buttons: [
                              {extend: 'colvis'},
                              {extend: 'copy'},
                              {extend: 'csv'},
                              {extend: 'print'}
                        ]},
                                    columnDefs: [
                                        {
                                            'data' : 'id_statut',
                                            "targets": 12,
                                            render: function (data, type, row, meta) {
                                                if (type === 'display') {
                                                    var label = 'label-default';
                                    if (data == "A Valider SH") {
                                                    label = 'label-warning';
                                                    }
                                                if (data == "A Valider RI") {
                                                    label = 'label-warning';
                                                }
                                                if (data == "A planifier") {
                                                    label = 'bg-purple';
                                                }
                                                if (data == "A traiter") {
                                                    label = 'bg-brown';
                                                }
                                                if (data == "En cours de traitement") {
                                                    label = 'label-info';
                                                }
                                                if (data == 'Manque Information' ) {
                                                    label = 'bg-teal';
                                                }
                                                if (data == "A Valider" ) {
                                                    label = 'bg-pink';
                                                }
                                                if (data == "Manque Information RI" ) {
                                                    label = 'bg-violet';
                                                }
                                                if (data === 'Traité' ) {
                                                    label = 'bg-violet';
                                                }
                                        return '' + data + '';
                                            }
                                            return data;
                                        }
                                    }
                                ]
                                });

The actual result:

what i'm trying to achieve:

http://demo.interface.club/limitless/demo/bs4/Template/layout_1/LTR/default/full/datatable_basic.html

Body:
Solved it by adding data.substr(x,y) to the words with accents

$(document).ready(function(){
$("input[type=submit]").button();
$('.table').dataTable({
              scrollX: true,
              dom: 'lBfrtip',
              buttons: {
                    dom: {
                        button: {
                            className: 'btn btn-default'
                        }
                    },
                    buttons: [
                            {extend: 'colvis'},
                            {extend: 'copy'},
                            'excel',
                            {
                            extend: 'pdf',
                            orientation: 'landscape',
                            exportOptions: {
                            columns: 'thead th:not(.noExport)'
                            }
                            },
                            {
                            extend: 'print',
                            exportOptions: {
                            columns: 'thead th:not(.noExport)'
                            }
                            }
                            ]},
                                columnDefs: [
                        {
                        'data' : 'id',
                        "targets": 1,
                        render: function (data, type, row, meta) {

                                            if (type === 'display') {
                                                var label = 'label-default';
                                            if (data == "A valider") {
                                                label = 'bg-orange';
                                                }
                                            if (data == "Encours") {
                                                label = 'label-info';
                                            }
                                            if (data.substr(0,5) == "Annul") {
                                                label = 'bg-danger';
                                            }
                                            if (data.substr(0,6) == "Affect") {
                                                label = 'bg-green';
                                            }
                                            if (data.substr(0,2) == "Cl") {
                                                label = 'bg-brown';
                                            }
                                            if (data.substr(0,5) == 'Trait' ) {
                                                label = 'bg-success';
                                            }
                                            if (data == "Traitement en cours" ) {
                                                label = 'bg-primary';
                                            }
                                            if (data.substr(0,5) == "Achev" ) {
                                                label = 'bg-teal';
                                            }
                                            if (data.substr(0,8) == "Actions " ) {
                                                label = 'bg-pink';
                                            }
                                            if (data.substr(0,12) == "Actions Valid" ) {
                                                label = 'bg-indigo-400';
                                            }
                                            if (data.substr(0,6) == "Clotur" ) {
                                                label = 'bg-slate';
                                            }
                                    return '<span class="label ' + label + '">' + data + '</span>';
                                        }
                                        return data;
                                    }
                                }
                            ]
                            });


问:
Converting VARCHAR to Date using TO_DATE
I have a set of data where the col is VARCHAR() but I need it to be in DATE format.

I was trying to do it as follows:

```<code>CREATE OR REPLACE TABLE df_new
    AS SELECT
col1 AS NAME
col2 AS first_name
col3 AS last_name
,TO_DATE(col4, 'yyyymmdd') AS date
FROM df_old
</code>```

but I am getting an error "Can't parse '' as date with format 'yyyymmdd'".

I have tried messing with the input for the date format (such as 'yyyy/mm/dd') but I am pretty new to SQL so I am unsure of how to proceed.

答:
I resolved the issue as follows:</p>

```<code>CREATE OR REPLACE TABLE df_new
    AS SELECT
col1 AS NAME
,col2 AS first_name
,col3 AS last_name
,CASE WHEN col4 = '' THEN NULL ELSE TO_DATE(col4, 'YYYY-MM-DD') END AS date
FROM df_old
</code>```

Body:
I have a set of data where the col is VARCHAR() but I need it to be in DATE format.

I was trying to do it as follows:

CREATE OR REPLACE TABLE df_new
    AS SELECT
col1 AS NAME
col2 AS first_name
col3 AS last_name
,TO_DATE(col4, 'yyyymmdd') AS date
FROM df_old

but I am getting an error "Can't parse '' as date with format 'yyyymmdd'".

I have tried messing with the input for the date format (such as 'yyyy/mm/dd') but I am pretty new to SQL so I am unsure of how to proceed.

Body:
I resolved the issue as follows:

CREATE OR REPLACE TABLE df_new
    AS SELECT
col1 AS NAME
,col2 AS first_name
,col3 AS last_name
,CASE WHEN col4 = '' THEN NULL ELSE TO_DATE(col4, 'YYYY-MM-DD') END AS date
FROM df_old


问:
Select the most recent record with groupby in Laravel
I have two tables entries similar as follows:

```<code>gym_clients
+---------+---------+-----------------+
|      id | first_name|     last_name |
+---------+-----------+---------------+
|      1  |  Name 1   |        Last 1 |
|      2  |  Name 2   |        Last 2 |
+---------+-----------+---------------+

gym_client_purchases

+---------+---------+-----------------+
|      id | client_id | purchase_date |
+---------+-----------+---------------+
|      15 |       1   |    2018-04-01 |
|      16 |       1   |    2018-05-01 |
|      17 |       2   |    2018-05-01 |
+---------+-----------+---------------+

</code>```

I want to group by the purchases of each client and show the latest.

I tried this query but the groupby shows me the oldest purchase (id 15).

any ideas?

```<code> $this->data['latestSubscriptions'] = GymPurchase::select('first_name', 'last_name', 'gym_client_purchases.*')
              ->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id')
              ->groupBy('gym_client_purchases.client_id')
              ->orderBy('gym_client_purchases.purchase_date', 'desc')
              ->get();
</code>```

Thanks in advance.

答:
First, when you use group by you have o specify in this clause the columns for which the query is gioing to group, so I suggest to you to try you query on sql engine.

You will have something like this

```<code>select first_name, last_name, A.*
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id
order By A.purchase_date desc
</code>```

and you will notice that it doesn't work

Maybe what you want is something like this

```<code>select A.client_id, B.first_name, B.last_name, max(A.purchase_date)
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id, B.first_name, B.last_name
order By max(A.purchase_date) desc
</code>```

Body:
I have two tables entries similar as follows:

gym_clients
+---------+---------+-----------------+
|      id | first_name|     last_name |
+---------+-----------+---------------+
|      1  |  Name 1   |        Last 1 |
|      2  |  Name 2   |        Last 2 |
+---------+-----------+---------------+

gym_client_purchases

+---------+---------+-----------------+
|      id | client_id | purchase_date |
+---------+-----------+---------------+
|      15 |       1   |    2018-04-01 |
|      16 |       1   |    2018-05-01 |
|      17 |       2   |    2018-05-01 |
+---------+-----------+---------------+

I want to group by the purchases of each client and show the latest.

I tried this query but the groupby shows me the oldest purchase (id 15).

any ideas?

 $this->data['latestSubscriptions'] = GymPurchase::select('first_name', 'last_name', 'gym_client_purchases.*')
              ->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id')
              ->groupBy('gym_client_purchases.client_id')
              ->orderBy('gym_client_purchases.purchase_date', 'desc')
              ->get();

Thanks in advance.

Body:
First, when you use group by you have o specify in this clause the columns for which the query is gioing to group, so I suggest to you to try you query on sql engine.

You will have something like this

select first_name, last_name, A.*
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id
order By A.purchase_date desc

and you will notice that it doesn't work

Maybe what you want is something like this

select A.client_id, B.first_name, B.last_name, max(A.purchase_date)
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id, B.first_name, B.last_name
order By max(A.purchase_date) desc


问:
How to extract text from these colored images?
I want to extract the text on Labels from the images. The images are coloured and are in a real-life environment. PFA images. Sample Image

I have tried multiple solutions:

I'm able to read text from flat images using Tesseract but it's not working if the text is at a certain angle.

Tried a lot of image pre-processing converting it to Binary and grayscale but not able to extract the required text.

Since the above step failed I was not able to de-skew the text either.

```<code>    image = cv2.imread("p18-73.png",0)
    thresh = cv2.adaptiveThreshold(image,255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11,2)
    coords = np.column_stack(np.where(thresh > 0))
    angle = cv2.minAreaRect(coords)[-1]
</code>```

The above pre-processing code is not working. Can you please tell me what is the best way to approach this image?

答:
Did you check the result of cv2.adaptiveThreshold()?
The result of cv2.adaptiveThreshold() is like this:

I think this is not what you want.
Try to use global threshold cv2.threshold(), and adjust the threshold value.

```<code>ret, thresh = cv2.threshold(image, 240, 255, cv2.THRESH_BINARY)
</code>```

Also, you can add cv2.morphologyEx() to remove the noise.

```<code>kernel = np.ones((2,2),np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
</code>```

Body:
I want to extract the text on Labels from the images. The images are coloured and are in a real-life environment. PFA images. Sample Image

I have tried multiple solutions:

I'm able to read text from flat images using Tesseract but it's not working if the text is at a certain angle.

Tried a lot of image pre-processing converting it to Binary and grayscale but not able to extract the required text.

Since the above step failed I was not able to de-skew the text either.

    image = cv2.imread("p18-73.png",0)
    thresh = cv2.adaptiveThreshold(image,255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11,2)
    coords = np.column_stack(np.where(thresh > 0))
    angle = cv2.minAreaRect(coords)[-1]

The above pre-processing code is not working. Can you please tell me what is the best way to approach this image?

Body:
Did you check the result of cv2.adaptiveThreshold()?
The result of cv2.adaptiveThreshold() is like this:

I think this is not what you want.
Try to use global threshold cv2.threshold(), and adjust the threshold value.

ret, thresh = cv2.threshold(image, 240, 255, cv2.THRESH_BINARY)

Also, you can add cv2.morphologyEx() to remove the noise.

kernel = np.ones((2,2),np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)


问:
reading csv file in python with pandas
I have a program that aggregates several .csv files into one. When I execute to add 3 files of the same structure (number and names of columns) it passes a message of success, informing that 3 files have been joined in a total of 1154341 lines. When I add another file of the same structure, the message is updated to four files and 1446553 lines. So far so good. When I use the pandas to read them (pd.read_csv (file.csv)), the two files have the same size, the smaller file size. When I analyze a single column, note the difference in indices of the two dataframes:

```<code> #Union of 3 .csv files
 >>>df_reembolsos_1['ideCadastro']
 0               NaN
 1               NaN
 2               NaN
 ...................
 1154338    195997.0
 1154339    195997.0
 Name: ideCadastro, Length: 1154339, dtype: float64

 # Union of 4 .csv file
 >>> df_reembolsos_2['ideCadastro]
 0               NaN
 1               NaN
 2               NaN
 ...................
 1446550    195997
 1446551    195997
 Name: ideCadastro, Length: 1154339, dtype: object
</code>```

It strikes me that in reading the first file the number of indexes is equal to the size, while in the second scenario the number of indexes is larger than the size. I have looked at the two files and they really are different and have the expected size for joining the different file numbers. One difference I notice is the following warning message when reading the larger file:

DtypeWarning: Columns (1,2,3,4,5,8,10,11,12,13,15,22,23,28) have mixed types.

When I read the smaller file, this message only refers to column number 1. So I wonder if this problem is a limitation of pandas or if it is some problem with the data, and how can I solve it.

答:
This excellent answer covers the DtypeWarning pretty thoroughly. Specify your Dtypes on read.

As for the indexes being of unexpected size:

When you append, you can ignore the index.

On read, you can use the .read_csv kwarg index_col -- If that is not properly being interpreted by pandas that could be a culprit.

Check that read_csv is really reading the correct number of rows, that there aren't a bunch of empty rows, et cetera.

Title: reading csv file in python with pandas

Body:
I have a program that aggregates several .csv files into one. When I execute to add 3 files of the same structure (number and names of columns) it passes a message of success, informing that 3 files have been joined in a total of 1154341 lines. When I add another file of the same structure, the message is updated to four files and 1446553 lines. So far so good. When I use the pandas to read them (pd.read_csv (file.csv)), the two files have the same size, the smaller file size. When I analyze a single column, note the difference in indices of the two dataframes:

 #Union of 3 .csv files
 >>>df_reembolsos_1['ideCadastro']
 0               NaN
 1               NaN
 2               NaN
 ...................
 1154338    195997.0
 1154339    195997.0
 Name: ideCadastro, Length: 1154339, dtype: float64

 # Union of 4 .csv file
 >>> df_reembolsos_2['ideCadastro]
 0               NaN
 1               NaN
 2               NaN
 ...................
 1446550    195997
 1446551    195997
 Name: ideCadastro, Length: 1154339, dtype: object

It strikes me that in reading the first file the number of indexes is equal to the size, while in the second scenario the number of indexes is larger than the size. I have looked at the two files and they really are different and have the expected size for joining the different file numbers. One difference I notice is the following warning message when reading the larger file:

DtypeWarning: Columns (1,2,3,4,5,8,10,11,12,13,15,22,23,28) have mixed types.

When I read the smaller file, this message only refers to column number 1. So I wonder if this problem is a limitation of pandas or if it is some problem with the data, and how can I solve it.


问:
Store un-submitted data using Shared Preferences
I need to store data which hasn't been saved yet using Shared Preferences. To give a quick example, in my application I want that if the user filled the sign-up form and closed the application, his information will still be filled up when he re-enters the application. Would you suggest any tutorials?

答:
How about creating a ViewModel for your activity , your signup activity for instance.
This ViewModel will be your handler for your SharedPreferences and for keeping track of your data , say the values of the username and password text fields.
now you can override the method  onCleared() and add there the implementation of writing to SharedPreferences.

in your activity you will need :

listen to your text fields using TextWatcher and probably override void afterTextChanged(Editable s) (since the user might just close the app) and inside update your ViewModel with the current value.

load data from your ViewModel in order to init your UI inside OnCreate() in case you have any data saved in your SharedPreferences.

onCleared()

This method will be called when this ViewModel is no longer used and will be destroyed.


问:
How can I prevent the backspace key from navigating back?
On IE I can do this with the (terribly non-standard, but working) jQuery

```<code>if ($.browser.msie)
    $(document).keydown(function(e) { if (e.keyCode == 8) window.event.keyCode = 0;});
</code>```

But is it possible to do in a way which works on Firefox, or in a cross-browser way for a bonus?

For the record:

```<code>$(document).keydown(function(e) { if (e.keyCode == 8) e.stopPropagation(); });
</code>```

does nothing.

```<code>$(document).keydown(function(e) { if (e.keyCode == 8) e.preventDefault(); });
</code>```

solves the problem, but renders the backspace key unusable on the page, which is even worse than the original behaviour.

EDIT:
The reason I do this is that I'm not creating a simple web page but a large application. It is incredibly annoying to lose 10 minutes of work just because you pressed backspace in the wrong place. The ratio of preventing mistakes vs. annoying users should be way above 1000/1 by preventing the backspace key from navigating back.

EDIT2: I'm not trying to prevent history navigation, just accidents.

EDIT3: @brentonstrines comment (moved here since the question is so popular): This is a long-term 'fix', but you could throw your support behind the Chromium bug to change this behavior in webkit

答:
This code solves the problem in all browsers:</p>

```<code>onKeydown:function(e)
{
    if (e.keyCode == 8)
    {
      var d = e.srcElement || e.target;
      if (!((d.tagName.toUpperCase() == 'BODY') || (d.tagName.toUpperCase() == 'HTML')))
      {
         doPrevent = false;
      }
       else
      {
         doPrevent = true;
      }
    }
    else
    {
       doPrevent = false;
    }
      if (doPrevent)
      {
         e.preventDefault();
       }

  }
</code>```

Body:
On IE I can do this with the (terribly non-standard, but working) jQuery

if ($.browser.msie)
    $(document).keydown(function(e) { if (e.keyCode == 8) window.event.keyCode = 0;});

But is it possible to do in a way which works on Firefox, or in a cross-browser way for a bonus?

For the record:

$(document).keydown(function(e) { if (e.keyCode == 8) e.stopPropagation(); });

does nothing.

$(document).keydown(function(e) { if (e.keyCode == 8) e.preventDefault(); });

solves the problem, but renders the backspace key unusable on the page, which is even worse than the original behaviour.

EDIT:
The reason I do this is that I'm not creating a simple web page but a large application. It is incredibly annoying to lose 10 minutes of work just because you pressed backspace in the wrong place. The ratio of preventing mistakes vs. annoying users should be way above 1000/1 by preventing the backspace key from navigating back.

EDIT2: I'm not trying to prevent history navigation, just accidents.

EDIT3: @brentonstrines comment (moved here since the question is so popular): This is a long-term 'fix', but you could throw your support behind the Chromium bug to change this behavior in webkit

Body:
This code solves the problem in all browsers:

onKeydown:function(e)
{
    if (e.keyCode == 8)
    {
      var d = e.srcElement || e.target;
      if (!((d.tagName.toUpperCase() == 'BODY') || (d.tagName.toUpperCase() == 'HTML')))
      {
         doPrevent = false;
      }
       else
      {
         doPrevent = true;
      }
    }
    else
    {
       doPrevent = false;
    }
      if (doPrevent)
      {
         e.preventDefault();
       }

  }


问:
GroupBy only one field, not all the fields I have in Select
I am working with the next table:

```<code>**ID    Value   Data**
1   30  25/4
1   20  26/4
1   20  27/4
3   10  25/4
4   20  26/4
5   30  26/4
</code>```

And I need to query the table and have the next result:

```<code>**ID    Value   Data**
1   70  "Any value, can be 25/4, 26/4 or 27/4"
3   10  25/4
4   20  26/4
5   30  26/4
</code>```

I try to query using GroupBy, but If add the all fields (ID, Value and Data) the result returns the 1st table. And, if I only GroupBy field ID, I am having the next error:

ORA-00979: not a GROUP BY expression

Can anyone help about how to do it?

答:
We could arbitrarily take the minimum Data value in each ID group:

```<code>SELECT ID, SUM(Value) AS Value, MIN(Data) AS Data
FROM yourTable
GROUP BY ID;
</code>```

Body:
I am working with the next table:

**ID    Value   Data**
1   30  25/4
1   20  26/4
1   20  27/4
3   10  25/4
4   20  26/4
5   30  26/4

And I need to query the table and have the next result:

**ID    Value   Data**
1   70  "Any value, can be 25/4, 26/4 or 27/4"
3   10  25/4
4   20  26/4
5   30  26/4

I try to query using GroupBy, but If add the all fields (ID, Value and Data) the result returns the 1st table. And, if I only GroupBy field ID, I am having the next error:

ORA-00979: not a GROUP BY expression

Can anyone help about how to do it?

Body:
We could arbitrarily take the minimum Data value in each ID group:

SELECT ID, SUM(Value) AS Value, MIN(Data) AS Data
FROM yourTable
GROUP BY ID;


问:
Making a scrollable div that encompasses the entire height of the PDF
I am embedding a PDF into my webpage.  I'm doing some tom-foolery to hide the status bar (including the download buttons and page numbers) so I can control them externally (I want to be able to force a different download when they try to download the document).  If it makes any difference (such as a solution that will only work/won't work given a framework), I'm using React.

I can set the active page of the PDF using a URL, but after the load of that page I can't get the scroll position of the document to update the page number.

I think a solution for this is to contain the embedded PDF in a div that I can personally control.  To do this, I want the embedded object to have a height that is the sum of the vertical height of all of the pages of the PDF combined, and then encase that in a div with a set height.  I can, from there, monitor the scroll position of the document to determine the current page.

```<code><div class='encasing-div'>
    <div class='toolbar'/>
    <object data='some.pdf' type='application/pdf'>
        <embed src='some.pdf' type='application/pdf' wmode='opaque'/>
    </object>
</div>
</code>```

I can't get the embedded PDF to be the full height of the document.  I know the number of pages in the document on page load, but I don't know how/if I can use that to adjust the height properly.

How does one go about making the embedded object the height of the entire PDF, thus eliminating the scroll from the embedded object and allowing an external scroll to be used?

Edit:  Here's a picture attemping to explain what I'm looking for.  In the second part of the picture, the stuff outside of the div would be hidden but scrollable to.

答:
well once i had the same probleme i figure it out like this and it solve everything for me hope it will help you too

```<code><div class="PDfDiv">
     <object data="some.pdf" type="application/pdf"  height="100%" width="100%">
          <param name="src"value="some.pdf" />
     </object>
  </div>
</code>```

and in your CSS add this :

```<code>.PDfDiv{
    height: 100vh;
}
</code>```

Body:
I am embedding a PDF into my webpage.  I'm doing some tom-foolery to hide the status bar (including the download buttons and page numbers) so I can control them externally (I want to be able to force a different download when they try to download the document).  If it makes any difference (such as a solution that will only work/won't work given a framework), I'm using React.

I can set the active page of the PDF using a URL, but after the load of that page I can't get the scroll position of the document to update the page number.

I think a solution for this is to contain the embedded PDF in a div that I can personally control.  To do this, I want the embedded object to have a height that is the sum of the vertical height of all of the pages of the PDF combined, and then encase that in a div with a set height.  I can, from there, monitor the scroll position of the document to determine the current page.

    <object data='some.pdf' type='application/pdf'>
        <embed src='some.pdf' type='application/pdf' wmode='opaque'/>
    </object>

I can't get the embedded PDF to be the full height of the document.  I know the number of pages in the document on page load, but I don't know how/if I can use that to adjust the height properly.

How does one go about making the embedded object the height of the entire PDF, thus eliminating the scroll from the embedded object and allowing an external scroll to be used?

Edit:  Here's a picture attemping to explain what I'm looking for.  In the second part of the picture, the stuff outside of the div would be hidden but scrollable to.

Body:
well once i had the same probleme i figure it out like this and it solve everything for me hope it will help you too

<div class="PDfDiv">
     <object data="some.pdf" type="application/pdf"  height="100%" width="100%">
          <param name="src"value="some.pdf" />
     </object>
  </div>

and in your CSS add this :

.PDfDiv{
    height: 100vh;
}


问:
'Ambiguous argument" due to whitespace in filename?
I want to remove a huge ISO file from the git repository. it still resides inside the .git folder and I read that I need to "rewrite history" to remove it from there. Therefore, according to the official API, I must use the following command:

```<code> git filter-branch --tree-filter 'rm -f
 ZeusSRC_Hardware_RPi_image_Raspberry Pi_außen_20.05.2019.zip'
</code>```

As you can see, the filename does contain a whitespace. When executing the command, I get the following error:

```<code>  fatal: ambiguous argument 'ZeusSRC_Hardware_RPi_image_Raspberry':
  unknown revision or path not in the working tree.
  Use '--' to separate paths from revisions, like this:
  'git <command> [<revision>...] -- [<file>...]'
</code>```

I'm pretty new to this and so I dont really know what might cause such an error. My first guess was the whitespace, since the error message also "stops" the filename at the whitespace. And if it truly is the whitespace, what can I do to circumvent this error?

答: You need to put the filename into quotes "file name.zip", else the command will think that it is a new argument after the space.</p>

Body:
I want to remove a huge ISO file from the git repository. it still resides inside the .git folder and I read that I need to "rewrite history" to remove it from there. Therefore, according to the official API, I must use the following command:

 git filter-branch --tree-filter 'rm -f
 ZeusSRC_Hardware_RPi_image_Raspberry Pi_außen_20.05.2019.zip'

As you can see, the filename does contain a whitespace. When executing the command, I get the following error:

  fatal: ambiguous argument 'ZeusSRC_Hardware_RPi_image_Raspberry':
  unknown revision or path not in the working tree.
  Use '--' to separate paths from revisions, like this:
  'git <command> [<revision>...] -- [<file>...]'

I'm pretty new to this and so I dont really know what might cause such an error. My first guess was the whitespace, since the error message also "stops" the filename at the whitespace. And if it truly is the whitespace, what can I do to circumvent this error?


问:
sum after subtracting first element of particular column with all the elements of another column and repeat with 2 element and so on in R programming
I would like to sum post subtracting all elements of datestamp-1 with 1st element of datestamp-2, and repeat the same for 2nd element of datestamp-2 and so on in R

```<code>datestamp1 datestamp2 load_percent
2019-05-28 2019-05-25 0.01883
2019-05-29 2019-05-26 0.72340
</code>```

Expected result is as mentioned below.

```<code>datestamp1 datestamp2 weighted_index
2019-05-28 2019-05-25 2.95
2019-05-29 2019-05-26 2.20
</code>```

Logic being

```<code>1. 2019-05-28 - 2019-05-25 = 3 * 0.01 = 0.056
2. 2019-05-29 - 2019-05-25 = 4 * 0.72 = 2.893
</code>```

sum of 0.056 and 2.893 is 2.95

similarly

```<code>3. 2019-05-28 - 2019-05-26 = 2 * 0.01 = 0.037
4. 2019-05-29 - 2019-05-26 = 3 * 0.72 = 2.170
</code>```

and sum of 0.037 and 2.170 is 2.20

答:
We can use outer to get the difference between the two date columns, then get the colSums of the product with 'load_percent'

```<code>df1$weighted_index <- with(df1, colSums(outer(datestamp1,
          datestamp2, FUN = `-` ) * load_percent))

df1
#  datestamp1 datestamp2 load_percent weighted_index
#1 2019-05-28 2019-05-25      0.01883        2.95009
#2 2019-05-29 2019-05-26      0.72340        2.20786
</code>```

data

```<code>df1 <- structure(list(datestamp1 = structure(c(18044, 18045), class = "Date"),
    datestamp2 = structure(c(18041, 18042), class = "Date"),
    load_percent = c(0.01883, 0.7234)), row.names = c(NA, -2L
), class = "data.frame")
</code>```

Body:
I would like to sum post subtracting all elements of datestamp-1 with 1st element of datestamp-2, and repeat the same for 2nd element of datestamp-2 and so on in R

datestamp1 datestamp2 load_percent
2019-05-28 2019-05-25 0.01883
2019-05-29 2019-05-26 0.72340

Expected result is as mentioned below.

datestamp1 datestamp2 weighted_index
2019-05-28 2019-05-25 2.95
2019-05-29 2019-05-26 2.20

Logic being

1. 2019-05-28 - 2019-05-25 = 3 * 0.01 = 0.056
2. 2019-05-29 - 2019-05-25 = 4 * 0.72 = 2.893

sum of 0.056 and 2.893 is 2.95

similarly

3. 2019-05-28 - 2019-05-26 = 2 * 0.01 = 0.037
4. 2019-05-29 - 2019-05-26 = 3 * 0.72 = 2.170

and sum of 0.037 and 2.170 is 2.20

Body:
We can use outer to get the difference between the two date columns, then get the colSums of the product with 'load_percent'

df1$weighted_index <- with(df1, colSums(outer(datestamp1,
          datestamp2, FUN = `-` ) * load_percent))

df1
#  datestamp1 datestamp2 load_percent weighted_index
#1 2019-05-28 2019-05-25      0.01883        2.95009
#2 2019-05-29 2019-05-26      0.72340        2.20786

data

df1 <- structure(list(datestamp1 = structure(c(18044, 18045), class = "Date"),
    datestamp2 = structure(c(18041, 18042), class = "Date"),
    load_percent = c(0.01883, 0.7234)), row.names = c(NA, -2L
), class = "data.frame")


问:
How to write a double back button pressed to exit app using flutter
I'm new to flutter, and I saw many android apps can exit when double press back button.

The first time press back button, app shows a toast"press again to exit app".
The following second press, app exits.
Of course, the time between two press must be not long.

How to do it in flutter?

答:
You can try this package.

Inside a Scaffold that wraps all your Widgets, place the DoubleBackToCloseApp passing a SnackBar:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: DoubleBackToCloseApp(
          child: Home(),
          snackBar: const SnackBar(
            content: Text('Tap back again to leave'),
          ),
        ),
      ),
    );
  }
}
```
<p>The solution below must be considered deprecated because it causes a few issues that were tackled in the package mentioned. For instance, the app closes if the snack bar was dismissed by the user (see hcbpassos/double_back_to_close_app#2).</p>
<h2>Old answer</h2>
<p>You can also opt for a solution involving <code>SnackBar</code>. It's not as simple as Andrey Turkovsky's answer, but it's quite more elegant and you won't depend on a library.</p>
<pre class="lang-dart prettyprint-override"><code>class _FooState extends State<Foo> {
  static const snackBarDuration = Duration(seconds: 3);

  final snackBar = SnackBar(
    content: Text('Press back again to leave'),
    duration: snackBarDuration,
  );

  DateTime backButtonPressTime;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // The BuildContext must be from one of the Scaffold's children.
      body: Builder(
        builder: (context) {
          return WillPopScope(
            onWillPop: () => handleWillPop(context),
            child: Text('Place your child here'),
          );
        },
      ),
    );
  }

  Future<bool> handleWillPop(BuildContext context) async {
    final now = DateTime.now();
    final backButtonHasNotBeenPressedOrSnackBarHasBeenClosed =
        backButtonPressTime == null ||
            now.difference(backButtonPressTime) > snackBarDuration;

    if (backButtonHasNotBeenPressedOrSnackBarHasBeenClosed) {
      backButtonPressTime = now;
      Scaffold.of(context).showSnackBar(snackBar);
      return false;
    }

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

Body:
You can try this package.

Inside a Scaffold that wraps all your Widgets, place the DoubleBackToCloseApp passing a SnackBar:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: DoubleBackToCloseApp(
          child: Home(),
          snackBar: const SnackBar(
            content: Text('Tap back again to leave'),
          ),
        ),
      ),
    );
  }
}

The solution below must be considered deprecated because it causes a few issues that were tackled in the package mentioned. For instance, the app closes if the snack bar was dismissed by the user (see hcbpassos/double_back_to_close_app#2).

Old answer

You can also opt for a solution involving SnackBar. It's not as simple as Andrey Turkovsky's answer, but it's quite more elegant and you won't depend on a library.

class _FooState extends State<Foo> {
  static const snackBarDuration = Duration(seconds: 3);

  final snackBar = SnackBar(
    content: Text('Press back again to leave'),
    duration: snackBarDuration,
  );

  DateTime backButtonPressTime;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // The BuildContext must be from one of the Scaffold's children.
      body: Builder(
        builder: (context) {
          return WillPopScope(
            onWillPop: () => handleWillPop(context),
            child: Text('Place your child here'),
          );
        },
      ),
    );
  }

  Future<bool> handleWillPop(BuildContext context) async {
    final now = DateTime.now();
    final backButtonHasNotBeenPressedOrSnackBarHasBeenClosed =
        backButtonPressTime == null ||
            now.difference(backButtonPressTime) > snackBarDuration;

    if (backButtonHasNotBeenPressedOrSnackBarHasBeenClosed) {
      backButtonPressTime = now;
      Scaffold.of(context).showSnackBar(snackBar);
      return false;
    }

    return true;
  }
}


问:
I have a problem creating separate table for images
I'm making a small database for some products and O need to add multiple images for one product.

I've created a separate table to add images URL with product_id, image_id.

The thing is how do I set the product id in images table while I'm adding a new product!

答:
Most probably, the product_id is auto increment primary key, and when you insert a record in products table, the new id is generated that can be obtained using LAST_INSERT_ID() function of mysql, or if you are using PDO, you can use lastInsertId() PDO fucntion for this as well.

If you prefer MySQL function then it can be used in insert query for images as :

```<code>INSERT INTO images VALUES(product_id, image_id) VALUES(LAST_INSERT_ID(), yourimageid)
</code>```

Or using PDO:

```<code>$product_id = $db->lastInsertId(); //where $db is pdo object
</code>```

and after that you can use $product id in next insert queries.

Body:
Most probably, the product_id is auto increment primary key, and when you insert a record in products table, the new id is generated that can be obtained using LAST_INSERT_ID() function of mysql, or if you are using PDO, you can use lastInsertId() PDO fucntion for this as well.

If you prefer MySQL function then it can be used in insert query for images as :

INSERT INTO images VALUES(product_id, image_id) VALUES(LAST_INSERT_ID(), yourimageid)

Or using PDO:

$product_id = $db->lastInsertId(); //where $db is pdo object

and after that you can use $product id in next insert queries.


答:
Just use min() or max():

```<code>select id, sum(value), min(data)
from t
group by id;
</code>```

If you actually want a random value, you can use:

```<code>select id, sum(value),
       min(data) keep (dense_rank first order by dbms_random.random)
from t
group by id;
</code>```

Title: GroupBy only one field, not all the fields I have in Select

Body:
Just use min() or max():

select id, sum(value), min(data)
from t
group by id;

If you actually want a random value, you can use:

select id, sum(value),
       min(data) keep (dense_rank first order by dbms_random.random)
from t
group by id;


问:
A pythonic way to insert a space before capital letters but not insert space between an Abbreviation
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word" but I also have some abbreviations as well, Like in the text "General Manager or VP".

I found an answer from David Underhill in this post:

A pythonic way to insert a space before capital letters

While this answer helps me to not insert spaces between abbreviations inside the text like "DaveIsAFKRightNow!Cool"

But it sure inserts a space between V and P in "VP".

I only have 25 experience points and i am unable to comment on the existing post, i am left with no other choice than to create another post for this similar sort of problem.

I am not that good at RegEx and not able to figure how to handle this situation.

I have tried this:

```<code>re_outer = re.compile(r'([^A-Z ])([A-Z])')
re_inner = re.compile(r'(?<!^)([A-Z])([^A-Z])')
re_outer.sub(r'\1 \2', re_inner.sub(r' \1\2', 'DaveIsAFKRightNow!Cool'))
</code>```

It gives me 'Dave Is AFK Right Now! Cool'

My text sample is this:

```<code>General Manager or VP Torrance, CARequired education
</code>```

I want the output as: General Manager or VP Torrance, CA Required education

The Output i am getting is: General Manager or V P Torrance, CA Required education

答:
You may swap the replacements to first insert spaces before uppercase letters that are preceded with chars other than uppercase letters and spaces, and then append a space before words that start with 1+ uppercase letters that are followed with an uppercase and a lowercase letter:

```<code>import re
re_outer = re.compile(r'([^A-Z ])([A-Z])')
re_inner = re.compile(r'\b[A-Z]+(?=[A-Z][a-z])')
print(re_inner.sub(r'\g<0> ', re_outer.sub(r'\1 \2', 'DaveIsAFKRightNow!Cool')))
# => Dave Is AFK Right Now! Cool
print(re_inner.sub(r'\g<0> ', re_outer.sub(r'\1 \2', 'General Manager or VP Torrance, CARequired education')))
# => General Manager or VP Torrance, CA Required education
</code>```

See the Python demo

The \b[A-Z]+(?=[A-Z][a-z]) regex matches

\b - word boundary

[A-Z]+ - 1+ uppercase letters that are

(?=[A-Z][a-z]) - followed with an uppercase letter and a lowercase letter.

Note that \g<0> inserts the whole match in the replacement pattern.

Body:
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word" but I also have some abbreviations as well, Like in the text "General Manager or VP".

I found an answer from David Underhill in this post:

A pythonic way to insert a space before capital letters

While this answer helps me to not insert spaces between abbreviations inside the text like "DaveIsAFKRightNow!Cool"

But it sure inserts a space between V and P in "VP".

I only have 25 experience points and i am unable to comment on the existing post, i am left with no other choice than to create another post for this similar sort of problem.

I am not that good at RegEx and not able to figure how to handle this situation.

I have tried this:

re_outer = re.compile(r'([^A-Z ])([A-Z])')
re_inner = re.compile(r'(?<!^)([A-Z])([^A-Z])')
re_outer.sub(r'\1 \2', re_inner.sub(r' \1\2', 'DaveIsAFKRightNow!Cool'))

It gives me 'Dave Is AFK Right Now! Cool'

My text sample is this:

General Manager or VP Torrance, CARequired education

I want the output as: General Manager or VP Torrance, CA Required education

The Output i am getting is: General Manager or V P Torrance, CA Required education

Body:
You may swap the replacements to first insert spaces before uppercase letters that are preceded with chars other than uppercase letters and spaces, and then append a space before words that start with 1+ uppercase letters that are followed with an uppercase and a lowercase letter:

import re
re_outer = re.compile(r'([^A-Z ])([A-Z])')
re_inner = re.compile(r'\b[A-Z]+(?=[A-Z][a-z])')
print(re_inner.sub(r'\g<0> ', re_outer.sub(r'\1 \2', 'DaveIsAFKRightNow!Cool')))
# => Dave Is AFK Right Now! Cool
print(re_inner.sub(r'\g<0> ', re_outer.sub(r'\1 \2', 'General Manager or VP Torrance, CARequired education')))
# => General Manager or VP Torrance, CA Required education

See the Python demo

The \b[A-Z]+(?=[A-Z][a-z]) regex matches

\b - word boundary

[A-Z]+ - 1+ uppercase letters that are

(?=[A-Z][a-z]) - followed with an uppercase letter and a lowercase letter.

Note that \g<0> inserts the whole match in the replacement pattern.


问:
R data.table values depending on previous row
I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.

I have tried using data.table, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift() function, but could not fit it in my temporary solution.

Here is a toy example:

library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

for(i in DT[,.I]){

  DT[i, c('a','b','c') := {
    if(iter == 1) {
      a = 1
      b = 2
      c = 3
    } else { # if it is not the first iteration
      a = DT[i-1, a + b] # read the values from the previous row to compute the new values
      b = DT[i-1, b] - a
      c = a / b + DT[i-1, c]
    }

    .(a, b, c)
  }]

}
```

<p>and here's the output:</p>

```     a  b          c iter
 1:  1  2  3.0000000    1
 2:  3 -1  0.0000000    2
 3:  2 -3 -0.6666667    3
 4: -1 -2 -0.1666667    4
 5: -3  1 -3.1666667    5
 6: -2  3 -3.8333333    6
 7:  1  2 -3.3333333    7
 8:  3 -1 -6.3333333    8
 9:  2 -3 -7.0000000    9
10: -1 -2 -6.5000000   10
```

Can someone help me improve the code?

Body:
I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.

I have tried using data.table, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift() function, but could not fit it in my temporary solution.

Here is a toy example:

library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

for(i in DT[,.I]){

  DT[i, c('a','b','c') := {
    if(iter == 1) {
      a = 1
      b = 2
      c = 3
    } else { # if it is not the first iteration
      a = DT[i-1, a + b] # read the values from the previous row to compute the new values
      b = DT[i-1, b] - a
      c = a / b + DT[i-1, c]
    }

    .(a, b, c)
  }]

}

and here's the output:

     a  b          c iter
 1:  1  2  3.0000000    1
 2:  3 -1  0.0000000    2
 3:  2 -3 -0.6666667    3
 4: -1 -2 -0.1666667    4
 5: -3  1 -3.1666667    5
 6: -2  3 -3.8333333    6
 7:  1  2 -3.3333333    7
 8:  3 -1 -6.3333333    8
 9:  2 -3 -7.0000000    9
10: -1 -2 -6.5000000   10

Can someone help me improve the code?

Body:
In fact you can solve your problem by using a recursive function call where you propagate your values from function call to function call and don't need to use the values of the previous row.
In base you could do it like:

DT = data.frame(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

fun <- function(a, b, c, n) {
  a <- a + b
  b <- b - a
  c <- a/b + c
  n <- n - 1
  if(n<=0) {return(c(a,b,c))}
  return(rbind(c(a,b,c),fun(a,b,c,n)))
}

DT[1,1:3] <- 1:3
DT[-1,1:3] <- fun(DT[1,1], DT[1,2], DT[1,3], 9)
DT

    a  b          c iter
1   1  2  3.0000000    1
2   3 -1  0.0000000    2
3   2 -3 -0.6666667    3
4  -1 -2 -0.1666667    4
5  -3  1 -3.1666667    5
6  -2  3 -3.8333333    6
7   1  2 -3.3333333    7
8   3 -1 -6.3333333    8
9   2 -3 -7.0000000    9
10 -1 -2 -6.5000000   10

Alternatively you can simply make a for loop:

DT = data.frame(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)
a <- 1
b <- 2
c <- 3
for(i in seq_len(nrow(DT))) {
  DT[i,1:3] <- c(a,b,c)
  a <- a + b
  b <- b - a
  c <- a/b + c
}
DT

    a  b          c iter
1   1  2  3.0000000    1
2   3 -1  0.0000000    2
3   2 -3 -0.6666667    3
4  -1 -2 -0.1666667    4
5  -3  1 -3.1666667    5
6  -2  3 -3.8333333    6
7   1  2 -3.3333333    7
8   3 -1 -6.3333333    8
9   2 -3 -7.0000000    9
10 -1 -2 -6.5000000   10

But this will also be slow. A fast solution is given e.g. by IceCreamToucan.


问:
How to disable lex-web-ui microphone?
I followed this tutorial in setting up lex bot: https://aws.amazon.com/blogs/machine-learning/deploy-a-web-ui-for-your-chatbot/
How do I disable the microphone

I've tried modifying the lex-web-ui.js file but it keeps reverting to original versions. (I've updated the version in S3 stack)

Thank you

答:
In lex-web-ui.loader.min.js remove ,a.setAttribute("allow","microphone"). When updated, set public read only access.

Ensure that the code refers to updated file. In broswer script, add  above where the chatbot is loaded.

Title: How to disable lex-web-ui microphone?


问:
How to adjust microphone sensitivity [not volume] using Web Audio API
i would like to achieve in the same way discord app is doing, calibrate the audio input to be triggered at a certain volume (Decibel, ...) and not bellow that volume.

I'm creating a video call app and i want before the call allow the user to setup his devices correctly. Actually the sensitivity is too high and there is a lot of undesirable noise (You can even hear a bug fly).

I did a lot of unsuccessful research about how to achieve this with the Web Audio API.

At the beginning i tried to use the GainNode but it's just a way to amplify/attenuate (+/-) the sound like a volume.

After i tried using the BiquadFilterNode but it's just some filters to attenuate/amplify the audio around a certain frequency.

I think there is maybe a way using AudioWorklet but i don't find any clear documentation about how to solve my problem.

I would like in the same way i'm modifying the gain create a function setVolumeThreshold that regarding a certain db (or other kind of value) cut the sound bellow that.

```<code>var start = () => navigator.mediaDevices.getUserMedia({audio: true})
  .then(stream => audio.srcObject = modifyGain(stream, 2.5))
  .catch(e => log(e));

var modifyGain = (stream, gainValue) => {
  var ctx = new AudioContext();
  var src = ctx.createMediaStreamSource(stream);
  var dst = ctx.createMediaStreamDestination();
  var gainNode = ctx.createGain();
  gainNode.gain.value = gainValue;
  [src, gainNode, dst].reduce((a, b) => a && a.connect(b));
  return dst.stream;
};
</code>```

Here a jsFiddle using that code snippet.

Thanks a lot to those will try to help me !

答:
I did a similar project quite a while ago using ScriptProcessorNode - https://github.com/cwilso/volume-meter/.  It should be easily portable to AudioWorklet.
 Also of interest is the "noise gate" effect in https://github.com/cwilso/Audio-Input-Effects, which I think is closer to what you want?</p>

Body:
i would like to achieve in the same way discord app is doing, calibrate the audio input to be triggered at a certain volume (Decibel, ...) and not bellow that volume.

I'm creating a video call app and i want before the call allow the user to setup his devices correctly. Actually the sensitivity is too high and there is a lot of undesirable noise (You can even hear a bug fly).

I did a lot of unsuccessful research about how to achieve this with the Web Audio API.

At the beginning i tried to use the GainNode but it's just a way to amplify/attenuate (+/-) the sound like a volume.

After i tried using the BiquadFilterNode but it's just some filters to attenuate/amplify the audio around a certain frequency.

I think there is maybe a way using AudioWorklet but i don't find any clear documentation about how to solve my problem.

I would like in the same way i'm modifying the gain create a function setVolumeThreshold that regarding a certain db (or other kind of value) cut the sound bellow that.

var start = () => navigator.mediaDevices.getUserMedia({audio: true})
  .then(stream => audio.srcObject = modifyGain(stream, 2.5))
  .catch(e => log(e));

var modifyGain = (stream, gainValue) => {
  var ctx = new AudioContext();
  var src = ctx.createMediaStreamSource(stream);
  var dst = ctx.createMediaStreamDestination();
  var gainNode = ctx.createGain();
  gainNode.gain.value = gainValue;
  [src, gainNode, dst].reduce((a, b) => a && a.connect(b));
  return dst.stream;
};

Here a jsFiddle using that code snippet.

Thanks a lot to those will try to help me !


问:
How to fix Laravel throwing FatalThrowableError when trying to broadcast a new event
I was following a tutorial to get Laravel to broadcast real-time but got stuck after just a few minutes of following along. Laravel throws the following message to me "Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, integer given, called in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 775"

I've tried to redo the tutorial several times to make sure that I didn't miss a thing but the problem is still the same after several tries.
Even checking the stack trace and documentation didn't give me any clue.

I've uncommented the following line in config/app.php:

```<code>App\Providers\BroadcastServiceProvider::class,
</code>```

I've added the following lines to App\Providers\EventServiceProvider:

```<code>use App\Events\RideCreated;
use App\Listeners\RideCreatedListener;
</code>```

and the following after protected $listen = [ in the same file

```<code>    RideCreated::class => [
        RideCreatedListener::class,
    ],
</code>```

this is the setup of the route used for testing (web.php):

```<code>Route::get('/test', function(){
    event(new RideCreated());
    return "test";
});
</code>```

and this is how RideCreated.php looks like:

```<code><?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class RideCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('RideCreated');
    }
}
</code>```

the listener (RideCreatedListener.php) looks like this:

```<code><?php

namespace App\Listeners;

use App\Events\RideCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class RideCreatedListener
{

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  RideCreated  $event
     * @return void
     */
    public function handle(RideCreated $event)
    {
        //
    }
}

</code>```

I expected when visiting the /test rout to see test on screen but actually got the error message displayed.

my first thought was that the ShouldBroadcast implementation in RideCreated.php somehow causes the problem since removing implement ShouldBroadcast makes the error disappear. the only problem is that removing it is no option since it's needed for Pusher to work.

答:
This may sound strange, but we have been resolving this issue f2f. My answer is just for other people that might read this.

It turned out that the queue was not configured such that a default queue could be resolved by Laravel. The error was fixed by adding the $bradcastQueue property to the RideCreated class. See Broadcast Queue

Body:
I was following a tutorial to get Laravel to broadcast real-time but got stuck after just a few minutes of following along. Laravel throws the following message to me "Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, integer given, called in /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 775"

I've tried to redo the tutorial several times to make sure that I didn't miss a thing but the problem is still the same after several tries.
Even checking the stack trace and documentation didn't give me any clue.

I've uncommented the following line in config/app.php:

App\Providers\BroadcastServiceProvider::class,

I've added the following lines to App\Providers\EventServiceProvider:

use App\Events\RideCreated;
use App\Listeners\RideCreatedListener;

and the following after protected $listen = [ in the same file

    RideCreated::class => [
        RideCreatedListener::class,
    ],

this is the setup of the route used for testing (web.php):

Route::get('/test', function(){
    event(new RideCreated());
    return "test";
});

and this is how RideCreated.php looks like:

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class RideCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('RideCreated');
    }
}

the listener (RideCreatedListener.php) looks like this:

<?php

namespace App\Listeners;

use App\Events\RideCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class RideCreatedListener
{

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  RideCreated  $event
     * @return void
     */
    public function handle(RideCreated $event)
    {
        //
    }
}

I expected when visiting the /test rout to see test on screen but actually got the error message displayed.

my first thought was that the ShouldBroadcast implementation in RideCreated.php somehow causes the problem since removing implement ShouldBroadcast makes the error disappear. the only problem is that removing it is no option since it's needed for Pusher to work.