问:
Automatically email when a cell in column has certain value
I have a column with certain text that I use for signals.
When a cell value in the column has the text "Signal1" or "Singal2" then send email with title that "Signals were found".
When scanning the column any other cell expect for "Signal1" or "Signal2" can be ignored.

This is what I have so far but it's only for one cell one signal:

```<code> function CheckSignals() {

   // Fetch data
   var dataRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Signal").getRange("H2:H29");
   var data = dataRange.getValue();

   // Check for signals
   if (data = "Go Short" || "Go Long"){

     // Fetch the email address and send
     var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange("C2");
     var emailAddress = emailRange.getValues();

     // Send Alert Email.
     var message = 'Signal1 ' + data; // Second column
     var subject = 'Signals were found';
     MailApp.sendEmail(emailAddress, subject, message);
     }
 }
</code>```

This is working but it's too simple...
There are two signals I have to scan for in the column:
"Singal1" and "Signal2".

For example, if column H was scanned three "Signal1" and/or "Signal2" was found. The email content should contain information from the whole row for each cell where it was found.

Example email:

Subject: Signals was found

Message:

Signal 1 was found in the following rows with the following data:
Row6: data from row 6 column A, data from row 6 column B,data from row 6 column C,data from row 6 column D, ...up to column H

Row11: Brown, Denver, 23, 1967, 11:00, 34, etc...

The spreadsheet always have 29 rows, where the first row is headers.
The spreadsheet has 9 columns (A - H).

答:
You want to retrieve rows, when the values of the column "H2:H29" is Go Short or Go Long.

Values are always in "A2:H29".

You want to send the retrieved rows as one email.

If my understanding is correct, how about this modification?

Modification points:

At first, the values of "A2:H29" are retrieved. Then, the rows including Go Short or Go Long in the column "H" are retrieved.

In this modified script, when the rows including Go Short or Go Long in the column "H" are retrieved, the base of message is created.

Modified script:

```<code>function CheckSignals() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Fetch data
  var data = ss.getSheetByName("Signal").getRange("A2:H29").getValues();

  // Check for signals
  var contents = data.map(function(e, i) {return e[7] == "Go Short" || e[7] == "Go Long" ? e[7] + " Row " + (i + 2) + ": " + e.join(", ") : ""}).filter(String);

  if (contents.length > 0) {

    // Fetch the email address and send
    var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange("C2");
    var emailAddress = emailRange.getValues();

    // Send Alert Email.
    var message = contents.join("\n");
    var subject = 'Signals were found';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}
</code>```

Note:

The format of message is different between your script and your question. So in this modification, the required values are used, because I couldn't understand about the correct one you want. Please modify this for your situation.

I could't understand about Second column of var message = 'Signal1 ' + data; // Second column.

References:

map()

filter()

join()

If I misunderstood your question and this was not the result you want, I apologize.

Edit:

From your shared Spreadsheet, I modified your script again. The differences between your initial question and shared Spreadsheet are as follows.

Values of Signal1, Signal2 and Go Short and Go Long cannot be found at the column "H". Those values can be seen at the columns of "D", "E", "F" and "G".

In your script in your question, Go Short and Go Long are used. But in your shared Spreadsheet, Go short and Go long are used.

By above differences, my modified script didn't work. This is due to my poor skill. I apologize for this situation. I reflected above differences and your shared Spreadsheet to my modified script. Please confirm the following modified script.

Modified script:

```<code>function CheckSignals() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Fetch data
  var data = ss.getSheetByName("Signal").getRange("A2:H29").getValues();

  // Check for signals
  var searchValues = ["Go short", "Go long"];
  var contents = data.map(function(row, i) {return searchValues.some(function(e) {return ~row.indexOf(e)}) ? row[7] + " Row " + (i + 2) + ": " + row.join(", ") : ""}).filter(String);

  if (contents.length > 0) {

    // Fetch the email address and send
    var emailRange = ss.getSheetByName("Email").getRange("C2");
    var emailAddress = emailRange.getValue();

    // Send Alert Email.
    var message = contents.join("\n");
    var subject = 'Signals were found';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}
</code>```

Note:

About the format of the output values, I couldn't understand about it from your question and reply comment. So I prepared the values as a sample. So about this, please modify for your situation.

Body:
I have a column with certain text that I use for signals.
When a cell value in the column has the text "Signal1" or "Singal2" then send email with title that "Signals were found".
When scanning the column any other cell expect for "Signal1" or "Signal2" can be ignored.

This is what I have so far but it's only for one cell one signal:

 function CheckSignals() {

   // Fetch data
   var dataRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Signal").getRange("H2:H29");
   var data = dataRange.getValue();

   // Check for signals
   if (data = "Go Short" || "Go Long"){

     // Fetch the email address and send
     var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange("C2");
     var emailAddress = emailRange.getValues();

     // Send Alert Email.
     var message = 'Signal1 ' + data; // Second column
     var subject = 'Signals were found';
     MailApp.sendEmail(emailAddress, subject, message);
     }
 }

This is working but it's too simple...
There are two signals I have to scan for in the column:
"Singal1" and "Signal2".

For example, if column H was scanned three "Signal1" and/or "Signal2" was found. The email content should contain information from the whole row for each cell where it was found.

Example email:

Subject: Signals was found

Message:

Signal 1 was found in the following rows with the following data:
Row6: data from row 6 column A, data from row 6 column B,data from row 6 column C,data from row 6 column D, ...up to column H

Row11: Brown, Denver, 23, 1967, 11:00, 34, etc...

The spreadsheet always have 29 rows, where the first row is headers.
The spreadsheet has 9 columns (A - H).

Body:
You want to retrieve rows, when the values of the column "H2:H29" is Go Short or Go Long.

Values are always in "A2:H29".

You want to send the retrieved rows as one email.

If my understanding is correct, how about this modification?

Modification points:

At first, the values of "A2:H29" are retrieved. Then, the rows including Go Short or Go Long in the column "H" are retrieved.

In this modified script, when the rows including Go Short or Go Long in the column "H" are retrieved, the base of message is created.

Modified script:

function CheckSignals() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Fetch data
  var data = ss.getSheetByName("Signal").getRange("A2:H29").getValues();

  // Check for signals
  var contents = data.map(function(e, i) {return e[7] == "Go Short" || e[7] == "Go Long" ? e[7] + " Row " + (i + 2) + ": " + e.join(", ") : ""}).filter(String);

  if (contents.length > 0) {

    // Fetch the email address and send
    var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange("C2");
    var emailAddress = emailRange.getValues();

    // Send Alert Email.
    var message = contents.join("\n");
    var subject = 'Signals were found';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

Note:

The format of message is different between your script and your question. So in this modification, the required values are used, because I couldn't understand about the correct one you want. Please modify this for your situation.

I could't understand about Second column of var message = 'Signal1 ' + data; // Second column.

References:

map()

filter()

join()

If I misunderstood your question and this was not the result you want, I apologize.

Edit:

From your shared Spreadsheet, I modified your script again. The differences between your initial question and shared Spreadsheet are as follows.

Values of Signal1, Signal2 and Go Short and Go Long cannot be found at the column "H". Those values can be seen at the columns of "D", "E", "F" and "G".

In your script in your question, Go Short and Go Long are used. But in your shared Spreadsheet, Go short and Go long are used.

By above differences, my modified script didn't work. This is due to my poor skill. I apologize for this situation. I reflected above differences and your shared Spreadsheet to my modified script. Please confirm the following modified script.

Modified script:

function CheckSignals() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Fetch data
  var data = ss.getSheetByName("Signal").getRange("A2:H29").getValues();

  // Check for signals
  var searchValues = ["Go short", "Go long"];
  var contents = data.map(function(row, i) {return searchValues.some(function(e) {return ~row.indexOf(e)}) ? row[7] + " Row " + (i + 2) + ": " + row.join(", ") : ""}).filter(String);

  if (contents.length > 0) {

    // Fetch the email address and send
    var emailRange = ss.getSheetByName("Email").getRange("C2");
    var emailAddress = emailRange.getValue();

    // Send Alert Email.
    var message = contents.join("\n");
    var subject = 'Signals were found';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

Note:

About the format of the output values, I couldn't understand about it from your question and reply comment. So I prepared the values as a sample. So about this, please modify for your situation.


来源: stackexchange

问:
jupyter-client has to be installed but “jupyter kernelspec --version” exited with code 127
I have already installed Jupyter notebook in my ubuntu 16.04 machine. In jupyter notebook there is by default python installed. Now I want to use R from jupyter notebook.

To do so I followed IRkernel installation link and run below commands:

```<code>install.packages('devtools')

devtools::install_github('IRkernel/IRkernel')
</code>```

But when I run
IRkernel::installspec() command it shows below error:

jupyter-client has to be installed but “jupyter kernelspec --version” exited with code 127

I am now confused why this error occurs.

答:
I tried to install IRkernel on my Windows machine. I experienced a similar problem when I ran from within R:

```<code>> IRkernel::installspec(user = FALSE)
Error in IRkernel::installspec(user = FALSE) :
  jupyter-client has to be installed but “jupyter kernelspec --version” exited with code 1.
</code>```

I did not use conda to install Jupyter on my machine, but pip. I have some programmes installed which use python under the hood. It means that I have more than one Python instance on my machine and more Jupyter instances too. To be sure I was referencing the right Jupyter instance, I did this:

```<code>> setwd('C:/usr/lib/Python36-32/Scripts')
> IRkernel::installspec(user = FALSE)
[InstallKernelSpec] Installed kernelspec ir in C:\ProgramData\jupyter\kernels\ir
</code>```

Besides Python, I can now also use R within my notebooks.

ContentLicense: CC BY-SA 3.0

Body:
I have already installed Jupyter notebook in my ubuntu 16.04 machine. In jupyter notebook there is by default python installed. Now I want to use R from jupyter notebook.

To do so I followed IRkernel installation link and run below commands:

install.packages('devtools')

devtools::install_github('IRkernel/IRkernel')

But when I run
IRkernel::installspec() command it shows below error:

jupyter-client has to be installed but “jupyter kernelspec --version” exited with code 127

I am now confused why this error occurs.

Body:
I tried to install IRkernel on my Windows machine. I experienced a similar problem when I ran from within R:

> IRkernel::installspec(user = FALSE)
Error in IRkernel::installspec(user = FALSE) :
  jupyter-client has to be installed but “jupyter kernelspec --version” exited with code 1.

I did not use conda to install Jupyter on my machine, but pip. I have some programmes installed which use python under the hood. It means that I have more than one Python instance on my machine and more Jupyter instances too. To be sure I was referencing the right Jupyter instance, I did this:

> setwd('C:/usr/lib/Python36-32/Scripts')
> IRkernel::installspec(user = FALSE)
[InstallKernelSpec] Installed kernelspec ir in C:\ProgramData\jupyter\kernels\ir

Besides Python, I can now also use R within my notebooks.

ContentLicense: CC BY-SA 4.0


问:
Problem with DialogFragment creation and invocation
I'm creating a simple DialogFragment with two buttons, which is supposed only to show a Toast when you select any of the two options. This dialog is displayed when you press one certain button on a activity.
For some reason, the code doesn't show any kind of error but when i click the button, the app crashes.
How do I resolve this?

I was first trying to do a custom XML file and java file for the Dialog, but i couldn't make that work either. Google's documentation and other tutorials didn't help either

public class Config extends AppCompatActivity {

```<code>Button btncanc;
Button btnreestab;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_config);
    btncanc = (Button) findViewById(R.id.btncnacelset);
    btnreestab = (Button) findViewById(R.id.btnrest);

    btncanc.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Toast toast = Toast.makeText(getApplicationContext(),"Operación cancelada",Toast.LENGTH_SHORT);
            toast.show();

            Config.this.finish();
        }
    });
    btnreestab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

            builder.setMessage("Hola");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast toast = Toast.makeText(getApplicationContext(),"hola",Toast.LENGTH_SHORT);
                    toast.show();
                }
            });
            builder.setNegativeButton("cancela", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast toast = Toast.makeText(getApplicationContext(),"adios",Toast.LENGTH_SHORT);
                    toast.show();
                }
            });
            AlertDialog dialog = builder.create(); dialog.show();
        }
    });
}
</code>```

}

答:
You can copy your style from your context. Make your alert dialog initialization with.

```<code>new AlertDialog.Builder(Config.this)
</code>```

in other way you can define a custom style in style.xml such as

```<code><style name="myDialog" parent="Theme.AppCompat.Dialog">
    <item name="android:windowNoTitle">true</item>
    ...
</style
</code>```

and initialize alert dialog with

```<code>AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext(), R.style.myDialog);
</code>```

The reason for this crash is the AppCompatActivity has the Theme.AppCompat so you should use this theme.
checkout that crash.

You need to use a Theme.AppCompat theme (or descendant) with this
  activity

Body:
I'm creating a simple DialogFragment with two buttons, which is supposed only to show a Toast when you select any of the two options. This dialog is displayed when you press one certain button on a activity.
For some reason, the code doesn't show any kind of error but when i click the button, the app crashes.
How do I resolve this?

I was first trying to do a custom XML file and java file for the Dialog, but i couldn't make that work either. Google's documentation and other tutorials didn't help either

public class Config extends AppCompatActivity {

Button btncanc;
Button btnreestab;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_config);
    btncanc = (Button) findViewById(R.id.btncnacelset);
    btnreestab = (Button) findViewById(R.id.btnrest);

    btncanc.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Toast toast = Toast.makeText(getApplicationContext(),"Operación cancelada",Toast.LENGTH_SHORT);
            toast.show();

            Config.this.finish();
        }
    });
    btnreestab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

            builder.setMessage("Hola");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast toast = Toast.makeText(getApplicationContext(),"hola",Toast.LENGTH_SHORT);
                    toast.show();
                }
            });
            builder.setNegativeButton("cancela", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast toast = Toast.makeText(getApplicationContext(),"adios",Toast.LENGTH_SHORT);
                    toast.show();
                }
            });
            AlertDialog dialog = builder.create(); dialog.show();
        }
    });
}

}

Body:
You can copy your style from your context. Make your alert dialog initialization with.

new AlertDialog.Builder(Config.this)

in other way you can define a custom style in style.xml such as

<style name="myDialog" parent="Theme.AppCompat.Dialog">
    <item name="android:windowNoTitle">true</item>
    ...
</style

and initialize alert dialog with

AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext(), R.style.myDialog);

The reason for this crash is the AppCompatActivity has the Theme.AppCompat so you should use this theme.
checkout that crash.

You need to use a Theme.AppCompat theme (or descendant) with this
  activity


问:
Mojolicious(hypnotoad) - enforce TLS v1.2
How to enforce Mojolicious(hypnotoad) app to use TLS v1.2?

mojo version output:

```<code>CORE
  Perl        (v5.16.3, linux)
  Mojolicious (8.0, Supervillain)

OPTIONAL
  Cpanel::JSON::XS 4.04+  (n/a)
  EV 4.0+                 (4.22)
  IO::Socket::Socks 0.64+ (n/a)
  IO::Socket::SSL 2.009+  (2.060)
  Net::DNS::Native 0.15+  (n/a)
  Role::Tiny 2.000001+    (2.000005)
</code>```

hypnotoad conf:

```<code>{
     hypnotoad => {
         listen => ['https://myserver.domain.com:xxxx?cert=/path/to/cert/file.cer&key=/path/to/key/file.key'],
     }
}
</code>```

This is how I start hypnotoad:

```<code>hypnotoad -f script/apps
</code>```

I have updated the IO::Socket::SSL module as suggested somewhere. It din't work.

Much appreciate any guidance.

答:
Configure version with value TLSv1_2, e.g. in my_app.conf

```<code>{
    secrets => ['………'],
    hypnotoad => {
        listen  => ['https://localhost:8443?cert=server_cert.pem&key=server_key.pem&version=TLSv1_2'],
    }
}
</code>```

Test with curl -k -v https://localhost:8443. Daemon will serve 1.3 by default, but use 1.2 when forced to do so.

Body:
How to enforce Mojolicious(hypnotoad) app to use TLS v1.2?

mojo version output:

CORE
  Perl        (v5.16.3, linux)
  Mojolicious (8.0, Supervillain)

OPTIONAL
  Cpanel::JSON::XS 4.04+  (n/a)
  EV 4.0+                 (4.22)
  IO::Socket::Socks 0.64+ (n/a)
  IO::Socket::SSL 2.009+  (2.060)
  Net::DNS::Native 0.15+  (n/a)
  Role::Tiny 2.000001+    (2.000005)

hypnotoad conf:

{
     hypnotoad => {
         listen => ['https://myserver.domain.com:xxxx?cert=/path/to/cert/file.cer&key=/path/to/key/file.key'],
     }
}

This is how I start hypnotoad:

hypnotoad -f script/apps

I have updated the IO::Socket::SSL module as suggested somewhere. It din't work.

Much appreciate any guidance.

Body:
Configure version with value TLSv1_2, e.g. in my_app.conf

{
    secrets => ['………'],
    hypnotoad => {
        listen  => ['https://localhost:8443?cert=server_cert.pem&key=server_key.pem&version=TLSv1_2'],
    }
}

Test with curl -k -v https://localhost:8443. Daemon will serve 1.3 by default, but use 1.2 when forced to do so.


问:
Firebase Authentication fails after publishing App
I am using 2 google accounts and 2 different firebase projects for Development and Release for android app.
I have Implemented Google Authentication on both of them.
Both operate well when I have the build. i.e Dev also performs Authentication and release build as well.
When I publish my app on Google Play Console and download it via play store, Google Authentication fails. It gives Error "Sign In Cancelled! RC: 0"

答:
I got solution.....

Open Play console -> Release Management -> App Sign in -> SHA-1 Certificate.

Copy SHA-1 Key and Past in Firebase Console

Go To Firebase Project -> Project Setting -> SHA Certificate Fingerprint -> Add Fingerprint-> Paste SHA-1 Key


问:
How Alb Ingress Controller target-type:instance forward requests
https://github.com/kubernetes-sigs/aws-alb-ingress-controller/blob/master/docs/guide/ingress/annotation.md#target-type

In above link it is mentioned that "instance mode" will route traffic to all ec2 instances within cluster on NodePort opened for your service.
so how does kube-proxy make sure that request is served only once in case multiple replicas of pods are running in different instances and how does it makes sure that requests are evenly served from all pods?

答:
As per documentation:

Amazon Elastic Load Balancing Application Load Balancer (ALB) is a popular AWS service that load balances incoming traffic at the application layer (layer 7) across multiple targets, such as Amazon EC2 instances.

The AWS ALB Ingress controller is a controller that triggers the creation of an ALB and the necessary supporting AWS resources whenever a Kubernetes user declares an Ingress resource on the cluster. The Ingress resource uses the ALB to route HTTP[s] traffic to different endpoints within the cluster.

With instance mode, ingress traffic start from ALB and reach Node Port opened for service. Traffic is routed to the container POD within cluster.
  Moreover target-type: "instance mode" is default setting in AWS ALB ingress controller and service must be type of "NodePort" or "LoadBalancer" to use this mode.

Managing ALBs is automatic, and you only need to define your ingress resources as you would typically do. ALB ingress controller POD which is running inside the Kubernetes cluster communicates with Kubernetes API and does all the work. However, this POD is only a control plane, it doesn't do any proxying and stuff like that.

Your Application Load Balancer periodically sends requests to its registered targets to test their status. These tests are called health checks. Alb-ingress-controller is performing "health checks" for targets groups. Different "health check's" on target groups can be controlled using annotations.

You can find more information about ALB ingress and NodePort here and here

Hope this help.


问:
Select 2 products from each category in MySQL
Pretty similar to MYSQL - select first 4 records for each category in a table but there isn't an accepted answer and the one answer there doesn't make much sense so i'm asking again.

I have a PRODUCTS table with 3 columns: ID, NAME and CATEGORY
What i would like to know now is if it's at all possible to select 2 products for each distinct category without doing queries in a PHP loop.

The order of the selected products is of no importance, they might as well be random. But it's important that i only have max 2 products per category.

So a good result set would be

```<code>ID  ; NAME   ; CATEGORY
:::::::::::::::::::::::
152 ; APPLE  ; FRUIT
185 ; ORANGE ; FRUIT
145 ; BEEF   ; MEAT
141 ; PORK   ; MEAT
410 ; PEPSI  ; DRINKS
585 ; CARROT ; VEGETABLES
585 ; TOMATO ; VEGETABLES
</code>```

答:
Something along these lines will work:

```<code>SELECT id, name, category
FROM (
  SELECT *,
         IF( @prev <> category,
             @rownum := 1,
             @rownum := @rownum+1
         ) AS rank,
         @prev := category,
         @rownum
  FROM (
    SELECT * FROM products
    ORDER BY category, rand()
  ) random_prodcts
) products_ranked
WHERE rank <= 2;
</code>```

It orders them randomly within the categories, then pulls them out tracking how many it's got from each.

Not sure how nicely it will scale though.

EDIT: Tried it with a few thousand records and it seems ok.

Body:
Pretty similar to MYSQL - select first 4 records for each category in a table but there isn't an accepted answer and the one answer there doesn't make much sense so i'm asking again.

I have a PRODUCTS table with 3 columns: ID, NAME and CATEGORY
What i would like to know now is if it's at all possible to select 2 products for each distinct category without doing queries in a PHP loop.

The order of the selected products is of no importance, they might as well be random. But it's important that i only have max 2 products per category.

So a good result set would be

ID  ; NAME   ; CATEGORY
:::::::::::::::::::::::
152 ; APPLE  ; FRUIT
185 ; ORANGE ; FRUIT
145 ; BEEF   ; MEAT
141 ; PORK   ; MEAT
410 ; PEPSI  ; DRINKS
585 ; CARROT ; VEGETABLES
585 ; TOMATO ; VEGETABLES

Body:
Something along these lines will work:

SELECT id, name, category
FROM (
  SELECT *,
         IF( @prev <> category,
             @rownum := 1,
             @rownum := @rownum+1
         ) AS rank,
         @prev := category,
         @rownum
  FROM (
    SELECT * FROM products
    ORDER BY category, rand()
  ) random_prodcts
) products_ranked
WHERE rank <= 2;

It orders them randomly within the categories, then pulls them out tracking how many it's got from each.

Not sure how nicely it will scale though.

EDIT: Tried it with a few thousand records and it seems ok.


问:
collect numbers and convert them to date in angularjs
I have 3 scopes in angularjs, one for year, one for month and one for day coming from 3 input boxes. I want to combine them as date, the following code insert the date correctly but with 22:00:00 added to it like  2019-06-01 22:00:00.000.
How to insert the date only without time

HTML

```<code><div class="col-md-1">
    <div class="form-group has-error">
        <label class="title_lable">Year:</label>
        <input id="code" type="number" class="form-control input-sm"
               ng-model="year">
    </div>
</div>
<div class="col-md-2">
    <div class="form-group has-error">
        <label class="title_lable">Latin Description:</label>
        <input type="text" class="form-control input-sm"
               ng-model="latindesc">
    </div>
</div>
<div class="col-md-2">
    <div class="form-group">
        <label class="title_lable">Local Description:</label>
        <input type="text" class="form-control input-sm"
               ng-model="localdesc">
    </div>
</div>
<div class="col-md-1">
    <div class="form-group">
        <label class="title_lable">Month:</label>
        <select ng-show="lang==1" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthanm for m in months">
        </select>
        <select ng-show="lang==0" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthenm for m in months">
        </select>
    </div>
</div>
<div class="col-md-1">
    <div class="form-group">
        <label class="title_lable">Day:</label>
        <input type="number" class="form-control input-sm" ng-model="day">
    </div>
</div>
</code>```

Angular

```<code>var dFrom = new Date($scope.month + '/' + ($scope.day + 1) + '/' + $scope.year );
        var days = $scope.ndays;
        console.log(days);
        var todate = new Date($scope.month + '/' + ($scope.day +1) + '/' + $scope.year);
        todate = addDays(todate, days - 1);
        console.log(todate);

        var vacation = {
            Sys_Key: $scope.syskey,
            Vac_Code: $scope.code,
            L_Desc: $scope.latindesc,
            A_Desc: $scope.localdesc,
            V_Start_Date: $scope.day,
            V_Month: $scope.month,
            V_Days_Count: $scope.ndays,
            V_Year: $scope.year,
            From_Date: dFrom,
            To_Date: todate
        }
</code>```

```<code>function addDays(startDate, numberOfDays) {
    var returnDate = new Date(
        startDate.getFullYear(),
        startDate.getMonth(),
        startDate.getDate() + numberOfDays,
        startDate.getHours(),
        startDate.getMinutes(),
        startDate.getSeconds()
    );
    return returnDate;
}
</code>```

答: When adding in javascript, be sure you are using numerical values and not strings. You can convert strings to integers with parseInt(string)

Body:
I have 3 scopes in angularjs, one for year, one for month and one for day coming from 3 input boxes. I want to combine them as date, the following code insert the date correctly but with 22:00:00 added to it like  2019-06-01 22:00:00.000.
How to insert the date only without time

HTML

        Year:
        <input id="code" type="number" class="form-control input-sm"
               ng-model="year">

        Latin Description:
        <input type="text" class="form-control input-sm"
               ng-model="latindesc">

        Local Description:
        <input type="text" class="form-control input-sm"
               ng-model="localdesc">

        Month:
        <select ng-show="lang==1" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthanm for m in months">
        </select>
        <select ng-show="lang==0" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthenm for m in months">
        </select>

        Day:
        <input type="number" class="form-control input-sm" ng-model="day">

Angular

var dFrom = new Date($scope.month + '/' + ($scope.day + 1) + '/' + $scope.year );
        var days = $scope.ndays;
        console.log(days);
        var todate = new Date($scope.month + '/' + ($scope.day +1) + '/' + $scope.year);
        todate = addDays(todate, days - 1);
        console.log(todate);

        var vacation = {
            Sys_Key: $scope.syskey,
            Vac_Code: $scope.code,
            L_Desc: $scope.latindesc,
            A_Desc: $scope.localdesc,
            V_Start_Date: $scope.day,
            V_Month: $scope.month,
            V_Days_Count: $scope.ndays,
            V_Year: $scope.year,
            From_Date: dFrom,
            To_Date: todate
        }

function addDays(startDate, numberOfDays) {
    var returnDate = new Date(
        startDate.getFullYear(),
        startDate.getMonth(),
        startDate.getDate() + numberOfDays,
        startDate.getHours(),
        startDate.getMinutes(),
        startDate.getSeconds()
    );
    return returnDate;
}


问:
Why can glibc strcspn() safely access memory apparently past the end of a string?
GNU libc has this implementation of strcspn(), which, quote,

Returns the length of the maximum initial segment of S
  which contains no characters from REJECT.

It's clever in its implementation in that it creates a 256-entry lookup table to make the operation of finding whether a character is in the reject set a simple O(1) array lookup, as opposed to e.g. the OpenBSD implementation which uses nested loops.

However, I'm curious how the c0/c1/c2/c3 loop below can access memory past the apparent end of str without a page fault or similar.

Does the C standard, for instance, guarantee that all strings, whether on the stack or heap or statically allocated, have their allocations aligned up to 4 bytes, so it's safe to access up to 3 past the last NUL?

I've added some comments in the code below; the original (as linked above) has none whatsoever.

/* Align a pointer by rounding down to closest size. */
#define PTR_ALIGN_DOWN(base, size) ...

size_t strcspn (const char *str, const char *reject)
{
  if ((reject[0] == '\0') || (reject[1] == '\0'))
    return __strchrnul (str, reject [0]) - str;

  // Build a lookup table containing all characters from `reject`;
  // due to the way the `do/while` loop below is constructed, `table`
  // will end up having `table[0] = 1` always, which works as an
  // exit condition.

  unsigned char p[256] = {0};
  unsigned char *s = (unsigned char*) reject;
  unsigned char tmp;
  do
    p[tmp = *s++] = 1;
  while (tmp);

  // Check the first 4 bytes "by hand".
  s = (unsigned char*) str;
  if (p[s[0]]) return 0;
  if (p[s[1]]) return 1;
  if (p[s[2]]) return 2;
  if (p[s[3]]) return 3;

  // Align the pointer (for whichever reason?)
  s = (unsigned char *) PTR_ALIGN_DOWN (s, 4);

  unsigned int c0, c1, c2, c3;
  do
    {
      s += 4;  // Loop over 4 characters at a time (the first 4 bytes were checked before)
      c0 = p[s[0]];
      c1 = p[s[1]];
      c2 = p[s[2]];
      c3 = p[s[3]];
    }
  // break if any of c0, c1, c2, or c3 is nonzero,
  // i.e. if we've either found one of the characters in `reject`, or a zero
  while ((c0 | c1 | c2 | c3) == 0);

  size_t count = s - (unsigned char *) str;
  // figure out the actual offset based on which of c0..3 is set
  return (c0 | c1) != 0 ? count - c0 + 1 : count - c2 + 3;
}
```

答:
That loop is preceded by the line:

```<code>s = (unsigned char *) PTR_ALIGN_DOWN (s, 4);
</code>```

Which ensures that s is aligned to 4 bytes. The loop then reads 4 bytes at a time. This guarantees that even if it reads past the end of the string, the extra bytes read will still be within the same 4-byte word.

If you go strictly by the C standard, this results in undefined behavior. But glibc assumes that on the platforms it runs on, the page size is a multiple of 4 bytes, and that reading past the end of a buffer will not cause any issues as long as it's within the same page.

Body:
That loop is preceded by the line:

s = (unsigned char *) PTR_ALIGN_DOWN (s, 4);

Which ensures that s is aligned to 4 bytes. The loop then reads 4 bytes at a time. This guarantees that even if it reads past the end of the string, the extra bytes read will still be within the same 4-byte word.

If you go strictly by the C standard, this results in undefined behavior. But glibc assumes that on the platforms it runs on, the page size is a multiple of 4 bytes, and that reading past the end of a buffer will not cause any issues as long as it's within the same page.


问:
TeamCity dotCover report path for Sonar
I'm trying to integrate the sonar analysis into by TeamCity build process. I have a NUnit build step which runs my unit tests and then runs dotCover for the coverage.

My next step is the sonar-runner. The configuration that currently exists is; gallio.mode=dotCover, sonar.gallio.mode=reuseReport but I also need sonar.gallio.reports.path.

Does anybody know the path to the dotCover report generated in the the previous step?

答:
Below is what worked for me. I am on TC 2018.2.4 and the bundled version of the dotCover was not generating anything so I upgraded that to the latest version as well which is 2019.1.1

I could not make the agent use the latest version of the dotcover tools so I had to construct the folder path for that rather than using the default %teamcity.dotCover.home% variable.

I also did not want to use the temp folder as things were getting deleted there by the build.

```<code>$snapshot_file_list = Get-ChildItem "%system.teamcity.build.tempDir%" -recurse -Filter coverage_dotcover*.data | select -ExpandProperty FullName
Echo "dotCover Snapshot files"
Echo $snapshot_file_list
$joined_snapshot_files = $snapshot_file_list -join ";"
Echo "Merging data files to %system.teamcity.build.checkoutDir%\dotcovermerge.dcvr"
& "%teamcity.agent.tools.dir%\JetBrains.dotCover.CommandLineTools.2019.1.1\dotCover.exe" merge /Source=$joined_snapshot_files /Output="%system.teamcity.build.checkoutDir%\dotcovermerge.dcvr" /LogFile="%system.teamcity.build.checkoutDir%\dotCover.log"
Echo "Generating dotCover Html report"
Echo "%system.teamcity.build.checkoutDir%\%sonar.coverageReport%"
& "%teamcity.agent.tools.dir%\JetBrains.dotCover.CommandLineTools.2019.1.1\dotCover.exe" report /ReportType=HTML /Source="%system.teamcity.build.checkoutDir%\dotcovermerge.dcvr" /Output="%system.teamcity.build.checkoutDir%\%sonar.coverageReport%"
</code>```

Title: TeamCity dotCover report path for Sonar

Body:
Below is what worked for me. I am on TC 2018.2.4 and the bundled version of the dotCover was not generating anything so I upgraded that to the latest version as well which is 2019.1.1

I could not make the agent use the latest version of the dotcover tools so I had to construct the folder path for that rather than using the default %teamcity.dotCover.home% variable.

I also did not want to use the temp folder as things were getting deleted there by the build.

$snapshot_file_list = Get-ChildItem "%system.teamcity.build.tempDir%" -recurse -Filter coverage_dotcover*.data | select -ExpandProperty FullName
Echo "dotCover Snapshot files"
Echo $snapshot_file_list
$joined_snapshot_files = $snapshot_file_list -join ";"
Echo "Merging data files to %system.teamcity.build.checkoutDir%\dotcovermerge.dcvr"
& "%teamcity.agent.tools.dir%\JetBrains.dotCover.CommandLineTools.2019.1.1\dotCover.exe" merge /Source=$joined_snapshot_files /Output="%system.teamcity.build.checkoutDir%\dotcovermerge.dcvr" /LogFile="%system.teamcity.build.checkoutDir%\dotCover.log"
Echo "Generating dotCover Html report"
Echo "%system.teamcity.build.checkoutDir%\%sonar.coverageReport%"
& "%teamcity.agent.tools.dir%\JetBrains.dotCover.CommandLineTools.2019.1.1\dotCover.exe" report /ReportType=HTML /Source="%system.teamcity.build.checkoutDir%\dotcovermerge.dcvr" /Output="%system.teamcity.build.checkoutDir%\%sonar.coverageReport%"


问:
Android Login monitoring using Foreground service
I am trying to implement a login status monitoring in my application. What I am trying to achieve is calling an API in background service continuously. It will give a response depending on if the user is eligible to remain logged in. If the response states the user is not eligible to remain logged in, then the app should log out.

How I Implemented this

I created a foreground service and called the API inside an AsyncTask method. I called this method inside the service's onStartCommand() method.

My doubts

Is this the proper way to implement this work flow?.

I called the login activity from service like this

```<code>    Intent dialogIntent = new Intent(BluetoothLeService.this,SplashScreen.class);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(dialogIntent);
</code>```

How do I finish the Activity from the service?

EDIT- Why Iam trying this way

If a user's activation is removed manually from back end then according to this work flow app will sign out automatically.Basically my app is a BLE based alert system.So logout after certain time is not possible.The only situation for logout is if the back end (ie; the service providers) find that user is not eligible for using the service, they will change the mentioned API result is to false.Due to this scenario I calls the API all time.What will be a better workaround for this?

答:
You can achieve your task much easier than you can imagine. As for me I use tokens for authorization and further service usage. I think that call API in service will make your app to work slowly.

So, I use retrofit in my app development and I think that in your project you use this library or volley. And what about tokens? After successful login I receive two tokens: access_token+refresh_token. First token is used for getting ordinary info. And refresh_token is used for updating access_token. If your refresh_token will be expired you have to logout from your app. And don't try to send API request in background it is bad idea.

Main schema of using tokens: login -> getting two tokens (access+refresh) -> using access_token in ordinary request (get data from API or send smth) -> refresh tokens with using refresh_token

So, for example at my server I use 0,5 hour between token refreshing. Refresh_token won't be valid until your access_token will get expired.

For example article about this tokens.

handling error in okhttp:

```<code> private final OkHttpClient client = new OkHttpClient();

    public void run() throws Exception {
      Request request = new Request.Builder()
          .url("url_url_url")
          .build();

      client.newCall(request).enqueue(new Callback() {
        @Override public void onFailure(Call call, IOException e) {
          e.printStackTrace();
        }

        @Override public void onResponse(Call call, Response response) throws IOException {
          if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

          System.out.println(response.body().string());
        }
      });
    }
</code>```

UPDATE

So the last variant of solution: create class which will contain method with api call. You will call this method before every request. This method will return true/false. If false - you will logout from your app, if true - continue working with app. Good luck :)

Body:
I am trying to implement a login status monitoring in my application. What I am trying to achieve is calling an API in background service continuously. It will give a response depending on if the user is eligible to remain logged in. If the response states the user is not eligible to remain logged in, then the app should log out.

How I Implemented this

I created a foreground service and called the API inside an AsyncTask method. I called this method inside the service's onStartCommand() method.

My doubts

Is this the proper way to implement this work flow?.

I called the login activity from service like this

    Intent dialogIntent = new Intent(BluetoothLeService.this,SplashScreen.class);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(dialogIntent);

How do I finish the Activity from the service?

EDIT- Why Iam trying this way

If a user's activation is removed manually from back end then according to this work flow app will sign out automatically.Basically my app is a BLE based alert system.So logout after certain time is not possible.The only situation for logout is if the back end (ie; the service providers) find that user is not eligible for using the service, they will change the mentioned API result is to false.Due to this scenario I calls the API all time.What will be a better workaround for this?

Body:
You can achieve your task much easier than you can imagine. As for me I use tokens for authorization and further service usage. I think that call API in service will make your app to work slowly.

So, I use retrofit in my app development and I think that in your project you use this library or volley. And what about tokens? After successful login I receive two tokens: access_token+refresh_token. First token is used for getting ordinary info. And refresh_token is used for updating access_token. If your refresh_token will be expired you have to logout from your app. And don't try to send API request in background it is bad idea.

Main schema of using tokens: login -> getting two tokens (access+refresh) -> using access_token in ordinary request (get data from API or send smth) -> refresh tokens with using refresh_token

So, for example at my server I use 0,5 hour between token refreshing. Refresh_token won't be valid until your access_token will get expired.

For example article about this tokens.

handling error in okhttp:

 private final OkHttpClient client = new OkHttpClient();

    public void run() throws Exception {
      Request request = new Request.Builder()
          .url("url_url_url")
          .build();

      client.newCall(request).enqueue(new Callback() {
        @Override public void onFailure(Call call, IOException e) {
          e.printStackTrace();
        }

        @Override public void onResponse(Call call, Response response) throws IOException {
          if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

          System.out.println(response.body().string());
        }
      });
    }

UPDATE

So the last variant of solution: create class which will contain method with api call. You will call this method before every request. This method will return true/false. If false - you will logout from your app, if true - continue working with app. Good luck :)


问:
user Login web service required using prestashop api
I am working on prestashop web services for my android app, i searched a lot in google, but i did not find proper document/proper explanation. Can any one please guide me how to do user login/authentication using prestashop web services?.  </p>

答:
You can make a call to the customer endpoint filtering by the customer's email. The result would have a "passwd" field, which is a hashed password which could either be md5 or bcrypt since Prestashop supports both. You can then hash the customer's password input and compare with the "passwd" field in the response. If the length of the "passwd" field is 32 (md5), you'll need parameter _COOKIE_KEY_ set in /app/config/parameters.php as a salt to generate your hash;

Make the call like this https://yourprestashopurl.com/api/customers?filter[email]=email@email.com&display=full

For md5 (if passwd is 32 characters long):
$hash = md5(_COOKIE_KEY_ . $input_password);
You can then compare $hash with passwd

For bcrypt (if passwd is 60 characters long):
Option 1:
$verify = password_verify($input_password, passwd);
You can accept $input_password when this returns true, otherwise $input_password is invalid

Option 2:
$hash = password_hash($input_password, PASSWORD_BCRYPT);
You can then compare $hash with passwd

Note: password_hash and password_verify are both built-in php functions since PHP 5.5.0


问:
Query relation and group by in query builder
Getting a sql error in my query, i believe maybe is malformed my query builder but cant figure out what im doing wrong.

Alredy tried testing my query directlly in the DB and it works, but when translating with query builder it doesnt work.

```<code>$totalUserForCountry = DB::table('countries')
    ->select('countries.name', DB::raw('COUNT(users.country_id) as total'))
    ->join('users', 'users.country_id', '=', 'countries.id')
    ->groupBy('users.country_id')
    ->get();
</code>```

My error code is:

SQLSTATE[42000]: Syntax error or access violation: 1055 'db.countries.name' isn't in GROUP BY (SQL: select countries.name, COUNT(users.country_id) as total from countries

  inner join users on users.country_id = countries.id group by users.country_id)

Mysql query directlly to DB:

```<code>SELECT ct.name AS CountryName, COUNT(us.country_id) AS NumberOfUsers FROM countries AS ct
        INNER JOIN users AS us
        ON
        us.country_id = ct.id
        GROUP BY us.country_id;
</code>```

P.S. It only works if i disable 'strict' mode to false

答:
when using group by clause in sql query, the select clause can have only those columns which you have used in group clause.

the sql query for the above problem will be:

```<code>SELECT ct.name AS CountryName, COUNT(us.country_id) AS NumberOfUsers FROM countries AS ct
    INNER JOIN users AS us
    ON
    us.country_id = ct.id
    GROUP BY us.country_id,ct.name;
</code>```

Body:
Getting a sql error in my query, i believe maybe is malformed my query builder but cant figure out what im doing wrong.

Alredy tried testing my query directlly in the DB and it works, but when translating with query builder it doesnt work.

$totalUserForCountry = DB::table('countries')
    ->select('countries.name', DB::raw('COUNT(users.country_id) as total'))
    ->join('users', 'users.country_id', '=', 'countries.id')
    ->groupBy('users.country_id')
    ->get();

My error code is:

SQLSTATE[42000]: Syntax error or access violation: 1055 'db.countries.name' isn't in GROUP BY (SQL: select countries.name, COUNT(users.country_id) as total from countries

  inner join users on users.country_id = countries.id group by users.country_id)

Mysql query directlly to DB:

SELECT ct.name AS CountryName, COUNT(us.country_id) AS NumberOfUsers FROM countries AS ct
        INNER JOIN users AS us
        ON
        us.country_id = ct.id
        GROUP BY us.country_id;

P.S. It only works if i disable 'strict' mode to false

Body:
when using group by clause in sql query, the select clause can have only those columns which you have used in group clause.

the sql query for the above problem will be:

SELECT ct.name AS CountryName, COUNT(us.country_id) AS NumberOfUsers FROM countries AS ct
    INNER JOIN users AS us
    ON
    us.country_id = ct.id
    GROUP BY us.country_id,ct.name;


问:
Repeat a command while true or x times (equivalent of while/for loop)
I would like to repeat this command as many times as there is still sometextin the field note (several rows from the table itemNotes could have one or more sometext in the field note):

```<code>UPDATE itemNotes
SET
  note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
WHERE
  INSTR(LOWER(note), 'sometext') >= 0;
</code>```

So a proto-code would be :

```<code>While (SELECT * FROM itemNotes  WHERE note like "%sometext%") >1

    UPDATE itemNotes
    SET
      note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
    WHERE
      INSTR(LOWER(note), 'sometext') >= 0;
END
</code>```

But apparently Sqlite3 doesn't support While loop or for loop. They can be emulated with something like this but I have difficulties integrating what I want with this query:

```<code>    WITH b(x,y) AS
    (
        SELECT 1,2
        UNION ALL
        SELECT x+ 1, y + 1

    FROM b
    WHERE x < 20
) SELECT * FROM b;
</code>```

Any idea how to do this?

PS: I don't use replace because I want to replace all the case combinations of sometext (e.g. sometext, SOMEtext, SOmeText...) cf this question

Current input and desired output:

For a single row, a note field could look like (and many rows in the table itemNotescould look like this one):

```<code>There is SOmetext and also somETExt and more SOMETEXT and even more sometext
</code>```

The query should output:

```<code>There is abc and also abc and more abc and even more abc
</code>```

I am doing it on the zotero.sqlite, which is created by this file (line 85). The table is created by this query

```<code>CREATE TABLE itemNotes (
    itemID INTEGER PRIMARY KEY,
    parentItemID INT,
    note TEXT,
    title TEXT,
    FOREIGN KEY (itemID) REFERENCES items(itemID) ON DELETE CASCADE,
    FOREIGN KEY (parentItemID) REFERENCES items(itemID) ON DELETE CASCADE
);
</code>```

答:
You just have your answer in your query:

```<code>UPDATE itemNotes
SET
  note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
WHERE
  note LIKE "%sometext%";
</code>```

It will update all rows that contain sometext in the note field

UPDATE

If you want to update the field which has multiple occurrences in different cases and maintain the rest of the text the simplest solution imo is to use regex and for that you need an extension

```<code>UPDATE itemNotes
SET
  note = regex_replace('\bsometext\b',note,'abc')
WHERE
  note LIKE "%sometext%";
</code>```

Body:
I would like to repeat this command as many times as there is still sometextin the field note (several rows from the table itemNotes could have one or more sometext in the field note):

UPDATE itemNotes
SET
  note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
WHERE
  INSTR(LOWER(note), 'sometext') >= 0;

So a proto-code would be :

While (SELECT * FROM itemNotes  WHERE note like "%sometext%") >1

    UPDATE itemNotes
    SET
      note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
    WHERE
      INSTR(LOWER(note), 'sometext') >= 0;
END

But apparently Sqlite3 doesn't support While loop or for loop. They can be emulated with something like this but I have difficulties integrating what I want with this query:

    WITH b(x,y) AS
    (
        SELECT 1,2
        UNION ALL
        SELECT x+ 1, y + 1

    FROM b
    WHERE x < 20
) SELECT * FROM b;

Any idea how to do this?

PS: I don't use replace because I want to replace all the case combinations of sometext (e.g. sometext, SOMEtext, SOmeText...) cf this question

Current input and desired output:

For a single row, a note field could look like (and many rows in the table itemNotescould look like this one):

There is SOmetext and also somETExt and more SOMETEXT and even more sometext

The query should output:

There is abc and also abc and more abc and even more abc

I am doing it on the zotero.sqlite, which is created by this file (line 85). The table is created by this query

CREATE TABLE itemNotes (
    itemID INTEGER PRIMARY KEY,
    parentItemID INT,
    note TEXT,
    title TEXT,
    FOREIGN KEY (itemID) REFERENCES items(itemID) ON DELETE CASCADE,
    FOREIGN KEY (parentItemID) REFERENCES items(itemID) ON DELETE CASCADE
);

Body:
You just have your answer in your query:

UPDATE itemNotes
SET
  note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
WHERE
  note LIKE "%sometext%";

It will update all rows that contain sometext in the note field

UPDATE

If you want to update the field which has multiple occurrences in different cases and maintain the rest of the text the simplest solution imo is to use regex and for that you need an extension

UPDATE itemNotes
SET
  note = regex_replace('\bsometext\b',note,'abc')
WHERE
  note LIKE "%sometext%";


问:
Which Angular Material version should I install to be compatible with Angular4?
Which Angular Material version should I install to be compatible with Angular4?

I have used below command to install angular Material on the top of Angular 4 project.

```<code>npm install @angular/materail
npm install @angular/cdk
npm install @angular/animations
</code>```

While I try to run the app I am getting below error.

```<code>/node_modules/@angular/cdk/observers/typings/observe-content.d.ts (33,22): Type 'ElementRef' is not generic.
</code>```

答: You can choose a version between 2.0.0-beta.3 and 2.0.0-beta.12 depending on your minor angular version. Refer to package.json file in @angular/material repository to determine which one is more fittable to you.

Body:
Which Angular Material version should I install to be compatible with Angular4?

I have used below command to install angular Material on the top of Angular 4 project.

npm install @angular/materail
npm install @angular/cdk
npm install @angular/animations

While I try to run the app I am getting below error.

/node_modules/@angular/cdk/observers/typings/observe-content.d.ts (33,22): Type 'ElementRef' is not generic.


问:
How to automatically insert my new userId in all table related?
i have 4 tables
Customer table
Department table
shopping Table
planning Table
my question is :once i register the new user i want the same ID i to nsert inside all the tablse so that i can easily left join or etc with it
i had a look at foreign key but it does not do the job
im using mvc ( went from empty mvc using entity framework)
any help will be welcome.</p>

答:
you really need to look into EF first, and maybe include some code to your question. As far as I anderstood, you want something like this:</p>

```<code>using (var context = new MyDbContext())
{
  var user = new User(){Name = "test", ....};
  context.User.Add(user);
  context.SaveChanges();

  int id = user.Id; //you get the id after the insert in the db

 // here you can create new Customer, Department, Shopping Objects and insert it with the user id
}
</code>```

Body:
you really need to look into EF first, and maybe include some code to your question. As far as I anderstood, you want something like this:

using (var context = new MyDbContext())
{
  var user = new User(){Name = "test", ....};
  context.User.Add(user);
  context.SaveChanges();

  int id = user.Id; //you get the id after the insert in the db

 // here you can create new Customer, Department, Shopping Objects and insert it with the user id
}


问:
How to prevent PowerShell from showing a window (blink of an eye), when launching it as a scheduled task with -WindowStyle Hidden?
When launching PowerShell.exe as a scheduled task with the options -WindowStyle Hidden -NoProfile -Command <cmd>, the blue PowerShell window opens in the blink of an eye and then dissapears (runs as a background process).

How can I prevent the blue PowerShell window from appearing in a split second, which can lead to confusion for the end-user?

答:
On the General tab of the scheduled task, select "Run whether user is logged on or not" to ensure the task does not pop up a window.

To do the same thing in PowerShell, use -LogonType S4U for the task principal configuration. Example below:

```<code>$action = New-ScheduledTaskAction -Execute notepad.exe
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1)
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType S4U -RunLevel Highest

Register-ScheduledTask -TaskName "Test1337" -TaskPath "\" -Action $action -Trigger $trigger -Principal $principal
</code>```

Tested and confirmed on Windows Server 2016 build 1607 (and many other versions by way of previous deployments using this same method).

Body:
On the General tab of the scheduled task, select "Run whether user is logged on or not" to ensure the task does not pop up a window.

To do the same thing in PowerShell, use -LogonType S4U for the task principal configuration. Example below:

$action = New-ScheduledTaskAction -Execute notepad.exe
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1)
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType S4U -RunLevel Highest

Register-ScheduledTask -TaskName "Test1337" -TaskPath "\" -Action $action -Trigger $trigger -Principal $principal

Tested and confirmed on Windows Server 2016 build 1607 (and many other versions by way of previous deployments using this same method).


问:
Get first three bits from a byte
My question is simple, i need to convert the first three bits of a byte to a integer (Enum) value. However the things i try i always get a 0 back. This is wat the document says:

Bit 0-3: These bits indicate the connection state.

Value 0 to 14 indicate the connection state. Value 3 = Connected

Now the response i get (from a serial device) is a encoded byte stream of ASCII hex values, so i first need to convert it from a hex string to byte array and then get the bits from it. This is my code so far:

```<code>Dim strResonse As String = "0C03" 'This should result in a connection state value of 3

Dim ConState(2) As Byte
ConState = HexStringToByteArray(strResonse)
Dim int As Integer = ConState(1) << 1 And ConState(1) << 2 And ConState(1) << 3
Debug.Print(int.ToString)

Private Function HexStringToByteArray(ByVal shex As String) As Byte()
    Dim B As Byte() = Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
    Return Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
End Function
</code>```

答:
It would be easier to use bit operation

```<code>Dim connectionState As Integer
Dim response As Integer = &HC03

' Get the first 4 bits. 15 in binary is 1111
connectionState = response And 15
</code>```

If your input is really a string, there a built-in way to convert to integer.

```<code>Dim response As Integer = Convert.ToInt32("C03", 16)
</code>```

If you really want to get an array, I suggest you use the built in method.

```<code>Dim allBits As Byte() = BitConverter.GetBytes(response)
</code>```

There also the BitArray class that can be handy.

Title: Get first three bits from a byte

Body:
My question is simple, i need to convert the first three bits of a byte to a integer (Enum) value. However the things i try i always get a 0 back. This is wat the document says:

Bit 0-3: These bits indicate the connection state.

Value 0 to 14 indicate the connection state. Value 3 = Connected

Now the response i get (from a serial device) is a encoded byte stream of ASCII hex values, so i first need to convert it from a hex string to byte array and then get the bits from it. This is my code so far:

Dim strResonse As String = "0C03" 'This should result in a connection state value of 3

Dim ConState(2) As Byte
ConState = HexStringToByteArray(strResonse)
Dim int As Integer = ConState(1) << 1 And ConState(1) << 2 And ConState(1) << 3
Debug.Print(int.ToString)

Private Function HexStringToByteArray(ByVal shex As String) As Byte()
    Dim B As Byte() = Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
    Return Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
End Function

Body:
It would be easier to use bit operation

Dim connectionState As Integer
Dim response As Integer = &HC03

' Get the first 4 bits. 15 in binary is 1111
connectionState = response And 15

If your input is really a string, there a built-in way to convert to integer.

Dim response As Integer = Convert.ToInt32("C03", 16)

If you really want to get an array, I suggest you use the built in method.

Dim allBits As Byte() = BitConverter.GetBytes(response)

There also the BitArray class that can be handy.


问:
Angular RxJS: event emitted twice
I've coded two observables:

One for cathing form submit events:

```<code><form role="form" (ngSubmit)="search()">
   ...
</form>
</code>```

And search() is reached and emits:

```<code>private search(): void {
    this.searchClickSubject.next();
}
</code>```

In component constructor:

```<code>private searchClickSubject:Subject<void>;
private searchClick$:Observable<any>;

constructor() {
    this.searchClickSubject = new Subject<void>();
    this.searchClick$ = this.searchClickSubject.asObservable();
}
</code>```

As you can see I create an Observable from subject searchClickSubject using searchClickSubject.asObservable method on searchClick$.

From now on, I'm using this searchClick$ Observable in order to catch submit form.

After that, I'm creating another Observable:

```<code>    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: 10
        })
    );
</code>```

So, each time a Query is emitted I make requestm using custom pipeable functions:

```<code>    this.metrics$ = this.searchQuery$
        .pipe(
          pageLoading(),
          makeRequest(),
          loadedPage()
        );
</code>```

This is my ngOnInit():

```<code>public ngOnInit() {
    // Grab search button click event
    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: 10
        })
    );

    this.metrics$ = this.searchQuery$
        .pipe(
          //...
        );
}
</code>```

However, request is launched twice.

I create subscriptions using async pipeline:

```<code><div class="row" *ngIf="!(metrics$ | async)" style="margin: 1.54em;">

<div *ngIf="metrics$ | async; let metric;"...
</code>```

Any ideas?

答:
You have subscribed to metrics$ two times, instead of this you can use as syntax, as below

```<code><div *ngIf="metrics$ | async as metric; else loading">
   <!-- Statements when metrics data found  -->
</div>

<ng-template #loading>
   <!-- Loading stuff...  -->
  <div class="row" style="margin: 1.54em;">
</ng-template>
</code>```

Refer Handling observables with NgIf & Async Pipe for more details.

Title: Angular RxJS: event emitted twice

Body:
I've coded two observables:

One for cathing form submit events:

<form role="form" (ngSubmit)="search()">
   ...
</form>

And search() is reached and emits:

private search(): void {
    this.searchClickSubject.next();
}

In component constructor:

private searchClickSubject:Subject<void>;
private searchClick$:Observable<any>;

constructor() {
    this.searchClickSubject = new Subject<void>();
    this.searchClick$ = this.searchClickSubject.asObservable();
}

As you can see I create an Observable from subject searchClickSubject using searchClickSubject.asObservable method on searchClick$.

From now on, I'm using this searchClick$ Observable in order to catch submit form.

After that, I'm creating another Observable:

    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: 10
        })
    );

So, each time a Query is emitted I make requestm using custom pipeable functions:

    this.metrics$ = this.searchQuery$
        .pipe(
          pageLoading(),
          makeRequest(),
          loadedPage()
        );

This is my ngOnInit():

public ngOnInit() {
    // Grab search button click event
    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: 10
        })
    );

    this.metrics$ = this.searchQuery$
        .pipe(
          //...
        );
}

However, request is launched twice.

I create subscriptions using async pipeline:

<div *ngIf="metrics$ | async; let metric;"...

Any ideas?

Body:
You have subscribed to metrics$ two times, instead of this you can use as syntax, as below

<div *ngIf="metrics$ | async as metric; else loading">
   <!-- Statements when metrics data found  -->
</div>

<ng-template #loading>
   <!-- Loading stuff...  -->
  <div class="row" style="margin: 1.54em;">
</ng-template>

Refer Handling observables with NgIf & Async Pipe for more details.


问:
how to detect the android back click using JavaScript/reactjs?
I want to detect the android back click using JavaScript/react js in mobile web-view.

Current Code:

```<code>componentDidMount()  {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

 onDeviceReady() {
        // Register the event listener
        document.addEventListener("backbutton", onBackKeyDown, false);
    }

onBackKeyDown=()=>{
console.log("oBackKeyDown");}
</code>```

What I have Tried:

1) adding event listener like

```<code>document.addEventListener("backbutton", onBackKeyDown, false)
</code>```

2) Then This

```<code>window.addEventListener("hashchange", function(e) {
  // ...
})
</code>```

Nothing seems to be working.

I wanted console to print BackKeyDown but nothing is happening.

Question:

Is there was a to do this in pure JavaScript or in reactJS (without react native features like react navigation etc)?

Thanks.

答:
popstate listener will detect  back button pressed but it will also detect forward button pressed.

window.addEventListener("popstate", (e)=>{
    console.log("back button pressed);
})

Body:
I want to detect the android back click using JavaScript/react js in mobile web-view.

Current Code:

componentDidMount()  {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

 onDeviceReady() {
        // Register the event listener
        document.addEventListener("backbutton", onBackKeyDown, false);
    }

onBackKeyDown=()=>{
console.log("oBackKeyDown");}

What I have Tried:

1) adding event listener like

document.addEventListener("backbutton", onBackKeyDown, false)

2) Then This

window.addEventListener("hashchange", function(e) {
  // ...
})

Nothing seems to be working.

I wanted console to print BackKeyDown but nothing is happening.

Question:

Is there was a to do this in pure JavaScript or in reactJS (without react native features like react navigation etc)?

Thanks.


问:
Iteratively generate numeric values
I have a table, let's call it Foo, there is a field called Bar in the table, also, there is a field called LoremIpsum.

Bar is an nvarchar but I'm only interested in Bar values which are convertable to an integer number.

LoremIpsum is also a number.

I want to get the first n (value) numbers beginning with k from my Foo table where LoremIpsum has a specific value (LoremIpsum1) and (value) not in select Bar from Foo where LoremIpsum = LoremIpsum1

My input is: (LoremIpsum1, n, k)

where LoremIpsum1 is a particular value for LoremIpsum, n is the number of numbers to get and k is the offset.

My output should be a set of numbers which don't exist in the table as Bar values if LoremIpsum = LoremIpsum1. My current command:

```<code>WITH    q AS
        (
        SELECT convert(bigint, 50000) AS num
        UNION ALL
        SELECT  convert(bigint, num + 1)
        FROM    q
        )
SELECT  top 200 *
FROM    q
where convert(bigint, num) not in (select convert(bigint, Bar) from Foo where LoremIpsum = 68 and isnumeric(Bar + 'e0') = 1)
option (maxrecursion 365);
</code>```

This query doesn't always work, at a computer the problem was that an nvarchar couldn't be converted to a bigint, probably it was a problem with the settings, the other error occurs if the needed recursion is deeper than the given maxrecursion.

In this case n = 200, k = 50000, LoremIpsum1 = 68

The main problem is that this query is recursive and I would like to modify it to be an iterative query.

Any help is greatly appreciated.

Best regards,
Lajos Arpad.

答:
You can use a permanent number table that has enough numbers for your need instead of the recursive cte.

```<code>create table NumberTable(Num int primary key)
</code>```

You can use your recursive cte to populate the number table. Since it is just a one time thing the performance should not be that big deal and if it is you can have a look here.

```<code>WITH    q AS
        (
        SELECT 0 AS num
        UNION ALL
        SELECT  num + 1
        FROM    q
        )
insert into NumberTable(Num)
select top 10000 num
from q
option (maxrecursion 0)
</code>```

Use the number table in your query with the offset.

```<code>declare @n int = 200
declare @k int = 50000

SELECT  top (@n) num+@k
FROM    NumberTable
--where convert(bigint, num+k) not in (select ...
</code>```

Title: Iteratively generate numeric values

Body:
I have a table, let's call it Foo, there is a field called Bar in the table, also, there is a field called LoremIpsum.

Bar is an nvarchar but I'm only interested in Bar values which are convertable to an integer number.

LoremIpsum is also a number.

I want to get the first n (value) numbers beginning with k from my Foo table where LoremIpsum has a specific value (LoremIpsum1) and (value) not in select Bar from Foo where LoremIpsum = LoremIpsum1

My input is: (LoremIpsum1, n, k)

where LoremIpsum1 is a particular value for LoremIpsum, n is the number of numbers to get and k is the offset.

My output should be a set of numbers which don't exist in the table as Bar values if LoremIpsum = LoremIpsum1. My current command:

WITH    q AS
        (
        SELECT convert(bigint, 50000) AS num
        UNION ALL
        SELECT  convert(bigint, num + 1)
        FROM    q
        )
SELECT  top 200 *
FROM    q
where convert(bigint, num) not in (select convert(bigint, Bar) from Foo where LoremIpsum = 68 and isnumeric(Bar + 'e0') = 1)
option (maxrecursion 365);

This query doesn't always work, at a computer the problem was that an nvarchar couldn't be converted to a bigint, probably it was a problem with the settings, the other error occurs if the needed recursion is deeper than the given maxrecursion.

In this case n = 200, k = 50000, LoremIpsum1 = 68

The main problem is that this query is recursive and I would like to modify it to be an iterative query.

Any help is greatly appreciated.

Best regards,
Lajos Arpad.

Body:
You can use a permanent number table that has enough numbers for your need instead of the recursive cte.

create table NumberTable(Num int primary key)

You can use your recursive cte to populate the number table. Since it is just a one time thing the performance should not be that big deal and if it is you can have a look here.

WITH    q AS
        (
        SELECT 0 AS num
        UNION ALL
        SELECT  num + 1
        FROM    q
        )
insert into NumberTable(Num)
select top 10000 num
from q
option (maxrecursion 0)

Use the number table in your query with the offset.

declare @n int = 200
declare @k int = 50000

SELECT  top (@n) num+@k
FROM    NumberTable
--where convert(bigint, num+k) not in (select ...


问:
Use service workers with Webpack dev-server inside Docker container
I'm trying to use service workers inside a web app using Webpack and Docker.

Everything I made for the moment is working well (service worker, webpack config, worker registration...)

Actually my app is running inside a Docker container, in this container I can start my webpack build to create all my JS files.

But now I would like to be able to use webpack dev-server and HMR with my service worker.

To do that I used https://github.com/oliviertassinari/serviceworker-webpack-plugin that correctly made a reference of my service worker inside the manifest.json

Then when I access through my web browser to my application, every built assets are found except my worker.

I run my dev-server using (I use webpack-encore), inside my docker container

```<code>encore dev-server --hot --host 0.0.0.0 --port 8080
</code>```

To load my assets the browser request them on 0.0.0.0:8080 but my worker is registered from localhost:8000 so the request fail with 404 error because the worker is located 0.0.0.0:8080/sw.js instead localhost:8080/sw.js.

I would know if this was possible to fix this behavior and made my service worker working inside the webpack-dev-server on a docker container.

I know service workers are listening only their scope, in my case localhost:8000/* but the webpack-dev-server is 0.0.0.0:8080.

This is why I asking if this is possible to change this behavior to made it work, and if someone already had this problem.

Thanks

答:
You need to expose port 8000 from your Docker container as well as port 8080. You must expose multiple ports from your Docker container for multiple web services on different ports.

```<code>docker run -p 8080:8080 -p 8000:8000
</code>```

Official documentation

Body:
I'm trying to use service workers inside a web app using Webpack and Docker.

Everything I made for the moment is working well (service worker, webpack config, worker registration...)

Actually my app is running inside a Docker container, in this container I can start my webpack build to create all my JS files.

But now I would like to be able to use webpack dev-server and HMR with my service worker.

To do that I used https://github.com/oliviertassinari/serviceworker-webpack-plugin that correctly made a reference of my service worker inside the manifest.json

Then when I access through my web browser to my application, every built assets are found except my worker.

I run my dev-server using (I use webpack-encore), inside my docker container

encore dev-server --hot --host 0.0.0.0 --port 8080

To load my assets the browser request them on 0.0.0.0:8080 but my worker is registered from localhost:8000 so the request fail with 404 error because the worker is located 0.0.0.0:8080/sw.js instead localhost:8080/sw.js.

I would know if this was possible to fix this behavior and made my service worker working inside the webpack-dev-server on a docker container.

I know service workers are listening only their scope, in my case localhost:8000/* but the webpack-dev-server is 0.0.0.0:8080.

This is why I asking if this is possible to change this behavior to made it work, and if someone already had this problem.

Thanks

Body:
You need to expose port 8000 from your Docker container as well as port 8080. You must expose multiple ports from your Docker container for multiple web services on different ports.

docker run -p 8080:8080 -p 8000:8000

Official documentation


问:
JSON Schema Is it possible to use if/then/else which refer to outside property
I want to add conditionally required based on value of some other property.
'companyName' and 'companyAddress' should be required only if 'isInexperienced'
value is false.

Schema

```<code>{
  "type": "object",
  "properties": {
    "previous_employment_section": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "companyAddress": {
            "type": "string"
          },
          "companyName": {
            "type": "string"
          }
        },
        "if": {
          "#/properties/isInexperienced": {
            "const": false
          }
        },
        "then": {
          "required": [
            "companyName",
            "companyAddress"
          ]
        }
      }
    },
    "isInexperienced": {
      "type": "boolean"
    }
  }
}
</code>```

Data

```<code>{
  "previous_employment_section": [],
  "isInexperienced": true
}
</code>```

答:
I do not fully understand the intention of your original schema, but how about this one?</p>

```<code>{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "previous_employment_section": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "companyAddress": {
                        "type": "string"
                    },
                    "companyName": {
                        "type": "string"
                    }
                }
            }
        },
        "isInexperienced": {
            "type": "boolean"
        }
    },
    "if": {
        "properties": {
            "isInexperienced": {
                "const": false
            }
        }
    },
    "then": {
        "properties": {
            "previous_employment_section": {
                "items": {
                    "required": [
                        "companyName",
                        "companyAddress"
                    ]
                },
                "minItems": 1
            }
        }
    }
}
</code>```

Body:
I want to add conditionally required based on value of some other property.
'companyName' and 'companyAddress' should be required only if 'isInexperienced'
value is false.

Schema

{
  "type": "object",
  "properties": {
    "previous_employment_section": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "companyAddress": {
            "type": "string"
          },
          "companyName": {
            "type": "string"
          }
        },
        "if": {
          "#/properties/isInexperienced": {
            "const": false
          }
        },
        "then": {
          "required": [
            "companyName",
            "companyAddress"
          ]
        }
      }
    },
    "isInexperienced": {
      "type": "boolean"
    }
  }
}

Data

{
  "previous_employment_section": [],
  "isInexperienced": true
}

Body:
I do not fully understand the intention of your original schema, but how about this one?

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "previous_employment_section": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "companyAddress": {
                        "type": "string"
                    },
                    "companyName": {
                        "type": "string"
                    }
                }
            }
        },
        "isInexperienced": {
            "type": "boolean"
        }
    },
    "if": {
        "properties": {
            "isInexperienced": {
                "const": false
            }
        }
    },
    "then": {
        "properties": {
            "previous_employment_section": {
                "items": {
                    "required": [
                        "companyName",
                        "companyAddress"
                    ]
                },
                "minItems": 1
            }
        }
    }
}


问:
Efficiency of multiple require-ing of modules in node.js
To simplify, let's have an entry.js, which requires common.js (with very universal functions), and routines.js (which contains project-specific functions). routines.js too requires common.js.

I don't expect the above scenario to be a problem, but in general, are the multiple requires, by modules which require one another a bad practice and is there a better approach? I'm thinking requiring within the entry.js and passing over to functions. Or is this microoptimizing and multiple requires are no big deal?

答:
I don't imagine this being a big deal as Node caches each "require" for you as long as the resolved filename is exactly the same (in most instances it will be, however the node docs list some cases where it may not be)

I found this post to have a nice simple explanation of how the module/require system in node works.


问:
Javascript regex with variable, exact match and multiple matches
I am trying to create a RegExp with a specific variable, which matches the variable exactly and replaces all possible occurrences. I found some different answers here but they do not seem to work with my problem.

This is my code:

```<code>for(var translation in translations) {
  var regex = new RegExp("^" + translation + "$");
  htmlContent = htmlContent.replace(regex, translations[translation][lang]);
}
</code>```

"translations" is a JSON which looks like this:

```<code>{
"report_a_return-placeholder": {
    "de": "Rücksendung melden",
    "en": "Report a return",
    "nl": "rapporteer een terugkeer",
    "fi": "raportoi palautuksesta",
    "da": "rapportere et afkast",
    "no": "rapporter en retur",
    "sv": "rapportera en avkastning"
  }
}
</code>```

And I am replacing inside the html:

```<code><div id="Report_a_return">
    <span>report_a_return-placeholder</span>
</div>
</code>```

When I try creating the regex without the anchors, everything works fine and the regex replaces. However, I have some translations which start similarly so the regex replaced them even though it was not an exact match. That's why I need anchors. But when doing it like above, nothing is replaced!

Edit:

to clarify with a better example. I have the problem that e.g. "pay-placeholder" and "cofirm_and_pay-placeholder" both match "confirm_and_pay-placeholder". But I want "pay-placeholder" to only match "pay-placeholder" and "confirm_and_pay-placeholder" to match only that. That doesnt work rn. (if I just use newRexExp('pay-placeholder') this matches also the string "confirm_and_pay-placeholder")

答:
Your ^ character tells the regex that it should match from the beginning of the string and your $ tells to match to the end of the string.

That means your regex only works for a string like report_a_return-placeholder and nothing more. Remove both of the characters and everything will be fine.

I love using regex.com to check what is happening and get a full reference of regular expressions.

regexr.com example

This one could work for you as long as there is one translation string per tag.

```<code>var translations = {'pay_placeholder': 'FooBar'}
var translation = 'pay_placeholder'
var regex = new RegExp('(<\\w+>)(' + translation + ')(<\\/\\w+>)')

var match = '<span>pay_placeholder</span>'.replace(regex, (match, p1, p2, p3, offset, str ) => {
    return p1 + translations[p2] + p3
})

var didntMatch = '<span>confirm_and_pay_placeholder</span>'.replace(regex, (match, p1, p2, p3, offset, str ) => {
    return p1 + translations[p2] + p3
})

console.log(match, didntMatch)
</code>```

Body:
I am trying to create a RegExp with a specific variable, which matches the variable exactly and replaces all possible occurrences. I found some different answers here but they do not seem to work with my problem.

This is my code:

for(var translation in translations) {
  var regex = new RegExp("^" + translation + "$");
  htmlContent = htmlContent.replace(regex, translations[translation][lang]);
}

"translations" is a JSON which looks like this:

{
"report_a_return-placeholder": {
    "de": "Rücksendung melden",
    "en": "Report a return",
    "nl": "rapporteer een terugkeer",
    "fi": "raportoi palautuksesta",
    "da": "rapportere et afkast",
    "no": "rapporter en retur",
    "sv": "rapportera en avkastning"
  }
}

And I am replacing inside the html:

    report_a_return-placeholder

When I try creating the regex without the anchors, everything works fine and the regex replaces. However, I have some translations which start similarly so the regex replaced them even though it was not an exact match. That's why I need anchors. But when doing it like above, nothing is replaced!

Edit:

to clarify with a better example. I have the problem that e.g. "pay-placeholder" and "cofirm_and_pay-placeholder" both match "confirm_and_pay-placeholder". But I want "pay-placeholder" to only match "pay-placeholder" and "confirm_and_pay-placeholder" to match only that. That doesnt work rn. (if I just use newRexExp('pay-placeholder') this matches also the string "confirm_and_pay-placeholder")

Body:
Your ^ character tells the regex that it should match from the beginning of the string and your $ tells to match to the end of the string.

That means your regex only works for a string like report_a_return-placeholder and nothing more. Remove both of the characters and everything will be fine.

I love using regex.com to check what is happening and get a full reference of regular expressions.

regexr.com example

This one could work for you as long as there is one translation string per tag.

var translations = {'pay_placeholder': 'FooBar'}
var translation = 'pay_placeholder'
var regex = new RegExp('(<\\w+>)(' + translation + ')(<\\/\\w+>)')

var match = '<span>pay_placeholder</span>'.replace(regex, (match, p1, p2, p3, offset, str ) => {
    return p1 + translations[p2] + p3
})

var didntMatch = '<span>confirm_and_pay_placeholder</span>'.replace(regex, (match, p1, p2, p3, offset, str ) => {
    return p1 + translations[p2] + p3
})

console.log(match, didntMatch)


问:
Change default location of vimrc
In Vim, is it possible to change the default location of the user vimrc file, i.e., from $HOME/.vimrc to some other location ?</p>

答:
I feel like the simplest solution is to just have a single line in ~/.vimrc that loads the vimrc from the other location, i.e.:

```<code>source PATH/TO/OTHER/LOCATION/.vimrc
</code>```

Title: Change default location of vimrc

Body:
I feel like the simplest solution is to just have a single line in ~/.vimrc that loads the vimrc from the other location, i.e.:

source PATH/TO/OTHER/LOCATION/.vimrc


问:
how to save multiple ckeditor in php?
I have create a multiple ckeditor in php, it can display the panel of ckeditor correctly, but when I click update after adding something in it, it didn't save to the database.</p>

```<code><?php
if(isset($_POST["action"])&&($_POST["action"]=="update")){
$id = $_POST['id'];

$content = $_POST['content'];

$query_update = "UPDATE `correspond` SET content='$content' WHERE id='$id'";

mysql_query($query_update);

header("Location: correspond.php");
}
?>

<table>
<?php while($row_correspond_result=mysql_fetch_assoc($correspond_result)){ ?>
<tr class="table table-bordered table-striped"><form action="" method="POST" name="correspond_form" id="correspond_formJoin">
<tbody id="myTable">
<td colspan="3" align="center"><div contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?>        </div>
<script>
var elements = document.getElementsByClassName( 'myContent' );
for ( var i = 0; i < elements.length; ++i ) {
CKEDITOR.inline( elements[ i ], { /* config for this instance */ } );
}});
</script>
</td>
</tr><tr>
<td colspan="2"></td>
<td align="center">
<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update"></td>

</form></tr><?php }?> </tbody></table>
</code>```

答:
This div Converted to TextArea

From

```<code><div contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?>        </div>
</code>```

To

```<code><textarea contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?> </textarea>
</code>```

Title: how to save multiple ckeditor in php?

Body:
I have create a multiple ckeditor in php, it can display the panel of ckeditor correctly, but when I click update after adding something in it, it didn't save to the database.

<?php
if(isset($_POST["action"])&&($_POST["action"]=="update")){
$id = $_POST['id'];

$content = $_POST['content'];

$query_update = "UPDATE `correspond` SET content='$content' WHERE id='$id'";

mysql_query($query_update);

header("Location: correspond.php");
}
?>

<?php while($row_correspond_result=mysql_fetch_assoc($correspond_result)){ ?>

<form action="" method="POST" name="correspond_form" id="correspond_formJoin">

<?php echo $row_correspond_result["content"];?>

<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update">

</form>
<?php }?>

Body:
This div Converted to TextArea

From

<div contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?>        </div>

To

<textarea contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?> </textarea>


问:
Drupal - Mandatory CCK date and time field - Only date is mandatory
I have a CCK field of date and time. The widget type is 'Text Field with Date Pop-up calendar'. The field is mandatory.

The date works fine, but if you leave the time blank (hours and minutes), the node can be created and the time field reads '(All day)'. How can I make it mandatory to specify a time in hours and minutes?

Thanks

答: In the date settings you have granularity, I think selecting hours and minutes there might solve your problem.</p>

ContentLicense: CC BY-SA 2.5


问:
authentication to oauth fails on IIS
I use oauth authentication to add contacts to google Contacts api
when I deploy to iis I get this error:

Server Error in '/' Application. Access is denied Description: An
  unhandled exception occurred during the execution of the current web
  request. Please review the stack trace for more information about the
  error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: Access is
  denied

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Stack Trace:

```<code>[Win32Exception (0x80004005): Access is denied]
   System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo) +604
   System.Diagnostics.Process.Start(ProcessStartInfo startInfo) +60
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__16.MoveNext() +258

[NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=347204707806-a44e1b5q57mqr0bkvic9gd03ms52nk0c.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A54450%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth2%2Fcontacts%20https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds" for authorization. See inner exception for details.]
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__16.MoveNext() +832
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__8.MoveNext() +701
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__4.MoveNext() +572
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() +426

 string clientId = xxxxxxx.apps.googleusercontent.com";
            string clientSecret = "xxxxxxxxxxxxxxxxxx";

        string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts" };     // view your basic profile info.

        // Use the current Google .net client library to get the Oauth2 stuff.
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                , scopes
                                                                                , "teste"
                                                                            , CancellationToken.None
                                                                                , new FileDataStore(Server.MapPath("/") + "Datastore", true)).Result;
        try
        {
            // Translate the Oauth permissions to something the old client libray can read
            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.AccessToken = credential.Token.AccessToken;
            parameters.RefreshToken = credential.Token.RefreshToken;

            RequestSettings settings = new RequestSettings("contacts-241820", parameters);
            ContactsRequest cr = new ContactsRequest(settings);
            if (User.Identity.IsAuthenticated)

                CreateContact(cr);
</code>```

答:
Ok, looking at your code, looks like the code you are running is based on .NET Core, and I think you have to be sure that for running the app on IIS, you need to be sure that you have IIS ANCM installed.

See also https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/aspnet-core-module?view=aspnetcore-2.2

Title: authentication to oauth fails on IIS

Body:
I use oauth authentication to add contacts to google Contacts api
when I deploy to iis I get this error:

Server Error in '/' Application. Access is denied Description: An
  unhandled exception occurred during the execution of the current web
  request. Please review the stack trace for more information about the
  error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: Access is
  denied

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Stack Trace:

[Win32Exception (0x80004005): Access is denied]
   System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo) +604
   System.Diagnostics.Process.Start(ProcessStartInfo startInfo) +60
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__16.MoveNext() +258

[NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=347204707806-a44e1b5q57mqr0bkvic9gd03ms52nk0c.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A54450%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth2%2Fcontacts%20https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds" for authorization. See inner exception for details.]
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__16.MoveNext() +832
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__8.MoveNext() +701
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__4.MoveNext() +572
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() +426

 string clientId = xxxxxxx.apps.googleusercontent.com";
            string clientSecret = "xxxxxxxxxxxxxxxxxx";

        string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts" };     // view your basic profile info.

        // Use the current Google .net client library to get the Oauth2 stuff.
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                , scopes
                                                                                , "teste"
                                                                            , CancellationToken.None
                                                                                , new FileDataStore(Server.MapPath("/") + "Datastore", true)).Result;
        try
        {
            // Translate the Oauth permissions to something the old client libray can read
            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.AccessToken = credential.Token.AccessToken;
            parameters.RefreshToken = credential.Token.RefreshToken;

            RequestSettings settings = new RequestSettings("contacts-241820", parameters);
            ContactsRequest cr = new ContactsRequest(settings);
            if (User.Identity.IsAuthenticated)

                CreateContact(cr);