问:
How to prevent form submission until onsubmit function completes?
For my onsubmit function, I have a function that requests for user's location and adds their location to the input values of my form.
However, when the user clicks on the submit button and a pop-up appears and asks the user to allow the browser to know their location, my form always submits before the user could answer the pop-up. This leaves the function incompleted and the input values become undefined.

I have tried adding a "return true;" statement until my onsubmit function ends, but the form still gets submitted prior. I have also tried adding  "e.preventDefault();" before my function completes. None of the methods worked so far...

My form:

<form action="/login" onsubmit="getLocation()" method="POST">
    <button type="submit" class="btn btn-dark">Login</button>
    <input id="currentUserLattitude" type=hidden name="currentLocation" value="placeholder">
    <input id="currentUserLongitude" type=hidden name="currentLocation" value="placeholder">
</form>
```

<p>The onsubmit function:  </p>

```function getLocation(e) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
        return true;
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function onGeoSuccess(position) {
    document.getElementById("currentUserLattitude").value = position.coords.latitude;
    document.getElementById("currentUserLongitude").value = position.coords.longitude;
}

function onGeoError(err) {
    alert("Error code " + err.code + ". " + err.message);
}
```

答:
Use an id and event listener, prevent default on submit, wrap your function in a promise, and only submit if the result is true:

function getLocation(e) {
  // Create new promise
  return new Promise(resolve => {
    if (navigator.geolocation) {
      // Since getCurrentPosition is asynchronous, resolve in the onsuccess callback.
      navigator.geolocation.getCurrentPosition(
        position => {
          onGeoSuccess(position);
          // Resolving here will return back to the .then()
          resolve();
        },
        error => {
          onGeoError(error);
          resolve();
        }
      );
    } else {
      alert("Geolocation is not supported by this browser.");
      // Return to the .then()
      resolve();
    }
  });
}

function onGeoSuccess(position) {
  document.getElementById("currentUserLattitude").value =
    position.coords.latitude;
  document.getElementById("currentUserLongitude").value =
    position.coords.longitude;
}

function onGeoError(err) {
  alert("Error code " + err.code + ". " + err.message);
}

document.getElementById("form").addEventListener("submit", e => {
  // Prevent submission
  e.preventDefault();
  // Call your function and wait for a response
  getLocation().then(() => {
    // Submit the form
    return e.target.submit();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form" action="/login" onsubmit="getLocation()" method="POST">

  <button type="submit" class="btn btn-dark">Login</button>
  <input id="currentUserLattitude" type=hidden name="currentLocation" value="placeholder">
  <input id="currentUserLongitude" type=hidden name="currentLocation" value="placeholder">

</form></code>```

Body:
For my onsubmit function, I have a function that requests for user's location and adds their location to the input values of my form.
However, when the user clicks on the submit button and a pop-up appears and asks the user to allow the browser to know their location, my form always submits before the user could answer the pop-up. This leaves the function incompleted and the input values become undefined.

I have tried adding a "return true;" statement until my onsubmit function ends, but the form still gets submitted prior. I have also tried adding  "e.preventDefault();" before my function completes. None of the methods worked so far...

My form:

<form action="/login" onsubmit="getLocation()" method="POST">
    <button type="submit" class="btn btn-dark">Login</button>
    <input id="currentUserLattitude" type=hidden name="currentLocation" value="placeholder">
    <input id="currentUserLongitude" type=hidden name="currentLocation" value="placeholder">
</form>

The onsubmit function:

function getLocation(e) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
        return true;
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function onGeoSuccess(position) {
    document.getElementById("currentUserLattitude").value = position.coords.latitude;
    document.getElementById("currentUserLongitude").value = position.coords.longitude;
}

function onGeoError(err) {
    alert("Error code " + err.code + ". " + err.message);
}

Body:
Use an id and event listener, prevent default on submit, wrap your function in a promise, and only submit if the result is true:

function getLocation(e) {
  // Create new promise
  return new Promise(resolve => {
    if (navigator.geolocation) {
      // Since getCurrentPosition is asynchronous, resolve in the onsuccess callback.
      navigator.geolocation.getCurrentPosition(
        position => {
          onGeoSuccess(position);
          // Resolving here will return back to the .then()
          resolve();
        },
        error => {
          onGeoError(error);
          resolve();
        }
      );
    } else {
      alert("Geolocation is not supported by this browser.");
      // Return to the .then()
      resolve();
    }
  });
}

function onGeoSuccess(position) {
  document.getElementById("currentUserLattitude").value =
    position.coords.latitude;
  document.getElementById("currentUserLongitude").value =
    position.coords.longitude;
}

function onGeoError(err) {
  alert("Error code " + err.code + ". " + err.message);
}

document.getElementById("form").addEventListener("submit", e => {
  // Prevent submission
  e.preventDefault();
  // Call your function and wait for a response
  getLocation().then(() => {
    // Submit the form
    return e.target.submit();
  });
});

<form id="form" action="/login" onsubmit="getLocation()" method="POST">

  <button type="submit" class="btn btn-dark">Login</button>
  <input id="currentUserLattitude" type=hidden name="currentLocation" value="placeholder">
  <input id="currentUserLongitude" type=hidden name="currentLocation" value="placeholder">

</form>


来源: stackexchange

问:
Query to find accounts with specified months
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

```<code>SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH
</code>```

I am still getting account ids which where in JULY

答:
Your date formats look like Oracle, so I will answer for that database.

The idea is to use conditional aggregation:

```<code>SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH >= DATE '2018-05-01' AND
      DATA_MONTH < DATE '2018-08-01'
GROUP BY ACCOUNT_ID
HAVING COUNT(DISTINCT DATA_MONTH) = 2 AND
       MAX(DATA_MONTH) < DATE '2018-07-01';
</code>```

This assumes that all your dates are on the first of the month.

ContentLicense: CC BY-SA 4.0

Body:
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH

I am still getting account ids which where in JULY

Body:
Your date formats look like Oracle, so I will answer for that database.

The idea is to use conditional aggregation:

SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH >= DATE '2018-05-01' AND
      DATA_MONTH < DATE '2018-08-01'
GROUP BY ACCOUNT_ID
HAVING COUNT(DISTINCT DATA_MONTH) = 2 AND
       MAX(DATA_MONTH) < DATE '2018-07-01';

This assumes that all your dates are on the first of the month.


问:
Z3 v4.1 does not accept negative integers as input
I have installed Z3 version 4.1 and I attempt to use it programmatically in a java application. My application is communicating with the Z3 via ProcessBuilder. The version of Z3 is verified as 4.1 by using the /version command line argument.

However, Z3 does not accept negative constants as part of expressions. When I attempt to provide a negative integers I get the following message:

```<code>(error "line 4 column 31: unknown constant -1")
</code>```

This is the input I provide to Z3:

```<code>(push)
(declare-fun y () Int )
(define-fun x () Int y )
(assert (and (<= y 1000) (>= y -1) ) )
(assert (= x 42) )
(check-sat)
(pop)
</code>```

I am using the following arguments to instantiate the Z3:

```<code>Z3 /smt2 /in /t:2
</code>```

Any help is appreciated. Thank you in advance.

答: Try (- 1). See bottom of page 38 in http://smtlib.cs.uiowa.edu/papers/smt-lib-reference-v2.6-r2017-07-18.pdf

Body:
I have installed Z3 version 4.1 and I attempt to use it programmatically in a java application. My application is communicating with the Z3 via ProcessBuilder. The version of Z3 is verified as 4.1 by using the /version command line argument.

However, Z3 does not accept negative constants as part of expressions. When I attempt to provide a negative integers I get the following message:

(error "line 4 column 31: unknown constant -1")

This is the input I provide to Z3:

(push)
(declare-fun y () Int )
(define-fun x () Int y )
(assert (and (<= y 1000) (>= y -1) ) )
(assert (= x 42) )
(check-sat)
(pop)

I am using the following arguments to instantiate the Z3:

Z3 /smt2 /in /t:2

Any help is appreciated. Thank you in advance.


问:
Java thread per connection model vs NIO
Is the non-blocking Java NIO still slower than your standard thread per connection asynchronous socket?

In addition, if you were to use threads per connection, would you just create new threads or would you use a very large thread pool?

I'm writing an MMORPG server in Java that should be able to scale 10000 clients easily given powerful enough hardware, although the maximum amount of clients is 24000 (which I believe is impossible to reach for the thread per connection model because of a 15000 thread limit in Java).
From a three year old article, I've heard that blocking IO with a thread per connection model was still 25% faster than NIO (namely, this document http://www.mailinator.com/tymaPaulMultithreaded.pdf), but can the same still be achieved on this day? Java has changed a lot since then, and I've heard that the results were questionable when comparing real life scenarios because the VM used was not Sun Java.
Also, because it is an MMORPG server with many concurrent users interacting with each other, will the use of synchronization and thread safety practices decrease performance to the point where a single threaded NIO selector serving 10000 clients will be faster? (all the work doesn't necessary have to be processed on the thread with the selector, it can be processed on worker threads like how MINA/Netty works).

Thanks!

答:
If you do client side network calls, most likely you just need plain socket io.

If you are creating server side technologies, then NIO would help you in separating the network io part from fulfillment/processing work.
  IO threads configured as 1 or 2 for network IO. Worker threads are for actual processing part(which ranges from 1 to N, based on machine capabilities).

ContentLicense: CC BY-SA 2.5

Title: Java thread per connection model vs NIO


问:
How can I keep Wordpress from stripping out my
 and
 tags?
Wordpress strips out
 and
 tags when switching between the visual and the text editors. Well, to be specific, it doesn't actually strip them out of the content, but it does not display them in the text editor view. Is there a way to stop it from hiding those tags?

I know about the tinymce advanced plugin, but is there a way to stop this behavior on a per-post/per-page basis without having to install the plugin?

答: If the post is custom post type, you can add meta box with add_meta_box and there you can initialize your own editor with wp_editor which can be customized. For example you can pass settings to the tinymce like force_p_newslines which should force every new line to start with new paragraph

ContentLicense: CC BY-SA 3.0

Title: How can I keep Wordpress from stripping out my <p> and <br> tags?


问:
My request in ajax with PUT method is returning error 500
I'm trying to use Ajax's put method to update my table, which is stored on a rest server but I'm getting 500 error (intenal server error), I do not know what to do, can anyone help me? I'm new to ajax programming </p>

```<code>$(document).on('click', "#modalgravar", function(){

var eURL = 'http://localhost:8081/datasnap/rest/TCadastros/Grupo/';
    var Ecdgrupo = $("#Cdgrupoedit").val();
    var Egrupo = $("#grupoedit").val();
    var eData ={"Cdgrupo": Ecdgrupo, "Grupos": Egrupo};

alert(JSON.stringify(eData));

    $.ajax({
       type:'PUT',
       url: eURL,
       data: JSON.stringify(eData),
        success: function(){
        alert("Editado!");
              },
        error: function(){
            alert("ERRO:  O grupo não foi editado!");
        }
    });
</code>```

答: Problem solved! The problem was that there were missing headers on the server, so I was having trouble with cors.</p>

Body:
I'm trying to use Ajax's put method to update my table, which is stored on a rest server but I'm getting 500 error (intenal server error), I do not know what to do, can anyone help me? I'm new to ajax programming

$(document).on('click', "#modalgravar", function(){

var eURL = 'http://localhost:8081/datasnap/rest/TCadastros/Grupo/';
    var Ecdgrupo = $("#Cdgrupoedit").val();
    var Egrupo = $("#grupoedit").val();
    var eData ={"Cdgrupo": Ecdgrupo, "Grupos": Egrupo};

alert(JSON.stringify(eData));

    $.ajax({
       type:'PUT',
       url: eURL,
       data: JSON.stringify(eData),
        success: function(){
        alert("Editado!");
              },
        error: function(){
            alert("ERRO:  O grupo não foi editado!");
        }
    });


问:
Vertical align using Material UI Paper
I want to vertically align some text in a Material UI Paper component.

The code is here.

```<code>import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(3, 2),
    height: 200,
    verticalAlign: 'middle'
  },
}));

function PaperSheet() {
  const classes = useStyles();

  return (
    <div>
      <Paper className={classes.root}>
        <Typography variant="h5" component="h3">
          This is a sheet of paper.
        </Typography>
        <Typography component="p">
          Paper can be used to build surface or other elements for your application.
        </Typography>
      </Paper>
    </div>
  );
}

export default PaperSheet;
</code>```

答:
vertical-align CSS property only works with display: block element.

An option for you could be to declare your root class using flexbox:

```<code>const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(3, 2),
    height: 200,
    display: "flex",
    flexDirection: "column",
    justifyContent: "center"
  },
}));
</code>```

Title: Vertical align using Material UI Paper

Body:
I want to vertically align some text in a Material UI Paper component.

The code is here.

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(3, 2),
    height: 200,
    verticalAlign: 'middle'
  },
}));

function PaperSheet() {
  const classes = useStyles();

  return (

      <Paper className={classes.root}>
        <Typography variant="h5" component="h3">
          This is a sheet of paper.
        </Typography>
        <Typography component="p">
          Paper can be used to build surface or other elements for your application.
        </Typography>
      </Paper>

  );
}

export default PaperSheet;

Body:
vertical-align CSS property only works with display: block element.

An option for you could be to declare your root class using flexbox:

const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(3, 2),
    height: 200,
    display: "flex",
    flexDirection: "column",
    justifyContent: "center"
  },
}));


答:
You can re-cast your non-linear constraint as two linear ones and include both in sureg:

```<code>sysuse auto.dta, clear

constraint 1 [Eq1]mpg = [Eq1]headroom
constraint 2 [Eq2]headroom = [Eq2]length

sureg (Eq1: price = mpg trunk weight rep78 headroom) (Eq2: price = headroom length), ///
      corr constraint(1 2)
</code>```

You can then test if the constraint is satisfied as follows:

```<code>assert _b[Eq1:mpg] * _b[Eq2:headroom] == _b[Eq1:headroom] * _b[Eq2:length]
</code>```

Title: Non-linear constraint in a system of linear equations

Body:
I am trying to estimate a system of simultaneous labor supply within couples (called eq1 for women and eq2 for men) with the sureg command in Stata 14 for Windows.

When I try to add a linear constraint the regression works. However, I need to impose a non-linear constraint on four coefficients but as soon as I add this, I get the following error message:

the constraint caused an error

Below you can find a reproducible example:

sysuse auto.dta

constraint 1 [Eq1]mpg*[Eq2]headroom = [Eq1]headroom*[Eq2]length

sureg (Eq1: price = mpg trunk weight rep78 headroom) ///
      (Eq2 : price = headroom length), ///
      corr constraint(1)

(note: constraint number 1 caused error r(131))
(note: constraint number 1 caused error r(131))

Seemingly unrelated regression
--------------------------------------------------------------------------
Equation             Obs   Parms        RMSE    "R-sq"       chi2        P
--------------------------------------------------------------------------
Eq1                   69       5    2392.918    0.3150      29.32   0.0000
Eq2                   69       2    2581.831    0.2026      18.01   0.0001
--------------------------------------------------------------------------

------------------------------------------------------------------------------
             |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
Eq1          |
         mpg |  -26.58347   29.65312    -0.90   0.370    -84.70252    31.53558
       trunk |   31.52432   38.05785     0.83   0.407    -43.06769    106.1163
      weight |   1.363126   .3241408     4.21   0.000     .7278219     1.99843
       rep78 |    171.411   113.7883     1.51   0.132    -51.60992     394.432
    headroom |  -377.2506   360.8804    -1.05   0.296    -1084.563     330.062
       _cons |   2687.868   1603.852     1.68   0.094    -455.6242    5831.361
-------------+----------------------------------------------------------------
Eq2          |
    headroom |  -325.9389   402.3103    -0.81   0.418    -1114.453    462.5749
      length |   50.51478   12.27884     4.11   0.000      26.4487    74.58087
       _cons |  -2387.561   2125.435    -1.12   0.261    -6553.338    1778.215
------------------------------------------------------------------------------

Correlation matrix of residuals:

        Eq1     Eq2
Eq1  1.0000
Eq2  0.9292  1.0000

Breusch-Pagan test of independence: chi2(1) =    59.574, Pr = 0.0000

When using my real data, I get the same error. This makes it impossible to implement a non-linear constraint in the sureg estimation, which I really need to impose in my model.

Body:
You can re-cast your non-linear constraint as two linear ones and include both in sureg:

sysuse auto.dta, clear

constraint 1 [Eq1]mpg = [Eq1]headroom
constraint 2 [Eq2]headroom = [Eq2]length

sureg (Eq1: price = mpg trunk weight rep78 headroom) (Eq2: price = headroom length), ///
      corr constraint(1 2)

You can then test if the constraint is satisfied as follows:

assert _b[Eq1:mpg] * _b[Eq2:headroom] == _b[Eq1:headroom] * _b[Eq2:length]


问:
Syntax error in SiddhiQL, no viable alternative at input '@sink'
I'm trying to send a synchronous request using http-request (source) and http-response (sink) in Siddhi based on an example here.

I have an API, which I'm able to hit using a curl command. This is my curl command and the output.

```<code>curl http://localhost/parser/ -d '{"q":"test input", "project":"sample_project","model":"sample_model"}'
{
  "intent": {
    "name": "Cat A",
    "confidence": 0.7
  },
  "entities": [],
  "intent_ranking": [
    {
      "name": "Cat A",
      "confidence": 0.7
    },
    {
      "name": "Cat B",
      "confidence": 0.6
    },
    {
      "name": "Cat C",
      "confidence": 0.01
  ],
  "text": "test input",
  "project": "sample_project",
  "model": "sample_model"
}
</code>```

I'm trying to do something similar using Siddhi.

This is my code.

```<code>@source(type='http-request', source.id='StreamSource', receiver.url='http://localhost/parser', connection.timeout='150000', @map(type='json', @attributes(messageId='trp:messageId')))
define stream SourceStream (messageId string, text string, project string, model string);

@sink(type='http-response', source.id='StreamSource', message.id='{{messageId}}', @map(type='json', @payload('{{results}}')) define stream SinkStream (messageId string, results String);
</code>```

The error I'm getting in the @sink line is that:

```<code>Syntax error in SiddhiQL, no viable alternative at input ';\r\n\r\n@sink(type='http-response', source.id='StockStreamSource', message.id='{{messageId}}', @map(type='json', @payload('{{results}}')) define'. no viable alternative at input ';\r\n\r\n@sink(type='http-response', source.id='StockStreamSource', message.id='{{messageId}}', @map(type='json', @payload('{{results}}')) define'
</code>```

Is there something I'm missing here?

答:
You are missing parentheses at the end of your sink definition. Below is the fixed definition

```<code>@sink(type='http-response', source.id='StreamSource', message.id='{{messageId}}', @map(type='json', @payload('{{results}}')))
define stream SinkStream (messageId string, results String);
</code>```

You will face issues after this also as you have only mapped messagedID attribute in your input mapping. ie

```<code>@map(type='json', @attributes(messageId='trp:messageId'))
</code>```

Please map other attributes as well there.

Body:
I'm trying to send a synchronous request using http-request (source) and http-response (sink) in Siddhi based on an example here.

I have an API, which I'm able to hit using a curl command. This is my curl command and the output.

curl http://localhost/parser/ -d '{"q":"test input", "project":"sample_project","model":"sample_model"}'
{
  "intent": {
    "name": "Cat A",
    "confidence": 0.7
  },
  "entities": [],
  "intent_ranking": [
    {
      "name": "Cat A",
      "confidence": 0.7
    },
    {
      "name": "Cat B",
      "confidence": 0.6
    },
    {
      "name": "Cat C",
      "confidence": 0.01
  ],
  "text": "test input",
  "project": "sample_project",
  "model": "sample_model"
}

I'm trying to do something similar using Siddhi.

This is my code.

@source(type='http-request', source.id='StreamSource', receiver.url='http://localhost/parser', connection.timeout='150000', @map(type='json', @attributes(messageId='trp:messageId')))
define stream SourceStream (messageId string, text string, project string, model string);

@sink(type='http-response', source.id='StreamSource', message.id='{{messageId}}', @map(type='json', @payload('{{results}}')) define stream SinkStream (messageId string, results String);

The error I'm getting in the @sink line is that:

Syntax error in SiddhiQL, no viable alternative at input ';\r\n\r\n@sink(type='http-response', source.id='StockStreamSource', message.id='{{messageId}}', @map(type='json', @payload('{{results}}')) define'. no viable alternative at input ';\r\n\r\n@sink(type='http-response', source.id='StockStreamSource', message.id='{{messageId}}', @map(type='json', @payload('{{results}}')) define'

Is there something I'm missing here?

Body:
You are missing parentheses at the end of your sink definition. Below is the fixed definition

@sink(type='http-response', source.id='StreamSource', message.id='{{messageId}}', @map(type='json', @payload('{{results}}')))
define stream SinkStream (messageId string, results String);

You will face issues after this also as you have only mapped messagedID attribute in your input mapping. ie

@map(type='json', @attributes(messageId='trp:messageId'))

Please map other attributes as well there.


问:
Create flag indicating if year variable is in the range of start:end variables in data.table
I have a data.table with 3 date variables: year, start, end.

```<code>test <- data.table(year=2001:2003,start=c(2003,2002,2000),end=c(2003,2004,2002),x_desired=c(F,T,F))
</code>```

O want to create a new variable x, indicating, for each row, if year is in the range defined by start and end. The correct desired result is in the variable x_desired.

I imagined this could be done with:

```<code>test[,x:=(year %in% start:end)]
</code>```

but the result is clearly not correct. I wanted the ranges to be defined row-by-row, but don't know how to express that.

答:
another way

set(DT, NULL, "x", between(DT$year, DT$start, DT$end))
```

<p>benchmark</p>

<pre class="lang-r prettyprint-override"><code>library(data.table)
setDTthreads(40L)
n = 1e9
set.seed(123)
DT = data.table(year =sample( 2001:2003, n, replace = TRUE),
                start=sample( c(2003,2002,2000), n, replace = TRUE),
                end  =sample( c(2003,2004,2002), n, replace = TRUE) )
d = copy(DT)

system.time({DT[, x := FALSE ]; DT[ year %between% list(start,end), x := TRUE]})
system.time(set(d, NULL, "x", between(DT$year, DT$start, DT$end)))

all.equal(d, DT)
</code>```

timings

```<code>1e6

> system.time({DT[, x := FALSE ]; DT[ year %between% list(start,end), x := TRUE]})
   user  system elapsed
  0.433   0.056   0.053
> system.time(set(d, NULL, "x", between(DT$year, DT$start, DT$end)))
   user  system elapsed
  0.152   0.000   0.025

1e8

> system.time({DT[, x := FALSE ]; DT[ year %between% list(start,end), x := TRUE]})
   user  system elapsed
  3.811   1.889   3.061
> system.time(set(d, NULL, "x", between(DT$year, DT$start, DT$end)))
   user  system elapsed
  2.650   1.112   2.132

1e9

> system.time({DT[, x := FALSE ]; DT[ year %between% list(start,end), x := TRUE]})
   user  system elapsed
 32.073  32.600  27.347
> system.time(set(d, NULL, "x", between(DT$year, DT$start, DT$end)))
   user  system elapsed
 21.798   8.517  18.248
</code>```

Body:
I have a data.table with 3 date variables: year, start, end.

test <- data.table(year=2001:2003,start=c(2003,2002,2000),end=c(2003,2004,2002),x_desired=c(F,T,F))

O want to create a new variable x, indicating, for each row, if year is in the range defined by start and end. The correct desired result is in the variable x_desired.

I imagined this could be done with:

test[,x:=(year %in% start:end)]

but the result is clearly not correct. I wanted the ranges to be defined row-by-row, but don't know how to express that.

Body:
another way

set(DT, NULL, "x", between(DT$year, DT$start, DT$end))

benchmark

library(data.table)
setDTthreads(40L)
n = 1e9
set.seed(123)
DT = data.table(year =sample( 2001:2003, n, replace = TRUE),
                start=sample( c(2003,2002,2000), n, replace = TRUE),
                end  =sample( c(2003,2004,2002), n, replace = TRUE) )
d = copy(DT)

system.time({DT[, x := FALSE ]; DT[ year %between% list(start,end), x := TRUE]})
system.time(set(d, NULL, "x", between(DT$year, DT$start, DT$end)))

all.equal(d, DT)

timings

1e6

> system.time({DT[, x := FALSE ]; DT[ year %between% list(start,end), x := TRUE]})
   user  system elapsed
  0.433   0.056   0.053
> system.time(set(d, NULL, "x", between(DT$year, DT$start, DT$end)))
   user  system elapsed
  0.152   0.000   0.025

1e8

> system.time({DT[, x := FALSE ]; DT[ year %between% list(start,end), x := TRUE]})
   user  system elapsed
  3.811   1.889   3.061
> system.time(set(d, NULL, "x", between(DT$year, DT$start, DT$end)))
   user  system elapsed
  2.650   1.112   2.132

1e9

> system.time({DT[, x := FALSE ]; DT[ year %between% list(start,end), x := TRUE]})
   user  system elapsed
 32.073  32.600  27.347
> system.time(set(d, NULL, "x", between(DT$year, DT$start, DT$end)))
   user  system elapsed
 21.798   8.517  18.248


问:
$window.focus() doesn't work on existing tabs in iOS Safari
When I open a new window with var win = window.open("", "name") and then focus the window using win.focus() this works for the first time in iOS Safari.

But when the existing window is referenced again by name using window.open I can't focus again in iOS Safari. In Chrome this works fine.

Is there any way how I can focus on an already existing tab just knowing the name?

I created a fiddle for testing: https://jsfiddle.net/szqnu38f/

答:
This seems to be a bug within iOS Safari.

Generally, it is not possible to set the focus again on an existing named tab. This is also the case when a link with target set to a name is clicked again after the tab was opened --> see https://jsfiddle.net/g3bk1v5a/4/

```<code><a href="http://www.google.com" target="test">Test</a>
</code>```

Therefore, I opened a bug report at Apple.

Body:
This seems to be a bug within iOS Safari.

Generally, it is not possible to set the focus again on an existing named tab. This is also the case when a link with target set to a name is clicked again after the tab was opened --> see https://jsfiddle.net/g3bk1v5a/4/

<a href="http://www.google.com" target="test">Test</a>

Therefore, I opened a bug report at Apple.


问:
Getting the GUI of an app that went poof!
Today my Visual Studio disappeared. I can see devenv.exe in the 'Processes' tab in Task Manager but not in the Applications tab. I have unsaved changes. Is there a way to "revive" VS so changes can be saved?</p>

答:
I know it isn't a solution but VS if terminated unexpectedly (task manager end process) will usually recover open unsaved files when you re open it, Just make sure you open it directly and not by double clicking the sln file.

I would only try this as a last resort incase it doesn't recover the files.

HTH

OwnerDisplayName: Abdu


问:
Run .bat file from Mobaxterm
When I am trying to run .bat file from mobaxterm on windows, it opens a default cmd window and closes it when the process is finished. Instead I want it to run from mobaxterm and log the info into a file . I searched the documentation but no luck finding the info. Any help would be appreciated.

Thanks.

答: You could add "session loging" as default or just for certain sessions:

Title: Run .bat file from Mobaxterm


问:
Prevent QDockWidget autosizing behaviour
Qt 5.5.0

In my application, I have a QGraphicsView as the main widget and a QDockWidget for properties.
The goal is for the user to select an item in the graphics view and, depending on the item, present the appropriate properties for that item.

I achieve this by having a properties manager widget with a layout containing each of the properties widgets. I have signals and slots hooked up for getting the currently selected item, and then show() the widget I need and hide() the rest.

This works great! However, when selecting different items, the dock shrinks or grows based on the shown widget. It is very jarring, and rather annoying. The thing is though, that when the user manually resizes the dock, it maintains that size. I want the maintained size to be default rather than this autosizing behaviour.

Things I've tried:

I've tried changing the sizePolicy() of the dock and the mainwindow: No effect.

I've set a minimum size for my properties manager which does indeed prevent the dock from shrinking when a smaller set of properties is shown. However, I still want the user to be able to shrink the dock to a smaller size if they wish, and this method prevents that...

Conclusion:

Is there a flag or something that is set when the user resizes the dock that tells it to maintain that size? If so, is there a way to manually set it?

I haven't tried subclassing QDockWidget or QMainWindow yet. Is there a method(s) that I can override to achieve the correct behaviour?

Thanks for any help!

答:
First, create your dock widget:

```<code>QDockWidget *dock = new QDockWidget;
</code>```

Now set size policy to dock's widget.

If dock is vertical:

```<code>dock->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Expanding);
</code>```

If dock is horizontal:

```<code>dock->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Ignored);
</code>```

Set your widget to dock:

```<code>QWidget *myWidget = new QWidget;
dock->setWidget(myWidget);
</code>```

Now set size policy to dock's widget.

If dock is vertical:

```<code>dock->widget()->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Expanding);
</code>```

If dock is horizontal:

```<code>dock->widget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Ignored);
</code>```

Finally, add dock to main window:

If dock is vertical:

```<code>mainWindow->addDockWidget(Qt::LeftDockWidgetArea, dock);
mainWindow->resizeDocks({dock}, {0}, Qt::Horizontal);
</code>```

If dock is horizontal:

```<code>mainWindow->addDockWidget(Qt::TopDockWidgetArea, dock);
mainWindow->resizeDocks({dock}, {0}, Qt::Vertical);
</code>```

Body:
First, create your dock widget:

QDockWidget *dock = new QDockWidget;

Now set size policy to dock's widget.

If dock is vertical:

dock->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Expanding);

If dock is horizontal:

dock->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Ignored);

Set your widget to dock:

QWidget *myWidget = new QWidget;
dock->setWidget(myWidget);

Now set size policy to dock's widget.

If dock is vertical:

dock->widget()->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Expanding);

If dock is horizontal:

dock->widget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Ignored);

Finally, add dock to main window:

If dock is vertical:

mainWindow->addDockWidget(Qt::LeftDockWidgetArea, dock);
mainWindow->resizeDocks({dock}, {0}, Qt::Horizontal);

If dock is horizontal:

mainWindow->addDockWidget(Qt::TopDockWidgetArea, dock);
mainWindow->resizeDocks({dock}, {0}, Qt::Vertical);


问:
Align footer at the bottom of the content, push to right of the sidebar
I wanted to place the footer at the bottom of the content, but not spread across the whole width of the page. The footer should always be bottom if the content is not place i.e. as shown in figure 1. The sidebar can be toggled by the button place at the navbar.

I was only able to get as shown below:

The sidebar should push the footer to the right, but it is always at the top. As, when the sidebar is hidden or collapsed the footer should occupy the width of the page as occupied buy the content.

HTML implementation is in the following structure:

```<code><div class="wrapper">
   <!-- Navbar -->
   <nav class="navbar navbar-expand-sm fixed-top navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
      <div class="container-fluid">
      </div>
   </nav>
   <!-- Sidebar -->
   <div id="sidebar" class="shadow-sm"></div>
   <!-- Page Content -->
   <div id="content">
      <div class="container-fluid">
         <div class="card">
            <div class="card-body">
               <h1>
                  Collapsing Menu
                  <small class="text-muted">Version 2.1</small>
               </h1>
            </div>
         </div>
      </div>
   </div>
</div>
<footer id="page-footer" class="py-3 bg-dark text-light">
   <div class="container">

   </div>
</footer>
</code>```

CSS for the footer and sidebar:

```<code>footer {
    bottom: 0;
    left: 0;
    position: fixed;
    width: 100%;
}
#sidebar {
    margin-top: 54px;
    width: 250px;
    position: fixed;
    top: 0;
    left: 0;
    height: calc(100vh - 55px);
    z-index: 999;
    padding: 10px;
    -webkit-transition: right .5s ease,left .5s ease;
    -moz-transition: right .5s ease,left .5s ease;
    -o-transition: right .5s ease,left .5s ease;
    transition: right .5s ease,left .5s ease;
}
</code>```

答:
.sidebar {
   height: 100vh;
  width:20%;
  background:red;
}
.wrapper{
  display:flex;

}
.page{
  width:80%;
    display:flex;
  flex-direction:column;
  justify-content: space-between;
  height:;

}
.content{
  width:100%;
  height:200px;
  background-color:green;
}
footer {
  width:calc(100%);
  height:50px;
  background-color:blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="sidebar">sidebar</div>
  <div class="page">
    <div class="content">my content</div>
    <footer>my footer </footer>
  </div>
</div></code>```

this is another method with only css!

Body:
I wanted to place the footer at the bottom of the content, but not spread across the whole width of the page. The footer should always be bottom if the content is not place i.e. as shown in figure 1. The sidebar can be toggled by the button place at the navbar.

I was only able to get as shown below:

The sidebar should push the footer to the right, but it is always at the top. As, when the sidebar is hidden or collapsed the footer should occupy the width of the page as occupied buy the content.

HTML implementation is in the following structure:

                  Collapsing Menu
                  Version 2.1

CSS for the footer and sidebar:

footer {
    bottom: 0;
    left: 0;
    position: fixed;
    width: 100%;
}
#sidebar {
    margin-top: 54px;
    width: 250px;
    position: fixed;
    top: 0;
    left: 0;
    height: calc(100vh - 55px);
    z-index: 999;
    padding: 10px;
    -webkit-transition: right .5s ease,left .5s ease;
    -moz-transition: right .5s ease,left .5s ease;
    -o-transition: right .5s ease,left .5s ease;
    transition: right .5s ease,left .5s ease;
}

Body:
.sidebar {
   height: 100vh;
  width:20%;
  background:red;
}
.wrapper{
  display:flex;

}
.page{
  width:80%;
    display:flex;
  flex-direction:column;
  justify-content: space-between;
  height:;

}
.content{
  width:100%;
  height:200px;
  background-color:green;
}
footer {
  width:calc(100%);
  height:50px;
  background-color:blue;
}

<div class="wrapper">
  <div class="sidebar">sidebar</div>
  <div class="page">
    <div class="content">my content</div>
    <footer>my footer </footer>
  </div>
</div>

this is another method with only css!


问:
iloc'ing one level of a multiindex
I have multiindex dataframe, something like:

```<code>df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)]))
df['foo']="bar"
df.index.names=['people', 'socket']
</code>```

What I'd like to do is iloc-slice all the rows associated with the first three people in the index.  IE: retrieve all the rows where people is either matt mike or dave.

As far as I can tell, though, this is not at all supported by pandas. Saw some gross levels-related hacks, but they didn't even work.  get_level_values(0) doesn't give distinct level values,  and levels() returns an unsorted frozenset.

edit:  I should have said  that .loc-based solutions won't work for me.

答:
Another option:</p>

```<code>df[df.index.get_level_values(0)
     .isin({'matt','mike','dave'})]
</code>```

Title: iloc'ing one level of a multiindex

Body:
I have multiindex dataframe, something like:

df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)]))
df['foo']="bar"
df.index.names=['people', 'socket']

What I'd like to do is iloc-slice all the rows associated with the first three people in the index.  IE: retrieve all the rows where people is either matt mike or dave.

As far as I can tell, though, this is not at all supported by pandas. Saw some gross levels-related hacks, but they didn't even work.  get_level_values(0) doesn't give distinct level values,  and levels() returns an unsorted frozenset.

edit:  I should have said  that .loc-based solutions won't work for me.

Body:
Another option:

df[df.index.get_level_values(0)
     .isin({'matt','mike','dave'})]


问:
How to refresh a single item in a FlatList in React-Native?
I made a Like function with React and Flask API, it works pretty well, it makes the Like action but it only appears when I refresh the whole list. Somehow I want to refresh the Like picture and the Like count at the post. </p>

<p>I tried to put extraData in my FlatList but that does not solve my problem... </p>

```<code>handleClick() {
    const headers = {
      'Authorization': 'jwt ' + this.props.jwt
    };
    const action = this.props.has_liked?  'unlike':'like'
    axios.post("http://127.0.0.1:5000/API/likeaction",{
        id: this.props.id,
        action: action
    }, {
      headers: headers
    })
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error)
    });
    this.setState({liked: action})
  }
    render() {
      const img = this.props.has_liked?  require('../assets/icons/heart-filled.png') : require('../assets/icons/heart-no-fill.png')
        return(
        <View style={{flex:1, marginTop: 10, marginBottom:16, left: 20}}>
         <View style={{flex: 1, flexDirection: 'row'}}>
         <Image source={this.props.image_uri} style={{height:42, width: 42, borderRadius:21}}/>
          <Text style={{left:20,paddingTop:6}}>{this.props.author}</Text>
          <Text style={{position: 'absolute', right: 40, paddingTop:6,fontSize:12,color:'#babbbc'}}> {this.props.date} </Text>
         </View>
        <View style={{flex:1, left: 60, right:20,width: '70%', marginTop:-10}}>
          <Text style={{fontWeight:'bold',fontSize:18,marginBottom:6}}>{this.props.title} </Text>
          <Text style={{fontSize:16,marginBottom:6 }}>{this.props.content}</Text>
        <View style={{flex: 1, flexDirection: 'row'}}>
          <TouchableOpacity onPress={this.handleClick}>
          <Image style={{width:24, height:24, marginBottom:6, marginTop:6}} source={img} />
          </TouchableOpacity>
          <Text style={{paddingTop:10, marginLeft:6, fontSize:14,color:'#bfbfbf'}}>{this.props.likes}</Text>
        </View>
        </View>
      </View>
      );
    }

  }
</code>```

```<code><FlatList
            data={this.state.dataSource}
            extraData={this.state}
            renderItem={({item}) => <PostView title={item.title}
                                        content={item.content}
                                        author={item.author}
                                        date={item.date_posted}
                                        likes={item.likes}
                                        has_liked={item.has_liked}
                                        jwt = {this.props.screenProps.jwt}
                                        id = {item.id}
                                        image_uri={{uri:'http://127.0.0.1:5000/static/profile_pics/'+item.profile_image}}/> }
                                        refreshing={this.state.refreshing}
                                        onRefresh={this.handleRefresh}
                                        keyExtractor={item => item.id}/>
        </View>
</code>```

答:
try with in home

```<code>this.state = {
        loading: true,
        email: '',
        error: '',
        refreshing: false,
        dataSource: [],
        updated: false
      }

handleChange = () => {
    this.setState({ updated: true })
    }

handleRefresh = () => {
 this.setState({
   refreshing: true,
   data: this.state.dataSource
  }, () => {
    this.makeRemoteRequest()
   })
        }
</code>```

Replace

```<code><PostView title={item.title}
....
/>
</code>```

with

```<code><PostView title={item.title}
    .....
    handleChange={this.handleChange}/>

    extraData={this.state}

and update
</code>```

and

```<code>  handleClick() {
    const headers = {
      'Authorization': 'jwt ' + this.props.jwt
    };
    axios.post("http://127.0.0.1:5000/API/likeaction",{
        id: this.props.id,
    }, {
      headers: headers
    })
    .then((response) => {
      console.log(response.data);
      if(response.data.account == "liked"){
        this.setState({liked:true})
      }else{
        this.setState({liked:false})
      }
    })
    .catch((error) => {
      console.log(error)
    });
  }
</code>```

with

```<code>handleClick() {
    const headers = {
      'Authorization': 'jwt ' + this.props.jwt
    };
    axios.post("http://127.0.0.1:5000/API/likeaction",{
        id: this.props.id,
    }, {
      headers: headers
    })
    .then((response) => {
      console.log(response.data);
      this.props.handleChange(true);
      if(response.data.account == "liked"){
        this.setState({liked:true})
      }else{
        this.setState({liked:false})
      }
    })
    .catch((error) => {
      console.log(error)
    });
  }

const img = this.state.liked?  require('../assets/icons/heart-filled.png') : require('../assets/icons/heart-no-fill.png')
</code>```

with

```<code>const img = this.state.liked ?  require('../assets/icons/heart-filled.png') : require('../assets/icons/heart-no-fill.png')
</code>```

Body:
I made a Like function with React and Flask API, it works pretty well, it makes the Like action but it only appears when I refresh the whole list. Somehow I want to refresh the Like picture and the Like count at the post.

I tried to put extraData in my FlatList but that does not solve my problem...

handleClick() {
    const headers = {
      'Authorization': 'jwt ' + this.props.jwt
    };
    const action = this.props.has_liked?  'unlike':'like'
    axios.post("http://127.0.0.1:5000/API/likeaction",{
        id: this.props.id,
        action: action
    }, {
      headers: headers
    })
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error)
    });
    this.setState({liked: action})
  }
    render() {
      const img = this.props.has_liked?  require('../assets/icons/heart-filled.png') : require('../assets/icons/heart-no-fill.png')
        return(
        <View style={{flex:1, marginTop: 10, marginBottom:16, left: 20}}>
         <View style={{flex: 1, flexDirection: 'row'}}>
         <Image source={this.props.image_uri} style={{height:42, width: 42, borderRadius:21}}/>
          <Text style={{left:20,paddingTop:6}}>{this.props.author}</Text>
          <Text style={{position: 'absolute', right: 40, paddingTop:6,fontSize:12,color:'#babbbc'}}> {this.props.date} </Text>
         </View>
        <View style={{flex:1, left: 60, right:20,width: '70%', marginTop:-10}}>
          <Text style={{fontWeight:'bold',fontSize:18,marginBottom:6}}>{this.props.title} </Text>
          <Text style={{fontSize:16,marginBottom:6 }}>{this.props.content}</Text>
        <View style={{flex: 1, flexDirection: 'row'}}>
          <TouchableOpacity onPress={this.handleClick}>
          <Image style={{width:24, height:24, marginBottom:6, marginTop:6}} source={img} />
          </TouchableOpacity>
          <Text style={{paddingTop:10, marginLeft:6, fontSize:14,color:'#bfbfbf'}}>{this.props.likes}</Text>
        </View>
        </View>
      </View>
      );
    }

  }

<FlatList
            data={this.state.dataSource}
            extraData={this.state}
            renderItem={({item}) => <PostView title={item.title}
                                        content={item.content}
                                        author={item.author}
                                        date={item.date_posted}
                                        likes={item.likes}
                                        has_liked={item.has_liked}
                                        jwt = {this.props.screenProps.jwt}
                                        id = {item.id}
                                        image_uri={{uri:'http://127.0.0.1:5000/static/profile_pics/'+item.profile_image}}/> }
                                        refreshing={this.state.refreshing}
                                        onRefresh={this.handleRefresh}
                                        keyExtractor={item => item.id}/>
        </View>

Body:
try with in home

this.state = {
        loading: true,
        email: '',
        error: '',
        refreshing: false,
        dataSource: [],
        updated: false
      }

handleChange = () => {
    this.setState({ updated: true })
    }

handleRefresh = () => {
 this.setState({
   refreshing: true,
   data: this.state.dataSource
  }, () => {
    this.makeRemoteRequest()
   })
        }

Replace

<PostView title={item.title}
....
/>

with

<PostView title={item.title}
    .....
    handleChange={this.handleChange}/>

    extraData={this.state}

and update

and

  handleClick() {
    const headers = {
      'Authorization': 'jwt ' + this.props.jwt
    };
    axios.post("http://127.0.0.1:5000/API/likeaction",{
        id: this.props.id,
    }, {
      headers: headers
    })
    .then((response) => {
      console.log(response.data);
      if(response.data.account == "liked"){
        this.setState({liked:true})
      }else{
        this.setState({liked:false})
      }
    })
    .catch((error) => {
      console.log(error)
    });
  }

with

handleClick() {
    const headers = {
      'Authorization': 'jwt ' + this.props.jwt
    };
    axios.post("http://127.0.0.1:5000/API/likeaction",{
        id: this.props.id,
    }, {
      headers: headers
    })
    .then((response) => {
      console.log(response.data);
      this.props.handleChange(true);
      if(response.data.account == "liked"){
        this.setState({liked:true})
      }else{
        this.setState({liked:false})
      }
    })
    .catch((error) => {
      console.log(error)
    });
  }

const img = this.state.liked?  require('../assets/icons/heart-filled.png') : require('../assets/icons/heart-no-fill.png')

with

const img = this.state.liked ?  require('../assets/icons/heart-filled.png') : require('../assets/icons/heart-no-fill.png')


问:
How to rate limit scan to AWS DynamoDB for AWS CLI?
I have created the following query to query my table :

```<code>aws dynamodb scan --table-name TableName --scan-filter '{
"attributeName" : {
    "AttributeValueList" : [ {"S" : "StringToQuery"}],
    "ComparisonOperator" : "CONTAINS"
}
}'
</code>```

This is causing a spike in read capacity for that table, which will probably lead to throttling of customer requests. I couldn't find any command line option to limit the rate in https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html, but I did find a java script with rate limit : https://aws.amazon.com/blogs/developer/rate-limited-scans-in-amazon-dynamodb/

Is there any way to do it from AWS CLI?

答: You can disable pagination and manually make the paginated calls with a bash loop. This way you can delay a certain amount based on the time the previous call took and the consumed read capacity.</p>

Body:
I have created the following query to query my table :

aws dynamodb scan --table-name TableName --scan-filter '{
"attributeName" : {
    "AttributeValueList" : [ {"S" : "StringToQuery"}],
    "ComparisonOperator" : "CONTAINS"
}
}'

This is causing a spike in read capacity for that table, which will probably lead to throttling of customer requests. I couldn't find any command line option to limit the rate in https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html, but I did find a java script with rate limit : https://aws.amazon.com/blogs/developer/rate-limited-scans-in-amazon-dynamodb/

Is there any way to do it from AWS CLI?


问:
Which is better to use: regex.containsMatchIn(String) or String.contains(regex) and why?
If i have a String called "text" and a Regex (called "regex" for ease) i want to check it against, should i use:

```<code>regex.containsMatchIn(text)
</code>```

or should i use:

```<code>text.contains(regex)
</code>```

Both seem to be successful but i am unsure of the best practices concerning this.

答:
The Kotlin documentation says:

contains

Returns true if this char sequence contains the specified other sequence of characters as a substring.

containsMatchIn

Indicates whether the regular expression can find at least one match in the specified input.

It looks like both do pretty much the same thing, so functionally it doesn't matter too much which you use.

However, since you're dealing with regex, I feel like using containsMatchIn is more appropriate since it's part of the regex library and intended for that purpose specifically.

Where contains can be used for more than just regex, e.g. for finding if 'flow' is a substring of 'overflow'. So, it's likely less appropriate to use it for regex, if we're being picky.

Body:
If i have a String called "text" and a Regex (called "regex" for ease) i want to check it against, should i use:

regex.containsMatchIn(text)

or should i use:

text.contains(regex)

Both seem to be successful but i am unsure of the best practices concerning this.


问:
Update a record in one table (gridview) and add it in another table
So what I mean is... Lets say we have this table named "Matched_table":

```<code>Date          Game   Client        cost
12-12-2001    Game1  Jonh          200
12-12-2003    Game2  Jonathan      100
</code>```

Now we have another table named "NonMatched_table", this table is for the records that don't have records that match with "costumer name", also this table lets the user update the Costumer name column to make the record a "match record":

```<code>   Date      Game      Costumer name     cost
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Carl           200   <--- Updated Record:
</code>```

When Updated this should happen:

----   "Matched_ table"----

```<code>   Date          Game   Client        cost
   12-12-2001    Game1  Jonh          200
   12-12-2003    Game2  Jonathan      100
   12-05-2001    Game1  Carl          200
</code>```

----   "NonMatched_table"    ---

```<code>Date      Game        Costumer name     cost
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Empty           200
</code>```

Doesn't exist a query that does that or something? I'm doing in c# this query string query = "UPDATE NonMatched_table SET costumer= @costumer where ID = @Id Insert into Matched_table"; I'm Wondering if I could do like an Insert into after or before and a delete too to erase the record

答:
Unless you have very specific reasons to do that you can follow a much simpler approach:

Have all records in one table, e.g. MyTable with columns Date, Game, Client, Cost.

Simply use SELECT to filter the table. For unmatched records the query is:

SELECT * FROM MyTable WHERE Client IS NULL

For matched records the query is:

SELECT * FROM MyTable WHERE Client IS NOT NULL

Alternatively, you can use the above queries to create two views of MyTable one for matched and one for unmatched records.

Your approach while possible will raise data integrity issues sooner or later, I am afraid.

UPDATE

Just for the fun of it here's a working sample of what I suggest:

ASPX

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:SqlDataSource
                ID="SqlDataSourceUnmatched"
                runat="server"
                ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
                SelectCommand="SELECT [Id], [Date], [Game], [Client], [Cost] FROM [MyTable] WHERE ([Client] IS NULL)"
                UpdateCommand="UPDATE [MyTable] SET [Date]=@Date, [Game]=@Game, [Client]=@Client, [Cost]=@Cost WHERE [Id]=@Id"
                OnUpdating="SqlDataSourceUnmatched_Updating">
                <UpdateParameters>
                    <asp:Parameter Name="Id" Type="Int32"/>
                    <asp:Parameter Name="Date" Type="DateTime" />
                    <asp:Parameter Name="Game" />
                    <asp:Parameter Name="Client" />
                    <asp:Parameter Name="Cost" Type="Int32" />
                </UpdateParameters>
            </asp:SqlDataSource>
            <br />
            <asp:GridView
                ID="GridViewUnmatched"
                runat="server"
                AutoGenerateColumns="False"
                DataSourceID="SqlDataSourceUnmatched"
                OnRowUpdated="GridViewUnmatched_RowUpdated">
                <Columns>
                    <asp:BoundField
                        DataField="Id"
                        HeaderText="Id"  />
                    <asp:BoundField
                        DataField="Date"
                        HeaderText="Date"  />
                    <asp:BoundField
                        DataField="Game"
                        HeaderText="Game" />
                    <asp:BoundField
                        DataField="Client"
                        HeaderText="Customer Name" />
                    <asp:BoundField
                        DataField="Cost"
                        HeaderText="Cost" />
                    <asp:CommandField
                        ButtonType="Link"
                        ShowEditButton="true"
                        ItemStyle-Width="100" />
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource
                ID="SqlDataSourceMatched"
                runat="server"
                ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
                SelectCommand="SELECT [Date], [Game], [Client], [Cost] FROM [MyTable] WHERE ([Client] IS NOT NULL)">
            </asp:SqlDataSource>
            <br />
            <asp:GridView
                ID="GridViewMatched"
                runat="server"
                AutoGenerateColumns="False"
                DataSourceID="SqlDataSourceMatched">
                <Columns>
                    <asp:BoundField
                        DataField="Date"
                        HeaderText="Date"/>
                    <asp:BoundField
                        DataField="Game"
                        HeaderText="Game" />
                    <asp:BoundField
                        DataField="Client"
                        HeaderText="Client" />
                    <asp:BoundField
                        DataField="Cost"
                        HeaderText="Cost" />
                </Columns>
                <EmptyDataTemplate>
                    No matched records.
                </EmptyDataTemplate>
            </asp:GridView>
        </div>
    </form>
</body>
</html>
</code>```

Code behind

```<code>public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void GridViewUnmatched_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        GridViewMatched.DataBind();
    }

    protected void SqlDataSourceUnmatched_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        // assert the record update
        e.Command.Parameters["@Date"].Value = DateTime.Now;
    }
}
</code>```

Hope it helps. I am using Visual Studio 2017 and the target framework is .NET 4.6.1.

Body:
So what I mean is... Lets say we have this table named "Matched_table":

Date          Game   Client        cost
12-12-2001    Game1  Jonh          200
12-12-2003    Game2  Jonathan      100

Now we have another table named "NonMatched_table", this table is for the records that don't have records that match with "costumer name", also this table lets the user update the Costumer name column to make the record a "match record":

   Date      Game      Costumer name     cost
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Carl           200   <--- Updated Record:

When Updated this should happen:

----   "Matched_ table"----

   Date          Game   Client        cost
   12-12-2001    Game1  Jonh          200
   12-12-2003    Game2  Jonathan      100
   12-05-2001    Game1  Carl          200

----   "NonMatched_table"    ---

Date      Game        Costumer name     cost
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Empty           200
12-05-2001   Game1       Empty           200

Doesn't exist a query that does that or something? I'm doing in c# this query string query = "UPDATE NonMatched_table SET costumer= @costumer where ID = @Id Insert into Matched_table"; I'm Wondering if I could do like an Insert into after or before and a delete too to erase the record

Body:
Unless you have very specific reasons to do that you can follow a much simpler approach:

Have all records in one table, e.g. MyTable with columns Date, Game, Client, Cost.

Simply use SELECT to filter the table. For unmatched records the query is:

SELECT * FROM MyTable WHERE Client IS NULL

For matched records the query is:

SELECT * FROM MyTable WHERE Client IS NOT NULL

Alternatively, you can use the above queries to create two views of MyTable one for matched and one for unmatched records.

Your approach while possible will raise data integrity issues sooner or later, I am afraid.

UPDATE

Just for the fun of it here's a working sample of what I suggest:

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:SqlDataSource
                ID="SqlDataSourceUnmatched"
                runat="server"
                ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
                SelectCommand="SELECT [Id], [Date], [Game], [Client], [Cost] FROM [MyTable] WHERE ([Client] IS NULL)"
                UpdateCommand="UPDATE [MyTable] SET [Date]=@Date, [Game]=@Game, [Client]=@Client, [Cost]=@Cost WHERE [Id]=@Id"
                OnUpdating="SqlDataSourceUnmatched_Updating">
                <UpdateParameters>
                    <asp:Parameter Name="Id" Type="Int32"/>
                    <asp:Parameter Name="Date" Type="DateTime" />
                    <asp:Parameter Name="Game" />
                    <asp:Parameter Name="Client" />
                    <asp:Parameter Name="Cost" Type="Int32" />
                </UpdateParameters>
            </asp:SqlDataSource>
            <br />
            <asp:GridView
                ID="GridViewUnmatched"
                runat="server"
                AutoGenerateColumns="False"
                DataSourceID="SqlDataSourceUnmatched"
                OnRowUpdated="GridViewUnmatched_RowUpdated">
                <Columns>
                    <asp:BoundField
                        DataField="Id"
                        HeaderText="Id"  />
                    <asp:BoundField
                        DataField="Date"
                        HeaderText="Date"  />
                    <asp:BoundField
                        DataField="Game"
                        HeaderText="Game" />
                    <asp:BoundField
                        DataField="Client"
                        HeaderText="Customer Name" />
                    <asp:BoundField
                        DataField="Cost"
                        HeaderText="Cost" />
                    <asp:CommandField
                        ButtonType="Link"
                        ShowEditButton="true"
                        ItemStyle-Width="100" />
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource
                ID="SqlDataSourceMatched"
                runat="server"
                ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
                SelectCommand="SELECT [Date], [Game], [Client], [Cost] FROM [MyTable] WHERE ([Client] IS NOT NULL)">
            </asp:SqlDataSource>
            <br />
            <asp:GridView
                ID="GridViewMatched"
                runat="server"
                AutoGenerateColumns="False"
                DataSourceID="SqlDataSourceMatched">
                <Columns>
                    <asp:BoundField
                        DataField="Date"
                        HeaderText="Date"/>
                    <asp:BoundField
                        DataField="Game"
                        HeaderText="Game" />
                    <asp:BoundField
                        DataField="Client"
                        HeaderText="Client" />
                    <asp:BoundField
                        DataField="Cost"
                        HeaderText="Cost" />
                </Columns>
                <EmptyDataTemplate>
                    No matched records.
                </EmptyDataTemplate>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Code behind

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void GridViewUnmatched_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        GridViewMatched.DataBind();
    }

    protected void SqlDataSourceUnmatched_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        // assert the record update
        e.Command.Parameters["@Date"].Value = DateTime.Now;
    }
}

Hope it helps. I am using Visual Studio 2017 and the target framework is .NET 4.6.1.


问:
Formatting Masscan Output
I have the following output output from Masscan's -oG option:

```<code># Masscan 1.0.6 scan initiated Mon May  6 08:45:19 2019
# Ports scanned: TCP(13107;1-13107) UDP(0;) SCTP(0;) PROTOCOLS(0;)
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//
</code>```

How can I manipulate this output using awk, cut, grep, sed, etc. to get the following format:

```<code>192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443
</code>```

答:
try this:

```<code>#!/bin/bash

# define testcontent
content=$(cat << EOT
# Masscan 1.0.6 scan initiated Mon May  6 08:45:19 2019
# Ports scanned: TCP(13107;1-13107) UDP(0;) SCTP(0;) PROTOCOLS(0;)
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//
EOT
)

# declare associative array
declare -A dict

# loop over all ip lines
while read -r ip port; do
   # save ports
   dict[$ip]+="$port "
         # ignore lines start with #, grep ip an port from content
done < <(sed '/^#/d;s/Host: \([^ ]*\).*Ports: \([0-9]*\).*/\1 \2/' <<< "$content")

# loop over assocative array
for key in  "${!dict[@]}"; do

   # sort ports in string
   sorted=$(echo "${dict[$key]}" | tr " " "\n" | sort -n | tr "\n" ,)

   # extract leading ,
   ports="${sorted#*,}"

   # print key an ports without tailing ,
   printf "%s %s\n" "$key" "${ports%,*}"
done | sort
</code>```

Output

```<code>192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443
</code>```

Title: Formatting Masscan Output

Body:
I have the following output output from Masscan's -oG option:

# Masscan 1.0.6 scan initiated Mon May  6 08:45:19 2019
# Ports scanned: TCP(13107;1-13107) UDP(0;) SCTP(0;) PROTOCOLS(0;)
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//

How can I manipulate this output using awk, cut, grep, sed, etc. to get the following format:

192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443

Body:
try this:

#!/bin/bash

# define testcontent
content=$(cat << EOT
# Masscan 1.0.6 scan initiated Mon May  6 08:45:19 2019
# Ports scanned: TCP(13107;1-13107) UDP(0;) SCTP(0;) PROTOCOLS(0;)
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//
EOT
)

# declare associative array
declare -A dict

# loop over all ip lines
while read -r ip port; do
   # save ports
   dict[$ip]+="$port "
         # ignore lines start with #, grep ip an port from content
done < <(sed '/^#/d;s/Host: \([^ ]*\).*Ports: \([0-9]*\).*/\1 \2/' <<< "$content")

# loop over assocative array
for key in  "${!dict[@]}"; do

   # sort ports in string
   sorted=$(echo "${dict[$key]}" | tr " " "\n" | sort -n | tr "\n" ,)

   # extract leading ,
   ports="${sorted#*,}"

   # print key an ports without tailing ,
   printf "%s %s\n" "$key" "${ports%,*}"
done | sort

Output

192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443


问:
Angular: How to update queryParams without changing route on a template
There is a similar question here but it is not referred to the template.

What I want is to create a link that simply adds or modifies a queryParamenters in the currently -unkwown- route.

```<code><a [routerLink]="[¿¿¿???]" [queryParams]="{ pageIndex: 3 }"
 {{ 3 }}
</a>
</code>```

答:
Okay, it seems it's as easy as:</p>

```<code><a [routerLink]="[]" [queryParams]="{ pageIndex: 3 }"
 {{ 3 }}
</a>
</code>```

Body:
There is a similar question here but it is not referred to the template.

What I want is to create a link that simply adds or modifies a queryParamenters in the currently -unkwown- route.

<a [routerLink]="[¿¿¿???]" [queryParams]="{ pageIndex: 3 }"
 {{ 3 }}

Body:
Okay, it seems it's as easy as:

<a [routerLink]="[]" [queryParams]="{ pageIndex: 3 }"
 {{ 3 }}
</a>


问:
How to remove the last characters in a file name using Bash?
I have several .txt files in a folder, their names look as follows:

```<code>file1.txt
file2.txt
file2.txt_newfile.txt
file3.txt
file4.txt
file4.txt_newfile.txt
file5.txt_newfile.txt
...
</code>```

I am trying to remove _newfile.txt from the file names. If the file is present, it should be overwritten by the new file (e.g. file2.txt will be replaced, but file5.txt will just be renamed).

Expected output:

```<code>file1.txt
file2.txt # this was file2.txt_newfile.txt
file3.txt
file4.txt # file4.txt_newfile.txt
file5.txt #file5.txt_newfile.txt
...
</code>```

I tried the following code:

```<code>for i in $(find . -name "*_newfile.txt" -print); do
mv -f "$file" "${file%????????????}"
done
</code>```

However, I get the following error:

```<code>mv: rename  to : No such file or directory
</code>```

What am I doing wrong and how can I rename these files?

答:
For many people maybe an unusual solution, but for me this is a typical vi job.
What many people might not remember, you can pipe the content of the vi buffer through a shell, even with debugging output (sh -x).

What I do in such or similar situations, where I do not want to loose too much time thinking about cool regular expressions or shell trickeries ... the pragmatic way ... vi supports you ;-)

Here we go:

```<code>1. enter directory with those files that you want to rename
2. start vi
3. !!ls *_newfile.txt
note: the !! command prompts you at the bottom to enter a command, the output of the ls command fills the vi buffer
4. dG
deletes all lines from your position 1 to the end of buffer, with a copy of it in the yank buffer
5. PP
paste 2 times the yank buffer
6. !G sort
!G prompts you at the bottom to pipe the buffer through sort
now you have all the lines double to save the work of typing filename again
7. with a combination of JkJk
you join the lines, so you have now the filename 2 times in a line like here:
file2.txt_newfile.txt file2.txt_newfile.txt
8. now add a mv command at the beginning of each line using an ex command
:%s/^/mv /
9. now remove the not needed trailing "_newfile.txt", again with an ex command
:%s/_newfile.txt$//
Now you have i.e. the following line(s) in the vi buffer:
mv file2.txt_newfile.txt file2.txt
10 back to line 1 to that you feed the whole buffer to the shell in the next step
1G
11. feed the shell commands to the shell and show some debug command
!G sh -x
12. check the results in the folder within vi, you will get the output of the ls command into the buffer
!!ls -l
</code>```

Finally quit vi.

It looks maybe on the 1st glimpse like many steps, but if you know vi, then this goes blindingly fast and you have the additional advantage that you have all possibilities to save the instructions to a file for documentation purposes or to work things out to create a script, etc.

Body:
I have several .txt files in a folder, their names look as follows:

file1.txt
file2.txt
file2.txt_newfile.txt
file3.txt
file4.txt
file4.txt_newfile.txt
file5.txt_newfile.txt
...

I am trying to remove _newfile.txt from the file names. If the file is present, it should be overwritten by the new file (e.g. file2.txt will be replaced, but file5.txt will just be renamed).

Expected output:

file1.txt
file2.txt # this was file2.txt_newfile.txt
file3.txt
file4.txt # file4.txt_newfile.txt
file5.txt #file5.txt_newfile.txt
...

I tried the following code:

for i in $(find . -name "*_newfile.txt" -print); do
mv -f "$file" "${file%????????????}"
done

However, I get the following error:

mv: rename  to : No such file or directory

What am I doing wrong and how can I rename these files?

Body:
For many people maybe an unusual solution, but for me this is a typical vi job.
What many people might not remember, you can pipe the content of the vi buffer through a shell, even with debugging output (sh -x).

What I do in such or similar situations, where I do not want to loose too much time thinking about cool regular expressions or shell trickeries ... the pragmatic way ... vi supports you ;-)

Here we go:

1. enter directory with those files that you want to rename
2. start vi
3. !!ls *_newfile.txt
note: the !! command prompts you at the bottom to enter a command, the output of the ls command fills the vi buffer
4. dG
deletes all lines from your position 1 to the end of buffer, with a copy of it in the yank buffer
5. PP
paste 2 times the yank buffer
6. !G sort
!G prompts you at the bottom to pipe the buffer through sort
now you have all the lines double to save the work of typing filename again
7. with a combination of JkJk
you join the lines, so you have now the filename 2 times in a line like here:
file2.txt_newfile.txt file2.txt_newfile.txt
8. now add a mv command at the beginning of each line using an ex command
:%s/^/mv /
9. now remove the not needed trailing "_newfile.txt", again with an ex command
:%s/_newfile.txt$//
Now you have i.e. the following line(s) in the vi buffer:
mv file2.txt_newfile.txt file2.txt
10 back to line 1 to that you feed the whole buffer to the shell in the next step
1G
11. feed the shell commands to the shell and show some debug command
!G sh -x
12. check the results in the folder within vi, you will get the output of the ls command into the buffer
!!ls -l

Finally quit vi.

It looks maybe on the 1st glimpse like many steps, but if you know vi, then this goes blindingly fast and you have the additional advantage that you have all possibilities to save the instructions to a file for documentation purposes or to work things out to create a script, etc.


问:
How to get gender voice from URL parameter in google text to speech API in PHP?
I have build the text to speech api in php using google cloud. I am able to pass other parameters such as pitch, speaking rate, text from URL parameter but I just want to know how I can do the same for gender voice?

I have tried passing it as string or passing the whole argument but none of these work.

```<code>$synthesisInputText = (new SynthesisInput())->setText($_GET['text']);

            $voice = (new VoiceSelectionParams())
                ->setLanguageCode($_GET['lang']))
                // ->setName('en-IN-Wavenet-A')
                ->setSsmlGender(SsmlVoiceGender::FEMALE);

            $audioConfig = (new AudioConfig())
                ->setAudioEncoding(AudioEncoding::MP3)
                ->setPitch($_GET['pitch'])
                ->setSpeakingRate($_GET['speking_rate']);

            $response = $this->client->synthesizeSpeech($synthesisInputText, $voice, $audioConfig);

            $audioContent = $response->getAudioContent();

            file_put_contents($this->file,$audioContent);
</code>```

I am able to get all other parameters correctly but I want get setSsmlGender(SsmlVoiceGender::$_GET['voice']) from URL parameter as well. Any help would be great?

答:
Use the SsmlVoiceGender::value() method to convert your input to the proper enum value:

```<code>use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;

$genderInput = $_GET['voice'];
try {
    $gender = SsmlVoiceGender::value($genderInput);
} catch (\UnexpectedValueException $e) {
    // Invalid input. Hardcode a value?
    $gender = SsmlVoiceGender::MALE;
}

$voice->setSsmlGender($gender);
</code>```

Make sure you are using google/cloud-voice-text-to-speech v0.4.0 or higher. If you're using google/cloud, be sure to use v0.98.0 or higher.

Body:
I have build the text to speech api in php using google cloud. I am able to pass other parameters such as pitch, speaking rate, text from URL parameter but I just want to know how I can do the same for gender voice?

I have tried passing it as string or passing the whole argument but none of these work.

$synthesisInputText = (new SynthesisInput())->setText($_GET['text']);

            $voice = (new VoiceSelectionParams())
                ->setLanguageCode($_GET['lang']))
                // ->setName('en-IN-Wavenet-A')
                ->setSsmlGender(SsmlVoiceGender::FEMALE);

            $audioConfig = (new AudioConfig())
                ->setAudioEncoding(AudioEncoding::MP3)
                ->setPitch($_GET['pitch'])
                ->setSpeakingRate($_GET['speking_rate']);

            $response = $this->client->synthesizeSpeech($synthesisInputText, $voice, $audioConfig);

            $audioContent = $response->getAudioContent();

            file_put_contents($this->file,$audioContent);

I am able to get all other parameters correctly but I want get setSsmlGender(SsmlVoiceGender::$_GET['voice']) from URL parameter as well. Any help would be great?

Body:
Use the SsmlVoiceGender::value() method to convert your input to the proper enum value:

use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;

$genderInput = $_GET['voice'];
try {
    $gender = SsmlVoiceGender::value($genderInput);
} catch (\UnexpectedValueException $e) {
    // Invalid input. Hardcode a value?
    $gender = SsmlVoiceGender::MALE;
}

$voice->setSsmlGender($gender);

Make sure you are using google/cloud-voice-text-to-speech v0.4.0 or higher. If you're using google/cloud, be sure to use v0.98.0 or higher.


问:
In python, super() is always called first in a method. Are there situations where it should be called later?
Are there situations where you want to do some processing before you call super()?

This is a contrived example.  Are there better examples?  Is this considered pythonic?

```<code>class Base(object):
    def __init__(self, name):
        print "Base %s created" % name
        self._name = name

class UpperBase(A):
    """ Similar to base but the name is in uppercase. """
    def __init__(self, name):
        name = name.upper()
        super(UpperBase, self).__init__(name)
</code>```

答:
Sometimes you need to validate the arguments before calling super():

```<code>class UpperBase(Base):
    def __init__(self, name):
        if not name_valid(name):
            raise ValueError()
        super(UpperBase, self).__init__(name)
</code>```

I don't see why this wouldn't be pythonic, because it's the easiest way to do it and it's straightforward.
Also, read @JHSaunders' comment, he makes a good point.

Body:
Are there situations where you want to do some processing before you call super()?

This is a contrived example.  Are there better examples?  Is this considered pythonic?

class Base(object):
    def __init__(self, name):
        print "Base %s created" % name
        self._name = name

class UpperBase(A):
    """ Similar to base but the name is in uppercase. """
    def __init__(self, name):
        name = name.upper()
        super(UpperBase, self).__init__(name)

Body:
Sometimes you need to validate the arguments before calling super():

class UpperBase(Base):
    def __init__(self, name):
        if not name_valid(name):
            raise ValueError()
        super(UpperBase, self).__init__(name)

I don't see why this wouldn't be pythonic, because it's the easiest way to do it and it's straightforward.
Also, read @JHSaunders' comment, he makes a good point.


问:
GKE: Identity-aware proxy > L7 load balancer > Custom host and path rules > Error code 11
I am using GKE Identity-aware proxy > L7 load balancer > Custom host and path rules. It works fine for the root-path. But it does not work for custom paths.

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.global-static-ip-name: "my-static-ip"
spec:
  rules:
  - host: my.custom.org
    http:
      paths:
      - path: /v1/*
        backend:
          serviceName: webv1
          servicePort: 8080
      - path: /v3/*
        backend:
          serviceName: webv3
          servicePort: 8080
      - path: /nginx/*
        backend:
          serviceName: nginx
          servicePort: 80
      - path: /*
        backend:
          serviceName: nginx
          servicePort: 80
</code>```

Path / and /nginx/ works fine. /v2/ and /v3/ throws There was a problem with your request. Error code 11.

If I disable the IAP, everything works fine.

Environment:

Kubernetes version (use kubectl version): 1.12.7-gke.17

Cloud provider or hardware configuration: GKE

Setting up HTTP Load Balancing with Ingress @ https://cloud.google.com/kubernetes-engine/docs/tutorials/http-balancer

Enabling Cloud IAP for GKE @ https://cloud.google.com/iap/docs/enabling-kubernetes-howto

答:
This error code 11 is related to a misconfiguration of the OAuth client ID1.

I see that you the failing one are using a different serviceport. If you are serving the following 2 URLs from two different backends both may have IAP enabled but configured with different clientIds.

As of GCP does not support different clientIds for different paths, and the effort for IAP to use a single clientId across b/e services is underway. For now, if you can verify the clientId, and change it to a single one if they are different, that would work.

The recommended approach would be setting up an NGINX proxy. The ingress + IAP only have one service to deal with instead of two, and it will work like a charm.

Body:
I am using GKE Identity-aware proxy > L7 load balancer > Custom host and path rules. It works fine for the root-path. But it does not work for custom paths.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.global-static-ip-name: "my-static-ip"
spec:
  rules:
  - host: my.custom.org
    http:
      paths:
      - path: /v1/*
        backend:
          serviceName: webv1
          servicePort: 8080
      - path: /v3/*
        backend:
          serviceName: webv3
          servicePort: 8080
      - path: /nginx/*
        backend:
          serviceName: nginx
          servicePort: 80
      - path: /*
        backend:
          serviceName: nginx
          servicePort: 80

Path / and /nginx/ works fine. /v2/ and /v3/ throws There was a problem with your request. Error code 11.

If I disable the IAP, everything works fine.

Environment:

Kubernetes version (use kubectl version): 1.12.7-gke.17

Cloud provider or hardware configuration: GKE

Setting up HTTP Load Balancing with Ingress @ https://cloud.google.com/kubernetes-engine/docs/tutorials/http-balancer

Enabling Cloud IAP for GKE @ https://cloud.google.com/iap/docs/enabling-kubernetes-howto


问:
Get filename from string path in javascript?
How to get the filename from string-path in javascript?

Here is my code

```<code>var nameString = "/app/base/controllers/filename.js"; //this is the input path string
</code>```

do something here to get only the filename

```<code>var name = ???   //this value should equal to filename.js
</code>```

答:
Here one more detailed solution using Regular Expressions.

Alternative 1 (generic): Get a file name (whatever) from a string path.

const FILE_NAME_REGEX = /(.+)\/(.+)$/

console.log("/home/username/my-package/my-file1.ts".replace(FILE_NAME_REGEX, '$2'))

console.log("/home/username/my-package/my-file2.js".replace(FILE_NAME_REGEX, '$2'))```
</div>
</div>
</p>

<p><strong>Alternative 2 (advanced):</strong> Get <em>only</em> a <code>.ts</code> file name from a string path.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const JS_PATH = "/home/username/my-package/my-file.spec.js"
const TS_PATH = "/home/username/my-package/my-file.spec.ts"

// RegExp accepts only `.ts` file names in lower case with optional dashes and dots
const TS_REGEX = /(.+)\/([a-z.-]+\.(ts))$/

// a. Get only the file name of a `.ts` path
console.log(TS_PATH.replace(TS_REGEX, '$2'))

// b. Otherwise it will return the complete path
console.log(JS_PATH.replace(TS_REGEX, '$2'))</code>```

Note: Additionally you can test first the regular expressions above in order to validate them before to getting the expected value.

TS_REGEX.test(TS_PATH)
// > true

TS_REGEX.test(JS_PATH)
// > false
```

More information at MDN - Regular Expressions

Body:
How to get the filename from string-path in javascript?

Here is my code

var nameString = "/app/base/controllers/filename.js"; //this is the input path string

do something here to get only the filename

var name = ???   //this value should equal to filename.js

Body:
Here one more detailed solution using Regular Expressions.

Alternative 1 (generic): Get a file name (whatever) from a string path.

const FILE_NAME_REGEX = /(.+)\/(.+)$/

console.log("/home/username/my-package/my-file1.ts".replace(FILE_NAME_REGEX, '$2'))

console.log("/home/username/my-package/my-file2.js".replace(FILE_NAME_REGEX, '$2'))

Alternative 2 (advanced): Get only a .ts file name from a string path.

const JS_PATH = "/home/username/my-package/my-file.spec.js"
const TS_PATH = "/home/username/my-package/my-file.spec.ts"

// RegExp accepts only `.ts` file names in lower case with optional dashes and dots
const TS_REGEX = /(.+)\/([a-z.-]+\.(ts))$/

// a. Get only the file name of a `.ts` path
console.log(TS_PATH.replace(TS_REGEX, '$2'))

// b. Otherwise it will return the complete path
console.log(JS_PATH.replace(TS_REGEX, '$2'))

Note: Additionally you can test first the regular expressions above in order to validate them before to getting the expected value.

TS_REGEX.test(TS_PATH)
// > true

TS_REGEX.test(JS_PATH)
// > false

More information at MDN - Regular Expressions


问:
word-vba: Unable to update linked image link
I have a document with two inlineshapes into a table on the document header. These inlineshapes are linked images. The folder containing these images has moved and I'm unable to change the image link by VBA code.

I'm working with Word 2016. The documents were created on Word 2003. The only way to access the images has been exploring the table cells and finding the inlineshapes into them
The inlineshapes have no field object defined (nothing)
I can update the link manually going into the File menu > Edit File Links...

I would like to be able to change the image links with vba and not having to do it manually

答:
Well, at last I found what happened.

The images have to be accessed as inlineshapes, not as fields

the path to the image is stored in the property InlineShape.LinkFormat.SourceFullName

Changing this property value and then updating the inlineshape it worked

Sorry if I've bothered you but I think it can be helpful to other users


问:
SQLNative query returning empty results
I'm trying to execute a query which needs 4 tables :

```<code>    @Query(value="SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode "
            + "and sd.id_synop_decode = sy.id_synop" + " and DATE(sy.date)= :date and "
                    + "sy.id_station = st.id_station and st.id_station= :stationId", nativeQuery=true)
    public List<Erreur> recherche(@Param("date") Date date, @Param("stationId") Long stationId);
</code>```

This query works fine et native sql, i pass an existing stationId and  a date like the following :

```<code>SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode and sd.id_synop_decode = sy.id_synop
            and DATE(sy.date)= '2019-05-27' and sy.id_station = st.id_station and st.id_station= 60355;
</code>```

This query works fine in Mysql Workbench.

Here's the actual controller i'm using for testing purpose :

```<code>@GetMapping("/station/{stationId}/erreurs/today")
    public List<Erreur> getTodayErreurByStationId(@PathVariable Long stationId)
    {
        List<Erreur> erreurs = new ArrayList<Erreur>();
        Optional<Station> stationOptional = stationRepository.findById(stationId);
        if(stationOptional.isPresent())
        {
            return erreurRepository.recherche(new Date(), stationId);
        }
        return null;
    }
</code>```

The expected results are the actual "Ererur" objects in my array list, but RestClient just returns an empty array [], while the query works just fine in mysql like i described it above.

So my question is : How can i write this query into Hql language so that i can return the right entities. Or how can i map my sql results to my target custom calss "Erreur"?

```<code>@Entity
@Getter @Setter @NoArgsConstructor
@Table(name="erreur")
public class Erreur {

    public Erreur(int section, int groupe, String info) {
        this.section = section;
        this.groupe = groupe;
        this.info = info;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_erreur")
    private Long id;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
    fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_synop")
    private SynopDecode synopDecode;

    @OneToOne
    @JoinColumn(name="id_controle")
    private Controle controle;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
            fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_station")
    private Station station;

    @Column(name="section")
    private int section;

    @Column(name="groupe")
    private int groupe;

    @Column(name="info")
    private String info;
}
</code>```

答:
If you want to use jpa convention directly then you will have to make associations between different entities i.e. how two entities are linked. When we define these associations then spring jpa knows how to convert method name or custom queries into SQL.

Your code will need to be something like

```<code>public class Erreur {
...
@ManyToOne
@JoinColumns//define how Erreur and SynopeDecone are linked
private SynopDecode synopDecode;
...
</code>```

```<code>public class SynopDecode {
...
@ManyToOne // or @OneToOne its not mentioned in question how these two are linked
@JoinColumns//define how SynopDecode and Synop are linked
private Synop synop;
...
</code>```

Then you can write your query like

```<code>@Query("select e from Erreur e LEFT JOIN e.synopDecode sy LEFT JOIN sy.synop sy WHERE DATE(sy.date) = :date AND sy.id_station = :stationId")
List<Erreur> getByDateAndStationId(@Param("date") Date date, @Param("stationId") Long stationId)
</code>```

You can't use method name based query because you want to use SQL function to match only "date" part of your date and not the whole timestamp.

Title: SQLNative query returning empty results

Body:
I'm trying to execute a query which needs 4 tables :

    @Query(value="SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode "
            + "and sd.id_synop_decode = sy.id_synop" + " and DATE(sy.date)= :date and "
                    + "sy.id_station = st.id_station and st.id_station= :stationId", nativeQuery=true)
    public List<Erreur> recherche(@Param("date") Date date, @Param("stationId") Long stationId);

This query works fine et native sql, i pass an existing stationId and  a date like the following :

SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode and sd.id_synop_decode = sy.id_synop
            and DATE(sy.date)= '2019-05-27' and sy.id_station = st.id_station and st.id_station= 60355;

This query works fine in Mysql Workbench.

Here's the actual controller i'm using for testing purpose :

@GetMapping("/station/{stationId}/erreurs/today")
    public List<Erreur> getTodayErreurByStationId(@PathVariable Long stationId)
    {
        List<Erreur> erreurs = new ArrayList<Erreur>();
        Optional<Station> stationOptional = stationRepository.findById(stationId);
        if(stationOptional.isPresent())
        {
            return erreurRepository.recherche(new Date(), stationId);
        }
        return null;
    }

The expected results are the actual "Ererur" objects in my array list, but RestClient just returns an empty array [], while the query works just fine in mysql like i described it above.

So my question is : How can i write this query into Hql language so that i can return the right entities. Or how can i map my sql results to my target custom calss "Erreur"?

@Entity
@Getter @Setter @NoArgsConstructor
@Table(name="erreur")
public class Erreur {

    public Erreur(int section, int groupe, String info) {
        this.section = section;
        this.groupe = groupe;
        this.info = info;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_erreur")
    private Long id;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
    fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_synop")
    private SynopDecode synopDecode;

    @OneToOne
    @JoinColumn(name="id_controle")
    private Controle controle;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
            fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_station")
    private Station station;

    @Column(name="section")
    private int section;

    @Column(name="groupe")
    private int groupe;

    @Column(name="info")
    private String info;
}

Body:
If you want to use jpa convention directly then you will have to make associations between different entities i.e. how two entities are linked. When we define these associations then spring jpa knows how to convert method name or custom queries into SQL.

Your code will need to be something like

public class Erreur {
...
@ManyToOne
@JoinColumns//define how Erreur and SynopeDecone are linked
private SynopDecode synopDecode;
...

public class SynopDecode {
...
@ManyToOne // or @OneToOne its not mentioned in question how these two are linked
@JoinColumns//define how SynopDecode and Synop are linked
private Synop synop;
...

Then you can write your query like

@Query("select e from Erreur e LEFT JOIN e.synopDecode sy LEFT JOIN sy.synop sy WHERE DATE(sy.date) = :date AND sy.id_station = :stationId")
List<Erreur> getByDateAndStationId(@Param("date") Date date, @Param("stationId") Long stationId)

You can't use method name based query because you want to use SQL function to match only "date" part of your date and not the whole timestamp.