问:
Firestore: update all where
I need to

update "users" Firestore collection documents
  whereEqualTo("somefield", true)

For many updates I think it could be WriteBatch with a lot of updates, but maybe there is another smart way to do this?

For example, if I need to update 10M(millions) of users - it would be OutOfMemoryException on Android device.

答: IMHO the only way to achieve this is create cloud function for firestore which will get chunks of your data and then you can update a field you want.</p>

Title: Firestore: update all where


来源: stackexchange

问:
create a link with xslt in html to other html
I have the following xml code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-model href="http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng" type="application/xml" schematypens="http://relaxng.org/ns/structure/1.0"?>
<?xml-model href="http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng" type="application/xml"
        schematypens="http://purl.oclc.org/dsdl/schematron"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0">
    <teiHeader/>
    <text>
        <head n="3">Capitulo primeyro</head>
        <pb facs="folio16r.jpg"/>
        <div>
            <p>... figurado <app>
                <lem>pollo</lem>
                <rdg wit="#A">pollo</rdg>
                <rdg wit="#B">pello</rdg>
            </app> Parayso ...</p>
            <p> ... <app>
                <lem>sacarõ</lem>
                <rdg wit="#A">sacarõ</rdg>
                <rdg wit="#B">ssaee</rdg>
                </app> ...</p>
        </div>
        <pb facs="folio16v.jpg"/>
        <div>
            <p> .... os fisicos <app>
                <lem>dessesperarom</lem>
                <rdg wit="#A">desseperarom</rdg>
                <rdg wit="#B">desesperõ</rdg>
                </app> ... que assy <app>
                <lem>saa</lem>
                <rdg wit="#A">sooa</rdg>
                <rdg wit="#B">saa</rdg>
                </app> ...</p>
        </div>
    </body>
</text>
</code>```

With my XSL I already obtain 3 different HTML (one for A, one for B and one with lemma). I created a template in XSL for app:

```<code><xsl:template match="app">
    <xsl:variable name="appNumber" select="count(preceding::app) + 1"/>
    <a href="#app_{$appNumber}"><xsl:apply-templates select="lem"/></a>
</xsl:template>

<xsl:template match="app" mode="footnote">
    <xsl:variable name="appNumber" select="count(preceding::app) + 1"/>
    <li id="app_{$appNumber}">
        <xsl:for-each select="rdg">
            <i><xsl:apply-templates/></i><xsl:text> </xsl:text>
            <a>
                <xsl:attribute name="href">
                    <xsl:text>#</xsl:text>
                    <xsl:apply-templates select="app"/>
                </xsl:attribute>
                <xsl:value-of select="substring-after(@wit, '#')">
                </xsl:value-of>
            </a>
            <xsl:text> </xsl:text>
            <br/>
            <xsl:if test="position() lt last()"></xsl:if>
        </xsl:for-each>
    </li>
</xsl:template>
</code>```

Now I have this html:

```<code><ul>
    <li id="app_1"><i>prophetas</i> <a href="#">Editor</a> <br /><i>prophetas</i> <a href="#">A</a> <br /></li>
    <li id="app_2"><i>pollo</i> <a href="#">Editor</a> <br /><i>pollo</i> <a href="#">A</a> <br /></li>
    <li id="app_3"><i>sacarõ</i> <a href="#">Editor</a> <br /><i>sacarõ</i> <a href="#">A</a> <br /></li>
    <li id="app_4"><i>dessesperarom</i> <a href="#">Editor</a> <br /><i>desseperarom</i> <a href="#">A</a> <br /></li>
    <li id="app_5"><i>saa</i> <a href="#">Editor</a> <br /><i>sooa</i> <a href="#">A</a> <br /></li>
    <li id="app_6"><i>ante</i> <a href="#">Editor</a> <br /><i>ante</i> <a href="#">A</a> <br /></li>
</ul>
</code>```

As you see a start to create a link in the li but I don't get what I want. I would like to say that the link goes from the wit (#A or #B or #Editor) to the same point of text in the other html. For example if I am looking a A html, in app, clicking on B I want to go to same point of text in B html. Can any one help?

答:
If I get it right, this is only about the right composition of the link. It seems you have one apparatus file which should be linked to the different source files on each apparatus entry. Actually, you were quite close. Try this:

```<code><xsl:attribute name="href">
    <xsl:value-of select="substring-after(@wit, '#')"/>
    <xsl:text>.html#app_</xsl:text>
    <xsl:value-of select="$appNumber"/>
    <xsl:apply-templates select="app"/>
</xsl:attribute>
</code>```

This will produce links like this:

```<code><a href="A.html#app_2">A</a>
</code>```

I assume you have already figured it out for yourself after all the time. I wanted to answer this nonetheless, maybe it is still useful for someone.

ContentLicense: CC BY-SA 3.0

Body:
I have the following xml code:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-model href="http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng" type="application/xml" schematypens="http://relaxng.org/ns/structure/1.0"?>
<?xml-model href="http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng" type="application/xml"
        schematypens="http://purl.oclc.org/dsdl/schematron"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0">
    <teiHeader/>
    <text>
        Capitulo primeyro
        <pb facs="folio16r.jpg"/>

... figurado <app>
                <lem>pollo</lem>
                <rdg wit="#A">pollo</rdg>
                <rdg wit="#B">pello</rdg>
            </app> Parayso ...

 ... <app>
                <lem>sacarõ</lem>
                <rdg wit="#A">sacarõ</rdg>
                <rdg wit="#B">ssaee</rdg>
                </app> ...

        <pb facs="folio16v.jpg"/>

 .... os fisicos <app>
                <lem>dessesperarom</lem>
                <rdg wit="#A">desseperarom</rdg>
                <rdg wit="#B">desesperõ</rdg>
                </app> ... que assy <app>
                <lem>saa</lem>
                <rdg wit="#A">sooa</rdg>
                <rdg wit="#B">saa</rdg>
                </app> ...

</text>

With my XSL I already obtain 3 different HTML (one for A, one for B and one with lemma). I created a template in XSL for app:

<xsl:template match="app">
    <xsl:variable name="appNumber" select="count(preceding::app) + 1"/>
    <xsl:apply-templates select="lem"/>
</xsl:template>

<xsl:template match="app" mode="footnote">
    <xsl:variable name="appNumber" select="count(preceding::app) + 1"/>

        <xsl:for-each select="rdg">
            <xsl:apply-templates/><xsl:text> </xsl:text>

                <xsl:attribute name="href">
                    <xsl:text>#</xsl:text>
                    <xsl:apply-templates select="app"/>
                </xsl:attribute>
                <xsl:value-of select="substring-after(@wit, '#')">
                </xsl:value-of>

            <xsl:text> </xsl:text>

            <xsl:if test="position() lt last()"></xsl:if>
        </xsl:for-each>

</xsl:template>

Now I have this html:

prophetas Editor
prophetas A

pollo Editor
pollo A

sacarõ Editor
sacarõ A

dessesperarom Editor
desseperarom A

saa Editor
sooa A

ante Editor
ante A

As you see a start to create a link in the li but I don't get what I want. I would like to say that the link goes from the wit (#A or #B or #Editor) to the same point of text in the other html. For example if I am looking a A html, in app, clicking on B I want to go to same point of text in B html. Can any one help?

Body:
If I get it right, this is only about the right composition of the link. It seems you have one apparatus file which should be linked to the different source files on each apparatus entry. Actually, you were quite close. Try this:

<xsl:attribute name="href">
    <xsl:value-of select="substring-after(@wit, '#')"/>
    <xsl:text>.html#app_</xsl:text>
    <xsl:value-of select="$appNumber"/>
    <xsl:apply-templates select="app"/>
</xsl:attribute>

This will produce links like this:

<a href="A.html#app_2">A</a>

I assume you have already figured it out for yourself after all the time. I wanted to answer this nonetheless, maybe it is still useful for someone.


问:
Gathering list of 2-d tensors from a 3-d tensor in Keras
I have a 3-d Tensor named main_decoder of shape (None,9,256)

I want to extract 9 tensors of shape (None,256)

I have tried using Keras gather and the following is mode code snippet:

```<code>for i in range(0,9):
    sub_decoder_input = Lambda(lambda main_decoder:gather(main_decoder,(i)), name='lambda'+str(i))(main_decoder)
</code>```

the resultant is 9 lambda layers of shape (9,256)

How can I modify it so that I can get or gather 9 tensors of shape (None,256)

Thanks.

答:
You can slice the 3D tensor into 9 2D tensors and return a list of tensors from the Lambda layer.

main_decoder = Input(shape=(9, 256))
sub_decoder_input = Lambda(lambda x: [x[:, i, :] for i in range(9)])(main_decoder)

print(sub_decoder_input)
[<tf.Tensor 'lambda_1/strided_slice:0' shape=(?, 256) dtype=float32>,
 <tf.Tensor 'lambda_1/strided_slice_1:0' shape=(?, 256) dtype=float32>,
 <tf.Tensor 'lambda_1/strided_slice_2:0' shape=(?, 256) dtype=float32>,
 <tf.Tensor 'lambda_1/strided_slice_3:0' shape=(?, 256) dtype=float32>,
 <tf.Tensor 'lambda_1/strided_slice_4:0' shape=(?, 256) dtype=float32>,
 <tf.Tensor 'lambda_1/strided_slice_5:0' shape=(?, 256) dtype=float32>,
 <tf.Tensor 'lambda_1/strided_slice_6:0' shape=(?, 256) dtype=float32>,
 <tf.Tensor 'lambda_1/strided_slice_7:0' shape=(?, 256) dtype=float32>,
 <tf.Tensor 'lambda_1/strided_slice_8:0' shape=(?, 256) dtype=float32>]
```

Body:
I have a 3-d Tensor named main_decoder of shape (None,9,256)

I want to extract 9 tensors of shape (None,256)

I have tried using Keras gather and the following is mode code snippet:

for i in range(0,9):
    sub_decoder_input = Lambda(lambda main_decoder:gather(main_decoder,(i)), name='lambda'+str(i))(main_decoder)

the resultant is 9 lambda layers of shape (9,256)

How can I modify it so that I can get or gather 9 tensors of shape (None,256)

Thanks.


问:
Using AWK to sort lines and columns together
I'm doing an assignment where I've been asked to find files between a certain size and sha1sum them.  I've specifically been asked to provide the output in the following format:

Filename Sha1 File Size

all on one line.  I'm not able to create additional files.

I've tried the following:

```<code>for listed in $(find /my/output -type f -size -20000c):
do
sha1sum "$listed" | awk '{print $1}'
ls -l "$listed" | awk '{print $9 $5}'
done
</code>```

which gives me the required output fields, but not in the requested format, i.e.

```<code>sha1sum
filename filesize
</code>```

Could anyone suggest a manner in which I'd be able to get all of this on a single line?

Thank you :)

答:
If you use the stat command to avoid needing to parse the output of ls, you can simply echo all the values you need:

```<code>while IFS= read -r -d '' listed
do
  echo "$listed" $(sha1sum "$listed") $(stat -c "%s" "$listed")
done < <(find /my/output -type f -size -20000c -print0)
</code>```

Check your version of stat, though, the above is GNU. On OS X, e.g., would be

```<code>stat -f "%z" $listed
</code>```

Body:
I'm doing an assignment where I've been asked to find files between a certain size and sha1sum them.  I've specifically been asked to provide the output in the following format:

Filename Sha1 File Size

all on one line.  I'm not able to create additional files.

I've tried the following:

for listed in $(find /my/output -type f -size -20000c):
do
sha1sum "$listed" | awk '{print $1}'
ls -l "$listed" | awk '{print $9 $5}'
done

which gives me the required output fields, but not in the requested format, i.e.

sha1sum
filename filesize

Could anyone suggest a manner in which I'd be able to get all of this on a single line?

Thank you :)

Body:
If you use the stat command to avoid needing to parse the output of ls, you can simply echo all the values you need:

while IFS= read -r -d '' listed
do
  echo "$listed" $(sha1sum "$listed") $(stat -c "%s" "$listed")
done < <(find /my/output -type f -size -20000c -print0)

Check your version of stat, though, the above is GNU. On OS X, e.g., would be

stat -f "%z" $listed


问:
Manually skip a component from being created from the dfm
Is there a way to skip a component from being created from the dfm?

I have an visual component I sometimes do not want to be created. Of course I could create the component by hand, but this would be a lot of work since the component has a lot of items.

答:
Actually there is a way to accomplish this. Here is an example that skips a component of a specific class.

Add two event handlers to your form similar to these:

```<code>procedure TForm224.DoCreateComponent(Reader: TReader; ComponentClass: TComponentClass; var Component: TComponent);
begin
  if ComponentClass = <whatever component class shall be skipped> then begin
    Abort;
  end;
end;

procedure TForm224.DoReaderError(Reader: TReader; const Message: string; var Handled: Boolean);
begin
  Handled := True;
end;
</code>```

Then override the form's ReadState() method this way:

```<code>procedure TForm224.ReadState(Reader: TReader);
begin
  Reader.OnError := DoReaderError;
  Reader.OnCreateComponent := DoCreateComponent;
  inherited;
  Reader.OnError := nil;
  Reader.OnCreateComponent := nil;
end;
</code>```

If there are several instances of that component class and you need to check for an individual instance, you can use the TReader.OnSetName event:

```<code>procedure TForm224.ReadState(Reader: TReader);
begin
  ...
  Reader.OnSetName := DoSetName;
  inherited;
  Reader.OnSetName := nil;
  ...
end;

procedure TForm224.DoSetName(Reader: TReader; Component: TComponent; var Name: string);
begin
  if Name = <instance name> then begin
    Abort;
  end;
end;
</code>```

Body:
Actually there is a way to accomplish this. Here is an example that skips a component of a specific class.

Add two event handlers to your form similar to these:

procedure TForm224.DoCreateComponent(Reader: TReader; ComponentClass: TComponentClass; var Component: TComponent);
begin
  if ComponentClass = <whatever component class shall be skipped> then begin
    Abort;
  end;
end;

procedure TForm224.DoReaderError(Reader: TReader; const Message: string; var Handled: Boolean);
begin
  Handled := True;
end;

Then override the form's ReadState() method this way:

procedure TForm224.ReadState(Reader: TReader);
begin
  Reader.OnError := DoReaderError;
  Reader.OnCreateComponent := DoCreateComponent;
  inherited;
  Reader.OnError := nil;
  Reader.OnCreateComponent := nil;
end;

If there are several instances of that component class and you need to check for an individual instance, you can use the TReader.OnSetName event:

procedure TForm224.ReadState(Reader: TReader);
begin
  ...
  Reader.OnSetName := DoSetName;
  inherited;
  Reader.OnSetName := nil;
  ...
end;

procedure TForm224.DoSetName(Reader: TReader; Component: TComponent; var Name: string);
begin
  if Name = <instance name> then begin
    Abort;
  end;
end;


问:
WPF vs XNA vs Surface for gesture based interface
I wonder which of these 3 frameworks / combination of them is most suitable for gesture-based interface (based on touch or motion recognition)?

I see online some directions, of using WPF and Surface, but nothing concrete.

I will appreciate if someone who already worked on this can suggest an approach.

答:
Not sure why Adrman deleted his post, but I'm going to re-post his link to Shawn Hargreave's post about the touch API on windows:

http://blogs.msdn.com/b/shawnhar/archive/2010/09/09/touch-input-on-windows-in-xna-game-studio-4-0.aspx

If you're interested in still using XNA for your project, there are definitely still options as Shawn "touches" upon in the end of his post. For example, here is an article on the XNA UK UG site that shows how to implement touch on windows:

http://xna-uk.net/blogs/randomchaos/archive/2010/02/10/xna-and-windows-7-multi-touch.aspx

Now, that pretty much ties you to the API, but it stands to reason that you could refactor this so that it was more generic, and then eventually just use the built-in touch API (assuming they implement touch on windows, which I believe they will).

ContentLicense: CC BY-SA 2.5


问:
Fastest way to compute entropy in Python
In my project I need to compute the entropy of 0-1 vectors many times. Here's my code:

```<code>def entropy(labels):
    """ Computes entropy of 0-1 vector. """
    n_labels = len(labels)

    if n_labels <= 1:
        return 0

    counts = np.bincount(labels)
    probs = counts[np.nonzero(counts)] / n_labels
    n_classes = len(probs)

    if n_classes <= 1:
        return 0
    return - np.sum(probs * np.log(probs)) / np.log(n_classes)
</code>```

Is there a faster way?

答:
Uniformly distributed data (high entropy):

```<code>s=range(0,256)
</code>```

Shannon entropy calculation step by step:

```<code>import collections
import math

# calculate probability for each byte as number of occurrences / array length
probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
# [0.00390625, 0.00390625, 0.00390625, ...]

# calculate per-character entropy fractions
e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
# [0.03125, 0.03125, 0.03125, ...]

# sum fractions to obtain Shannon entropy
entropy = sum(e_x)
>>> entropy
8.0
</code>```

One-liner (assuming import collections):

```<code>def H(s): return sum([-p_x*math.log(p_x,2) for p_x in [n_x/len(s) for x,n_x in collections.Counter(s).items()]])
</code>```

A proper function:

```<code>import collections
import math

def H(s):
    probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
    e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
    return sum(e_x)
</code>```

Test cases - English text taken from CyberChef entropy estimator:

```<code>>>> H(range(0,256))
8.0
>>> H(range(0,64))
6.0
>>> H(range(0,128))
7.0
>>> H([0,1])
1.0
>>> H('Standard English text usually falls somewhere between 3.5 and 5')
4.228788210509104
</code>```

Body:
In my project I need to compute the entropy of 0-1 vectors many times. Here's my code:

def entropy(labels):
    """ Computes entropy of 0-1 vector. """
    n_labels = len(labels)

    if n_labels <= 1:
        return 0

    counts = np.bincount(labels)
    probs = counts[np.nonzero(counts)] / n_labels
    n_classes = len(probs)

    if n_classes <= 1:
        return 0
    return - np.sum(probs * np.log(probs)) / np.log(n_classes)

Is there a faster way?

Body:
Uniformly distributed data (high entropy):

s=range(0,256)

Shannon entropy calculation step by step:

import collections
import math

# calculate probability for each byte as number of occurrences / array length
probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
# [0.00390625, 0.00390625, 0.00390625, ...]

# calculate per-character entropy fractions
e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
# [0.03125, 0.03125, 0.03125, ...]

# sum fractions to obtain Shannon entropy
entropy = sum(e_x)
>>> entropy
8.0

One-liner (assuming import collections):

def H(s): return sum([-p_x*math.log(p_x,2) for p_x in [n_x/len(s) for x,n_x in collections.Counter(s).items()]])

A proper function:

import collections
import math

def H(s):
    probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
    e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
    return sum(e_x)

Test cases - English text taken from CyberChef entropy estimator:

>>> H(range(0,256))
8.0
>>> H(range(0,64))
6.0
>>> H(range(0,128))
7.0
>>> H([0,1])
1.0
>>> H('Standard English text usually falls somewhere between 3.5 and 5')
4.228788210509104

ContentLicense: CC BY-SA 4.0


问:
Typescript: Yarn Workspaces IDE Support (IntelliJ, VSCode ...)
Working on a larger typescript project we decided to move the code to a monorepo with yarn workspaces.

We use webpack to build and bundle and everything works well (especially the linking between local modules/packages).

Since yarn workspaces will store most of the node_modules in the mono repo's root folder, the IDE (IntelliJ as well as VSCode) have problems resolving the imports to any node_modules when coding inside a "inner" project (so called "package" of a monorepo).

The strange thing is that imports are not known but on the other hand most of the time you can navigate to the correct source / definition within the IDEs for the same import if you write it down manually.

We have tried to tell IntelliJ to look into another folder for node_modules, but still not satisfying.

Please share your experience with yarn workspaces / monorepo (e.g. lerna) and how you develop the code living in these monorepos.

Which IDE do you use?

Did you add any special configurations to the IDE and/or package.json, tsconfig.json?

答:
IDEA doesn't provide any support for Yarn workspaces; if you miss it, please follow WEB-29250 and linked tickets for updates.
You can try adding path mappings to your tsconfig.json - see https://intellij-support.jetbrains.com/hc/en-us/community/posts/207656825/comments/115000529564


问:
Request to enable GPS occuring twice if activity stopped and started again
I have an activity which requests the user to enable the GPS in the onStart() by showing a dialog with OK and CANCEL buttons. But if the user presses home button before interacting with the dialog, and starts the app again, a new dialog box appears on top of the old one and hence the user sees two dialog boxes one after the another. How can I dismiss the old dialog box in the onStop method of the activity?

Here is the relevant part of my code:

```<code>protected void onStart() {
    super.onStart();
    enableGPS();
}

private void enableGPS() {                                      //GPS ENABLE RELATED METHOD
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
            .checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result
                    .getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:                           //GPS ALREDY TURNED ON
                    if (locationServiceConnected) {
                        if (ActivityCompat.checkSelfPermission(enableGPSActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, enableGPSActivity.this);
                        }
                    }
                    else {
                        redirectStatus.setText("ERROR: Not able to connect to Location Service");
                        btnRetry.setVisibility(View.VISIBLE);
                    }
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:               //GPS NOT ALREDY TURNED ON, SHOW TURN ON DIALOG
                    try {
                        status.startResolutionForResult(enableGPSActivity.this, REQUEST_CHECK_SETTINGS); //CREATING DIALOG FOR GPS TURN ON
                    } catch (IntentSender.SendIntentException e) {
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:       //GPS CANNOT BE TURNED ON
                    redirectStatus.setText("Permission Available, not able to enable GPS");
                    btnRetry.setVisibility(View.VISIBLE);
                    break;
            }
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {             //GPS ENABLE RELATED METHOD, DIALOG FOR GPS TURN ON
    if (requestCode == REQUEST_CHECK_SETTINGS) {
        if (resultCode == Activity.RESULT_OK) {                 // GPS TURN ON ACCEPTED
            if (locationServiceConnected) {
                if (ActivityCompat.checkSelfPermission(enableGPSActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                    redirectStatus.setText("Please Wait. Fetching Your Current Location");
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, enableGPSActivity.this);
                }
            }
        }
        if (resultCode == Activity.RESULT_CANCELED) {               //GPS TURN ON REJECTED
            redirectStatus.setText("Permission Available, GPS Off");
            btnRetry.setVisibility(View.VISIBLE);
        }
    }
}
</code>```

}

答:
```<code>  //  declares variables name

        private AlertDialog gpsAlertDialog;
        private boolean  isGpsDialogShowing = false;
        private LocationManager manager;

      // check gps enable or not if enable than remove dialog else show gps enable dialog in onResume method

protected void onResume()
        {
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)&&!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                    ShowGpsDialog();
                } else {
                    removeGpsDialog();
                }

            }

 //   remove dialog on destroy activity

    @Override
        protected void onDestroy() {
            super.onDestroy();
            removeGpsDialog();
        }

 //   method for show dialog for gps enable

          private void ShowGpsDialog() {

                isGpsDialogShowing = true;
                AlertDialog.Builder gpsBuilder = new AlertDialog.Builder(
                        MainMenuDrawerActivity.this);
                gpsBuilder.setCancelable(false);
                gpsBuilder
                        .setTitle(getString(R.string.dialog_no_gps))
                        .setMessage(getString(R.string.dialog_no_gps_messgae))
                        .setPositiveButton(getString(R.string.dialog_enable_gps),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        // continue with delete
                                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                        startActivity(intent);
                                        removeGpsDialog();
                                    }
                                })

                        .setNegativeButton(getString(R.string.dialog_exit),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        // do nothing
                                        removeGpsDialog();
                                        finish();
                                    }
                                });
                gpsAlertDialog = gpsBuilder.create();
                gpsAlertDialog.show();
            }

      //  method for remove gps dialog

            private void removeGpsDialog() {
                if (gpsAlertDialog != null && gpsAlertDialog.isShowing()) {
                    gpsAlertDialog.dismiss();
                    isGpsDialogShowing = false;
                    gpsAlertDialog = null;

                }
            }
</code>```

Body:
I have an activity which requests the user to enable the GPS in the onStart() by showing a dialog with OK and CANCEL buttons. But if the user presses home button before interacting with the dialog, and starts the app again, a new dialog box appears on top of the old one and hence the user sees two dialog boxes one after the another. How can I dismiss the old dialog box in the onStop method of the activity?

Here is the relevant part of my code:

protected void onStart() {
    super.onStart();
    enableGPS();
}

private void enableGPS() {                                      //GPS ENABLE RELATED METHOD
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
            .checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result
                    .getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:                           //GPS ALREDY TURNED ON
                    if (locationServiceConnected) {
                        if (ActivityCompat.checkSelfPermission(enableGPSActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, enableGPSActivity.this);
                        }
                    }
                    else {
                        redirectStatus.setText("ERROR: Not able to connect to Location Service");
                        btnRetry.setVisibility(View.VISIBLE);
                    }
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:               //GPS NOT ALREDY TURNED ON, SHOW TURN ON DIALOG
                    try {
                        status.startResolutionForResult(enableGPSActivity.this, REQUEST_CHECK_SETTINGS); //CREATING DIALOG FOR GPS TURN ON
                    } catch (IntentSender.SendIntentException e) {
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:       //GPS CANNOT BE TURNED ON
                    redirectStatus.setText("Permission Available, not able to enable GPS");
                    btnRetry.setVisibility(View.VISIBLE);
                    break;
            }
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {             //GPS ENABLE RELATED METHOD, DIALOG FOR GPS TURN ON
    if (requestCode == REQUEST_CHECK_SETTINGS) {
        if (resultCode == Activity.RESULT_OK) {                 // GPS TURN ON ACCEPTED
            if (locationServiceConnected) {
                if (ActivityCompat.checkSelfPermission(enableGPSActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                    redirectStatus.setText("Please Wait. Fetching Your Current Location");
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, enableGPSActivity.this);
                }
            }
        }
        if (resultCode == Activity.RESULT_CANCELED) {               //GPS TURN ON REJECTED
            redirectStatus.setText("Permission Available, GPS Off");
            btnRetry.setVisibility(View.VISIBLE);
        }
    }
}

}


问:
mysql with many tables
I have a major problem getting this to work properly. Here is the deal.

I have 4 tables - timeline, connections, images, votes

Timeline table:

```<code>time_id
time_title
</code>```

etc.

The timeline table connects with the images table via the connections table

Connections table:

```<code>time_id
image_id
</code>```

So the connections hold information about the id of the "post" the timeline and about image id

Images table:

```<code>image_id
image_url
image_type
</code>```

Images table contains images that could be used in the same timeline(post), so by this i can see the connection by looking at the connection table.

I also have a votes table that holds information about votes for the specific timeline post

Votes table:

```<code>vote_id
time_id
</code>```

the votes table contains many rows of each time_id and the idea is to count the number of times to se wich is the most popular

So heres the question:
I need to get the 5 most voted time_titles and show them with the first image for each time_title(post) so that it look like this for example

Image 1 that corresponds to Title 1 - that is the highest voted

Image 2 that corresponds to Title 2 - that is the second highest voted

etc.

Each timeline row (post) can hold many images and i only want to show the first of each post.

Hope you understand my problem!

Thanks a lot!

答:
The query will be

```<code>SELECT
 count(v.vote_id) as vote_times
 t.time_title,
 (
  SELECT
   image_url
  FROM
   images
  WHERE
   image_id = (
       SELECT
        image_id
       FROM
        connections as c
       WHERE
        c.time_id = t.time_id
       LIMIT 1
      )
  LIMIT 1
 ) as image_url
FROM
 votes as v
  LEFT JOIN
   time as t
    on
     t.time_id = v.time_id
GROUP BY
 v.time_id
ORDER BY
 vote_times desc
LIMIT 5;
</code>```

This will work, but might not be the most optimized one.

-- EDIT
to get image_type also try

```<code>SELECT
    count(v.vote_id) as vote_times
    t.time_title,
 i.image_url,
 i.image_type

FROM
    votes as v
        LEFT JOIN
            time as t
                on
                    t.time_id = v.time_id
  LEFT JOIN
   images as i
    on
     i.image_id = (
         SELECT
          image_id
         FROM
          connections as c
         WHERE
          c.time_id = t.time_id
         LIMIT 1
        )
GROUP BY
    v.time_id
ORDER BY
    vote_times desc, image_type desc
LIMIT 5;
</code>```

Title: mysql with many tables

Body:
I have a major problem getting this to work properly. Here is the deal.

I have 4 tables - timeline, connections, images, votes

Timeline table:

time_id
time_title

etc.

The timeline table connects with the images table via the connections table

Connections table:

time_id
image_id

So the connections hold information about the id of the "post" the timeline and about image id

Images table:

image_id
image_url
image_type

Images table contains images that could be used in the same timeline(post), so by this i can see the connection by looking at the connection table.

I also have a votes table that holds information about votes for the specific timeline post

Votes table:

vote_id
time_id

the votes table contains many rows of each time_id and the idea is to count the number of times to se wich is the most popular

So heres the question:
I need to get the 5 most voted time_titles and show them with the first image for each time_title(post) so that it look like this for example

Image 1 that corresponds to Title 1 - that is the highest voted

Image 2 that corresponds to Title 2 - that is the second highest voted

etc.

Each timeline row (post) can hold many images and i only want to show the first of each post.

Hope you understand my problem!

Thanks a lot!

Body:
The query will be

SELECT
 count(v.vote_id) as vote_times
 t.time_title,
 (
  SELECT
   image_url
  FROM
   images
  WHERE
   image_id = (
       SELECT
        image_id
       FROM
        connections as c
       WHERE
        c.time_id = t.time_id
       LIMIT 1
      )
  LIMIT 1
 ) as image_url
FROM
 votes as v
  LEFT JOIN
   time as t
    on
     t.time_id = v.time_id
GROUP BY
 v.time_id
ORDER BY
 vote_times desc
LIMIT 5;

This will work, but might not be the most optimized one.

-- EDIT
to get image_type also try

SELECT
    count(v.vote_id) as vote_times
    t.time_title,
 i.image_url,
 i.image_type

FROM
    votes as v
        LEFT JOIN
            time as t
                on
                    t.time_id = v.time_id
  LEFT JOIN
   images as i
    on
     i.image_id = (
         SELECT
          image_id
         FROM
          connections as c
         WHERE
          c.time_id = t.time_id
         LIMIT 1
        )
GROUP BY
    v.time_id
ORDER BY
    vote_times desc, image_type desc
LIMIT 5;


问:
HazelcastSessionRepository - custom session ID
I need to use custom session ID for the new sessions created by  HazelcastSessionRepository`.

However, HazelcastSessionRepository uses private final class HazelcastSession.

Therefore it is not possible to simply extend HazelcastSessionRepository and override createSession method outside the package org.springframework.session.hazelcast.

Unfortunately, I can see just these 2 options here:

Create own implementation of SessionRepository - just copy of the HazelcastSessionRepository indeed with createSession method changed

Create an extension of HazelcastSessionRepository (with createSession method overridden) within my project in org.springframework.session.hazelcast package.

Is there any other option?

答: I don't think there's a way to create your own session ids yet, but feel free to open a feature request.</p>


问:
custom monolog logging channel in symfony2 command
In this cookbook article, we can see how to use a custom channel in a service. But how can I use a custom login channel in a command ?

I created a symfony2 command to perform something. I would like to use monolog to log things done by my command.

Actually, I want to write log for my command in another file than the logs of the application.

答:
For Symfony 3.3 because of autowire services when you want to log on seperate files follow this approach:

For example let us suppose we need to log on 2 rotating files:

exception.log: For exceptions caused in the application.

dataFetch.log: For calls to an api tha retrieves the applications data.

The on services.yml put:

```<code>monolog:
  channels: ['dataFetch', 'exception']

  handlers:

    dataFetch:
     type: 'rotating_file'
     level: info
     type: stream
     path: 'dataFetch.log'
     max_files: 7
     channels: dataFetch

    exception:
         type: 'rotating_file'
         level: error
         type: stream
         path: 'exception.log'
         max_files: 7
         channels: exception
</code>```

Now for the exception loger you can inject ad dependency the monolog.logger.exception while for the dataFetch you can dependency inject the monolog.logger.dataFetch.

Body:
For Symfony 3.3 because of autowire services when you want to log on seperate files follow this approach:

For example let us suppose we need to log on 2 rotating files:

exception.log: For exceptions caused in the application.

dataFetch.log: For calls to an api tha retrieves the applications data.

The on services.yml put:

monolog:
  channels: ['dataFetch', 'exception']

  handlers:

    dataFetch:
     type: 'rotating_file'
     level: info
     type: stream
     path: 'dataFetch.log'
     max_files: 7
     channels: dataFetch

    exception:
         type: 'rotating_file'
         level: error
         type: stream
         path: 'exception.log'
         max_files: 7
         channels: exception

Now for the exception loger you can inject ad dependency the monolog.logger.exception while for the dataFetch you can dependency inject the monolog.logger.dataFetch.


问:
Creating Generator object from record list within a function
I'm trying to create generator object for the list of records with the data from mysql database, so I'm passing the mysql cursor object to the function as parameter.

My issue here is if the "if block" containing yield records is commented then cust_records function works perfectly fine but if I uncomment the line then the function is not working.

Not sure if this is not the way to yield the list object in Python 3

My code so far:

```<code>def cust_records(result_set) :

    block_id = None
    records = []
    i = 0
    for row in result_set :
        records.append((row['id'], row, smaller_ids))

    if records :
        yield records
</code>```

答:
The point of generators is lazy evaluation, so storing all records in a list and yielding the list makes no sense at all. If you want to retain lazy evalution (which is IMHO preferable, specially if you have to work on arbitrary datasets that might get huge), you want to yield each record, ie:

```<code>def cust_records(result_set) :
    for row in result_set :
        yield (row['id'], row, smaller_ids)

# then
def example():
   cursor.execute(<your_sql_query_here>)
   for record in cust_records(cursor):
       print(record)
</code>```

else (if you really want to consume as much memory as possible) just male cust_record a plain function:

```<code>def cust_records(result_set) :
    records = []
    for row in result_set :
        records.append((row['id'], row, smaller_ids))
    return records
</code>```

Body:
I'm trying to create generator object for the list of records with the data from mysql database, so I'm passing the mysql cursor object to the function as parameter.

My issue here is if the "if block" containing yield records is commented then cust_records function works perfectly fine but if I uncomment the line then the function is not working.

Not sure if this is not the way to yield the list object in Python 3

My code so far:

def cust_records(result_set) :

    block_id = None
    records = []
    i = 0
    for row in result_set :
        records.append((row['id'], row, smaller_ids))

    if records :
        yield records

Body:
The point of generators is lazy evaluation, so storing all records in a list and yielding the list makes no sense at all. If you want to retain lazy evalution (which is IMHO preferable, specially if you have to work on arbitrary datasets that might get huge), you want to yield each record, ie:

def cust_records(result_set) :
    for row in result_set :
        yield (row['id'], row, smaller_ids)

# then
def example():
   cursor.execute(<your_sql_query_here>)
   for record in cust_records(cursor):
       print(record)

else (if you really want to consume as much memory as possible) just male cust_record a plain function:

def cust_records(result_set) :
    records = []
    for row in result_set :
        records.append((row['id'], row, smaller_ids))
    return records


问:
Promise.all: What are arguments of promise.all.catch(e)
What are arguments of promise.all.catch(e)

Is e an array of errors or object?

```<code>Promise.all([promise1, promise2, ..])
.then((result1, result2,..)=>{})
.catch((error1,error2..???)=>{

})
</code>```

How can we get array of errors? if not Promise.all then how?

答:
There is no difference between an error handling of a simple Promise and a Promise.all.

Which means :

```<code>Promise.all([p1, p2, p3, ...])
  .then((v) => {
     // ...
  })
  .catch((err) => {
     // ...
  });
</code>```

With one error in the catch.

Promise.all return in an array (in the then) all results of given Promises.

In case of error it throw the error, that you catch (1 error).

EDIT :
About the fact to get all errors which seems to be the real question here

Javascript is single threaded, which means that it can execute only one function at a time. Javascript asynchronism means only that I/O won't be blocking.

The way Promise.all work is that at the first encountered error, it throw. And stop other promises. So you cannot have multiple errors.

Body:
What are arguments of promise.all.catch(e)

Is e an array of errors or object?

Promise.all([promise1, promise2, ..])
.then((result1, result2,..)=>{})
.catch((error1,error2..???)=>{

})

How can we get array of errors? if not Promise.all then how?

Body:
There is no difference between an error handling of a simple Promise and a Promise.all.

Which means :

Promise.all([p1, p2, p3, ...])
  .then((v) => {
     // ...
  })
  .catch((err) => {
     // ...
  });

With one error in the catch.

Promise.all return in an array (in the then) all results of given Promises.

In case of error it throw the error, that you catch (1 error).

EDIT :
About the fact to get all errors which seems to be the real question here

Javascript is single threaded, which means that it can execute only one function at a time. Javascript asynchronism means only that I/O won't be blocking.

The way Promise.all work is that at the first encountered error, it throw. And stop other promises. So you cannot have multiple errors.


问:
How to concatenate two dataframes based on the particular columns?
There are 2 dataframes which have different columns.
I'm trying to concatenate them based on the first 3 columns.

```<code>   a b c X
1  H A 8 1
2  M D 3 2
3  H A 9 3
4  L C 9 4

   a b c Y
1  H A 8 4
2  M D 3 3
3  H A 9 2
4  L C 9 2
</code>```

It's the expected result:

```<code>   a b c X Y
1  H A 8 1 4
2  M D 3 2 3
3  H A 9 3 2
4  L C 9 4 2
</code>```

I can't find a efficient way to concatenate them!!

答:
```<code>new_df = pd.merge(df1, df2)
print (new_df)

output:-       a  b  c  X  Y
            0  H  A  8  1  4
            1  M  D  3  2  3
            2  H  A  9  3  2
            3  L  C  9  4  2
</code>```

Body:
There are 2 dataframes which have different columns.
I'm trying to concatenate them based on the first 3 columns.

   a b c X
1  H A 8 1
2  M D 3 2
3  H A 9 3
4  L C 9 4

   a b c Y
1  H A 8 4
2  M D 3 3
3  H A 9 2
4  L C 9 2

It's the expected result:

   a b c X Y
1  H A 8 1 4
2  M D 3 2 3
3  H A 9 3 2
4  L C 9 4 2

I can't find a efficient way to concatenate them!!


问:
How to data in segue using Swift
I'd like to pass my array from my first to my second ViewController.
In the end of my first VC I tried to pass it like this:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let secondVC = ViewController2()
    secondVC.passengers2 = passengers
    print(secondVC.passengers2)

    print(passengers)
    }
</code>```

"passengers" is my first array in "ViewController.swift" and "passengers2" my sewcond array in "ViewController2.swift".

When I go over to my second VC, the console tells me, that "passengers" and "passengers2" have the same value, but as soon as I am in "ViewController2.swift", "passengers2" is emtpy for some reason.

Does anyone know why?

答:
The problem in your code is that you instantiate a new ViewController2 object, which is never used.

You want to use the destination view controller that is inside your segue object, like that :

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destinationViewController as? ViewController2 {
        destinationVC.passengers2 = passengers
    }
}
</code>```

Title: How to data in segue using Swift

Body:
I'd like to pass my array from my first to my second ViewController.
In the end of my first VC I tried to pass it like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let secondVC = ViewController2()
    secondVC.passengers2 = passengers
    print(secondVC.passengers2)

    print(passengers)
    }

"passengers" is my first array in "ViewController.swift" and "passengers2" my sewcond array in "ViewController2.swift".

When I go over to my second VC, the console tells me, that "passengers" and "passengers2" have the same value, but as soon as I am in "ViewController2.swift", "passengers2" is emtpy for some reason.

Does anyone know why?

Body:
The problem in your code is that you instantiate a new ViewController2 object, which is never used.

You want to use the destination view controller that is inside your segue object, like that :

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destinationViewController as? ViewController2 {
        destinationVC.passengers2 = passengers
    }
}


问:
Remove words from string
I'm trying to remove certain words from a data frame:

```<code>name    age words
James   34  hello, my name is James.
John    30  hello, my name is John. Here is my favourite website https://stackoverflow.com
Jim 27  Hi! I'm another person whose name begins with a J! Here is something that should be filtered out: <filter>
</code>```

```<code>df<-structure(list(name = structure(c(1L, 3L, 2L), .Label = c("James",
"Jim", "John"), class = "factor"), age = c(34L, 30L, 27L), message = structure(1:3, .Label = c("hello, my name is James. ",
"hello, my name is John. Here is my favourite website https://stackoverflow.com",
"Hi! I'm another person whose name begins with a J! Here is something that should be filtered out: <filter>"
), class = "factor")), .Names = c("name", "age", "message"), class = "data.frame", row.names = c(NA,
-3L))
</code>```

I'm trying to remove all words containing matches to http or filter.

I would like to iterate over each row, split the string on white space and then ask whether the word contains either http or <filter> (or other words). If so, then I want to replace the word with a space.

There are a load of questions concerning removing words that exatly match another word, or list of words, but I can't find much on removing words that match some criteria (e.g. http or www.).

I've tried:

gsub, !grepl and tm_map approaches (e.g. this), but I can't get any of them to produce my expected output of:

```<code>name    age words
James   34  hello, my name is James.
John    30  hello, my name is John. Here is my favourite website
Jim 27  Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out:
</code>```

答:
We can use gsub

```<code>gsub("\\s(https:\\S+|<filter>)", "", df$message)
</code>```

Title: Remove words from string

Body:
I'm trying to remove certain words from a data frame:

name    age words
James   34  hello, my name is James.
John    30  hello, my name is John. Here is my favourite website https://stackoverflow.com
Jim 27  Hi! I'm another person whose name begins with a J! Here is something that should be filtered out: <filter>

df<-structure(list(name = structure(c(1L, 3L, 2L), .Label = c("James",
"Jim", "John"), class = "factor"), age = c(34L, 30L, 27L), message = structure(1:3, .Label = c("hello, my name is James. ",
"hello, my name is John. Here is my favourite website https://stackoverflow.com",
"Hi! I'm another person whose name begins with a J! Here is something that should be filtered out: <filter>"
), class = "factor")), .Names = c("name", "age", "message"), class = "data.frame", row.names = c(NA,
-3L))

I'm trying to remove all words containing matches to http or filter.

I would like to iterate over each row, split the string on white space and then ask whether the word contains either http or <filter> (or other words). If so, then I want to replace the word with a space.

There are a load of questions concerning removing words that exatly match another word, or list of words, but I can't find much on removing words that match some criteria (e.g. http or www.).

I've tried:

gsub, !grepl and tm_map approaches (e.g. this), but I can't get any of them to produce my expected output of:

name    age words
James   34  hello, my name is James.
John    30  hello, my name is John. Here is my favourite website
Jim 27  Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out:

Body:
We can use gsub

gsub("\\s(https:\\S+|<filter>)", "", df$message)


问:
Python: Search for DateTime inside a Dictionary that is Less than a certain DateTime
If I have the following data:

```<code>>data1 = ({'StartDT':'2017-01-01 04:54:00'},{'EndDT':'2017-01-01 08:56:00'},{'Code':'1234'})

>data2 = ({'StartDT':'2017-01-01 05:54:00'},{'EndDT':'2017-01-01 07:45:00'},{'Code':'1234'})
</code>```

Question 1 = In Python, what do you think is the best data structure for this?

Question 2 = My goal is to search for data(n) which has a StartDT which is less than a certain DateTime (example: '2017-01-01 06:30:00), and whose EndDT is greater than that certain DateTime.

Thanks for the help!

答:
Here's another approach to the problem.

```<code># First, let's put data in a more useful format...
data = [{'StartDT': '2017-01-01 04:54:00',
         'EndDT': '2017-01-01 08:56:00',
         'Code': '1234'},
        {'StartDT': '2017-01-01 05:54:00',
         'EndDT': '2017-01-01 07:45:00',
         'Code': '1234'}]

# Convert the date string to datetime (you should really do this as you insert
# the dictionaries into the list...
from datetime import datetime

def convert_timestamp(s):
    return datetime.strptime(s, '%Y-%m-%d %H:%M:%S')

for d in data:
    d['StartDT'] = convert_timestamp(d['StartDT'])
    d['EndDT'] = convert_timestamp(d['EndDT'])

# Next you can use filter and a function to help pick off the entries that
# meet your needs.

start_time = convert_timestamp('2017-01-01 05:30:00')
end_time = convert_timestamp('2017-01-01 08:30:00')

matching = filter(lambda d: d['StartDT'] < start_time and d['EndDT'] > end_time,
                  data)

print(repr(list(matching)))

# This could be rewritten as...
def is_out_of_range(start, end, d):
    return d['StartDT'] < start and d['EndDT'] > end

# We use partial() to add the start and end parameters, which leaves a function
# with one parameter left.  That will be the data passed in by filter.
from functools import partial
matching = filter(partial(is_out_of_range, start_time, end_time), data)

# Alternatively, you could avoid the partial with a lambda:
matching = filter(lambda d: is_out_of_range(start_time, end_time, d), data)

print(repr(list(matching)))
</code>```

You definitely want to use a different organization for your data (a list of dictionaries), and you'll need to convert your strings to something more useful (datetime instances).  That allows you to iterate through the data much better and do the matching you want.

Body:
If I have the following data:

>data1 = ({'StartDT':'2017-01-01 04:54:00'},{'EndDT':'2017-01-01 08:56:00'},{'Code':'1234'})

>data2 = ({'StartDT':'2017-01-01 05:54:00'},{'EndDT':'2017-01-01 07:45:00'},{'Code':'1234'})

Question 1 = In Python, what do you think is the best data structure for this?

Question 2 = My goal is to search for data(n) which has a StartDT which is less than a certain DateTime (example: '2017-01-01 06:30:00), and whose EndDT is greater than that certain DateTime.

Thanks for the help!

Body:
Here's another approach to the problem.

# First, let's put data in a more useful format...
data = [{'StartDT': '2017-01-01 04:54:00',
         'EndDT': '2017-01-01 08:56:00',
         'Code': '1234'},
        {'StartDT': '2017-01-01 05:54:00',
         'EndDT': '2017-01-01 07:45:00',
         'Code': '1234'}]

# Convert the date string to datetime (you should really do this as you insert
# the dictionaries into the list...
from datetime import datetime

def convert_timestamp(s):
    return datetime.strptime(s, '%Y-%m-%d %H:%M:%S')

for d in data:
    d['StartDT'] = convert_timestamp(d['StartDT'])
    d['EndDT'] = convert_timestamp(d['EndDT'])

# Next you can use filter and a function to help pick off the entries that
# meet your needs.

start_time = convert_timestamp('2017-01-01 05:30:00')
end_time = convert_timestamp('2017-01-01 08:30:00')

matching = filter(lambda d: d['StartDT'] < start_time and d['EndDT'] > end_time,
                  data)

print(repr(list(matching)))

# This could be rewritten as...
def is_out_of_range(start, end, d):
    return d['StartDT'] < start and d['EndDT'] > end

# We use partial() to add the start and end parameters, which leaves a function
# with one parameter left.  That will be the data passed in by filter.
from functools import partial
matching = filter(partial(is_out_of_range, start_time, end_time), data)

# Alternatively, you could avoid the partial with a lambda:
matching = filter(lambda d: is_out_of_range(start_time, end_time, d), data)

print(repr(list(matching)))

You definitely want to use a different organization for your data (a list of dictionaries), and you'll need to convert your strings to something more useful (datetime instances).  That allows you to iterate through the data much better and do the matching you want.


问:
Query to produce data only within the asked hour range
Oracle SQL:

I been trying to get this some snippet of query working. When you run it, it prompts you for an hour, and displays no records. I don’t want the query to have a static hour as it will need to be run 4 times a day.
So from the ‘&date’ input, I want it to show data for the past 24 hours. Is that possible?

```<code>dt_time = timestamp(6) field

select distinct to_char(dt_ time,'dd/mm/yyyy hh24'), fault_description
from order
where to_char(dt_time,'hh24') <= '&date' -24
order by to_char(dt_ time,'dd/mm/yyyy hh24');
</code>```

Example, if you enter 10 (when query executed) it will show the data from 10(:00) through to 10(:00)next day

[Hope there is enough info for someone to answer, please]

答:
```<code>WHERE DATEDIFF(SYSDATE,DT_TIME) * 24  < &DATE AND DT_TIME < SYSDATE
</code>```

Body:
Oracle SQL:

I been trying to get this some snippet of query working. When you run it, it prompts you for an hour, and displays no records. I don’t want the query to have a static hour as it will need to be run 4 times a day.
So from the ‘&date’ input, I want it to show data for the past 24 hours. Is that possible?

dt_time = timestamp(6) field

select distinct to_char(dt_ time,'dd/mm/yyyy hh24'), fault_description
from order
where to_char(dt_time,'hh24') <= '&date' -24
order by to_char(dt_ time,'dd/mm/yyyy hh24');

Example, if you enter 10 (when query executed) it will show the data from 10(:00) through to 10(:00)next day

[Hope there is enough info for someone to answer, please]


问:
Select data within today
I want to have query fetch all record falls with in today,

```<code>SELECT * from table where createddate >=  select date(‘now’) and createddate <=select date(‘now’)
</code>```

This query not working.

Below query working

```<code>SELECT * from table where createddate >= '2017-11-17 00:00:00' and createddate <= '2017-11-17 23:59:59'
</code>```

but I want to construct query like

```<code>SELECT * from table where createddate >=  select date(‘now 00:00:00’) and createddate <=select date(‘now 23:59:59’)
</code>```

答:
The date() function returns the date as a string in YYYY-mm-dd format. To add the time, simply concatenate the desired time values:

```<code>WHERE createddate BETWEEN date('now') || ' 00:00:00'
                      AND date('now') || ' 23:59:59'
</code>```

If you do not have an index on this column, or if speed does not matter, you can simply strip the time from the column value first:

```<code>WHERE date(createddate) = date('now')
</code>```

Title: Select data within today

Body:
I want to have query fetch all record falls with in today,

SELECT * from table where createddate >=  select date(‘now’) and createddate <=select date(‘now’)

This query not working.

Below query working

SELECT * from table where createddate >= '2017-11-17 00:00:00' and createddate <= '2017-11-17 23:59:59'

but I want to construct query like

SELECT * from table where createddate >=  select date(‘now 00:00:00’) and createddate <=select date(‘now 23:59:59’)

Body:
The date() function returns the date as a string in YYYY-mm-dd format. To add the time, simply concatenate the desired time values:

WHERE createddate BETWEEN date('now') || ' 00:00:00'
                      AND date('now') || ' 23:59:59'

If you do not have an index on this column, or if speed does not matter, you can simply strip the time from the column value first:

WHERE date(createddate) = date('now')


问:
how to store Gridview Boolean value in session variable and show another page in asp.net

GridView Page1 CodeBehinde1:

```<code>protected void  GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    bool Customs_Clearance = GridView1.SelectedRow.Cells[23].Text;
}

Session["customs_Clearance"] = Customs_Clearance;
</code>```

And Page2 Which Show session GridView Data Code Behind:
CheckBox

```<code>CheckCustomClearance.Text=Session ["customs_Clearance"].ToString();
</code>```

答:
Use the code below for your case.
I am assuming that the the column with index 23 is the boolean column and displayed as a checkbox column.

You can then always access in your other page Session["customs_Clearance"].

```<code>protected void  GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   //get selected row
   GridRow  selectedRow = GridView1.Rows[GridView1.SelectedIndex];

   //check if it's a checkbox column and set Session variable, if it is
   if(selectedRow.Cells[23].Controls[0] is CheckBox) {
     bool isChecked = (selectedRow.Cells[23].Controls[0] as CheckBox).Checked;
     Session["customs_Clearance"] = (isChecked == true ? "checked" : "unchecked");
   }
}
</code>```

Body:
GridView Page1 CodeBehinde1:

protected void  GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    bool Customs_Clearance = GridView1.SelectedRow.Cells[23].Text;
}

Session["customs_Clearance"] = Customs_Clearance;

And Page2 Which Show session GridView Data Code Behind:
CheckBox

CheckCustomClearance.Text=Session ["customs_Clearance"].ToString();

Body:
Use the code below for your case.
I am assuming that the the column with index 23 is the boolean column and displayed as a checkbox column.

You can then always access in your other page Session["customs_Clearance"].

protected void  GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   //get selected row
   GridRow  selectedRow = GridView1.Rows[GridView1.SelectedIndex];

   //check if it's a checkbox column and set Session variable, if it is
   if(selectedRow.Cells[23].Controls[0] is CheckBox) {
     bool isChecked = (selectedRow.Cells[23].Controls[0] as CheckBox).Checked;
     Session["customs_Clearance"] = (isChecked == true ? "checked" : "unchecked");
   }
}


问:
How to implement searching concept using keywords in SQL
Can anyone guide how to implement the keyword search concept in SQL.Is there only “Like” operator  available or any other options there?

Example:      -                 Table:

Keyword --      Questions        --      Answers

Where,pen        --   Where is my pen?  --  Pen is on the table

Where ,pen, kept -- where you have kept the pen  -- Pen is under the
table

Input  - Where is my pen?
Output should be  - “Pen is on the table”

In this part I have to split the keyword from input and check the keyword with db to send the output. I should  get only one output from above  .Because in second  row value  also have  “where,pen” keyword

Could anyone suggest  how this logic  will be implemented .
I would like to know If any keyword creating option can done in SQL part itself.

答:
You do not want to store the keywords in a comma separated list.  Instead, you want a separate table, say QuestionKeywords:

```<code>create table QuestionKeywords (
    QuestionKeywordsId int identity(1, 1) primary key,
    QuestionId int not null references Questions(QuestionId),
    Keyword varchar(255),
    constraint unq_QuestionKeywords_QuestionId_Keyword unique (QuestionId, Keyword)
);
</code>```

You can then search for keywords just using equality or in.

Body:
You do not want to store the keywords in a comma separated list.  Instead, you want a separate table, say QuestionKeywords:

create table QuestionKeywords (
    QuestionKeywordsId int identity(1, 1) primary key,
    QuestionId int not null references Questions(QuestionId),
    Keyword varchar(255),
    constraint unq_QuestionKeywords_QuestionId_Keyword unique (QuestionId, Keyword)
);

You can then search for keywords just using equality or in.


问:
Accounting for a single row in variable range?
So, I've been using various bits of code from various forums to put together macros to make my job easier, however I've hit a snag. I'm using the following bit of code to autofill and select a dynamic range that needs copying and pasting elsewhere:

```<code>Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row

Range("AP2").AutoFill Destination:=Range("AP2:AP" & lastRow)
Range("AQ2").AutoFill Destination:=Range("AQ2:AQ" & lastRow)
Range("AR2").AutoFill Destination:=Range("AR2:AR" & lastRow)
Range("AS2").AutoFill Destination:=Range("AS2:AS" & lastRow)
Range("AT2").AutoFill Destination:=Range("AT2:AT" & lastRow)
Range("AU2").AutoFill Destination:=Range("AU2:AU" & lastRow)

Range("AP2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
</code>```

The issue I face is, I believe, in the last line (although I'm sure somebody will tell me there's an easier way to address lines 3-8). In the instances where this variable range returns a single row, the Selection.End(xlDown) grabs all rows from row 2 to the bottom, meaning it's too large to paste into the destination. How could I amend this to account for single rows?

FYI the Selection.End(xlToRight) is always the same number of columns, if that helps at all.

答:
if you want just to select range AP:AU from the second to the last row, just: </p>

```<code>Range(Range("AP2"), Range("AU" & Cells.Rows.Count).End(xlUp)).Select
</code>```

<p>BTW. I suspect that next thing that you want to do is Selection.Copy. Don't do that, just replace .Select with .Copy. </p>

```<code>Range(Range("AP2"), Range("AU" & Cells.Rows.Count).End(xlUp)).Copy
</code>```

Body:
So, I've been using various bits of code from various forums to put together macros to make my job easier, however I've hit a snag. I'm using the following bit of code to autofill and select a dynamic range that needs copying and pasting elsewhere:

Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row

Range("AP2").AutoFill Destination:=Range("AP2:AP" & lastRow)
Range("AQ2").AutoFill Destination:=Range("AQ2:AQ" & lastRow)
Range("AR2").AutoFill Destination:=Range("AR2:AR" & lastRow)
Range("AS2").AutoFill Destination:=Range("AS2:AS" & lastRow)
Range("AT2").AutoFill Destination:=Range("AT2:AT" & lastRow)
Range("AU2").AutoFill Destination:=Range("AU2:AU" & lastRow)

Range("AP2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select

The issue I face is, I believe, in the last line (although I'm sure somebody will tell me there's an easier way to address lines 3-8). In the instances where this variable range returns a single row, the Selection.End(xlDown) grabs all rows from row 2 to the bottom, meaning it's too large to paste into the destination. How could I amend this to account for single rows?

FYI the Selection.End(xlToRight) is always the same number of columns, if that helps at all.

Body:
if you want just to select range AP:AU from the second to the last row, just:

Range(Range("AP2"), Range("AU" & Cells.Rows.Count).End(xlUp)).Select

BTW. I suspect that next thing that you want to do is Selection.Copy. Don't do that, just replace .Select with .Copy.

Range(Range("AP2"), Range("AU" & Cells.Rows.Count).End(xlUp)).Copy


问:
Swift UIWebView initial zoom scale
Hey i asked similar question some Days ago but no on could help me and no i'm think im closer to the problem. I have an WebView on my rootViewController and saved some Values for zoom scale and position of an local PDF, now i want set the Webview to this values when it appears so i tried the following.

```<code>   override func viewDidAppear(animated: Bool) {

    doLayoutThings()

}
    func doLayoutThings(){

    if(defaults.objectForKey("positionY") != nil){

        WebView.scrollView.setZoomScale(defaults.objectForKey("zoomlevel") as! CGFloat, animated: false)
        let offest = CGPoint(x: defaults.objectForKey("positionX") as! CGFloat, y: defaults.objectForKey("positionY") as! CGFloat)
        WebView.scrollView.setContentOffset(offest, animated:false)
        println(defaults.objectForKey("zoomlevel") as! CGFloat)

    }
</code>```

I know that there are the correct values are saved to UserDefaults but the Webview looks if i didn't make any scrolling or zooming.  I'm really happy about any solution Ideas.

答:
I am used this link to resolved this issue

In Swift

Initially i am try to change the web view zoom scale but it was not so working fine .

```<code>webview.scrollView.setZoomScale(1.5, animated: true)
</code>```

so i try to change it in webViewDidFinishLoad

```<code>func webViewDidFinishLoad(_ webView: UIWebView) {
    webview.scalesPageToFit = true

    let str = "var meta = document.createElement('meta');"
    let str1 = "meta.setAttribute( 'name', 'viewport' ); "
    let str2 = "meta.setAttribute( 'content', 'width = device-width, initial-scale = 1.0, user-scalable = yes' ); "
    let str3 = "document.getElementsByTagName('head')[0].appendChild(meta)"

    webview.stringByEvaluatingJavaScript(from: "\(str)\(str1)\(str2)\(str3)")

}
</code>```

if you need to change the zoom level, change the "initial-scale" to see the effect of initial level zooming.
It's really helpful for me.
Thanks "UIWebView set initial zoom scale programmatically when loading an external website?"

Title: Swift UIWebView initial zoom scale

Body:
Hey i asked similar question some Days ago but no on could help me and no i'm think im closer to the problem. I have an WebView on my rootViewController and saved some Values for zoom scale and position of an local PDF, now i want set the Webview to this values when it appears so i tried the following.

   override func viewDidAppear(animated: Bool) {

    doLayoutThings()

}
    func doLayoutThings(){

    if(defaults.objectForKey("positionY") != nil){

        WebView.scrollView.setZoomScale(defaults.objectForKey("zoomlevel") as! CGFloat, animated: false)
        let offest = CGPoint(x: defaults.objectForKey("positionX") as! CGFloat, y: defaults.objectForKey("positionY") as! CGFloat)
        WebView.scrollView.setContentOffset(offest, animated:false)
        println(defaults.objectForKey("zoomlevel") as! CGFloat)

    }

I know that there are the correct values are saved to UserDefaults but the Webview looks if i didn't make any scrolling or zooming.  I'm really happy about any solution Ideas.

Body:
I am used this link to resolved this issue

In Swift

Initially i am try to change the web view zoom scale but it was not so working fine .

webview.scrollView.setZoomScale(1.5, animated: true)

so i try to change it in webViewDidFinishLoad

func webViewDidFinishLoad(_ webView: UIWebView) {
    webview.scalesPageToFit = true

    let str = "var meta = document.createElement('meta');"
    let str1 = "meta.setAttribute( 'name', 'viewport' ); "
    let str2 = "meta.setAttribute( 'content', 'width = device-width, initial-scale = 1.0, user-scalable = yes' ); "
    let str3 = "document.getElementsByTagName('head')[0].appendChild(meta)"

    webview.stringByEvaluatingJavaScript(from: "\(str)\(str1)\(str2)\(str3)")

}

if you need to change the zoom level, change the "initial-scale" to see the effect of initial level zooming.
It's really helpful for me.
Thanks "UIWebView set initial zoom scale programmatically when loading an external website?"


问:
Find time difference between highest and lowest value in data frame and sort by factor
I have a data frame and it looks like this:

```<code>submition_id       time_answered
           2 2017-11-06 14:19:30
           2 2017-11-06 14:22:45
           2 2017-11-06 14:24:55
           2 2017-11-06 14:34:10
           4 2017-11-06 14:31:23
           4 2017-11-06 14:33:21
           5 2017-11-06 14:54:48
           5 2017-11-06 14:59:38
           5 2017-11-06 15:05:39
         ...                 ...
</code>```

So basically my submition_id column is a factor column and time_answered column is POSIXct column. I want to find the time difference for each factor which is basically max(x) - min(x). How can I do this effective with inbuilt functions? Such that I get

```<code>submition_id       difference
           2            14.67
           4             1.96
           5             9.77
         ...              ...
</code>```

I would like it in minutes as well.

答:
I believe there must be similar questions on SO.

However, for the sake of completeness, here is a data.table solution (including data):

```<code>library(data.table)
setDT(DT)[, .(diff = difftime(max(time_answered), min(time_answered), unit = 'mins')),
          by = submition_id]
</code>```

```<code>   submition_id           diff
1:            2 14.666667 mins
2:            4  1.966667 mins
3:            5 10.850000 mins
</code>```

Data

```<code>DT <- readr::read_table("submition_id       time_answered
           2 2017-11-06 14:19:30
           2 2017-11-06 14:22:45
           2 2017-11-06 14:24:55
           2 2017-11-06 14:34:10
           4 2017-11-06 14:31:23
           4 2017-11-06 14:33:21
           5 2017-11-06 14:54:48
           5 2017-11-06 14:59:38
           5 2017-11-06 15:05:39")
</code>```

Body:
I have a data frame and it looks like this:

submition_id       time_answered
           2 2017-11-06 14:19:30
           2 2017-11-06 14:22:45
           2 2017-11-06 14:24:55
           2 2017-11-06 14:34:10
           4 2017-11-06 14:31:23
           4 2017-11-06 14:33:21
           5 2017-11-06 14:54:48
           5 2017-11-06 14:59:38
           5 2017-11-06 15:05:39
         ...                 ...

So basically my submition_id column is a factor column and time_answered column is POSIXct column. I want to find the time difference for each factor which is basically max(x) - min(x). How can I do this effective with inbuilt functions? Such that I get

submition_id       difference
           2            14.67
           4             1.96
           5             9.77
         ...              ...

I would like it in minutes as well.

Body:
I believe there must be similar questions on SO.

However, for the sake of completeness, here is a data.table solution (including data):

library(data.table)
setDT(DT)[, .(diff = difftime(max(time_answered), min(time_answered), unit = 'mins')),
          by = submition_id]

   submition_id           diff
1:            2 14.666667 mins
2:            4  1.966667 mins
3:            5 10.850000 mins

Data

DT <- readr::read_table("submition_id       time_answered
           2 2017-11-06 14:19:30
           2 2017-11-06 14:22:45
           2 2017-11-06 14:24:55
           2 2017-11-06 14:34:10
           4 2017-11-06 14:31:23
           4 2017-11-06 14:33:21
           5 2017-11-06 14:54:48
           5 2017-11-06 14:59:38
           5 2017-11-06 15:05:39")


问:
Conditional Filtering with if in elasticsearch
I have the following filter.conf file in my logstash configuration:

```<code>filter {
    mutate {
        add_field => {
            "node" => "%{[@metadata][rabbitmq_headers][node]}"
            "connection" => "%{[@metadata][rabbitmq_headers][connection]}"
            "vhost" => "%{[@metadata][rabbitmq_headers][vhost]}"
            "user" => "%{[@metadata][rabbitmq_headers][user]}"
            "channel" => "%{[@metadata][rabbitmq_headers][channel]}"
            "exchange" => "%{[@metadata][rabbitmq_headers][exchange_name]}"
            "routing_keys" => "%{[@metadata][rabbitmq_headers][routing_keys]}"
            "routed_queues" => "%{[@metadata][rabbitmq_headers][routed_queues]}"
            "routing-key" => "%{[@metadata][rabbitmq_properties][routing-key]}"
        }
    }
    if [exchange] == "OUTGOING.E.TOPIC" {
      mutate { add_field => "status" => "Outgoing message" }
    } else if [exchange] == "INCOMING.E.TOPIC" {
      mutate { add_field => "status" => "Incoming message" }
    } else {
      mutate { add_field => "status" => "Unknown" }
    }
}
</code>```

But, when I try to run logstash I get:

```<code>Cannot create pipeline {:reason=>"Expected one of #, {, \", ', }
</code>```

In the if condition (If I remove it, it works). What am I doing wrong with the if condition?

答:
You're missing brackets around the "status" => "Outgoing message"

It would look like this:

```<code>if [exchange] == "OUTGOING.E.TOPIC" {
  mutate {
    add_field => {
      "status" => "Outgoing message"
    }
  }
} else if [exchange] == "INCOMING.E.TOPIC" {
  mutate { add_field => {"status" => "Incoming message"} }
} else {
  mutate { add_field => {"status" => "Unknown"} }
}
</code>```

You can see the documentation here.

Body:
I have the following filter.conf file in my logstash configuration:

filter {
    mutate {
        add_field => {
            "node" => "%{[@metadata][rabbitmq_headers][node]}"
            "connection" => "%{[@metadata][rabbitmq_headers][connection]}"
            "vhost" => "%{[@metadata][rabbitmq_headers][vhost]}"
            "user" => "%{[@metadata][rabbitmq_headers][user]}"
            "channel" => "%{[@metadata][rabbitmq_headers][channel]}"
            "exchange" => "%{[@metadata][rabbitmq_headers][exchange_name]}"
            "routing_keys" => "%{[@metadata][rabbitmq_headers][routing_keys]}"
            "routed_queues" => "%{[@metadata][rabbitmq_headers][routed_queues]}"
            "routing-key" => "%{[@metadata][rabbitmq_properties][routing-key]}"
        }
    }
    if [exchange] == "OUTGOING.E.TOPIC" {
      mutate { add_field => "status" => "Outgoing message" }
    } else if [exchange] == "INCOMING.E.TOPIC" {
      mutate { add_field => "status" => "Incoming message" }
    } else {
      mutate { add_field => "status" => "Unknown" }
    }
}

But, when I try to run logstash I get:

Cannot create pipeline {:reason=>"Expected one of #, {, \", ', }

In the if condition (If I remove it, it works). What am I doing wrong with the if condition?

Body:
You're missing brackets around the "status" => "Outgoing message"

It would look like this:

if [exchange] == "OUTGOING.E.TOPIC" {
  mutate {
    add_field => {
      "status" => "Outgoing message"
    }
  }
} else if [exchange] == "INCOMING.E.TOPIC" {
  mutate { add_field => {"status" => "Incoming message"} }
} else {
  mutate { add_field => {"status" => "Unknown"} }
}

You can see the documentation here.


问:
ArgumentNullException message without parameter name
I am throwing ArgumentNullException in part of my code in C#. I want to catch and display the error message of my exception. But without the parameter name. I want to pass the parameter name to the exception constructor.

```<code>throw new ArgumentNullException("myParameter", errorMessageStringVariable);
</code>```

If I call error.Message I get something like

errorMessageStringVariable
parameter name: myParameter

I want to display only the errorMessageStringVariable. Is it possible using ArgumentNullException, without some kind of formating on the error.Message?

答:
If you call:

```<code>new ArgumentNullException(null, errorMessageStringVariable)
</code>```

The exception message will be:

Value cannot be null. Parameter name: errorMessageStringVariable

If you instead use:

```<code>new ArgumentNullException(string.Empty, errorMessageStringVariable)
</code>```

you will only get the error message.

Body:
I am throwing ArgumentNullException in part of my code in C#. I want to catch and display the error message of my exception. But without the parameter name. I want to pass the parameter name to the exception constructor.

throw new ArgumentNullException("myParameter", errorMessageStringVariable);

If I call error.Message I get something like

errorMessageStringVariable
parameter name: myParameter

I want to display only the errorMessageStringVariable. Is it possible using ArgumentNullException, without some kind of formating on the error.Message?

Body:
If you call:

new ArgumentNullException(null, errorMessageStringVariable)

The exception message will be:

Value cannot be null. Parameter name: errorMessageStringVariable

If you instead use:

new ArgumentNullException(string.Empty, errorMessageStringVariable)

you will only get the error message.


问:
Angular 4 form validation on multiple fields
EDIT:
What I want to achieve is a validation on one single formControl and not the whole form. The validator should check all atom fields like house number, street etc. and then invalidate the google maps input control.

I am programming a form with Google Maps Autocomplete.
The user should enter a address into a input field that triggers the Google Maps autocomplete logic. When an address is selected the callback function selects the street, house number etc. and uses the API result to fill in the required address data fields.
The other form elements are displayed but readonly so we always get valid data and can perform validation on the inputs.

The problem is that my validator doesn't trigger the input field. The main input field is always valid and doesn't get the ng-invalid class.

```<code>@Component({
  selector: 'my-app',

  styles: [`
    .ng-valid {
      border:#0ff;
    }

    .ng-invalid {
      border:#f00;
    }
  `],
  template: `

  <form [formGroup]="testForm">
                <input type="text" formControlName="address">
                <input type="text" formControlName="tel">
                <input type="text" formControlName="mail">
            </form>
  `
})
export class AppComponent {
  testForm:FormGroup;

  constructor(private fb: FormBuilder) {
    this.testForm = this.fb.group({
            address:['', myValidator],
            tel:[''],
            mail:['']
        }, {
            validator: myValidator("tel", "mail")
        });
  }
}

export const myValidator = (field1, field2): ValidatorFn => (control: AbstractControl) => {
        if(control.get(field1).value=="test" && control.get(field2).value=="test2") {
            return null;
        }
        return { myValidator: { valid: false } };
    }
</code>```

I have made a punker of it so you can see it in action:
https://plnkr.co/edit/2kncVT6thQTU1HMCmyTy?p=preview

答:
Your form and validation seems to be working. I updated your plunker and added two divs to your template:

```<code><form [formGroup]="testForm">
    <input type="text" formControlName="address">
    <input type="text" formControlName="tel">
    <input type="text" formControlName="mail">
</form>
<div *ngIf="testForm.valid">Your form is valid! yay!</div>
<div *ngIf="testForm.invalid">Your form is invalid!</div>
</code>```

Here's the updated plunk:

https://plnkr.co/edit/wqMdBQFvj2pIjJkWeCoV?p=preview

Body:
EDIT:
What I want to achieve is a validation on one single formControl and not the whole form. The validator should check all atom fields like house number, street etc. and then invalidate the google maps input control.

I am programming a form with Google Maps Autocomplete.
The user should enter a address into a input field that triggers the Google Maps autocomplete logic. When an address is selected the callback function selects the street, house number etc. and uses the API result to fill in the required address data fields.
The other form elements are displayed but readonly so we always get valid data and can perform validation on the inputs.

The problem is that my validator doesn't trigger the input field. The main input field is always valid and doesn't get the ng-invalid class.

@Component({
  selector: 'my-app',

  styles: [`
    .ng-valid {
      border:#0ff;
    }

    .ng-invalid {
      border:#f00;
    }
  `],
  template: `

  <form [formGroup]="testForm">
                <input type="text" formControlName="address">
                <input type="text" formControlName="tel">
                <input type="text" formControlName="mail">
            </form>
  `
})
export class AppComponent {
  testForm:FormGroup;

  constructor(private fb: FormBuilder) {
    this.testForm = this.fb.group({
            address:['', myValidator],
            tel:[''],
            mail:['']
        }, {
            validator: myValidator("tel", "mail")
        });
  }
}

export const myValidator = (field1, field2): ValidatorFn => (control: AbstractControl) => {
        if(control.get(field1).value=="test" && control.get(field2).value=="test2") {
            return null;
        }
        return { myValidator: { valid: false } };
    }

I have made a punker of it so you can see it in action:
https://plnkr.co/edit/2kncVT6thQTU1HMCmyTy?p=preview

Body:
Your form and validation seems to be working. I updated your plunker and added two divs to your template:

<form [formGroup]="testForm">
    <input type="text" formControlName="address">
    <input type="text" formControlName="tel">
    <input type="text" formControlName="mail">
</form>
<div *ngIf="testForm.valid">Your form is valid! yay!</div>
<div *ngIf="testForm.invalid">Your form is invalid!</div>

Here's the updated plunk:

https://plnkr.co/edit/wqMdBQFvj2pIjJkWeCoV?p=preview


问:
Console.ReadLine() throws nullpointer exception in Groovy
I started learning groovy yesterday and have been enjoying it thus far until I got to the part of the book where I have to take in inputs from the user using console().readLine() but I keep getting this error

```<code>Caught: java.lang.NullPointerException: Cannot invoke method readLine() on null object java.lang.NullPointerException: Cannot invoke method readLine() on null object
at com.usl.NewCodes.run(NewCodes.groovy:30)
</code>```

I have tried it in intelliJ both as a groovy script and in a class. I even went on to try it in the groovyConsole yet it still throws an error.

Here is the code

```<code>print("What is your name ");
def fName = System.console().readLine()
println("Hello" + fName)
</code>```

Thanks

答:
If you are using any IDE for Groovy, the input / output console will not be available to you hence throwing null pointer exception so, you can use the following, If you are using Intellij enable groovy console from Tools -> groovy console for I/O.</p>

```<code> println "What is your name?"
 println "Your name is:"+System.in.newReader().readLine()
</code>```

Body:
I started learning groovy yesterday and have been enjoying it thus far until I got to the part of the book where I have to take in inputs from the user using console().readLine() but I keep getting this error

Caught: java.lang.NullPointerException: Cannot invoke method readLine() on null object java.lang.NullPointerException: Cannot invoke method readLine() on null object
at com.usl.NewCodes.run(NewCodes.groovy:30)

I have tried it in intelliJ both as a groovy script and in a class. I even went on to try it in the groovyConsole yet it still throws an error.

Here is the code

print("What is your name ");
def fName = System.console().readLine()
println("Hello" + fName)

Thanks

Body:
If you are using any IDE for Groovy, the input / output console will not be available to you hence throwing null pointer exception so, you can use the following, If you are using Intellij enable groovy console from Tools -> groovy console for I/O.

 println "What is your name?"
 println "Your name is:"+System.in.newReader().readLine()


问:
Search date in array Mongodb
I have many documents like this one:

```<code>    {
    "_id" : ObjectId("54a94200aa76d3db6cd51977"),
    "URL" : "http://...",
    "Statistics" : [
        {
            "Date" : ISODate("2010-05-18T18:07:29.000+0000"),
            "Clicks" : NumberInt(250),
        },
        {
            "Date" : ISODate("2010-05-21T12:06:41.000+0000"),
            "Clicks" : NumberInt(165),
        },
        {
            "Date" : ISODate("2010-05-30T08:37:50.000+0000"),
            "Clicks" : NumberInt(263),
        }
    ]
}
</code>```

My query looks like this:

```<code>db.clicks.aggregate([
    { $match : 'Statistics.Date' : { $gte: new Date("2010-05-18T00:00:00.000Z"), $lte: new Date("2010-05-18T23:59:59.999Z") } },
    { $unwind' => '$Statistics' },
    { $group : { _id : { year : { $year : '$Statistics.Date' }, month : { $month : '$Statistics.Date' }, day : { $dayOfMonth : '$Statistics.Date' } }, Clicks : { $sum : '$Statistics.Clicks' } },
    { $sort : { _id : 1 } }
])
</code>```

When I try to sum up the clicks from a specific date it gives me all dates, instead of only one. What am I doing wrong? Thanks in advance.

Edit 1:
As there are >80.000 documents in that collection I can't do a $unwind before the $match. Also afaik this would be not a good idea, 'cause that would make the query slower than necessary.
The huge amount of documents and data in it is the reason why I have to use $sum. The document I made above is just an example and only the structure is the same as in my project.

The above query gives me back smth like this:

```<code>{
    "_id" : [
        {
        "year" : 2010,
        "month" : 5,
        "day" : 18
        }
    ],
    "Clicks" : 250
},
{
    "_id" : [
        {
        "year" : 2010,
        "month" : 4,
        "day" : 21
        }
    ],
    "Clicks" : 165
},
{
    "_id" : [
        {
        "year" : 2010,
        "month" : 5,
        "day" : 30
        }
    ],
    "Clicks" : 263
}
</code>```

If I don't use $group I also have to use $limit as the query would exceed 16MB otherwise:

```<code>db.clicks.aggregate([
        { $match : 'Statistics.Date' : { $gte: new Date("2010-05-18T00:00:00.000Z"), $lte: new Date("2010-05-18T23:59:59.999Z") } },
        { $unwind' : '$Statistics' },
        { $limit : 1 }
    ])
</code>```

This result:

```<code>{
    "_id" : ObjectId("54a94200aa76d3db6cd51977"),
    "URL" : "http://...",
    "Statistics" : {
        "Date" : {
            "sec" : 1274166878,
            "usec" : 0
        },
        "Clicks" : 250
    }
}
</code>```

Due to performance reasons I have to use $group and not using it is not an option.

As I have all done in PHP there may be some errors in the document, queries and results I mentioned. Hopefully this won't be a problem. I still haven't figured out what's causing my problem. Can anyone help me?

Edit 2:
As this seems to be an performance issue which can't be solved I'm migrating all the data from the 'Statistics' array into an own collection. Thx to anyone for your help.

答:
Things may have been solved but posting answer for ones who are seeking help from this question

```<code>{ $match : 'Statistics.Date' : { $gte: new Date("2010-05-18T00:00:00.000Z"),
enter code here$lte: new Date("2010-05-18T23:59:59.999Z") } }
</code>```

this match will filter main documents. What you want is to filter the documents inside Statistics array.

Now documents filtered by $match will contain full Statistic array. And unwinding after filtering may have Sub-document of Statistic whose sibling document(document that are in the same array) have passed $match condition.

Note: simple find projection:
  db.col_name.find({},{"Statistics.$":1}) will filter array too but
  $project in aggregation is not helping in filtering array of documents.

Title: Search date in array Mongodb

Body:
I have many documents like this one:

    {
    "_id" : ObjectId("54a94200aa76d3db6cd51977"),
    "URL" : "http://...",
    "Statistics" : [
        {
            "Date" : ISODate("2010-05-18T18:07:29.000+0000"),
            "Clicks" : NumberInt(250),
        },
        {
            "Date" : ISODate("2010-05-21T12:06:41.000+0000"),
            "Clicks" : NumberInt(165),
        },
        {
            "Date" : ISODate("2010-05-30T08:37:50.000+0000"),
            "Clicks" : NumberInt(263),
        }
    ]
}

My query looks like this:

db.clicks.aggregate([
    { $match : 'Statistics.Date' : { $gte: new Date("2010-05-18T00:00:00.000Z"), $lte: new Date("2010-05-18T23:59:59.999Z") } },
    { $unwind' => '$Statistics' },
    { $group : { _id : { year : { $year : '$Statistics.Date' }, month : { $month : '$Statistics.Date' }, day : { $dayOfMonth : '$Statistics.Date' } }, Clicks : { $sum : '$Statistics.Clicks' } },
    { $sort : { _id : 1 } }
])

When I try to sum up the clicks from a specific date it gives me all dates, instead of only one. What am I doing wrong? Thanks in advance.

Edit 1:
As there are >80.000 documents in that collection I can't do a $unwind before the $match. Also afaik this would be not a good idea, 'cause that would make the query slower than necessary.
The huge amount of documents and data in it is the reason why I have to use $sum. The document I made above is just an example and only the structure is the same as in my project.

The above query gives me back smth like this:

{
    "_id" : [
        {
        "year" : 2010,
        "month" : 5,
        "day" : 18
        }
    ],
    "Clicks" : 250
},
{
    "_id" : [
        {
        "year" : 2010,
        "month" : 4,
        "day" : 21
        }
    ],
    "Clicks" : 165
},
{
    "_id" : [
        {
        "year" : 2010,
        "month" : 5,
        "day" : 30
        }
    ],
    "Clicks" : 263
}

If I don't use $group I also have to use $limit as the query would exceed 16MB otherwise:

db.clicks.aggregate([
        { $match : 'Statistics.Date' : { $gte: new Date("2010-05-18T00:00:00.000Z"), $lte: new Date("2010-05-18T23:59:59.999Z") } },
        { $unwind' : '$Statistics' },
        { $limit : 1 }
    ])

This result:

{
    "_id" : ObjectId("54a94200aa76d3db6cd51977"),
    "URL" : "http://...",
    "Statistics" : {
        "Date" : {
            "sec" : 1274166878,
            "usec" : 0
        },
        "Clicks" : 250
    }
}

Due to performance reasons I have to use $group and not using it is not an option.

As I have all done in PHP there may be some errors in the document, queries and results I mentioned. Hopefully this won't be a problem. I still haven't figured out what's causing my problem. Can anyone help me?

Edit 2:
As this seems to be an performance issue which can't be solved I'm migrating all the data from the 'Statistics' array into an own collection. Thx to anyone for your help.

Body:
Things may have been solved but posting answer for ones who are seeking help from this question

{ $match : 'Statistics.Date' : { $gte: new Date("2010-05-18T00:00:00.000Z"),
enter code here$lte: new Date("2010-05-18T23:59:59.999Z") } }

this match will filter main documents. What you want is to filter the documents inside Statistics array.

Now documents filtered by $match will contain full Statistic array. And unwinding after filtering may have Sub-document of Statistic whose sibling document(document that are in the same array) have passed $match condition.

Note: simple find projection:
  db.col_name.find({},{"Statistics.$":1}) will filter array too but
  $project in aggregation is not helping in filtering array of documents.


问:
Angular 1.5 - Insert custom element after last element with certain property
Let's assume I'm having following code:

```<code><li ng-repeat="task in todoList">
    {{task.name}}
</li>
</code>```

And let's assume this is my dataset ( Assuming it's ordered by when, from now to future ) :

```<code>var todoList = [ { name : 'Work hard', when : 'Today'}, { name : 'Play hard', when : 'Today'}, { name : 'Relax hard', when : 'This week'}, ]
</code>```

How can I detect in the ng-repeat when the current repeated item is the last item with the property when set to Today ?

So I'll end up something with something like this

```<code><li ng-repeat="task in todoList">
    {{task.name}}
</li>
<!-- If last of current period, then show this -->
<li>
    <h3>Next period</h3>
</li>
</code>```

答:
You have to create a method that checks if the current item is the last today:</p>

```<code><li ng-repeat="task in todoList">
    <div ng-switch="lastToday(task)">
        <div ng-switch-when="false">{{task.name}}</div>
        <h3 ng-switch-when="true">Next period</h3>
    </div>
</li>

$scope.lastToday = function(task) {
    return ($scope.todoList.reverse().find(t => t.when === 'Today') || {} ).name === task.name;
}
</code>```

Body:
Let's assume I'm having following code:

    {{task.name}}

And let's assume this is my dataset ( Assuming it's ordered by when, from now to future ) :

var todoList = [ { name : 'Work hard', when : 'Today'}, { name : 'Play hard', when : 'Today'}, { name : 'Relax hard', when : 'This week'}, ]

How can I detect in the ng-repeat when the current repeated item is the last item with the property when set to Today ?

So I'll end up something with something like this

    {{task.name}}

Next period

Body:
You have to create a method that checks if the current item is the last today:

<li ng-repeat="task in todoList">
    <div ng-switch="lastToday(task)">
        <div ng-switch-when="false">{{task.name}}</div>
        <h3 ng-switch-when="true">Next period</h3>
    </div>
</li>

$scope.lastToday = function(task) {
    return ($scope.todoList.reverse().find(t => t.when === 'Today') || {} ).name === task.name;
}