问:
SQL query giving error on Oracle database
I'm trying to write a query to list accounts along with current balance, branch no to which it belongs and the average balance of that branch having a balance more than a average balance of the branch to which the account belongs.

The table name is acmaster, columns are acno, currbal, and branchno.

Records:

```<code>acno currbal branchno
1    1000     2
2    2000     2
3    3000     3
4    2000     3
</code>```

I am expecting result like this:

```<code>acno  currbal  branchno   AVG(currbal)
2     2000      2           1500
3     3000      3           2500
</code>```

This is my current query:

```<code>select acno,currbal,branchno,AVG(currbal) abal
from acmaster
group by branchno as bno
having abal < (select currbal from acmaster group by (select branchno from acmaster where branchno=bno));
</code>```

which gets error:

```<code>ORA-00933: SQL command not properly ended
00933. 00000 - "SQL command not properly ended"
*Cause:
*Action:
Error at Line: 3 Column: 19
</code>```

答:
Lets look at this a line at a time:

```<code>1> select acno,currbal,branchno,AVG(currbal) abal
2> from acmaster
3> group by branchno as bno
4> having abal < (select currbal from acmaster group by (select branchno from acmaster where branchno=bno));
</code>```

On line 3, you are trying to alias branchno as bno within the group by statement.  You can't do that, at least not in oracle.

On line 1, you reference columns acno and currbal without any form of aggregate function, but they don't exist in the group by clause on line 3.  Either add an aggregate function to each of these columns, or add them to the group by clause

In line 4 you try referencing abal from line 1, but in oracle you can't reference column aliases in the having clause, so use the aggregate AVG(currbal) instead.  Additionally Oracle does not allow subqueries in the group by clause, however, the gist of what you appear to be doing in line 4 is ensuring that AVG(currbal) is less than some currbal value for that branch, perhaps the MAX(currbal)?

Putting it all together this provides the answer you are looking for, though I'm not certain you even need the having clause, as it would eliminate records where the average balance equals the greatest balance (branchnos with a single record or where all records for the branchno have the same balance):

```<code>select max(acno) acno
     , max(currbal) currbal
     , branchno
     , AVG(currbal) abal
from acmaster a
group by branchno
having AVG(currbal) < MAX(currbal)
</code>```

Body:
I'm trying to write a query to list accounts along with current balance, branch no to which it belongs and the average balance of that branch having a balance more than a average balance of the branch to which the account belongs.

The table name is acmaster, columns are acno, currbal, and branchno.

Records:

acno currbal branchno
1    1000     2
2    2000     2
3    3000     3
4    2000     3

I am expecting result like this:

acno  currbal  branchno   AVG(currbal)
2     2000      2           1500
3     3000      3           2500

This is my current query:

select acno,currbal,branchno,AVG(currbal) abal
from acmaster
group by branchno as bno
having abal < (select currbal from acmaster group by (select branchno from acmaster where branchno=bno));

which gets error:

ORA-00933: SQL command not properly ended
00933. 00000 - "SQL command not properly ended"
*Cause:
*Action:
Error at Line: 3 Column: 19

Body:
Lets look at this a line at a time:

1> select acno,currbal,branchno,AVG(currbal) abal
2> from acmaster
3> group by branchno as bno
4> having abal < (select currbal from acmaster group by (select branchno from acmaster where branchno=bno));

On line 3, you are trying to alias branchno as bno within the group by statement.  You can't do that, at least not in oracle.

On line 1, you reference columns acno and currbal without any form of aggregate function, but they don't exist in the group by clause on line 3.  Either add an aggregate function to each of these columns, or add them to the group by clause

In line 4 you try referencing abal from line 1, but in oracle you can't reference column aliases in the having clause, so use the aggregate AVG(currbal) instead.  Additionally Oracle does not allow subqueries in the group by clause, however, the gist of what you appear to be doing in line 4 is ensuring that AVG(currbal) is less than some currbal value for that branch, perhaps the MAX(currbal)?

Putting it all together this provides the answer you are looking for, though I'm not certain you even need the having clause, as it would eliminate records where the average balance equals the greatest balance (branchnos with a single record or where all records for the branchno have the same balance):

select max(acno) acno
     , max(currbal) currbal
     , branchno
     , AVG(currbal) abal
from acmaster a
group by branchno
having AVG(currbal) < MAX(currbal)


来源: stackexchange

问:
ASP.net HTTP 404 - File not found instead of MaxRequestLength exception
I have a file upload control on my webpage. The maximum request length is set to 8 MB (maxRequestLength = 8192). I also have server validation that throws an error if the file is more than 4MB. The reason that its 8MB in the config is the leverage that's given to the user and also so that the application can be tested.

If I upload a file that's 9MB, I get thrown an exception Maximum request length exceeded., which is fine and working as expected. But when I try to upload a file that's 1GB, it shows me a HTTP 404 - File not found. Can someone please explain why this is happening and how can I get it to throw me a maxRequestLength exception?

I'm using IIS6.

答:
To my knowledge, there is no way to gracefully handle exceeding IIS's "maxRequestLength" setting. It can't even display a custom error page (since there is no corresponding HTTP code to respond to). The only way around this is to set maxRequestLength to some absurdly high number of kbytes, for example 51200 (50MB), and then check the ContentLength after the file has been uploaded (assuming the request didn't time out before 90 seconds). At that point, I can validate if the file <=5MB and display a friendly error.

You can also try this link.

You could also try something like this:

```<code>private void application_EndRequest(object sender, EventArgs e)
{
    HttpRequest request = HttpContext.Current.Request;
    HttpResponse response = HttpContext.Current.Response;

    if ((request.HttpMethod == "POST") &&
        (response.StatusCode == 404 && response.SubStatusCode == 13))
    {
        // Clear the response header but do not clear errors and transfer back to requesting page to handle error
        response.ClearHeaders();
        HttpContext.Current.Server.Transfer(request.AppRelativeCurrentExecutionFilePath);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To my knowledge, there is no way to gracefully handle exceeding IIS's "maxRequestLength" setting. It can't even display a custom error page (since there is no corresponding HTTP code to respond to). The only way around this is to set maxRequestLength to some absurdly high number of kbytes, for example 51200 (50MB), and then check the ContentLength after the file has been uploaded (assuming the request didn't time out before 90 seconds). At that point, I can validate if the file <=5MB and display a friendly error.

You can also try this link.

You could also try something like this:

private void application_EndRequest(object sender, EventArgs e)
{
    HttpRequest request = HttpContext.Current.Request;
    HttpResponse response = HttpContext.Current.Response;

    if ((request.HttpMethod == "POST") &&
        (response.StatusCode == 404 && response.SubStatusCode == 13))
    {
        // Clear the response header but do not clear errors and transfer back to requesting page to handle error
        response.ClearHeaders();
        HttpContext.Current.Server.Transfer(request.AppRelativeCurrentExecutionFilePath);
    }
}

ContentLicense: CC BY-SA 2.5


问:
Going from sort to order and back
sort and order return a vector of ordered values and indices of ordered values respectively.

It's simple to use order to implement sort:

```<code>v <- c(17, -5, 1, 20)

identical(v[order(v)], sort(v))
</code>```

[1] TRUE

What's the most straightforward way to use sort to implement order?

Here's what I came up with:

```<code>identical(sapply(sort(v), function(x) grep(paste0("^", x, "$"), v)), order(v))
</code>```

[1] TRUE

Not pretty. Is there a simpler way?

答:
Return the index in the sort function:

```<code>sort(v, index.return=TRUE)
#$x
#[1] -5  1 17 20

#$ix
#[1] 2 3 1 4        # this is the order to sort the vector
</code>```

```<code>identical(sort(v, index.return=TRUE)$ix, order(v))
# [1] TRUE
</code>```

Title: Going from sort to order and back

Body:
sort and order return a vector of ordered values and indices of ordered values respectively.

It's simple to use order to implement sort:

v <- c(17, -5, 1, 20)

identical(v[order(v)], sort(v))

[1] TRUE

What's the most straightforward way to use sort to implement order?

Here's what I came up with:

identical(sapply(sort(v), function(x) grep(paste0("^", x, "$"), v)), order(v))

[1] TRUE

Not pretty. Is there a simpler way?

Body:
Return the index in the sort function:

sort(v, index.return=TRUE)
#$x
#[1] -5  1 17 20

#$ix
#[1] 2 3 1 4        # this is the order to sort the vector

identical(sort(v, index.return=TRUE)$ix, order(v))
# [1] TRUE


问:
Neural network for multi label classification with large number of classes outputs only zero
I am training a neural network for multilabel classification, with a large number of classes (1000). Which means more than one output can be active for every input. On an average, I have two classes active per output frame. On training with a cross entropy loss the neural network resorts to outputting only zeros, because it gets the least loss with this output since 99.8% of my labels are zeros. Any suggestions on how I can push the network to give more weight to the positive classes? </p>

答:
Tensorflow has a loss function weighted_cross_entropy_with_logits, which can be used to give more weight to the 1's. So it should be applicable to a sparse multi-label classification setting like yours.

From the documentation:

This is like sigmoid_cross_entropy_with_logits() except that pos_weight, allows one to trade off recall and precision by up- or down-weighting the cost of a positive error relative to a negative error.

The argument pos_weight is used as a multiplier for the positive targets

If you use the tensorflow backend in Keras, you can use the loss function like this (Keras 2.1.1):

```<code>import tensorflow as tf
import keras.backend.tensorflow_backend as tfb

POS_WEIGHT = 10  # multiplier for positive targets, needs to be tuned

def weighted_binary_crossentropy(target, output):
    """
    Weighted binary crossentropy between an output tensor
    and a target tensor. POS_WEIGHT is used as a multiplier
    for the positive targets.

    Combination of the following functions:
    * keras.losses.binary_crossentropy
    * keras.backend.tensorflow_backend.binary_crossentropy
    * tf.nn.weighted_cross_entropy_with_logits
    """
    # transform back to logits
    _epsilon = tfb._to_tensor(tfb.epsilon(), output.dtype.base_dtype)
    output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)
    output = tf.log(output / (1 - output))
    # compute weighted loss
    loss = tf.nn.weighted_cross_entropy_with_logits(targets=target,
                                                    logits=output,
                                                    pos_weight=POS_WEIGHT)
    return tf.reduce_mean(loss, axis=-1)
</code>```

Then in your model:

```<code>model.compile(loss=weighted_binary_crossentropy, ...)
</code>```

I have not found many resources yet which report well working values for the pos_weight in relation to the number of classes, average active classes, etc.

Body:
Tensorflow has a loss function weighted_cross_entropy_with_logits, which can be used to give more weight to the 1's. So it should be applicable to a sparse multi-label classification setting like yours.

From the documentation:

This is like sigmoid_cross_entropy_with_logits() except that pos_weight, allows one to trade off recall and precision by up- or down-weighting the cost of a positive error relative to a negative error.

The argument pos_weight is used as a multiplier for the positive targets

If you use the tensorflow backend in Keras, you can use the loss function like this (Keras 2.1.1):

import tensorflow as tf
import keras.backend.tensorflow_backend as tfb

POS_WEIGHT = 10  # multiplier for positive targets, needs to be tuned

def weighted_binary_crossentropy(target, output):
    """
    Weighted binary crossentropy between an output tensor
    and a target tensor. POS_WEIGHT is used as a multiplier
    for the positive targets.

    Combination of the following functions:
    * keras.losses.binary_crossentropy
    * keras.backend.tensorflow_backend.binary_crossentropy
    * tf.nn.weighted_cross_entropy_with_logits
    """
    # transform back to logits
    _epsilon = tfb._to_tensor(tfb.epsilon(), output.dtype.base_dtype)
    output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)
    output = tf.log(output / (1 - output))
    # compute weighted loss
    loss = tf.nn.weighted_cross_entropy_with_logits(targets=target,
                                                    logits=output,
                                                    pos_weight=POS_WEIGHT)
    return tf.reduce_mean(loss, axis=-1)

Then in your model:

model.compile(loss=weighted_binary_crossentropy, ...)

I have not found many resources yet which report well working values for the pos_weight in relation to the number of classes, average active classes, etc.


问:
Soft 404 error: PHP not sending 404 header
I have a php script when page is not found in database, I send http headers 404 not found, instead php is sending HTTP 200. Google webmaster tools shows its a soft 404 error.

```<code><?php
if (mysql_num_rows($rs_press) == 0) {

    header("HTTP/1.1 404 Not Found");
    include('404.shtml');
    exit;

}
?>
</code>```

and the HTTP response for the page in GMT is quite strange shows HTTP 200 OK. Why is PHP sending 200, instead of 404 error as this is quite strange?.

The if code works correct but only the 404 headers are not sent. Here is the output of the page..

How do i fix?
I am running PHP 5.6/Apache on a Dedicated server, Smarty with SSL activated.

答:
The PHP header() function actually takes 3 arguments:

```<code>void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
</code>```

Try changing your code to this:

```<code><?php
if (mysql_num_rows($rs_press) == 0) {

    header("HTTP/1.1 404 Not Found", true, 404);
    include('404.shtml');
    exit;

}
?>
</code>```

Alternatively, you could try using the http_response_code() function.

Body:
I have a php script when page is not found in database, I send http headers 404 not found, instead php is sending HTTP 200. Google webmaster tools shows its a soft 404 error.

<?php
if (mysql_num_rows($rs_press) == 0) {

    header("HTTP/1.1 404 Not Found");
    include('404.shtml');
    exit;

}
?>

and the HTTP response for the page in GMT is quite strange shows HTTP 200 OK. Why is PHP sending 200, instead of 404 error as this is quite strange?.

The if code works correct but only the 404 headers are not sent. Here is the output of the page..

How do i fix?
I am running PHP 5.6/Apache on a Dedicated server, Smarty with SSL activated.

Body:
The PHP header() function actually takes 3 arguments:

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

Try changing your code to this:

<?php
if (mysql_num_rows($rs_press) == 0) {

    header("HTTP/1.1 404 Not Found", true, 404);
    include('404.shtml');
    exit;

}
?>

Alternatively, you could try using the http_response_code() function.


问:
Firestore rules when data doesn't exist
I'm trying to create a rule that only lets a user create/edit a document in which request.auth.uid matches the name of the document they're trying to create. From https://cloud.google.com/firestore/docs/security/secure-data:

Using variables from wildcards

When you match a rule using a database path with a wildcard, a
  variable is created with a name matching the string you included
  inside the curly brackets. You can then reference these variables in
  your security rules.

One common use of these types of wildcards is to store documents by
  userID, and then only allow users to access documents for which their
  userID matches the ID of the document.

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userIDFromWildcard}/ {
      // Users can only edit documents in the database if the documentID is
      // equal to their userID
      allow read, write: if request.auth.uid == userIDFromWildcard;
    }
  }
}
</code>```

I tried using this code in my rules, but it errors. When removing the last /, i.e. match /users/{userIDFromWildcard} instead of match /users/{userIDFromWildcard}/, it publishes, but permissions aren't granted if the document doesn't exist.

Edit: I also tried something like this, but I don't know how to do it correctly because of the lack of documentation:

```<code>allow read, write: if request.auth.uid == request.resource.__name__;
</code>```

This is the code I'm running that gets insufficient permissions:

```<code>this.items = afs.doc("/users/" + this.uid); // afs is AngularFirestore, this.uid is the uid of the authenticated user
</code>```

...

```<code>// the user is authenticated at this point
this.items.snapshotChanges().subscribe(snapshot => {
if (!snapshot.payload.exists) { // if user isn't in db
    function recursive() {
        // ...
        this.updateDB(); // called once because of conditional
    }
    recursive();
    } else {
        // ...
    }
}
</code>```

updateDB:

```<code>public updateDatabase(): void {
    const changes: Item = { name: this.name, username: this.username,
    photoURL: this.photoURL };
    this.items.set(changes).then((item) => { // causes error
        console.log("Saving successful");
    }, (err) => {
        console.log(err);
    }).catch((err) => {
        console.log(err);
    });
}
</code>```

答:
You probably need this setup for documents:

```<code>service cloud.firestore {
  match /database/{databases}/documents {
    match /users/{userId}/{document=**} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}
</code>```

Also, if you need to write to a sub-collections see this answer

And more info on wildcard matching in firestore here

Title: Firestore rules when data doesn't exist

Body:
I'm trying to create a rule that only lets a user create/edit a document in which request.auth.uid matches the name of the document they're trying to create. From https://cloud.google.com/firestore/docs/security/secure-data:

Using variables from wildcards

When you match a rule using a database path with a wildcard, a
  variable is created with a name matching the string you included
  inside the curly brackets. You can then reference these variables in
  your security rules.

One common use of these types of wildcards is to store documents by
  userID, and then only allow users to access documents for which their
  userID matches the ID of the document.

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userIDFromWildcard}/ {
      // Users can only edit documents in the database if the documentID is
      // equal to their userID
      allow read, write: if request.auth.uid == userIDFromWildcard;
    }
  }
}

I tried using this code in my rules, but it errors. When removing the last /, i.e. match /users/{userIDFromWildcard} instead of match /users/{userIDFromWildcard}/, it publishes, but permissions aren't granted if the document doesn't exist.

Edit: I also tried something like this, but I don't know how to do it correctly because of the lack of documentation:

allow read, write: if request.auth.uid == request.resource.__name__;

This is the code I'm running that gets insufficient permissions:

this.items = afs.doc("/users/" + this.uid); // afs is AngularFirestore, this.uid is the uid of the authenticated user

...

// the user is authenticated at this point
this.items.snapshotChanges().subscribe(snapshot => {
if (!snapshot.payload.exists) { // if user isn't in db
    function recursive() {
        // ...
        this.updateDB(); // called once because of conditional
    }
    recursive();
    } else {
        // ...
    }
}

updateDB:

public updateDatabase(): void {
    const changes: Item = { name: this.name, username: this.username,
    photoURL: this.photoURL };
    this.items.set(changes).then((item) => { // causes error
        console.log("Saving successful");
    }, (err) => {
        console.log(err);
    }).catch((err) => {
        console.log(err);
    });
}

Body:
You probably need this setup for documents:

service cloud.firestore {
  match /database/{databases}/documents {
    match /users/{userId}/{document=**} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}

Also, if you need to write to a sub-collections see this answer

And more info on wildcard matching in firestore here


问:
WP_Query sometimes returns zero results when there are matching posts - why?
This one has got me stumped.

I have a category.php file which contains this loop:

```<code><?php
if ( have_posts() ) : ?>
    <?php
    while ( have_posts() ) : the_post(); ?>
        <div class="entry-content description clearfix">
            <h2 class="category-subtitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <?php echo the_content(); ?>
            <?php global $withcomments; $withcomments = 1;
    ?>
        </div><!-- .entry-content -->
    <?php
    endwhile;
else :
    get_template_part( 'content', 'none' );
endif;
?>
</code>```

This block of code works fine and always returns the results one would expect.

In addition, outside the loop (after it, in case that matters), I've got a column to one side with this loop - I'm going to refer to this as the newsfeed loop for the sake of clarity:

```<code><h3 class="newsfeed-heading"><a href="/category/news/">Latest News</a></h3>
<?php
    // wp_reset_query(); * Same results with or without wp_reset_query
    $args = array(
    'cat' => 89,
    'order'   => 'ASC'
    );
    $custom_query = new WP_Query($args);
    //echo "<h2>Found: $custom_query->found_posts</h2>";
    while($custom_query->have_posts()) : $custom_query->the_post();
?>
    <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
        <h4 class="highlight1"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
        <p><?php $content = get_the_content(); echo mb_strimwidth($content, 0, 160, '...');?></p><div class="morelink"><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>">Read more</a></div>
    </div>
<?php endwhile;
  // wp_reset_postdata();  * Same results with or without wp_reset_postdata
?>
</code>```

Now, in the majority of cases, these two loops play nicely together and both loops return the set of results I'd expect. But not always.

As far as I can tell, I think if the main category loop only contains one result, then the newsfeed loop is always correct. But if the main category loop has multiple posts in the results set, the newsfeed loop frequently works fine. So I have not been able to spot a pattern.

I have tried putting wp_reset_query(); in different places, clutching at straws, but it doesn't make any difference.

Incidentally, when the newsfeed loop works, it always returns the correct results set. But when it doesn't, it always returns nothing and $custom_query->found_posts returns zero.

I would really appreciate some advice on where to look for a possible solution.

答: If anyone comes here looking for an answer and none of the other solutions work. I was able to make this work by add wp_die(); right before the end of my function call.

Body:
This one has got me stumped.

I have a category.php file which contains this loop:

<?php
if ( have_posts() ) : ?>
    <?php
    while ( have_posts() ) : the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

            <?php echo the_content(); ?>
            <?php global $withcomments; $withcomments = 1;
    ?>

    <?php
    endwhile;
else :
    get_template_part( 'content', 'none' );
endif;
?>

This block of code works fine and always returns the results one would expect.

In addition, outside the loop (after it, in case that matters), I've got a column to one side with this loop - I'm going to refer to this as the newsfeed loop for the sake of clarity:

Latest News

<?php
    // wp_reset_query(); * Same results with or without wp_reset_query
    $args = array(
    'cat' => 89,
    'order'   => 'ASC'
    );
    $custom_query = new WP_Query($args);
    //echo "
Found: $custom_query->found_posts
";
    while($custom_query->have_posts()) : $custom_query->the_post();
?>
    <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 160, '...');?>

<a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>">Read more

<?php endwhile;
  // wp_reset_postdata();  * Same results with or without wp_reset_postdata
?>

Now, in the majority of cases, these two loops play nicely together and both loops return the set of results I'd expect. But not always.

As far as I can tell, I think if the main category loop only contains one result, then the newsfeed loop is always correct. But if the main category loop has multiple posts in the results set, the newsfeed loop frequently works fine. So I have not been able to spot a pattern.

I have tried putting wp_reset_query(); in different places, clutching at straws, but it doesn't make any difference.

Incidentally, when the newsfeed loop works, it always returns the correct results set. But when it doesn't, it always returns nothing and $custom_query->found_posts returns zero.

I would really appreciate some advice on where to look for a possible solution.


问:
How to make VBA do the same actions while changing criteria until it hits an empty cell?
I am trying to create a simple VBA macro that would help me with some work that I am currently doing manually.

The idea is that there is a given list, of that list column "A" will contain data that I will need to filter on on another sheet, copy the result to another sheet and move on with the next cell below.

```<code>Sheets("Sheet4").Select
ActiveSheet.Range("$A$1:$R$25239").AutoFilter Field:=5, Criteria1:= _
    Sheets("Sheet3").Range("A3").Value
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Sheets("Sheet5").Select
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "+"
</code>```

I need VBA to repeat this step until the it hits the bottom of the list, however I also need the range to change to the cell one below at the Filter criteria.

I would really appreciate some help as I am a beginner.

答:
Your recorded code  can be replaced with

```<code> Dim source as range
 Set source = Sheets("Sheet4").Range("$A$1:$R$25239")
 dim crit as range
 set crit = Sheets("Sheet3").Range("A3")
 Dim dest as range

 source.AutoFilter Field:=5, Criteria1:= crit.Value
 set dest = sheets("Sheet5").range("a1").end(xldown).offset(1,0)
 Sheets("Sheet4").range("a1").currentregion.copy dest
 dest.offset(1,0) = "+"
</code>```

Now add a loop to achieve what you want

Body:
I am trying to create a simple VBA macro that would help me with some work that I am currently doing manually.

The idea is that there is a given list, of that list column "A" will contain data that I will need to filter on on another sheet, copy the result to another sheet and move on with the next cell below.

Sheets("Sheet4").Select
ActiveSheet.Range("$A$1:$R$25239").AutoFilter Field:=5, Criteria1:= _
    Sheets("Sheet3").Range("A3").Value
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Sheets("Sheet5").Select
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "+"

I need VBA to repeat this step until the it hits the bottom of the list, however I also need the range to change to the cell one below at the Filter criteria.

I would really appreciate some help as I am a beginner.

Body:
Your recorded code  can be replaced with

 Dim source as range
 Set source = Sheets("Sheet4").Range("$A$1:$R$25239")
 dim crit as range
 set crit = Sheets("Sheet3").Range("A3")
 Dim dest as range

 source.AutoFilter Field:=5, Criteria1:= crit.Value
 set dest = sheets("Sheet5").range("a1").end(xldown).offset(1,0)
 Sheets("Sheet4").range("a1").currentregion.copy dest
 dest.offset(1,0) = "+"

Now add a loop to achieve what you want


问:
PyTorch specific inspection issues in PyCharm
Has anyone been able to resolve PyTorch specific inspection issues in PyCharm? Previous posts for non-PyTorch related issues suggest upgrading PyCharm, but I'm currently at the latest version. One option is to of course disable certain inspections entirely, but I'd rather avoid that.

Example: torch.LongTensor(x) gives me "Unexpected argument...", whereas both call signatures (with and without x) are both supported.

答:
I believe it's because torch.LongTensor has no __init__ method for pycharm to find.

According to this source that I found thanks to this SO post :

Use __new__ when you need to control the creation of a new instance.
  Use __init__ when you need to control initialization of a new instance.

__new__ is the first step of instance creation.  It's called first,
  and is responsible for returning a new instance of your class.  In
  contrast, __init__ doesn't return anything; it's only responsible for
  initializing the instance after it's been created.

In general, you shouldn't need to override __new__ unless you're
  subclassing an immutable type like str, int, unicode or tuple.

Since Tensors are types, it makes sense to define only new and no init.

You can experiment this behavior by testing the following classes :

```<code>torch.LongTensor(1)  # Unexpected arguments
</code>```

Produces the warning while the following doesn't.

```<code>class MyLongTensor(torch.LongTensor):
    def __init__(self, *args, **kwargs):
        pass

MyLongTensor(1)  # No error
</code>```

To confirm that the absence of __init__ is the culprit try :

```<code>class Example(object):
    pass

Example(0)  # Unexpected arguments
</code>```

To find out by yourself, use pycharm to Ctrl+click on LongTensor then _TensorBase and look at the defined methods.

Body:
I believe it's because torch.LongTensor has no __init__ method for pycharm to find.

According to this source that I found thanks to this SO post :

Use __new__ when you need to control the creation of a new instance.
  Use __init__ when you need to control initialization of a new instance.

__new__ is the first step of instance creation.  It's called first,
  and is responsible for returning a new instance of your class.  In
  contrast, __init__ doesn't return anything; it's only responsible for
  initializing the instance after it's been created.

In general, you shouldn't need to override __new__ unless you're
  subclassing an immutable type like str, int, unicode or tuple.

Since Tensors are types, it makes sense to define only new and no init.

You can experiment this behavior by testing the following classes :

torch.LongTensor(1)  # Unexpected arguments

Produces the warning while the following doesn't.

class MyLongTensor(torch.LongTensor):
    def __init__(self, *args, **kwargs):
        pass

MyLongTensor(1)  # No error

To confirm that the absence of __init__ is the culprit try :

class Example(object):
    pass

Example(0)  # Unexpected arguments

To find out by yourself, use pycharm to Ctrl+click on LongTensor then _TensorBase and look at the defined methods.


问:
Regex for Phone Number in the MIDDLE of a string?
I've seen multiple questions/answers regarding phone number authentication, which is great, but all of them only seen to work IF the string is strictly a phone number. In my case, we might have receive a string like this:

"Okay, I've got your number as 313-123-1234. Now lets..."

The formatting of the phone number can vary as well, so I think it would be better if the regex could handle "any sequence of 10 numbers, ignoring (  )  -  ."

I've tried a few different things, including:

```<code>"^((\\+\\d{1,2}|1)[\\s.-]?)?\\(?[2-9](?!11)\\d{2}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$"
</code>```

and

```<code>"/[0-9]{10}\\b/"
</code>```

Among others, which, again, seen to work if it's the phone number by itself, but when I call:myStrig.matches(myRegex); on the full string, it always returns false.

With that being said, is there either a native solution, such as PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber) that would work with the example phrase mentioned above, or what is a regex that would actually work in this case?

Thanks!

答:
THE ANSWER

So, first of all, there's seems to be a known issue with Android's Pattern.matches(string, regex);. Instead, you should use:

```<code>    Pattern p = Pattern.compile(myRegex);
    Matcher m = p.matcher(myString);

    if(m.find()) {
        // true
    }
</code>```

Secondly, my original regex was still not working for all the scenarios I needed, but thanks to Wiktor Stribiżew suggestion, it now works.

He suggested replacing ^ with (?<!\\w) and $ with (?!\\w).

My regex now looks like this:

```<code>(?<!\w)((\+\d{1,2}|1)[\s.-]?)?\(?[2-9](?!11)\d{2}\)?[\s.-]?\d{3}[\s.-]?\d{4}(?!\w)
</code>```

And it works!

For reference, here are some of the basic scenarios I tested it with:

(313) 456 3450

(313) 456-3450

(313)-456-3450

313-456-3450

313.456.3450

313 456 3450

3134563450

Body:
I've seen multiple questions/answers regarding phone number authentication, which is great, but all of them only seen to work IF the string is strictly a phone number. In my case, we might have receive a string like this:

"Okay, I've got your number as 313-123-1234. Now lets..."

The formatting of the phone number can vary as well, so I think it would be better if the regex could handle "any sequence of 10 numbers, ignoring (  )  -  ."

I've tried a few different things, including:

"^((\\+\\d{1,2}|1)[\\s.-]?)?\\(?[2-9](?!11)\\d{2}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$"

and

"/[0-9]{10}\\b/"

Among others, which, again, seen to work if it's the phone number by itself, but when I call:myStrig.matches(myRegex); on the full string, it always returns false.

With that being said, is there either a native solution, such as PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber) that would work with the example phrase mentioned above, or what is a regex that would actually work in this case?

Thanks!

Body:
THE ANSWER

So, first of all, there's seems to be a known issue with Android's Pattern.matches(string, regex);. Instead, you should use:

    Pattern p = Pattern.compile(myRegex);
    Matcher m = p.matcher(myString);

    if(m.find()) {
        // true
    }

Secondly, my original regex was still not working for all the scenarios I needed, but thanks to Wiktor Stribiżew suggestion, it now works.

He suggested replacing ^ with (?<!\\w) and $ with (?!\\w).

My regex now looks like this:

(?<!\w)((\+\d{1,2}|1)[\s.-]?)?\(?[2-9](?!11)\d{2}\)?[\s.-]?\d{3}[\s.-]?\d{4}(?!\w)

And it works!

For reference, here are some of the basic scenarios I tested it with:

(313) 456 3450

(313) 456-3450

(313)-456-3450

313-456-3450

313.456.3450

313 456 3450

3134563450


问:
How to check that package is available to install?
How to check that package givent by name exactly is available to install?

Some packages may be not available when install packages by list:

```<code>pkg install some packages ... ruby-gems
</code>```

No packages available to install matching 'ruby-gems' have been found in the repositories

The pkg info show info only for installed packages:

```<code>pkg info ruby23-gems
</code>```

pkg: No package(s) matching ruby23-gems

Now install and check info:

```<code>pkg install ruby23-gems
pkg info ruby23-gems
</code>```

ruby23-gems-2.6.14

答:
The command pkg search have appropriate args:

```<code>pkg search -S name --exact ruby23-gems
</code>```

Where:

-S name - specify the field to search the repository catalogue on

--exact - pattern should be an exact match against the search field

Body:
How to check that package givent by name exactly is available to install?

Some packages may be not available when install packages by list:

pkg install some packages ... ruby-gems

No packages available to install matching 'ruby-gems' have been found in the repositories

The pkg info show info only for installed packages:

pkg info ruby23-gems

pkg: No package(s) matching ruby23-gems

Now install and check info:

pkg install ruby23-gems
pkg info ruby23-gems

ruby23-gems-2.6.14

Body:
The command pkg search have appropriate args:

pkg search -S name --exact ruby23-gems

Where:

-S name - specify the field to search the repository catalogue on

--exact - pattern should be an exact match against the search field


问:
How to sort likert heatmap by descending order of last column
Using likert package to plot some likert scales. When plotting bars they are sorted by default. I need to sort the heatmap the same way but no success so far.
As you can see heatmap is ordered by alphabetical text from questions.

Using demo data & code from package:

```<code># Reverse the levels
items24.reverse <- reverse.levels(items24)
l24.reverse <- likert(items24.reverse)
plot(l24.reverse)
</code>```

I want heatmap ordered like this:

答:
Likert package does not allow to do such manipulation.
Heatmap is ALWAYS ordered by alphabetically sorted text. So I suggest a workaround by forcing the text to be previously sorted by the column you think the most likely to be like bar chart sorting. A bit nasty but works:

```<code>   library(magrittr)
   library(dplyr)

# Get the results data frame out of the list
# and sort by last column ("Strongly agree")
# padding with zeros to avoid alphabetical ordering

 l24.results <- l24.reverse$results %>%
      dplyr::arrange(desc(`Strongly agree`)) %>%
      dplyr::mutate(Item = paste(str_pad(row_number(),2, pad = "0"), Item, sep = ' '))

# create a likert object again from the summary feature

  mylikert <- likert(summary = l24.results)

# plot again

plot(mylikert, type = "heat")
</code>```

Body:
Using likert package to plot some likert scales. When plotting bars they are sorted by default. I need to sort the heatmap the same way but no success so far.
As you can see heatmap is ordered by alphabetical text from questions.

Using demo data & code from package:

# Reverse the levels
items24.reverse <- reverse.levels(items24)
l24.reverse <- likert(items24.reverse)
plot(l24.reverse)

I want heatmap ordered like this:

Body:
Likert package does not allow to do such manipulation.
Heatmap is ALWAYS ordered by alphabetically sorted text. So I suggest a workaround by forcing the text to be previously sorted by the column you think the most likely to be like bar chart sorting. A bit nasty but works:

   library(magrittr)
   library(dplyr)

# Get the results data frame out of the list
# and sort by last column ("Strongly agree")
# padding with zeros to avoid alphabetical ordering

 l24.results <- l24.reverse$results %>%
      dplyr::arrange(desc(`Strongly agree`)) %>%
      dplyr::mutate(Item = paste(str_pad(row_number(),2, pad = "0"), Item, sep = ' '))

# create a likert object again from the summary feature

  mylikert <- likert(summary = l24.results)

# plot again

plot(mylikert, type = "heat")


问:
In a multithreaded (Java or .Net) program, can I assume that copying a variable is atomic?
I was worrying about race conditions in an application I'm designing, when I was wondering about this question.

Let's say I have a large array or collection of some sort that is managed by one component of my program, let's call that component Monitor. Its job is to regularly check if the collection is "dirty", i. e. has changed recently, and if so, write a snapshot to disk (this is to checkpoint the application in case a crash occurs) and mark it as clean again.

Other components of the same program, running in a different thread, call the Monitor's methods to add data to or modify data in the array/collection. Those methods mark the collection as dirty.

Now, the altering methods run in the other components' threads, right? And if I'm not so lucky, they might be called while the snapshot is written to disk, change data that has already been written, set the dirty flag and the Monitor's thread unsets it just after that, without having saved the changes (it was already past the element when it changed). So I have a dirty collection that's marked as clean.

For a while, I thought that I could maybe solve the problem by making a temporary copy of the collection, mark it clean and then go and serialize the copy. But would the copying be atomic, i. e. can I be sure that the collection will not change while I'm copying it?

Meanwhile, I think I have found better solutions, like

setting a lock flag before beginning the write to disk and make the data altering methods wait until the flag is unset

have the data altering methods write to a "change queue" instead of directly to the collection and have the thread that does the disk writing process that queue

and I think the lock flag might be the best way to go. But I'm still curious: Is copying a variable atomic?

Follow-up: Maybe this should go in a question of its own, but actually it's very much the same. According to the answers below, my "lock flag" approach might also not work, right? Because the data altering method might check the lock flag while it is being set to the "locked" value and decide it's not locked. So I need a special construction like a mutex if I really want to do this right, correct?

Kudos to erickson for his very helpful answer on my follow-up. I really should have made this two questions so I could have accepted two answers. Please, vote him up, too.

答:
No. For instance, long variables in Java are not atomic on 32-bit machines.

In addition, there's a "thread caching" issue - unless your variable is volatile or inside synchronized block, another thread may not see the change to variable value. This is true for all types of variables, not just long.

Read here: http://gee.cs.oswego.edu/dl/cpj/jmm.html, especially "atomicity" and "visibility" paragraphs.

OwnerDisplayName: Hanno

LastEditorDisplayName: Hanno

OwnerDisplayName: uzhin


问:
Can anyone review this page in IE 6/7/8 and tell me why it is breaking so badly?
http://iamwhitebox.com/staging/arkitek/index.php#press.htm

I think its just a float/margin bug but I haven't been able to pinpoint it

??

```<code><!DOCTYPE html>
<html>
<head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Arkitek Studios | Press</title>
    <link rel='stylesheet' type='text/css' href='css/core.css' />
<style>
    article, aside, details, figcaption, figure, footer, header,
    hgroup, menu, nav, section { display: block; }
    </style>
<!--[if IE]>
      <script src='http://html5shiv.googlecode.com/svn/trunk/html5.js'></script>
    <![endif]-->
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script> <script type='text/javascript' src='js/dynamicpage.js'></script>
</head>
<body>
<?php
    include_once 'includes/header.inc';
?>
<div id='guts'>
    <section id='page'>
        <div class='leftfloat logoPress'></div>
        <article class='rightfloat'>
            <img style='padding-top:12px;' src='img/img1.jpg' alt='#'>
        </article>
    <div style='padding-top:75px;'>
        <article style='width:275px;' class='leftfloat'>
            <nav id='press'>
                <ul>
                    <li><a href='#' alt=''>MISSION</a></li>
                    <li><a href='#' alt=''>CURRENT NEWS</a></li>
                    <li><a href='#' alt=''>PRESS RELEASES</a></li>
                    <li><a href='#' alt=''>STAFF BIOS</a></li>
                    <li><a href='#' alt=''>TESTIMONIALS</a></li>
                </ul>
            </nav>
        </article>
        <article style='width:250px;' class='leftfloat'>
            <p>To be a world-class design resource
            that contributes to the advancement
            of understanding in  science and
            technology.</p><br />
            <p>To skillfully blend education and
            entertainment to create effective,
            universal communications.</p><br />
            <p>To create accurate work that captivates,
            educates and ignites the imagination of
            people of all ages around the world.</p>
        </article>
        </div>
    </section>
</div>
<?php
    include_once 'includes/footer.inc';
?>
</body>
</html>
</code>```

答:
As commented by ScottE in your question, HTML5 and IE don't get along very well.

Using IE8 developer tool, one of the problem you can see is that the image is below your article tag, not within article tag as in other modern browser. This happens to all other article tags in your page as well.

Perhaps you should use div instead of article.

Body:
http://iamwhitebox.com/staging/arkitek/index.php#press.htm

I think its just a float/margin bug but I haven't been able to pinpoint it

??

<!DOCTYPE html>

    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Arkitek Studios | Press</title>
    <link rel='stylesheet' type='text/css' href='css/core.css' />

<?php
    include_once 'includes/header.inc';
?>

MISSION

CURRENT NEWS

PRESS RELEASES

STAFF BIOS

TESTIMONIALS

To be a world-class design resource
            that contributes to the advancement
            of understanding in  science and
            technology.

To skillfully blend education and
            entertainment to create effective,
            universal communications.

To create accurate work that captivates,
            educates and ignites the imagination of
            people of all ages around the world.

<?php
    include_once 'includes/footer.inc';
?>


问:
MySQL: Error #1067 when trying to add a boolean column with default 0
I'm developing a feature to show to the users how many unread messages there is on the site. So I'm trying to execute this query:

```<code>alter table messages add read boolean not null default 0
</code>```

But the server returns this message:

#1067 - Invalid default value for 'Data'

I can't see what is wrong. I'm running MariaDB/MySQL 5.7.20-0ubuntu0.16.04.1.

答: Found the problem. The "Data" column is with a invalid default value. I got this database restored from a server that has a different MySQL version.

Body:
I'm developing a feature to show to the users how many unread messages there is on the site. So I'm trying to execute this query:

alter table messages add read boolean not null default 0

But the server returns this message:

#1067 - Invalid default value for 'Data'

I can't see what is wrong. I'm running MariaDB/MySQL 5.7.20-0ubuntu0.16.04.1.


问:
Tar folder with backslash in the name
I am trying to archive a directory which has several backslashes in the name. My directory name is "\\abc\pqr\xyz". Here is the command I used.

```<code>tar -czf abc.tar "\\\\abc\\pqr\\xyz"
</code>```

I was getting this error.

```<code>tar: \\abc\pqr\\xyz: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
</code>```

答:
Use single quotes. You can test with echo:</p>

```<code>#!/bin/sh
echo "\\\\abc\\pqr\\xyz"
echo '\\\\abc\\pqr\\xyz'
</code>```

Title: Tar folder with backslash in the name

Body:
I am trying to archive a directory which has several backslashes in the name. My directory name is "\\abc\pqr\xyz". Here is the command I used.

tar -czf abc.tar "\\\\abc\\pqr\\xyz"

I was getting this error.

tar: \\abc\pqr\\xyz: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

Body:
Use single quotes. You can test with echo:

#!/bin/sh
echo "\\\\abc\\pqr\\xyz"
echo '\\\\abc\\pqr\\xyz'


问:
rxjs5 merge and error handling
I would like to combine/merge multiple Observables and when each of them is completed execute a finally function. The merge operator seems to execute each subscription in parallel, which is what I need, but if any of them throws an error the execution is halted.

RxJS version 4 has an operator mergeDelayError that should keep the all subscriptions executing till all of them are completed, but this operator isn't implemented in version 5.

Should I revert to a different operator?

```<code>var source1 = Rx.Observable.of(1,2,3).delay(3000);
var source2 = Rx.Observable.throw(new Error('woops'));
var source3 = Rx.Observable.of(4,5,6).delay(1000);

// Combine the 3 sources into 1

var source = Rx.Observable
  .merge(source1, source2, source3)
  .finally(() => {

    // finally is executed before all
    // subscriptions are completed.

    console.log('finally');

  });

var subscription = source.subscribe(
  x => console.log('next:', x),
  e => console.log('error:', e),
  () => console.log('completed'));
</code>```

JSBin

答:
If you don't want to swallow your errors, but want to delay them to the end, you can:

```<code>const mergeDelayErrors = [];
const sources = [source1, source2, source3].map(obs => obs.catch((error) => {
  mergeDelayErrors.push(error);
  return Rx.Observable.empty();
}));

return Rx.Observable
  .merge(...sources)
  .toArray()
  .flatMap(allEmissions => {
    let spreadObs = Rx.Observable.of(...allEmissions);
    if (mergeDelayErrors.length) {
      spreadObs = spreadObs.concat(Rx.Observable.throw(mergeDelayErrors));
    }
    return spreadObs;
  })
</code>```

You may want to throw only the first error, or create a CompositeError. I'm not sure how mergeDelayErrors originally behaved when multiple errors were thrown.

Unfortunately, because this implementation must wait until the all observables complete before emitting errors, it also waits until all observables complete before emitting next. This is likely not the original behavior of mergeDelayError, which is supposed to emit as a stream, rather than emitting them all at the end.

Title: rxjs5 merge and error handling

Body:
I would like to combine/merge multiple Observables and when each of them is completed execute a finally function. The merge operator seems to execute each subscription in parallel, which is what I need, but if any of them throws an error the execution is halted.

RxJS version 4 has an operator mergeDelayError that should keep the all subscriptions executing till all of them are completed, but this operator isn't implemented in version 5.

Should I revert to a different operator?

var source1 = Rx.Observable.of(1,2,3).delay(3000);
var source2 = Rx.Observable.throw(new Error('woops'));
var source3 = Rx.Observable.of(4,5,6).delay(1000);

// Combine the 3 sources into 1

var source = Rx.Observable
  .merge(source1, source2, source3)
  .finally(() => {

    // finally is executed before all
    // subscriptions are completed.

    console.log('finally');

  });

var subscription = source.subscribe(
  x => console.log('next:', x),
  e => console.log('error:', e),
  () => console.log('completed'));

JSBin

Body:
If you don't want to swallow your errors, but want to delay them to the end, you can:

const mergeDelayErrors = [];
const sources = [source1, source2, source3].map(obs => obs.catch((error) => {
  mergeDelayErrors.push(error);
  return Rx.Observable.empty();
}));

return Rx.Observable
  .merge(...sources)
  .toArray()
  .flatMap(allEmissions => {
    let spreadObs = Rx.Observable.of(...allEmissions);
    if (mergeDelayErrors.length) {
      spreadObs = spreadObs.concat(Rx.Observable.throw(mergeDelayErrors));
    }
    return spreadObs;
  })

You may want to throw only the first error, or create a CompositeError. I'm not sure how mergeDelayErrors originally behaved when multiple errors were thrown.

Unfortunately, because this implementation must wait until the all observables complete before emitting errors, it also waits until all observables complete before emitting next. This is likely not the original behavior of mergeDelayError, which is supposed to emit as a stream, rather than emitting them all at the end.


问:
How to find the N largest files in a git repository?
I wanted to find the 10 largest files in my repository. The script I came up with is as follows:

```<code>REP_HOME_DIR=<top level git directory>
max_huge_files=10

cd ${REP_HOME_DIR}
git verify-pack -v ${REP_HOME_DIR}/.git/objects/pack/pack-*.idx | \
  grep blob | \
  sort -r -k 3 -n | \
  head -${max_huge_files} | \
  awk '{ system("printf \"%-80s \" `git rev-list --objects --all | grep " $1 " | cut -d\" \" -f2`"); printf "Size:%5d MB Size in pack file:%5d MB\n", $3/1048576,  $4/1048576; }'
cd -
</code>```

Is there a better/more elegant way to do the same?

By "files" I mean the files that have been checked into the repository.

答:
An improvement to raphinesse's answer, sort by size with largest first:</p>

```<code>git rev-list --objects --all \
| git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
| awk '/^blob/ {print substr($0,6)}' \
| sort --numeric-sort --key=2 --reverse \
| head \
| cut --complement --characters=13-40 \
| numfmt --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest
</code>```

Body:
I wanted to find the 10 largest files in my repository. The script I came up with is as follows:

REP_HOME_DIR=<top level git directory>
max_huge_files=10

cd ${REP_HOME_DIR}
git verify-pack -v ${REP_HOME_DIR}/.git/objects/pack/pack-*.idx | \
  grep blob | \
  sort -r -k 3 -n | \
  head -${max_huge_files} | \
  awk '{ system("printf \"%-80s \" `git rev-list --objects --all | grep " $1 " | cut -d\" \" -f2`"); printf "Size:%5d MB Size in pack file:%5d MB\n", $3/1048576,  $4/1048576; }'
cd -

Is there a better/more elegant way to do the same?

By "files" I mean the files that have been checked into the repository.

Body:
An improvement to raphinesse's answer, sort by size with largest first:

git rev-list --objects --all \
| git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
| awk '/^blob/ {print substr($0,6)}' \
| sort --numeric-sort --key=2 --reverse \
| head \
| cut --complement --characters=13-40 \
| numfmt --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest


问:
Mark fields as dirty in Linq To Sql
One of my entities in my LinqToSql model has a field of type XElement, mapped to an XML column in SQL Server.

When I do the following:

```<code>myEntity.MyXmlField.Add(new XAttribute("attribute", "value"));
...
DataContext.SubmitChanges();
</code>```

The field does not get updated in the database (but other fields do).
I take it that the DataContext cannot track changes made inside the XElement and thus this field is not marked as dirty and does not get updated.

Is this the correct assumption and how can I fix it?

EDIT

After reading the link that The Scrum Meister provided, it looks like

```<code>myEntity.MyXmlField = new XElement(myEntity.MyXmlField);
</code>```

will solve the issue.

However this solution is quite specific to XElement (as it's easy to clone it), and involves a lot of processing if the XElement is large.

There's got to be a general way of letting the DataContext know that a field has changed.

答:
Alright, it looks like this is a known issue:
http://connect.microsoft.com/VisualStudio/feedback/details/360433/linq-to-sql-xml-fields-dont-update

Microsoft's recommendation is to use

```<code>myEntity.MyXmlField = new XElement(myEntity.MyXmlField);
</code>```

So I take it there is no better or general way of fixing this.

Title: Mark fields as dirty in Linq To Sql

Body:
One of my entities in my LinqToSql model has a field of type XElement, mapped to an XML column in SQL Server.

When I do the following:

myEntity.MyXmlField.Add(new XAttribute("attribute", "value"));
...
DataContext.SubmitChanges();

The field does not get updated in the database (but other fields do).
I take it that the DataContext cannot track changes made inside the XElement and thus this field is not marked as dirty and does not get updated.

Is this the correct assumption and how can I fix it?

EDIT

After reading the link that The Scrum Meister provided, it looks like

myEntity.MyXmlField = new XElement(myEntity.MyXmlField);

will solve the issue.

However this solution is quite specific to XElement (as it's easy to clone it), and involves a lot of processing if the XElement is large.

There's got to be a general way of letting the DataContext know that a field has changed.

Body:
Alright, it looks like this is a known issue:
http://connect.microsoft.com/VisualStudio/feedback/details/360433/linq-to-sql-xml-fields-dont-update

Microsoft's recommendation is to use

myEntity.MyXmlField = new XElement(myEntity.MyXmlField);

So I take it there is no better or general way of fixing this.


问:
How do you store datetime in MongoDB given that what I've tried has failed?
I'm trying to insert a datetime in MongoDB but I can not.

Here is the method I used:

```<code>var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({

    date : {
       type : Date
          }
});

module.exports = mongoose.model('test', testSchema);
</code>```

答:
```<code>try {
    Mongo mongo = new Mongo("yourhost", 27017);
    DB db = mongo.getDB("yourdb");

    DBCollection collection = db.getCollection("yourColl");
    DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = (Date)formatter.parse("2-Jun-2012")
    BasicDBObject time = new BasicDBObject("ts", date);
    collection.save(time);
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (MongoException e) {
    e.printStackTrace();
}
</code>```

Body:
I'm trying to insert a datetime in MongoDB but I can not.

Here is the method I used:

var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({

    date : {
       type : Date
          }
});

module.exports = mongoose.model('test', testSchema);


问:
Azure Stream Analytics tools for Visual Studio: Error when executing aggregated queries - "Object reference not set to an instance of an object"
We have followed the documentation Use Azure Stream Analytics tools for Visual Studio and made the Visual Studio capable of creating Azure Stream Analytics project.

We have created an Azure Stream Analytics(ASA) job with Local Input data in the following JSON format:

```<code>[
    {
        "Driver": "Lewis",
        "Speed": 0.8275496959686279,
        "Accelerator": 1,
        "Brakes": 0,
        "Steering": 0,
        "ErsBattery": 0.9398990273475647,
        "Gear": 0,
        "LapTimeMs": 107,
        "EventTime": "2016-04-01T00:00:00.107",
        "PosX": 1593.4061279296875,
        "PosY": 934.5406494140625,
        "PosZ": 101.44535064697266
    },
    {
        "Driver": "James",
        "Speed": 1.8795902729034424,
        "Accelerator": 1,
        "Brakes": 0,
        "Steering": 0,
        "ErsBattery": 0.9865896105766296,
        "Gear": 0,
        "LapTimeMs": 107,
        "EventTime": "2016-04-01T00:00:00.107",
        "PosX": 1593.3990478515625,
        "PosY": 934.5374145507812,
        "PosZ": 101.44610595703125
    },
    {
        "Driver": "Damon",
        "Speed": 0.4023849666118622,
        "Accelerator": 1,
        "Brakes": 0,
        "Steering": 0,
        "ErsBattery": 1,
        "Gear": 0,
        "LapTimeMs": 108,
        "EventTime": "2016-04-01T00:00:00.108",
        "PosX": 1593.411865234375,
        "PosY": 934.5435180664062,
        "PosZ": 101.44485473632812
    }
]
</code>```

Then we are running the query locally as below:

```<code>SELECT Driver, AVG(Speed) AS AvgSpeed
FROM Input
GROUP BY Driver, TumblingWindow(second, 10)
</code>```

After executing the query, we are getting an error message as "Error : Object reference not set to an instance of an object."

答: Open your Visual Studio IDE in Administrator mode, run your ASA query with local input and you will get the expected query result.

Body:
We have followed the documentation Use Azure Stream Analytics tools for Visual Studio and made the Visual Studio capable of creating Azure Stream Analytics project.

We have created an Azure Stream Analytics(ASA) job with Local Input data in the following JSON format:

[
    {
        "Driver": "Lewis",
        "Speed": 0.8275496959686279,
        "Accelerator": 1,
        "Brakes": 0,
        "Steering": 0,
        "ErsBattery": 0.9398990273475647,
        "Gear": 0,
        "LapTimeMs": 107,
        "EventTime": "2016-04-01T00:00:00.107",
        "PosX": 1593.4061279296875,
        "PosY": 934.5406494140625,
        "PosZ": 101.44535064697266
    },
    {
        "Driver": "James",
        "Speed": 1.8795902729034424,
        "Accelerator": 1,
        "Brakes": 0,
        "Steering": 0,
        "ErsBattery": 0.9865896105766296,
        "Gear": 0,
        "LapTimeMs": 107,
        "EventTime": "2016-04-01T00:00:00.107",
        "PosX": 1593.3990478515625,
        "PosY": 934.5374145507812,
        "PosZ": 101.44610595703125
    },
    {
        "Driver": "Damon",
        "Speed": 0.4023849666118622,
        "Accelerator": 1,
        "Brakes": 0,
        "Steering": 0,
        "ErsBattery": 1,
        "Gear": 0,
        "LapTimeMs": 108,
        "EventTime": "2016-04-01T00:00:00.108",
        "PosX": 1593.411865234375,
        "PosY": 934.5435180664062,
        "PosZ": 101.44485473632812
    }
]

Then we are running the query locally as below:

SELECT Driver, AVG(Speed) AS AvgSpeed
FROM Input
GROUP BY Driver, TumblingWindow(second, 10)

After executing the query, we are getting an error message as "Error : Object reference not set to an instance of an object."


问:
lexer, parser , trying to make an expression calculator
As the title says am trying to make an expression calculator using Ply , I still didnt finish the complete code just a part of it , but until now . I get this error :

Traceback (most recent call last):
   File "EX3.py", line 69, in
  module

     parser = yacc.yacc()    File "/Users/mostafa.osama2/anaconda3/lib/python3.6/site-packages/ply/yacc.py",
  line 3317, in yacc

     raise YaccError('Unable to build parser')
 ply.yacc.YaccError: Unable to build parser

here is my code :

```<code>import ply.lex as lex
import ply.yacc as yacc
import sys

tokens = ['INT','FLOAT' , 'NAME' , 'PLUS' , 'MINUS' , 'DIVIDE' , 'MULTIPLY' ,
'EQUALS']

#list of tokens , for grammar checking

t_PLUS = r'\+'
t_MINUS = r'\-'
t_MULTIPLY = r'\*'
t_DIVIDE = r'\/'
t_EQUALS = r'\='

t_ignore = r' ' # used for ignoring spaces between numbers and operators

#has to match name of token,

def t_FLOAT(t):
    r'\d+.\d+' # 1.2 is a float , 1.any number is a float
    t.value = float(t.value)
    return t

def t_INT(t):
    r'\d+'
    t.value = int(t.value)
    return t # t is our token object

def t_NAME(t):
    r'[a-zA-Z_][a-zA-Z_0-9]*' #star means 0 or more, first char is a-zA-z , second character is a-zA-z0-9
    t.type = 'NAME'
    return t

def t_error(t):
    print("Illegal characters!")
    t.lexer.skip(1) # skips 1 token onwards

lexer = lex.lex()

def p_calc(p): # p is  a  tuple
    '''
    calc : expression
        | empty
    '''
    print(p[1])

def p_expression(p):
    '''
    expression : expression PLUS expression
                | expression DIVIDE expression
                | expression PLUS expression
                | expression MINUS expression
    '''
    p[0] = (p[2] , p[1] , p[3])
def p_expression(p):
    '''
    expression : INT
                | FLOAT
    '''
    p[0] = p[1]
def p_empty(p):
    '''
    empty:
    '''
    p[0] = None

parser = yacc.yacc()
while True:
    try:
        s = input('')
    except EOFError: # when u press contorl D on keyboard
        break
        parser.parse(s)
</code>```

答:
Ply insists that parsing rules have whitespace between the name of the non-terminal and the colon. So empty: is not valid; you must write empty :

Also, as reported by Ply, you define two functions named p_expression. Ply requires that all parsing functions have different names (otherwise it has no way to call them), but it doesn't care what the names are, as long as they start with p_. So change one of the names.

Finally, you have two rules for addition, and no rule for multiplication. Ply will complain about the duplicate addition rule (after you fix the other problems). It will also complain that you are missing a p_error function.

ContentLicense: CC BY-SA 4.0

Body:
As the title says am trying to make an expression calculator using Ply , I still didnt finish the complete code just a part of it , but until now . I get this error :

Traceback (most recent call last):
   File "EX3.py", line 69, in
  module

     parser = yacc.yacc()    File "/Users/mostafa.osama2/anaconda3/lib/python3.6/site-packages/ply/yacc.py",
  line 3317, in yacc

     raise YaccError('Unable to build parser')
 ply.yacc.YaccError: Unable to build parser

here is my code :

import ply.lex as lex
import ply.yacc as yacc
import sys

tokens = ['INT','FLOAT' , 'NAME' , 'PLUS' , 'MINUS' , 'DIVIDE' , 'MULTIPLY' ,
'EQUALS']

#list of tokens , for grammar checking

t_PLUS = r'\+'
t_MINUS = r'\-'
t_MULTIPLY = r'\*'
t_DIVIDE = r'\/'
t_EQUALS = r'\='

t_ignore = r' ' # used for ignoring spaces between numbers and operators

#has to match name of token,

def t_FLOAT(t):
    r'\d+.\d+' # 1.2 is a float , 1.any number is a float
    t.value = float(t.value)
    return t

def t_INT(t):
    r'\d+'
    t.value = int(t.value)
    return t # t is our token object

def t_NAME(t):
    r'[a-zA-Z_][a-zA-Z_0-9]*' #star means 0 or more, first char is a-zA-z , second character is a-zA-z0-9
    t.type = 'NAME'
    return t

def t_error(t):
    print("Illegal characters!")
    t.lexer.skip(1) # skips 1 token onwards

lexer = lex.lex()

def p_calc(p): # p is  a  tuple
    '''
    calc : expression
        | empty
    '''
    print(p[1])

def p_expression(p):
    '''
    expression : expression PLUS expression
                | expression DIVIDE expression
                | expression PLUS expression
                | expression MINUS expression
    '''
    p[0] = (p[2] , p[1] , p[3])
def p_expression(p):
    '''
    expression : INT
                | FLOAT
    '''
    p[0] = p[1]
def p_empty(p):
    '''
    empty:
    '''
    p[0] = None

parser = yacc.yacc()
while True:
    try:
        s = input('')
    except EOFError: # when u press contorl D on keyboard
        break
        parser.parse(s)


问:
Android preferences problem
I am following this tutorial: link text

Preferences.java:

```<code>public class Preferences extends PreferenceActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
}
</code>```

}

PreferencesTutorial.java:

```<code>public class PreferencesTutorial extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button prefBtn = (Button) findViewById(R.id.prefButton);
        prefBtn.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                        Intent settingsActivity = new Intent(getBaseContext(),
                                        Preferences.class);
                        startActivity(settingsActivity);
                }
        });
 }
</code>```

}

Preferences.xml:

When application starts, and i click the prefButton, an error occures: "The application PreferencesTutorial (process PreferencesTutorial.com.examples) has stopped unexpectedly. Please try again"

I haven't found any mistakes in the code.
I would also like to show my filestructure if that helps:

AndroidManifest.xml:

What is wrong with the code?

Even if i add (where the cursor is)

```<code><activity
        android:name=".Preferences"
        android:label="@string/set_preferences">
    </activity>
</code>```

i still get the error.

答:
You probably do not have Preferences defined in your manifest.

However, as others have indicated, use adb logcat, DDMS, or the DDMS perspective in Eclipse to examine LogCat and see the stack trace associated with your crash.

Title: Android preferences problem

Body:
I am following this tutorial: link text

Preferences.java:

public class Preferences extends PreferenceActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
}

}

PreferencesTutorial.java:

public class PreferencesTutorial extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button prefBtn = (Button) findViewById(R.id.prefButton);
        prefBtn.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                        Intent settingsActivity = new Intent(getBaseContext(),
                                        Preferences.class);
                        startActivity(settingsActivity);
                }
        });
 }

}

Preferences.xml:

When application starts, and i click the prefButton, an error occures: "The application PreferencesTutorial (process PreferencesTutorial.com.examples) has stopped unexpectedly. Please try again"

I haven't found any mistakes in the code.
I would also like to show my filestructure if that helps:

AndroidManifest.xml:

What is wrong with the code?

Even if i add (where the cursor is)

<activity
        android:name=".Preferences"
        android:label="@string/set_preferences">
    </activity>

i still get the error.


问:
How to pass a blob created in javascript to JSF bean
My client side code deals with canvas drawing, and i generate a blob zip file of the shapes using javascript.
I want to use the zip at the server side. However, I am not able to find any solution.

I have tried using remote command, but using that i can only pass string parameters to the JSF bean.
I tried hacking the primefaces fileUpload plugin somehow so that I could pass my blob to the backing bean, but that also didn't work out.

答:
You can pass blob from JavaScript to JSF bean by encoding blob to some string representation, for example, to Base64 and passing it to Primefaces  p:remoteCommand, sending it to managed bean and finally decoding it there back to byte array.

Procedure would be following:

Convert blob to Base64

```<code> function prepareAndSendBlobToManagedBean(){
            //zipped file as blob
            var blob=...;
            ///convert blob to Base64 string
            var blobBase64String=convertToBase64(blob);
            sendBlobBase64([{name : 'blobBase64Name', value : blobBase64String}]);
        }
</code>```

(for converting from blob to base64 reffer to this accepted answer)

Add p:remoteCommand to your page

```<code><p:remoteCommand name="sendBlobBase64"
                 actionListener="#{yourBean.onBlobBase64Sent}" process="@this"/>
</code>```

In managed bean named yourBean you can catch it with

```<code>public void onBlobBase64Sent() {
   String blobBase64 = (String)FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("blobBase64Name");
   byte[]blob=java.util.Base64.getDecoder().decode(blobBase64);
}
</code>```

Body:
You can pass blob from JavaScript to JSF bean by encoding blob to some string representation, for example, to Base64 and passing it to Primefaces  p:remoteCommand, sending it to managed bean and finally decoding it there back to byte array.

Procedure would be following:

Convert blob to Base64

 function prepareAndSendBlobToManagedBean(){
            //zipped file as blob
            var blob=...;
            ///convert blob to Base64 string
            var blobBase64String=convertToBase64(blob);
            sendBlobBase64([{name : 'blobBase64Name', value : blobBase64String}]);
        }

(for converting from blob to base64 reffer to this accepted answer)

Add p:remoteCommand to your page

<p:remoteCommand name="sendBlobBase64"
                 actionListener="#{yourBean.onBlobBase64Sent}" process="@this"/>

In managed bean named yourBean you can catch it with

public void onBlobBase64Sent() {
   String blobBase64 = (String)FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("blobBase64Name");
   byte[]blob=java.util.Base64.getDecoder().decode(blobBase64);
}


问:
Count distinct using case when
Let me first start by saying I am new to mysql. I am transitioning from dumping data into excel and using voodoo from there so this new language can be perplexing but I am getting the hang of simple queries.

My first problem that I cannot find an answer for is that I am looking for billable medical encounters and then comparing them to how many patients were seen for that time period. (Edit: It is the "CASE WHEN statement that I am having issue with here)

Billable encounters are counted by unique encounters that can have one of any number of billable codes for that encounter to count as billable. (There are many more codes but I truncated for space)

This is what I have this far which of course is not working:

```<code>SELECT
            CONCAT(`users`.`ulname`,', ',`users`.`ufname`) AS Provider
                      , YEAR(e.`date`) AS 'YEAR'
                      , LEFT(MONTHNAME(e.date), 3) AS 'MONTH'
                      , COUNT(DISTINCT e.`patientID`) AS Pts
                      , COUNT(DISTINCT e.`encounterID` CASE WHEN d.`value`
IN ('99213','99214','99212','99203','99202','90832','99393') THEN END AS
Bill_Encs
                      , COUNT(e.`status`) AS 'Vts_CHK'
                      , COUNT(e.`status`) - COUNT(DISTINCT e.`encounterID`)
AS No_Codes

FROM enc e
    INNER JOIN `mobiledoc`.`users` ON `users`.`uid` = e.`ResourceId`
            INNER JOIN `billingdata` billing ON billing.`EncounterId` =
e.`encounterID`
            INNER JOIN items i ON i.`itemID` = billing.`itemID`
            INNER JOIN `itemdetail` d ON d.`itemID` = i.`itemID`
 WHERE e.`date` BETWEEN CAST('2017-10-26' AS DATE) AND CAST('2017-10-31' AS
DATE)
            AND d.`propID` = 13
            AND billing.`deleteFlag` = 0
            AND i.`deleteFlag` = 0
            AND e.status = "CHK"
            AND e.`deleteFlag` = 0
            AND e.`encType` = 1
            AND e.`ClaimReq` = 1
            AND `users`.`UserType` = 1

 GROUP BY Provider ASC, YEAR(e.`date`) ,MONTH(e.`date`) ASC;
</code>```

答:
If all else is equal (working) I think you just want conditional aggregation.

```<code>, COUNT(DISTINCT e.`encounterID` CASE WHEN d.`value`
IN ('99213','99214','99212','99203','99202','90832','99393') THEN END AS
Bill_Encs
</code>```

becomes

```<code>, COUNT(DISTINCT CASE WHEN d.`value`
IN ('99213','99214','99212','99203','99202','90832','99393') THEN e.`encounterID` END AS Bill_Encs
</code>```

Title: Count distinct using case when

Body:
Let me first start by saying I am new to mysql. I am transitioning from dumping data into excel and using voodoo from there so this new language can be perplexing but I am getting the hang of simple queries.

My first problem that I cannot find an answer for is that I am looking for billable medical encounters and then comparing them to how many patients were seen for that time period. (Edit: It is the "CASE WHEN statement that I am having issue with here)

Billable encounters are counted by unique encounters that can have one of any number of billable codes for that encounter to count as billable. (There are many more codes but I truncated for space)

This is what I have this far which of course is not working:

SELECT
            CONCAT(`users`.`ulname`,', ',`users`.`ufname`) AS Provider
                      , YEAR(e.`date`) AS 'YEAR'
                      , LEFT(MONTHNAME(e.date), 3) AS 'MONTH'
                      , COUNT(DISTINCT e.`patientID`) AS Pts
                      , COUNT(DISTINCT e.`encounterID` CASE WHEN d.`value`
IN ('99213','99214','99212','99203','99202','90832','99393') THEN END AS
Bill_Encs
                      , COUNT(e.`status`) AS 'Vts_CHK'
                      , COUNT(e.`status`) - COUNT(DISTINCT e.`encounterID`)
AS No_Codes

FROM enc e
    INNER JOIN `mobiledoc`.`users` ON `users`.`uid` = e.`ResourceId`
            INNER JOIN `billingdata` billing ON billing.`EncounterId` =
e.`encounterID`
            INNER JOIN items i ON i.`itemID` = billing.`itemID`
            INNER JOIN `itemdetail` d ON d.`itemID` = i.`itemID`
 WHERE e.`date` BETWEEN CAST('2017-10-26' AS DATE) AND CAST('2017-10-31' AS
DATE)
            AND d.`propID` = 13
            AND billing.`deleteFlag` = 0
            AND i.`deleteFlag` = 0
            AND e.status = "CHK"
            AND e.`deleteFlag` = 0
            AND e.`encType` = 1
            AND e.`ClaimReq` = 1
            AND `users`.`UserType` = 1

 GROUP BY Provider ASC, YEAR(e.`date`) ,MONTH(e.`date`) ASC;

Body:
If all else is equal (working) I think you just want conditional aggregation.

, COUNT(DISTINCT e.`encounterID` CASE WHEN d.`value`
IN ('99213','99214','99212','99203','99202','90832','99393') THEN END AS
Bill_Encs

becomes

, COUNT(DISTINCT CASE WHEN d.`value`
IN ('99213','99214','99212','99203','99202','90832','99393') THEN e.`encounterID` END AS Bill_Encs


问:
Core Data batch update
I am trying to run a batch update on selected objects in my Core Data database (SQLite) but my request returns 0 items updated (no error message). My entity "SDRDFileObject" has a property selected (Bool in my model), which I want to set to NO for all objects satisfying my fetch predicate:

```<code> NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(isLeaf == 1) AND (direction ==  1) AND (myLR == 1)"];

 NSEntityDescription *entity = [NSEntityDescription entityForName:@"SDRDFileObject"
                                     inManagedObjectContext:self.context];

NSBatchUpdateRequest *reqL = [[NSBatchUpdateRequest alloc] initWithEntity:entity];
reqL.predicate = predicate;
reqL.resultType = NSUpdatedObjectIDsResultType;

reqL.includesSubentities = YES;
reqL.propertiesToUpdate = @{
                            @"selected" : @(NO)
                            };

NSError *error;
NSBatchUpdateResult *resL = (NSBatchUpdateResult *)[self.context executeRequest:reqL error:&error];
</code>```

This returns 0 items updated. However, if I use the same settings to make an estimate of the number of affected objects I get 1764 (which is correct):

```<code> NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setPredicate:predicate];
[request setResultType:NSUpdatedObjectIDsResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:@[@"selected"]];

NSError *err;
NSUInteger count = [self.context countForFetchRequest:request error:&err];

NSLog(@"Estimated fetch request count : %li",count);
</code>```

Does anyone have suggestions as to what I am doing wrong here? Should I write the keyPath any different? I appreciate suggestions and help.

Update
I followed the suggestion for debugging the SQL commands and it seems to fail, although I am not sure how to interpret the error message. The first SQL calls are for the countForFetchRequest which suceeds and then comes the batch request that fails.

```<code>CoreData: sql: SELECT COUNT( DISTINCT t0.Z_PK) FROM ZSDRDFILEOBJECT t0     WHERE ( t0.ZISLEAF = ? AND  t0.ZDIRECTION = ? AND  t0.ZMYLR = ?)
CoreData: annotation: total count request execution time: 0.0005s for count of 0.
2017-11-15 16:56:09.560121+0100 TEST[69278:3739361] Estimated fetch  request count : 1764
CoreData: sql: BEGIN EXCLUSIVE
CoreData: sql: SELECT 0, t0.Z_PK FROM ZSDRDFILEOBJECT t0 WHERE (  t0.ZISLEAF = ? AND  t0.ZDIRECTION = ? AND  t0.ZMYLR = ?)
CoreData: annotation: sql connection fetch time: 0.0000s
CoreData: annotation: total fetch execution time: 0.0001s for 0 rows.
CoreData: sql: UPDATE OR FAIL ZSDRDFILEOBJECT SET ZSELECTED = ?, Z_OPT = (Z_OPT + 1) WHERE (ZISLEAF = ? AND ZDIRECTION = ? AND ZMYLR = ?)
CoreData: sql: pragma auto_vacuum
CoreData: annotation: sql execution time: 0.0000s
CoreData: sql: pragma auto_vacuum=2
CoreData: annotation: sql execution time: 0.0003s
CoreData: sql: COMMIT
</code>```

答:
The first SQL count returns 0, but the context returns 1764. So it looks like the objects which meet your criteria have not yet been saved to the SQLite store. The batch update works directly on the SQLite store, so it cannot update the unsaved items.

So either save the context first, or update the objects directly in the context - which should be quick, since they are already registered with the context and do not need to be fetched.

Title: Core Data batch update

Body:
I am trying to run a batch update on selected objects in my Core Data database (SQLite) but my request returns 0 items updated (no error message). My entity "SDRDFileObject" has a property selected (Bool in my model), which I want to set to NO for all objects satisfying my fetch predicate:

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(isLeaf == 1) AND (direction ==  1) AND (myLR == 1)"];

 NSEntityDescription *entity = [NSEntityDescription entityForName:@"SDRDFileObject"
                                     inManagedObjectContext:self.context];

NSBatchUpdateRequest *reqL = [[NSBatchUpdateRequest alloc] initWithEntity:entity];
reqL.predicate = predicate;
reqL.resultType = NSUpdatedObjectIDsResultType;

reqL.includesSubentities = YES;
reqL.propertiesToUpdate = @{
                            @"selected" : @(NO)
                            };

NSError *error;
NSBatchUpdateResult *resL = (NSBatchUpdateResult *)[self.context executeRequest:reqL error:&error];

This returns 0 items updated. However, if I use the same settings to make an estimate of the number of affected objects I get 1764 (which is correct):

 NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setPredicate:predicate];
[request setResultType:NSUpdatedObjectIDsResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:@[@"selected"]];

NSError *err;
NSUInteger count = [self.context countForFetchRequest:request error:&err];

NSLog(@"Estimated fetch request count : %li",count);

Does anyone have suggestions as to what I am doing wrong here? Should I write the keyPath any different? I appreciate suggestions and help.

Update
I followed the suggestion for debugging the SQL commands and it seems to fail, although I am not sure how to interpret the error message. The first SQL calls are for the countForFetchRequest which suceeds and then comes the batch request that fails.

CoreData: sql: SELECT COUNT( DISTINCT t0.Z_PK) FROM ZSDRDFILEOBJECT t0     WHERE ( t0.ZISLEAF = ? AND  t0.ZDIRECTION = ? AND  t0.ZMYLR = ?)
CoreData: annotation: total count request execution time: 0.0005s for count of 0.
2017-11-15 16:56:09.560121+0100 TEST[69278:3739361] Estimated fetch  request count : 1764
CoreData: sql: BEGIN EXCLUSIVE
CoreData: sql: SELECT 0, t0.Z_PK FROM ZSDRDFILEOBJECT t0 WHERE (  t0.ZISLEAF = ? AND  t0.ZDIRECTION = ? AND  t0.ZMYLR = ?)
CoreData: annotation: sql connection fetch time: 0.0000s
CoreData: annotation: total fetch execution time: 0.0001s for 0 rows.
CoreData: sql: UPDATE OR FAIL ZSDRDFILEOBJECT SET ZSELECTED = ?, Z_OPT = (Z_OPT + 1) WHERE (ZISLEAF = ? AND ZDIRECTION = ? AND ZMYLR = ?)
CoreData: sql: pragma auto_vacuum
CoreData: annotation: sql execution time: 0.0000s
CoreData: sql: pragma auto_vacuum=2
CoreData: annotation: sql execution time: 0.0003s
CoreData: sql: COMMIT


问:
How to create training data for RASA NLU through program nodejs
How to create training data through program for RASA NLU?
Actually I am developing an application using MEAN stack, this application prepares the data that needs to be trained with RASA NLU.

But I don't know how to pass this info from my nodejs server to RASA NLU. Is there any supported api's to achieve this?

答:
Rasa has a highly functional API as documented here.

To answer the specific question you can pass training data to the Rasa NLU API via the below commands:

If your training data is in a file:

```<code>curl -XPOST localhost:5000/train?project=my_project -d @data/examples/rasa/demo-rasa.json
</code>```

If your training data is in json format:

```<code>curl --request POST \
  --url 'http://localhost:5000/train?project=test&fixed_model_name=tested-project' \
  --header 'content-type: application/json' \
  --data ' {
  "rasa_nlu_data": {
    "regex_features": [
      {
        "name": "zipcode",
        "pattern": "[0-9]{5}"
      }
    ],
    "entity_synonyms": [
      {
        "value": "chinese",
        "synonyms": ["Chinese", "Chines", "chines"]
      },
      {
        "value": "vegetarian",
        "synonyms": ["veggie", "vegg"]
      }
    ],
    "common_examples": []
  }
}'
</code>```

Obviously you'll need to create the json file or payload. and in Node you wouldn't be using curl, but a library like request.

I've written a series of tutorials that may be good to help you get started interacting with Rasa's API.

Body:
Rasa has a highly functional API as documented here.

To answer the specific question you can pass training data to the Rasa NLU API via the below commands:

If your training data is in a file:

curl -XPOST localhost:5000/train?project=my_project -d @data/examples/rasa/demo-rasa.json

If your training data is in json format:

curl --request POST \
  --url 'http://localhost:5000/train?project=test&fixed_model_name=tested-project' \
  --header 'content-type: application/json' \
  --data ' {
  "rasa_nlu_data": {
    "regex_features": [
      {
        "name": "zipcode",
        "pattern": "[0-9]{5}"
      }
    ],
    "entity_synonyms": [
      {
        "value": "chinese",
        "synonyms": ["Chinese", "Chines", "chines"]
      },
      {
        "value": "vegetarian",
        "synonyms": ["veggie", "vegg"]
      }
    ],
    "common_examples": []
  }
}'

Obviously you'll need to create the json file or payload. and in Node you wouldn't be using curl, but a library like request.

I've written a series of tutorials that may be good to help you get started interacting with Rasa's API.


问:
How to check issues by version instead of build on crashlytics?
We have lot of builds for each version after we integrated the CI system.
However, if we want to check the issues of one specified version, we have to select all builds of this version, which is very inconvenient.

How to resolve this problem?

答: There is not a way to select multiple builds at this time. I'll let the team know you are interested :)</p>


问:
How to set command timeout in aspnetcore/entityframeworkcore
The place where the command timeout is set is no longer the same as earlier versions.

However, I cannot find anywhere that says how to change this.

What I am doing is uploading very large files which takes longer than the default 30 seconds to save.

Note that I ask about Command Timeout, not Migration Timeout as in another question.

答:
If you're using the DI container to manage the DbContext (i.e. you're adding the DbContext to the service collection), the command timeout can be specified in the options.

In Startup.ConfigureServices:

```<code>services.AddDbContext<YourDbContext>(options => options.UseSqlServer(
    this.Configuration.GetConnectionString("YourConnectionString"),
    sqlServerOptions => sqlServerOptions.CommandTimeout(60))
);
</code>```

Body:
If you're using the DI container to manage the DbContext (i.e. you're adding the DbContext to the service collection), the command timeout can be specified in the options.

In Startup.ConfigureServices:

services.AddDbContext<YourDbContext>(options => options.UseSqlServer(
    this.Configuration.GetConnectionString("YourConnectionString"),
    sqlServerOptions => sqlServerOptions.CommandTimeout(60))
);


问:
How to Deal with Null (GridView Container.DataItem)
whats wrong here, why is it complaining about closing the ")" ?

```<code><asp:TemplateField HeaderText="Name" SortExpression="Name">
                    <ItemTemplate>
                        <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>
                    </ItemTemplate>
                    <EditItemTemplate>
                       <asp:dropdownlist id="ddlStudent" runat="server" datasourceid="CountyDataSource"
                            datatextfield="Name" datavaluefield="Id" autopostback="false">
                        </asp:dropdownlist>
                    </EditItemTemplate>
                </asp:TemplateField>

 protected string FixNull(object dataItem, string fieldName)
 {
        if (dataItem != null)
        {
            System.Data.DataRowView cls = (System.Data.DataRowView)dataItem;
            if (!cls.Row.IsNull(fieldName))
                return (cls[fieldName]).ToString();
            else
                return " ";
        }
        else
            return " ";
    }

Compiler Error Message: CS1026: ) expected

Source Error: Line: 133

Line 131:                  <asp:TemplateField HeaderText="Name" SortExpression="Name">
Line 132:                    <ItemTemplate>
Line 133:    <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>
Line 134:                    </ItemTemplate>
Line 135:                    <EditItemTemplate>
</code>```

答:
I think, you do not need the ;

it should just read:

<%# FixNull((namespace.Student)(Container.DataItem), "Name") %>

Body:
whats wrong here, why is it complaining about closing the ")" ?

<asp:TemplateField HeaderText="Name" SortExpression="Name">
                    <ItemTemplate>
                        <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>
                    </ItemTemplate>
                    <EditItemTemplate>
                       <asp:dropdownlist id="ddlStudent" runat="server" datasourceid="CountyDataSource"
                            datatextfield="Name" datavaluefield="Id" autopostback="false">
                        </asp:dropdownlist>
                    </EditItemTemplate>
                </asp:TemplateField>

 protected string FixNull(object dataItem, string fieldName)
 {
        if (dataItem != null)
        {
            System.Data.DataRowView cls = (System.Data.DataRowView)dataItem;
            if (!cls.Row.IsNull(fieldName))
                return (cls[fieldName]).ToString();
            else
                return " ";
        }
        else
            return " ";
    }

Compiler Error Message: CS1026: ) expected

Source Error: Line: 133

Line 131:                  <asp:TemplateField HeaderText="Name" SortExpression="Name">
Line 132:                    <ItemTemplate>
Line 133:    <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>
Line 134:                    </ItemTemplate>
Line 135:                    <EditItemTemplate>


问:
How to provide code for tkinter toplevel before data can be accessed
I am trying to have my tkinter toplevel have an access key before the content can be printed.It doesn't output any error but when I provide the access key it doesn't print the content to my terminal.I changed the access key but still I am not able to print the data.

from tkinter import *

```<code>def qw():
    global en1
    if en1.get() == 2e2c2v:
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()

root.mainloop()
</code>```

答:
There's several problem:

The indentation is not good on your else lines (but I think it's an error of copy/paste)

if en1.get() == 2e2c2v: should be if en1.get() == "2e2c2v":

There is an error when you're entering the right key after the previous correction because tp is not global

Your complete code after correction should be:

```<code>from tkinter import *

def qw():
    global en1
    global tp
    if en1.get() == "2e2c2v":
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1
    global tp
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()
root.mainloop()
</code>```

EDIT:

And by the way, I think it would be better to use a class instead of using global. It would gives something like that:

```<code>import tkinter as tk

class Example:
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("400x400")

        tk.Button(self.root, text= "print", command=self.login_toplevel).pack()

    def start(self):
        self.root.mainloop()

    def qw(self):
        if self.en1.get() == "2e2c2v":
            print("You have visa to Paris")
            self.tp.destroy()  # after printing should close the toplevel window
        else:
            print("you dont have access to print the data")

    def login_toplevel(self):
        self.tp = tk.Toplevel()
        self.tp.geometry("300x300")
        self.en1 = tk.Entry(self.tp)
        self.en1.pack()
        b = tk.Button(self.tp, text="provide key to print", command=self.qw)
        b.pack()

Example().start()
</code>```

Body:
I am trying to have my tkinter toplevel have an access key before the content can be printed.It doesn't output any error but when I provide the access key it doesn't print the content to my terminal.I changed the access key but still I am not able to print the data.

from tkinter import *

def qw():
    global en1
    if en1.get() == 2e2c2v:
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()

root.mainloop()

Body:
There's several problem:

The indentation is not good on your else lines (but I think it's an error of copy/paste)

if en1.get() == 2e2c2v: should be if en1.get() == "2e2c2v":

There is an error when you're entering the right key after the previous correction because tp is not global

Your complete code after correction should be:

from tkinter import *

def qw():
    global en1
    global tp
    if en1.get() == "2e2c2v":
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1
    global tp
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()
root.mainloop()

EDIT:

And by the way, I think it would be better to use a class instead of using global. It would gives something like that:

import tkinter as tk

class Example:
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("400x400")

        tk.Button(self.root, text= "print", command=self.login_toplevel).pack()

    def start(self):
        self.root.mainloop()

    def qw(self):
        if self.en1.get() == "2e2c2v":
            print("You have visa to Paris")
            self.tp.destroy()  # after printing should close the toplevel window
        else:
            print("you dont have access to print the data")

    def login_toplevel(self):
        self.tp = tk.Toplevel()
        self.tp.geometry("300x300")
        self.en1 = tk.Entry(self.tp)
        self.en1.pack()
        b = tk.Button(self.tp, text="provide key to print", command=self.qw)
        b.pack()

Example().start()