问:
Would this be the right way of accessing variable from other class?
Would this be a right thing to do? I am trying to access the variable A defined in class random and read the variable 'A' value in some_other_class. Would this be the right way of accessing the variables from a different class?  </p>

```<code>public class random{
       int A = 10;

       public random(){
          // Does something
       }

    }

    public class some_other_class{

       //Creating a Class datatype variable to access vars from other class
       random accessing_random_class_vars;

       public some_other_class(){
          if(accessing_random_class_vars.A){
                 //Do something
             }
       }

    }
</code>```

答: By default the scope of the variable is "default", so your code is valid for the access. However it is recommended to make all data members private and use getter and setter for them to access. </p>

Body:
Would this be a right thing to do? I am trying to access the variable A defined in class random and read the variable 'A' value in some_other_class. Would this be the right way of accessing the variables from a different class?

public class random{
       int A = 10;

       public random(){
          // Does something
       }

    }

    public class some_other_class{

       //Creating a Class datatype variable to access vars from other class
       random accessing_random_class_vars;

       public some_other_class(){
          if(accessing_random_class_vars.A){
                 //Do something
             }
       }

    }


来源: stackexchange

问:
C# Load/Unload plugins
Is there anyway to have ClassLibrary plugins which can be loaded/unloaded. The only way I have found is using an AppDomain but that defeats the purpose as the plugin cannot use the hosts API.</p>

答:
The CLR can only unload an entire Appdomain, not an assembly. However there is no problem loading the same assembly in multiple appdomains.

This means that you can inject an instance of a type from assembly A into a new appdomain where it loads Assembly B. B can then use the instance from assembly A to talk to the main appdomain. As long as you dont pass any types from assembly B 'over the border' you'll be able to unload the appdomain and remove assembly B from memory.

Take a look at the MarshalByRefObject for more info about passing instances over AppDomain borders

ContentLicense: CC BY-SA 3.0

Title: C# Load/Unload plugins


问:
How can I check if the time is more than an hour later?
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.

Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?

Example:

```<code>DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing
</code>```

答:
You can use mysql TIMESTAMPDIFF like this:

```<code>SELECT TIMESTAMPDIFF(HOUR,'2003-02-01','2003-05-01 12:05:55');
</code>```

you can use one of the follwing units:

MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH,
  QUARTER, or YEAR.

ContentLicense: CC BY-SA 4.0

Body:
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.

Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?

Example:

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing

Body:
You can use mysql TIMESTAMPDIFF like this:

SELECT TIMESTAMPDIFF(HOUR,'2003-02-01','2003-05-01 12:05:55');

you can use one of the follwing units:

MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH,
  QUARTER, or YEAR.


问:
Best way style on mouseover/mouseout Angular
I'm dealing with the following issue:

As you can see,  all of my elements are taking the mouseover instead of just one. There's a way with arrays on this thread but I don't know if it's the better suit for me.

Here's my component code.
I'm using an *ngFor to generate all of the necessary elements and with the event (mouseover) and (mouseend) change the style of the image to css display: none and css display: block.

component.html

  <ng-container *ngFor="let auto of autos">

      {{ auto.submarca }} - {{ auto.marca }}

        Pellentesque habitant morbi tristique senectus et netus et malesuada
        fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
        ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
        egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend
        leo.

  </ng-container>

```

<h2>component.ts</h2>

<pre class="lang-js prettyprint-override"><code>export class CuadrosComponent implements OnInit {
  autos: any;
  constructor() {}
  displayText: string;
  displayImage: string;
  ngOnInit() {
    this.autos = AUTOS;
    this.displayImage = "block";
    this.displayText = "none";
  }

  onMouseOver() {
    this.displayText = "block";
    this.displayImage = "none";
  }

  onMouseOut(auto, cardCuadroTag) {
    this.displayText = "none";
    this.displayImage = "block";
  }

  setImageOnError(img) {
    img.src = "/assets/images/autos/not-found.png";
  }
}
</code>```

答:
You have a single component that display multiple element you want to style individually. But in order to do so, you are using a single instance variable shared between all those children elements.

The most intuitive solution would be to create a component that would display a single box and handle the mouse events.

Another solution would be to use a dictionnary to know which element should be styled differently, something like:

```<code>export class CuadrosComponent implements OnInit {
  hoveredComponents: {[id: string]: boolean};
  //...
  onMouseOver(id: string) {
    this.hoveredComponents[id]=true;
  }

  onMouseOut(id: string) {
    this.hoveredComponents[id]=false;
  }
</code>```

html:

```<code><ng-container *ngFor="let auto of autos">
    <div
      [id]="auto.submarca"
      class="card-cuadro"
      [class.hovered]="hoveredComponents[auto.submarca]"
      (mouseover)="onMouseOver(auto.submarca)"
      (mouseout)="onMouseOut(auto.submarca)"
      #cardCuadro
    >
</code>```

css:

```<code>.card-cuadro.hovered img {
    display: block;
}
.card-cuadro:not(.hovered) img {
    display: none;
}
</code>```

Body:
I'm dealing with the following issue:

As you can see,  all of my elements are taking the mouseover instead of just one. There's a way with arrays on this thread but I don't know if it's the better suit for me.

Here's my component code.
I'm using an *ngFor to generate all of the necessary elements and with the event (mouseover) and (mouseend) change the style of the image to css display: none and css display: block.

component.html

  <ng-container *ngFor="let auto of autos">

      {{ auto.submarca }} - {{ auto.marca }}

        Pellentesque habitant morbi tristique senectus et netus et malesuada
        fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
        ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
        egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend
        leo.

  </ng-container>

component.ts

export class CuadrosComponent implements OnInit {
  autos: any;
  constructor() {}
  displayText: string;
  displayImage: string;
  ngOnInit() {
    this.autos = AUTOS;
    this.displayImage = "block";
    this.displayText = "none";
  }

  onMouseOver() {
    this.displayText = "block";
    this.displayImage = "none";
  }

  onMouseOut(auto, cardCuadroTag) {
    this.displayText = "none";
    this.displayImage = "block";
  }

  setImageOnError(img) {
    img.src = "/assets/images/autos/not-found.png";
  }
}

Body:
You have a single component that display multiple element you want to style individually. But in order to do so, you are using a single instance variable shared between all those children elements.

The most intuitive solution would be to create a component that would display a single box and handle the mouse events.

Another solution would be to use a dictionnary to know which element should be styled differently, something like:

export class CuadrosComponent implements OnInit {
  hoveredComponents: {[id: string]: boolean};
  //...
  onMouseOver(id: string) {
    this.hoveredComponents[id]=true;
  }

  onMouseOut(id: string) {
    this.hoveredComponents[id]=false;
  }

html:

<ng-container *ngFor="let auto of autos">
    <div
      [id]="auto.submarca"
      class="card-cuadro"
      [class.hovered]="hoveredComponents[auto.submarca]"
      (mouseover)="onMouseOver(auto.submarca)"
      (mouseout)="onMouseOut(auto.submarca)"
      #cardCuadro
    >

css:

.card-cuadro.hovered img {
    display: block;
}
.card-cuadro:not(.hovered) img {
    display: none;
}


问:
Migrating MongoDB from localhost to server
I completed development of a web application for my university doing everything on localhost. Now I want to migrate the backend and the MongoDB to the stakeholder's (my university) server environment. I tried finding different ways to do so but I haven't found a solution. Please help me in resolving this. Any links and working examples or videos would help a lot.

Tech stack used for backend:

1. NodeJS

2. MongoDB

3. google maps client api

答:
I would suggest using a database software interface like
Studio 3T, Robot3T or any others that have a backup and/or export and/or import feature.

If you have access to the machine and can install tools for MongoDB there are some terminal tools to do this.

Mongo Import
https://docs.mongodb.com/manual/reference/program/mongoimport/

Mongo Export
https://docs.mongodb.com/manual/reference/program/mongoexport/#bin.mongoexport


问:
Use jq to merge keys with common id
consider a file 'b.json':

```<code>[
  {
    "id": 3,
    "foo": "cannot be replaced, id isn't in a.json, stay untouched",
    "baz": "do not touch3"
  },
  {
    "id": 2,
    "foo": "should be replaced with 'foo new2'",
    "baz": "do not touch2"
  }
]
</code>```

and 'a.json':

```<code>[
  {
    "id": 2,
    "foo": "foo new2",
    "baz": "don't care"
  }
]
</code>```

I want to update the key "foo" in b.json using jq with the matching value from a.json. It should also work with more than one entry in a.json.

Thus the desired output is:

```<code>[
  {
    "id": 3,
    "foo": "cannot be replaced, id isn't in a.json, stay untouched",
    "baz": "do not touch3"
  },
  {
    "id": 2,
    "foo": "foo new2",
    "baz": "do not touch2"
  }
]
</code>```

答:
Here's one of several possibilities that use INDEX/2. If your jq does not have this as a built-in, see below.

```<code>jq --argfile a a.json '
  INDEX($a[]; .id) as $dict
  | map( (.id|tostring) as $id
         | if ($dict|has($id)) then .foo = $dict[$id].foo
           else . end)' b.json
</code>```

There are other ways to pass in the contents of a.json and b.json.

Caveat

The above use of INDEX assumes there are no "collisions", which would happen if, for example, one of the objects has .id equal to 1 and another has .id equal to "1".  If there is a possibility of such a collision, then a more complex definition of INDEX could be used.

INDEX/2

Straight from builtin.jq:

```<code>def INDEX(stream; idx_expr):
  reduce stream as $row ({}; .[$row|idx_expr|tostring] = $row);
</code>```

Title: Use jq to merge keys with common id

Body:
consider a file 'b.json':

[
  {
    "id": 3,
    "foo": "cannot be replaced, id isn't in a.json, stay untouched",
    "baz": "do not touch3"
  },
  {
    "id": 2,
    "foo": "should be replaced with 'foo new2'",
    "baz": "do not touch2"
  }
]

and 'a.json':

[
  {
    "id": 2,
    "foo": "foo new2",
    "baz": "don't care"
  }
]

I want to update the key "foo" in b.json using jq with the matching value from a.json. It should also work with more than one entry in a.json.

Thus the desired output is:

[
  {
    "id": 3,
    "foo": "cannot be replaced, id isn't in a.json, stay untouched",
    "baz": "do not touch3"
  },
  {
    "id": 2,
    "foo": "foo new2",
    "baz": "do not touch2"
  }
]

Body:
Here's one of several possibilities that use INDEX/2. If your jq does not have this as a built-in, see below.

jq --argfile a a.json '
  INDEX($a[]; .id) as $dict
  | map( (.id|tostring) as $id
         | if ($dict|has($id)) then .foo = $dict[$id].foo
           else . end)' b.json

There are other ways to pass in the contents of a.json and b.json.

Caveat

The above use of INDEX assumes there are no "collisions", which would happen if, for example, one of the objects has .id equal to 1 and another has .id equal to "1".  If there is a possibility of such a collision, then a more complex definition of INDEX could be used.

INDEX/2

Straight from builtin.jq:

def INDEX(stream; idx_expr):
  reduce stream as $row ({}; .[$row|idx_expr|tostring] = $row);


问:
Not able to figure out the logical error in C program
A program that prints its input one word per line.

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}
</code>```

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
</code>```

答:
Remember your logic programming classes:

```<code>!(A || B) == (!A && !B)
!(A && B) == (!A || !B)
</code>```

In other words: your condition needs to read like this:

```<code>if ( c != ' ' && c != '\n' && c != '\t' )
</code>```

Body:
A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}

Body:
Remember your logic programming classes:

!(A || B) == (!A && !B)
!(A && B) == (!A || !B)

In other words: your condition needs to read like this:

if ( c != ' ' && c != '\n' && c != '\t' )


问:
Cannot Demultiplex Stream from Video created by Py OpenCV
I'm trying to use OpenCV to create a video out of individual frames. Although the code runs without error, I cannot play the resulting avi file. When I do, the error I get is Could not demultiplex stream.

The stripped down version of the code I'm using to do this is:

```<code>import caffe
import cv2
import fnmatch
import os

# Get Image List
image_list = fnmatch.filter('./sample/images','*.png')
image_list.sort()

# Create VideoWriter
# codec = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
# codec = -1
codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
video = cv2.VideoWriter( './movieT.avi',
                         codec,
                         20,
                         (289, 289))

for img_name in image_list:
    # Load image
    im_path = os.path.join('./sample/images',img_name)
    img = caffe.io.load_image(im_path)

    # Resize image to expected size
    img = caffe.io.resize(img,(289, 289, 3))

    # Write image
    video.write(img)
video.release()
</code>```

I Googled around a bit, and the main errors I see mentioned are ensuring the image sizes match the size expected by the cv2.VideoWiter and that I have the right codecs. I resize my images to ensure they are the right size and I tried a few different codecs. I also tried to install standard codecs using some apt-get install commands I also found by Googling around:

```<code>me@balin:~$ sudo apt update
me@balin:~$ sudo apt install libdvdnav4 libdvdread4 gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly libdvd-pkg
me@balin:~$ sudo apt install ubuntu-restricted-extras
</code>```

I am currently using:

```<code>Ubuntu 18.04
Python 2.7.17
cv2.__version__ 4.0.1
</code>```

答:
I think your problem in incorrect use of fnmatch.filter() which doesn't get filenames from folder but it is used only to check if filename match pattern.

See example from fnmatch

```<code>import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
</code>```

With your code I alwyas get empty list so later it can't add any image to video and I can't display this video.

But you can use glob.glob() for this

```<code>image_list = glob.glob('./sample/images/*.png')
</code>```

This code works for me

```<code>import cv2
import glob

image_list = glob.glob('./sample/images/*.png')
image_list.sort()
#print(image_list)

codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
video = cv2.VideoWriter('./movieT.avi', codec, 20, (289, 289))

for img_name in image_list:
    img = cv2.imread(img_name)
    img = cv2.resize(img, (289, 289))
    video.write(img)

video.release()
</code>```

Body:
I'm trying to use OpenCV to create a video out of individual frames. Although the code runs without error, I cannot play the resulting avi file. When I do, the error I get is Could not demultiplex stream.

The stripped down version of the code I'm using to do this is:

import caffe
import cv2
import fnmatch
import os

# Get Image List
image_list = fnmatch.filter('./sample/images','*.png')
image_list.sort()

# Create VideoWriter
# codec = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
# codec = -1
codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
video = cv2.VideoWriter( './movieT.avi',
                         codec,
                         20,
                         (289, 289))

for img_name in image_list:
    # Load image
    im_path = os.path.join('./sample/images',img_name)
    img = caffe.io.load_image(im_path)

    # Resize image to expected size
    img = caffe.io.resize(img,(289, 289, 3))

    # Write image
    video.write(img)
video.release()

I Googled around a bit, and the main errors I see mentioned are ensuring the image sizes match the size expected by the cv2.VideoWiter and that I have the right codecs. I resize my images to ensure they are the right size and I tried a few different codecs. I also tried to install standard codecs using some apt-get install commands I also found by Googling around:

me@balin:~$ sudo apt update
me@balin:~$ sudo apt install libdvdnav4 libdvdread4 gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly libdvd-pkg
me@balin:~$ sudo apt install ubuntu-restricted-extras

I am currently using:

Ubuntu 18.04
Python 2.7.17
cv2.__version__ 4.0.1

Body:
I think your problem in incorrect use of fnmatch.filter() which doesn't get filenames from folder but it is used only to check if filename match pattern.

See example from fnmatch

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)

With your code I alwyas get empty list so later it can't add any image to video and I can't display this video.

But you can use glob.glob() for this

image_list = glob.glob('./sample/images/*.png')

This code works for me

import cv2
import glob

image_list = glob.glob('./sample/images/*.png')
image_list.sort()
#print(image_list)

codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
video = cv2.VideoWriter('./movieT.avi', codec, 20, (289, 289))

for img_name in image_list:
    img = cv2.imread(img_name)
    img = cv2.resize(img, (289, 289))
    video.write(img)

video.release()


问:
Scala parser combinator all but last
What is the correct way to parse a list consuming all but the last element using scala parser-combinators?  For example, if I want to parse "spam spam spam spam spam and eggs" into List("spam", "spam", "spam", "spam") ~ "spam and eggs".

If I just use "spam".+, then all the spam is consumed before I get to match "spam and eggs".  Naturally, I could match on "and eggs" but in practice I might already have a complicated "spam and eggs" parser that I'd rather not alter.

答:
Here is a simple but inefficient version:</p>

```<code>def allButOne[T](p: Parser[T]): Parser[List[T]] = (p <~ guard(p)).+
</code>```

Title: Scala parser combinator all but last

Body:
Here is a simple but inefficient version:

def allButOne[T](p: Parser[T]): Parser[List[T]] = (p <~ guard(p)).+


问:
matrix by vector multiplication - R versus Matlab
I observed that matrix by vector multiplication with a large matrix is significantly slower in R (version 3.6.1) than in Matlab (version 2019b), while both languages rely on the (same?) BLAS library. See below a minimal example:

In Matlab:

```<code>n=900;
p=900;
A=reshape(1:(n*p),[n,p]);
x=ones(p,1);
tic()
for id = 1:1000
  x = A*x;
end
toc()
</code>```

In R:

```<code>n=900
p=900
A=matrix(c(1:(n*p)),nrow=n,ncol=p)
x=rep(1,ncol(A))
t0 <- Sys.time()
for(iter in 1:1000){
  x = A%*%x
}
t1 <- Sys.time()
print(t1-t0)
</code>```

I get a running execution time of roughly 0.05sec in Matlab versus 3.5sec in R using the same computer. Any idea of the reason for such difference?

Thanks.

[EDIT]: I add below a similar calculus in C (using the CBLAS library, compilation using gcc cblas_dgemv.c -lblas -o cblas_dgemv, where cblas_dgemv.c denotes the source file below). I get a running time of roughly 0.08s which is quite close to the running times obtained using Matlab (0.05s). I am still trying to figure out the reason of this huge running time in R (3.5s).

```<code>#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include "cblas.h"

int main(int argc, char **argv)
{
  int m=900,adr;
  double *A,*x,*y;
  struct timeval t0,t1;

  /* memory allocation and initialization */
  A = (double*)malloc(m*m*sizeof(double));
  x = (double*)malloc(m*sizeof(double));
  y = (double*)malloc(m*sizeof(double));
  for(adr=0;adr<m;adr++) x[adr] = 1.;
  for(adr=0;adr<m*m;adr++) A[adr] = adr;

  /* main loop */
  gettimeofday(&t0, NULL);
  for(adr=0;adr<1000;adr++)
    cblas_dgemv(CblasColMajor,CblasNoTrans,m,m,1.,A,m,x,1,0.,y,1);
  gettimeofday(&t1, NULL);
  printf("elapsed time = %.2e seconds\n",(double)(t1.tv_usec-t0.tv_usec)/1000000. + (double)(t1.tv_sec-t0.tv_sec));

  /* free memory */
  free(A);
  free(x);
  free(y);

  return EXIT_SUCCESS;
}
</code>```

Notice that I was not able to set y=x in the cblas_dgemv routine. Thus, this C calculus is slightly different from that done in R and Matlab codes above. However the compilation was done without optimization flag (no option -O3) and I checked that the matrix-vector product was indeed called at each iteration of the loop (performing 10x more iterations leads to a 10x longer running time).

答:
Here's something kind of shocking:

The precompiled R distribution that is downloaded from CRAN makes use of the reference BLAS/LAPACK implementation for linear algebra operations

The "reference BLAS" is the non-optimized, non-accelerated BLAS, unlike OpenBLAS or Intel MKL. Matlab uses MKL, which is accelerated.

This seems to be confirmed by sessionInfo() in my R 3.6.0 on macOS:

```<code>> sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib
</code>```

If I'm reading this right, that means that by default, R uses a slow BLAS, and if you want it to go fast, you need to do some configuration to get it to use a fast BLAS instead.

This is a little surprising to me. As I understand it, the reference BLAS is generally primarily used for testing and development, not for "actual work".

I get about the same timings as you in R 3.6 vs Matlab R2019b on macOS 10.14: 0.04 seconds in Matlab, 4.5 seconds in R. I think that's consistent with R using a non-accelerated BLAS.

Body:
I observed that matrix by vector multiplication with a large matrix is significantly slower in R (version 3.6.1) than in Matlab (version 2019b), while both languages rely on the (same?) BLAS library. See below a minimal example:

In Matlab:

n=900;
p=900;
A=reshape(1:(n*p),[n,p]);
x=ones(p,1);
tic()
for id = 1:1000
  x = A*x;
end
toc()

In R:

n=900
p=900
A=matrix(c(1:(n*p)),nrow=n,ncol=p)
x=rep(1,ncol(A))
t0 <- Sys.time()
for(iter in 1:1000){
  x = A%*%x
}
t1 <- Sys.time()
print(t1-t0)

I get a running execution time of roughly 0.05sec in Matlab versus 3.5sec in R using the same computer. Any idea of the reason for such difference?

Thanks.

[EDIT]: I add below a similar calculus in C (using the CBLAS library, compilation using gcc cblas_dgemv.c -lblas -o cblas_dgemv, where cblas_dgemv.c denotes the source file below). I get a running time of roughly 0.08s which is quite close to the running times obtained using Matlab (0.05s). I am still trying to figure out the reason of this huge running time in R (3.5s).

#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include "cblas.h"

int main(int argc, char **argv)
{
  int m=900,adr;
  double *A,*x,*y;
  struct timeval t0,t1;

  /* memory allocation and initialization */
  A = (double*)malloc(m*m*sizeof(double));
  x = (double*)malloc(m*sizeof(double));
  y = (double*)malloc(m*sizeof(double));
  for(adr=0;adr<m;adr++) x[adr] = 1.;
  for(adr=0;adr<m*m;adr++) A[adr] = adr;

  /* main loop */
  gettimeofday(&t0, NULL);
  for(adr=0;adr<1000;adr++)
    cblas_dgemv(CblasColMajor,CblasNoTrans,m,m,1.,A,m,x,1,0.,y,1);
  gettimeofday(&t1, NULL);
  printf("elapsed time = %.2e seconds\n",(double)(t1.tv_usec-t0.tv_usec)/1000000. + (double)(t1.tv_sec-t0.tv_sec));

  /* free memory */
  free(A);
  free(x);
  free(y);

  return EXIT_SUCCESS;
}

Notice that I was not able to set y=x in the cblas_dgemv routine. Thus, this C calculus is slightly different from that done in R and Matlab codes above. However the compilation was done without optimization flag (no option -O3) and I checked that the matrix-vector product was indeed called at each iteration of the loop (performing 10x more iterations leads to a 10x longer running time).

Body:
Here's something kind of shocking:

The precompiled R distribution that is downloaded from CRAN makes use of the reference BLAS/LAPACK implementation for linear algebra operations

The "reference BLAS" is the non-optimized, non-accelerated BLAS, unlike OpenBLAS or Intel MKL. Matlab uses MKL, which is accelerated.

This seems to be confirmed by sessionInfo() in my R 3.6.0 on macOS:

> sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

If I'm reading this right, that means that by default, R uses a slow BLAS, and if you want it to go fast, you need to do some configuration to get it to use a fast BLAS instead.

This is a little surprising to me. As I understand it, the reference BLAS is generally primarily used for testing and development, not for "actual work".

I get about the same timings as you in R 3.6 vs Matlab R2019b on macOS 10.14: 0.04 seconds in Matlab, 4.5 seconds in R. I think that's consistent with R using a non-accelerated BLAS.


问:
How to GET image in reactjs from api?
I am fetching an image from nodejs API after verifying with JWT token.
I am getting GET 200 ok response in browser Network header and picture can be seen in Preview, but I cannot use it in my app.

I am surely doing something wrong. Please let me know the proper way to display image from API.
On my backend nodejs, I am using res.sendFile to send the file.

```<code>class Card extends Component {
 constructor({props, pic, token}) {
super(props, pic, token);
this.state = {
  pic: pic,
};

urlFetch(data) {
 fetch(data, {
 headers: new Headers({
 'authorization': `Bearer ${this.props.token}`,
 'Content-Type': 'application/json'
 })
})
.then(response => {
 if (response.statusText === 'OK') {
  return data   // OR return response.url
  }
 })
}

render() {
const { pic } = this.state;

 return (
        <div>
          <img style={{width: 175, height: 175}} className='tc br3' alt='none' src={ this.urlFetch(pic) } />
        </div>
       );
      }
     }
</code>```

答:
I was able to render images from a backend call in React using a pattern similar to this using: react hooks, axios, and URL.createObjectURL

I used the URL.createObjectURL(blob) method and used the axios configuration { responseType: 'blob' } to make sure the the data type would fit.

```<code>const ImageComponent = (imageIds) => {
  const [images, setImages] = React.useState([])

  React.useEffect(() => {
    async function getImage (id) {
      let imageBlob
      try {
        imageBlob = (await axiosClient.get(`/api/image/${id}`, { responseType: 'blob' })).data
      } catch (err) {
        return null
      }
      return URL.createObjectURL(imageBlob)
    }
    async function getImages () {
      const imageArray = []
      for (const id of imageIds) {
        imageArray.push(await getImage(id))
      }
      setImages(imageArray)
    }

    getImages()
  }, [imageIds])

  return images.map((img, i) => {
    return <img src={img} alt={`image-${i}`} key={i} />
  })
}
</code>```

[Edit]: If your api is a protected route just make sure your axios http client is initialized with the token already

Title: How to GET image in reactjs from api?

Body:
I am fetching an image from nodejs API after verifying with JWT token.
I am getting GET 200 ok response in browser Network header and picture can be seen in Preview, but I cannot use it in my app.

I am surely doing something wrong. Please let me know the proper way to display image from API.
On my backend nodejs, I am using res.sendFile to send the file.

class Card extends Component {
 constructor({props, pic, token}) {
super(props, pic, token);
this.state = {
  pic: pic,
};

urlFetch(data) {
 fetch(data, {
 headers: new Headers({
 'authorization': `Bearer ${this.props.token}`,
 'Content-Type': 'application/json'
 })
})
.then(response => {
 if (response.statusText === 'OK') {
  return data   // OR return response.url
  }
 })
}

render() {
const { pic } = this.state;

 return (

       );
      }
     }

Body:
I was able to render images from a backend call in React using a pattern similar to this using: react hooks, axios, and URL.createObjectURL

I used the URL.createObjectURL(blob) method and used the axios configuration { responseType: 'blob' } to make sure the the data type would fit.

const ImageComponent = (imageIds) => {
  const [images, setImages] = React.useState([])

  React.useEffect(() => {
    async function getImage (id) {
      let imageBlob
      try {
        imageBlob = (await axiosClient.get(`/api/image/${id}`, { responseType: 'blob' })).data
      } catch (err) {
        return null
      }
      return URL.createObjectURL(imageBlob)
    }
    async function getImages () {
      const imageArray = []
      for (const id of imageIds) {
        imageArray.push(await getImage(id))
      }
      setImages(imageArray)
    }

    getImages()
  }, [imageIds])

  return images.map((img, i) => {
    return <img src={img} alt={`image-${i}`} key={i} />
  })
}

[Edit]: If your api is a protected route just make sure your axios http client is initialized with the token already


问:
Trying install a ppa package on Debian
after running this code sudo add-apt-repository ppa:thopiekar/sierrabreezein my bash using the debian 10 buster. the following error message appears right after trying sudo apt update:

```<code>Hit:1 http://security.debian.org/debian-security buster/updates InRelease
Hit:2 http://deb.debian.org/debian buster InRelease
Hit:3 http://deb.debian.org/debian buster-updates InRelease
Ign:4 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:5 http://dl.google.com/linux/chrome/deb stable Release
Get:7 http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu focal InRelease [15.4 kB]
Err:7 http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu focal InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY D51DB14E9FFECCF3
Reading package lists... Done
W: GPG error: http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu focal InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY D51DB14E9FFECCF3
E: The repository 'http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu focal InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details
</code>```

Edit

sudo apt install sierrabreeze:

```<code>Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 sierrabreeze : Depends: libc6 (>= 2.29) but 2.28-10 is to be installed
                Depends: libqt5core5a (>= 5.12.2) but 5.11.3+dfsg1-1+deb10u3 is to be installed
E: Unable to correct problems, you have held broken packages
</code>```

any help to solve this trouble?

答:
You can install the gpg key manually:

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys D51DB14E9FFECCF3
</code>```

Also you need to edit the thopiekar-ubuntu-sierrabreeze-focal.list file.

```<code>sudo nano /etc/apt/sources.list.d/thopiekar-ubuntu-sierrabreeze-focal.list
</code>```

Change focal to bionic:

```<code>deb http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu bionic main
</code>```

The run:

```<code>sudo apt update
sudo apt install sierrabreeze
</code>```

Title: Trying install a ppa package on Debian

Body:
after running this code sudo add-apt-repository ppa:thopiekar/sierrabreezein my bash using the debian 10 buster. the following error message appears right after trying sudo apt update:

Hit:1 http://security.debian.org/debian-security buster/updates InRelease
Hit:2 http://deb.debian.org/debian buster InRelease
Hit:3 http://deb.debian.org/debian buster-updates InRelease
Ign:4 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:5 http://dl.google.com/linux/chrome/deb stable Release
Get:7 http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu focal InRelease [15.4 kB]
Err:7 http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu focal InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY D51DB14E9FFECCF3
Reading package lists... Done
W: GPG error: http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu focal InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY D51DB14E9FFECCF3
E: The repository 'http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu focal InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details

Edit

sudo apt install sierrabreeze:

Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 sierrabreeze : Depends: libc6 (>= 2.29) but 2.28-10 is to be installed
                Depends: libqt5core5a (>= 5.12.2) but 5.11.3+dfsg1-1+deb10u3 is to be installed
E: Unable to correct problems, you have held broken packages

any help to solve this trouble?

Body:
You can install the gpg key manually:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys D51DB14E9FFECCF3

Also you need to edit the thopiekar-ubuntu-sierrabreeze-focal.list file.

sudo nano /etc/apt/sources.list.d/thopiekar-ubuntu-sierrabreeze-focal.list

Change focal to bionic:

deb http://ppa.launchpad.net/thopiekar/sierrabreeze/ubuntu bionic main

The run:

sudo apt update
sudo apt install sierrabreeze


问:
Best way to split data of varying length into columns
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

```<code>Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615
</code>```

Desired Output

```<code>Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615
</code>```

答:
Notepad++

Ctrl+H

Find: (.+) (\d+-\d+) (\d+-\d+) (\d+-\d+)$

Replace: \1; \2; \3; \4;

Check the Regular expression

Body:
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615

Desired Output

Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615


问:
creating a directory tree structure using bash
I'm trying to create a directory tree structure that has a parent , children and leaf nodes where each leaf nodes has a dependency on each other , like wise with the children nodes and parent.

Firstly , Has anyone succeeded doing this using bash scripting before?  Need to add the directory name and then later traverse through the tree.

答:
It's not real clear what you're thinking, but you can always call a BASH function recursively.  Here's an example factorial:

```<code>VALUE=1
function fact {
    if [ $1 -le 0 ]
    then
       echo $VALUE
    else
       let VALUE=VALUE*$1
       fact $(($1-1))
    fi
}
fact $1

$ bash fact.bash 5
120
</code>```

So you can write recursive functions to build and traverse your tree just as you would in another language.

One question, though: why do you want to do this in a shell script?  Why not, say, python?

Body:
It's not real clear what you're thinking, but you can always call a BASH function recursively.  Here's an example factorial:

VALUE=1
function fact {
    if [ $1 -le 0 ]
    then
       echo $VALUE
    else
       let VALUE=VALUE*$1
       fact $(($1-1))
    fi
}
fact $1

$ bash fact.bash 5
120

So you can write recursive functions to build and traverse your tree just as you would in another language.

One question, though: why do you want to do this in a shell script?  Why not, say, python?


答:
I'm not the biggest regex fan you'll ever meet.  Here's a straightforward way of doing it without regexes:

```<code>#!/usr/local/cpython-3.1/bin/python3

# Works on CPython 3.1 through 3.9

"""Keep lines between [TimingPoints] and [HitObjects], elliding empty lines."""

def main():
    """Read input and write actual-output."""
    display = False
    with open('input', 'r') as infile, open('actual-output', 'w') as outfile:
        for line in infile:
            line_sans_n = line.rstrip('\n')
            if not line_sans_n:
                # Skip blank lines
                continue
            if line_sans_n == '[HitObjects]':
                display = False
            if display:
                print(line_sans_n, file=outfile)
            if line_sans_n == '[TimingPoints]':
                display = True
</code>```

HTH

Title: Python regex ignore empty lines

Body:
I have data with the following structure:

[TimingPoints]
21082,410.958904109589,4,3,1,60,1,0
21082,-250,4,3,1,100,0,0
22725,-142.857142857143,4,3,1,100,0,0
23547,-166.666666666667,4,3,1,100,0,0

24369,-333.333333333335,4,3,1,100,0,0
27657,-200.000000000001,4,3,1,100,0,0
29301,-142.857142857143,4,3,1,100,0,0
30123,-166.666666666667,4,3,1,100,0,0
30945,-250,4,3,1,100,0,0

32588,-166.666666666667,4,3,1,100,0,0
34232,-250,4,3,1,100,0,0
35876,-142.857142857143,4,3,1,100,0,0
36698,-166.666666666667,4,3,1,100,0,0
37520,-250,4,3,1,100,0,0
42451,-142.857142857143,4,3,1,100,0,0

[HitObjects]
256,192,17794,12,0,20876,0:0:0:0:
159,96,21082,6,0,B|204:120|204:120|254:103|254:103|305:130|355:102,1,210
409,27,22725,2,0,P|446:96|405:179,1,171.499994766236
269,284,23547,2,0,B|317:250|324:193|324:193|328:220|350:236,1,146.999995513916

I'd like to read all lines under [TimingPoints] before [HitObjects] in a list.
Empty lines should be ignored.
So the final list should contain:

21082,410.958904109589,4,3,1,60,1,0
21082,-250,4,3,1,100,0,0
22725,-142.857142857143,4,3,1,100,0,0
23547,-166.666666666667,4,3,1,100,0,0
24369,-333.333333333335,4,3,1,100,0,0
27657,-200.000000000001,4,3,1,100,0,0
29301,-142.857142857143,4,3,1,100,0,0
30123,-166.666666666667,4,3,1,100,0,0
30945,-250,4,3,1,100,0,0
32588,-166.666666666667,4,3,1,100,0,0
34232,-250,4,3,1,100,0,0
35876,-142.857142857143,4,3,1,100,0,0
36698,-166.666666666667,4,3,1,100,0,0
37520,-250,4,3,1,100,0,0
42451,-142.857142857143,4,3,1,100,0,0

I tried it with the following regex pattern:
\[TimingPoints\]((.|\n)*)\[HitObjects] but it does not ignore the empty lines.
How can I match the lines to get what is described above?
Also how can I load all the matched lines in a list with python?

Body:
I'm not the biggest regex fan you'll ever meet.  Here's a straightforward way of doing it without regexes:

#!/usr/local/cpython-3.1/bin/python3

# Works on CPython 3.1 through 3.9

"""Keep lines between [TimingPoints] and [HitObjects], elliding empty lines."""

def main():
    """Read input and write actual-output."""
    display = False
    with open('input', 'r') as infile, open('actual-output', 'w') as outfile:
        for line in infile:
            line_sans_n = line.rstrip('\n')
            if not line_sans_n:
                # Skip blank lines
                continue
            if line_sans_n == '[HitObjects]':
                display = False
            if display:
                print(line_sans_n, file=outfile)
            if line_sans_n == '[TimingPoints]':
                display = True

HTH


问:
SeriLog in Asp.Net Core web app does not inject dependency properly
In Startup.cs Configure() method, I setup the logger like below:

```<code>        Serilog.Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .Enrich.FromLogContext()
            .WriteTo.RollingFile(new CompactJsonFormatter(), "c:\\temp\\myapp.json")
            .CreateLogger();

        loggerFactory.AddSerilog(Serilog.Log.Logger);
</code>```

ILogger and Log.Logger always evaluates to Serilog.Core.Pipeline.SilentLogger instead of what is setup. Am I missing any step in setting up DI?

答:
To get mine to work, I had to call the AddProvider method.

Something kinda like this:

```<code>        /* ok, need to get ILoggerFactory, i don't like this call to BuildServiceProvider, but that's what I had to do for my console-app (dotnetcore, not aspnetcore) */
        ILoggerFactory ilf = servColl.BuildServiceProvider().GetService<ILoggerFactory>();

        /* now create the SerilogLoggerProvider */
        Serilog.Extensions.Logging.SerilogLoggerProvider seriprovider = new Serilog.Extensions.Logging.SerilogLoggerProvider(serilogger, false);
        /* now cast the SerilogLoggerProvider to ILoggerProvider */
        Microsoft.Extensions.Logging.ILoggerProvider castSerilogger = seriprovider as Microsoft.Extensions.Logging.ILoggerProvider;

        /* now register the castSerilogger */
        ilf.AddProvider(castSerilogger);
</code>```

The above is a less-smooth version of something like this:

https://andrewlock.net/adding-serilog-to-the-asp-net-core-generic-host/

https://github.com/serilog/serilog-extensions-hosting

Here are a few breadcrumbs in case the above links fail

```<code>"public class SerilogLoggerFactory : ILoggerFactory"

"_provider = new SerilogLoggerProvider(logger, dispose);"
</code>```

Body:
In Startup.cs Configure() method, I setup the logger like below:

        Serilog.Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .Enrich.FromLogContext()
            .WriteTo.RollingFile(new CompactJsonFormatter(), "c:\\temp\\myapp.json")
            .CreateLogger();

        loggerFactory.AddSerilog(Serilog.Log.Logger);

ILogger and Log.Logger always evaluates to Serilog.Core.Pipeline.SilentLogger instead of what is setup. Am I missing any step in setting up DI?

Body:
To get mine to work, I had to call the AddProvider method.

Something kinda like this:

        /* ok, need to get ILoggerFactory, i don't like this call to BuildServiceProvider, but that's what I had to do for my console-app (dotnetcore, not aspnetcore) */
        ILoggerFactory ilf = servColl.BuildServiceProvider().GetService<ILoggerFactory>();

        /* now create the SerilogLoggerProvider */
        Serilog.Extensions.Logging.SerilogLoggerProvider seriprovider = new Serilog.Extensions.Logging.SerilogLoggerProvider(serilogger, false);
        /* now cast the SerilogLoggerProvider to ILoggerProvider */
        Microsoft.Extensions.Logging.ILoggerProvider castSerilogger = seriprovider as Microsoft.Extensions.Logging.ILoggerProvider;

        /* now register the castSerilogger */
        ilf.AddProvider(castSerilogger);

The above is a less-smooth version of something like this:

https://andrewlock.net/adding-serilog-to-the-asp-net-core-generic-host/

https://github.com/serilog/serilog-extensions-hosting

Here are a few breadcrumbs in case the above links fail

"public class SerilogLoggerFactory : ILoggerFactory"

"_provider = new SerilogLoggerProvider(logger, dispose);"


问:
.war file is not deployed in the Elastic Beanstalk environment
I'm deploying .war file with .ebextensions in EB environment using Jenkins pipeline. The deployment is succeeded and all the commands are executed in at the deployment stage, but when I check the /usr/share/tomcat8/webapps/ROOT/ I only see my .war file is there as it is, without extracting.

What would be the reason for this? and any idea about how to resolve that issue ? Please find my code snippet below.

```<code>zip -r app-${BUILD_NUMBER}.zip myapp.war .ebextensions

aws s3 cp myapp.war s3://inc-eb-deployments/inc-batch/myapp.war

</code>```

答:
Try deploying it to the webapps folder, not webapps/ROOT. Then tomcat should decompress to webapps/myapp.

If you want to deploy your application in the root directory you need to name your build output ROOT.war and place it in the webapps folder.

Body:
I'm deploying .war file with .ebextensions in EB environment using Jenkins pipeline. The deployment is succeeded and all the commands are executed in at the deployment stage, but when I check the /usr/share/tomcat8/webapps/ROOT/ I only see my .war file is there as it is, without extracting.

What would be the reason for this? and any idea about how to resolve that issue ? Please find my code snippet below.

zip -r app-${BUILD_NUMBER}.zip myapp.war .ebextensions

aws s3 cp myapp.war s3://inc-eb-deployments/inc-batch/myapp.war


问:
Setting a Jenkins Pipeline timeout for only a group of stages
I know that one can set a timeout for the entire pipeline script or a specific stage using options, but is there a way to set a timeout for a group of stages? For example a total 10 minute timeout (not 10 minute each) for only 3 out of the 5 stages, and let the other 2 run freely.

答:
Sure, you can create nested stages and define the timeout option for the parent stage:

pipeline {
    agent any
    stages{
        stage('Stage A') {
            options{
                timeout( time: 10, unit: 'SECONDS' )
            }
            stages {
                stage('Stage A1') {
                    steps {
                        sleep( time: 4, unit: 'SECONDS' )
                    }
                }
                stage('Stage A2') {
                    steps {
                        sleep( time: 4, unit: 'SECONDS' )
                    }
                }
                stage('Stage A3') {
                    steps {
                        sleep( time: 4, unit: 'SECONDS' )
                    }
                }
            }
        }
    }
}
```

Stage A3 will never be executed because of the parent timeout. It will be marked as "aborted":

Body:
Sure, you can create nested stages and define the timeout option for the parent stage:

pipeline {
    agent any
    stages{
        stage('Stage A') {
            options{
                timeout( time: 10, unit: 'SECONDS' )
            }
            stages {
                stage('Stage A1') {
                    steps {
                        sleep( time: 4, unit: 'SECONDS' )
                    }
                }
                stage('Stage A2') {
                    steps {
                        sleep( time: 4, unit: 'SECONDS' )
                    }
                }
                stage('Stage A3') {
                    steps {
                        sleep( time: 4, unit: 'SECONDS' )
                    }
                }
            }
        }
    }
}

Stage A3 will never be executed because of the parent timeout. It will be marked as "aborted":


问:
Is it possible to revise the resolution to a merge conflict in git?
I am working on a tex file together with a collaborator using git (using gitkraken).
We work on the same branch, and at some point there were some merge conflicts when one of us pushed our latest work onto that branch.
Since then we have continued working on this file, but we have realized that we would like to "redo" resolving the merge conflicts from a couple of commits back.

Is there a clean way to do this?

One thing I though of was to copy the version of the file in question (there is only one file of interest) and then just overwrite the current version of the file and then push that file onto the current branch, but I'm afraid this will overwrite some of the changes (that we'd like to keep) since the original conflict in question.
Another way could be to copy the old version that has some of the changes we'd like to keep and then use a diff tool to merge in selectively the things we'd like to change.

This last option is the best thing I could come up with. Is there a better way?

答:
Every commit—including merge commits—simply holds a full and complete snapshot of all of your files.

Once you're collaborating with other people, it's usually not worth a lot of effort to go back and "fix" previous commits.  In fact, that's technically impossible: you can't change any existing commits.  What you end up doing is providing new-and-improved alternative commits, in place of the originals.  For instance, suppose:

```<code>...--I--J
         \
          M--N--O   <-- branch (HEAD)
         /
...--K--L
</code>```

is the current situation, i.e., existing commits up through J and up through L got merged to make M, and you and they have since built N and O atop M.  You now discover that there's a "bug" in the snapshot stored in merge commit M due to some mis-resolution of conflicts.

The only way to make a corrected version of M is to make a new merge commit, M'.  (There are several ways of doing that.)  The result is:

```<code>...--I--J__
        |  \
        |   M--N--O   <-- branch
         \ /
          x
         / \
...--K--L---M'  <-- newbranch (HEAD)
</code>```

That is, bad merge M still exists even though you have now made new-and-improved merge M' on this new replacement branch newbranch.  You now need to copy N and O as well, to new-and-improved N' and O':

```<code>...--I--J__
        |  \
        |   M--N--O   <-- branch
         \ /
          x
         / \
...--K--L---M'-N'-O'  <-- newbranch (HEAD)
</code>```

Now you need to have everyone—you and everyone else—stop using the old chain, M-N-O as found by name branch, and start using instead the new chain, M'-N'-O'.  In your Git, you can erase the name branch and rename newbranch to branch.  In their Git, they'll have to do the same thing.  Everyone must change over at the same time.  This tends to be a lot of work.

It's usually better to just admit that the past has a bug in it.  Make a new commit atop O that fixes the problem:

```<code>...--I--J
         \
          M--N--O--P   <-- branch (HEAD)
         /
...--K--L
</code>```

Everyone can pick up new commit P as usual and just keep working as usual.  Sure, commits M-N-O have bad snapshots ... but so what?  Bad stuff happens all the time; version control is not about preventing bad stuff, but rather about letting you correct it.  You've corrected it.

Body:
Every commit—including merge commits—simply holds a full and complete snapshot of all of your files.

Once you're collaborating with other people, it's usually not worth a lot of effort to go back and "fix" previous commits.  In fact, that's technically impossible: you can't change any existing commits.  What you end up doing is providing new-and-improved alternative commits, in place of the originals.  For instance, suppose:

...--I--J
         \
          M--N--O   <-- branch (HEAD)
         /
...--K--L

is the current situation, i.e., existing commits up through J and up through L got merged to make M, and you and they have since built N and O atop M.  You now discover that there's a "bug" in the snapshot stored in merge commit M due to some mis-resolution of conflicts.

The only way to make a corrected version of M is to make a new merge commit, M'.  (There are several ways of doing that.)  The result is:

...--I--J__
        |  \
        |   M--N--O   <-- branch
         \ /
          x
         / \
...--K--L---M'  <-- newbranch (HEAD)

That is, bad merge M still exists even though you have now made new-and-improved merge M' on this new replacement branch newbranch.  You now need to copy N and O as well, to new-and-improved N' and O':

...--I--J__
        |  \
        |   M--N--O   <-- branch
         \ /
          x
         / \
...--K--L---M'-N'-O'  <-- newbranch (HEAD)

Now you need to have everyone—you and everyone else—stop using the old chain, M-N-O as found by name branch, and start using instead the new chain, M'-N'-O'.  In your Git, you can erase the name branch and rename newbranch to branch.  In their Git, they'll have to do the same thing.  Everyone must change over at the same time.  This tends to be a lot of work.

It's usually better to just admit that the past has a bug in it.  Make a new commit atop O that fixes the problem:

...--I--J
         \
          M--N--O--P   <-- branch (HEAD)
         /
...--K--L

Everyone can pick up new commit P as usual and just keep working as usual.  Sure, commits M-N-O have bad snapshots ... but so what?  Bad stuff happens all the time; version control is not about preventing bad stuff, but rather about letting you correct it.  You've corrected it.


问:
Kotlin map with function reference of a member function
Given the following two classes:

```<code>class Parent {
    val child : Child = Child()
}

class Child {
    fun doSomethingWithParent(parent : Parent) = Foo()
}

class Foo
</code>```

And a list of Parents:

```<code>val list = List<Parent>(10){_ -> Parent()}
</code>```

Instead of mapping with

```<code>list.map { it.child.doSomethingWithParent(it) } // works
</code>```

to use a function reference to doSomethingWithParent like

```<code>// does not work
list.map(Child::doSomethingWithParent)
list.map(Parent::child::doSomethingWithParent)
</code>```

答:
The clue is in the error messages.  (Which is why it's usually a good idea to give them in the question…)

In your line:

```<code>list.map(Child::doSomethingWithParent)
</code>```

which child should do something with each the listed parent?  You're not specifying that it's the listed parent's child.

And in your line:

```<code>list.map(Parent::child::doSomethingWithParent)
</code>```

what is the second :: supposed to indicate?  Parent::child is a method reference, not a class or object.

Body:
Given the following two classes:

class Parent {
    val child : Child = Child()
}

class Child {
    fun doSomethingWithParent(parent : Parent) = Foo()
}

class Foo

And a list of Parents:

val list = List<Parent>(10){_ -> Parent()}

Instead of mapping with

list.map { it.child.doSomethingWithParent(it) } // works

to use a function reference to doSomethingWithParent like

// does not work
list.map(Child::doSomethingWithParent)
list.map(Parent::child::doSomethingWithParent)

Body:
The clue is in the error messages.  (Which is why it's usually a good idea to give them in the question…)

In your line:

list.map(Child::doSomethingWithParent)

which child should do something with each the listed parent?  You're not specifying that it's the listed parent's child.

And in your line:

list.map(Parent::child::doSomethingWithParent)

what is the second :: supposed to indicate?  Parent::child is a method reference, not a class or object.


问:
Authentication during connection to MongoDB server instance using Java
Is it possible to make something like :

```<code>MongoClient mongo = new MongoClient(ip, port, usrName, password)
</code>```

in JAVA similar to the MongoVUE or other SQL based databases' authentication method.

There the authentication is done during connection to DB instance.

I don't see an appropriate instance method in  MongoClient java doc

And the  way in Authentication (Optional) Official docs

doesn't fit my goals, because it requires to change all the existing query methods in my application which don't use authentication now.

The way in Authenticate to MongoDB with the Java Driver looks exactly what i need, but there's no com.mongodb.MongoCredential class in  mongo 2.10.1 distribution.

答:
I needed to connect to multiple HOSTs, but also handle authentication:

Using version 3.12:

```<code>List<ServerAddress> seeds = new ArrayList<>();
seeds.add(new ServerAddress("localhost"))

credential = MongoCredential.createScramSha1Credential(
      user,
      db,
      pass.toCharArray()
);

mongoClient = MongoClients.create(
      MongoClientSettings.builder()
           .applyToClusterSettings(builder ->
                 builder.hosts(seeds))
           .credential(credential)
           .build());
</code>```

Body:
Is it possible to make something like :

MongoClient mongo = new MongoClient(ip, port, usrName, password)

in JAVA similar to the MongoVUE or other SQL based databases' authentication method.

There the authentication is done during connection to DB instance.

I don't see an appropriate instance method in  MongoClient java doc

And the  way in Authentication (Optional) Official docs

doesn't fit my goals, because it requires to change all the existing query methods in my application which don't use authentication now.

The way in Authenticate to MongoDB with the Java Driver looks exactly what i need, but there's no com.mongodb.MongoCredential class in  mongo 2.10.1 distribution.

Body:
I needed to connect to multiple HOSTs, but also handle authentication:

Using version 3.12:

List<ServerAddress> seeds = new ArrayList<>();
seeds.add(new ServerAddress("localhost"))

credential = MongoCredential.createScramSha1Credential(
      user,
      db,
      pass.toCharArray()
);

mongoClient = MongoClients.create(
      MongoClientSettings.builder()
           .applyToClusterSettings(builder ->
                 builder.hosts(seeds))
           .credential(credential)
           .build());


问:
VBA application-defined or object-defined error for refreshing pivot tables
Hello I recorded a macro in excel to refresh these pivot tables that I want selected, however when I try to run the Macro it gives me this error "application-defined or object-defined error". I'm not really sure why it's working as all I did was hit record Macro, refreshed the tables I wanted and use this to refresh the tables specified. </p>

```<code>Sub Refresh()
'
' Refresh Macro
'

'
    Sheets("F-Pivots").Select
    ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("P-Pivots").Select
    ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("F-Y-Reject P.").Select
    ActiveSheet.PivotTables("PivotTable3").PivotCache.Refresh
    Sheets("P-Y-Reject P.").Select
    ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("F-Y-DT P.").Select
    ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("P-Y-DT P.").Select
    ActiveSheet.PivotTables("PivotTable2").PivotCache.Refresh
    ActiveWindow.ScrollWorkbookTabs Sheets:=1
    ActiveWindow.ScrollWorkbookTabs Sheets:=1
    Sheets("Monthly Data").Select
    ActiveSheet.PivotTables("PivotTable2").PivotCache.Refresh
    Range("B4").Select
    ActiveSheet.PivotTables("PivotTable100").PivotCache.Refresh
    ActiveWindow.ScrollWorkbookTabs Sheets:=-1
    ActiveWindow.ScrollWorkbookTabs Sheets:=-1
    ActiveWindow.ScrollWorkbookTabs Sheets:=-1
    Sheets("Heatmap").Select
End Sub

</code>```

答:
I realized that some of the pivot tables have the same name and are located in different sheets, so I believe something is wrong.

The following code refers to the Pivot Tables by their name and refreshes their cache. The cache (source data) should be refreshed by all tables using them.

Code:
EDIT: Use refresh table method on the PivotTable

```<code>Public Sub Refresh()

    Range("PivotTable1").PivotTable.RefreshTable
    Range("PivotTable2").PivotTable.RefreshTable
    Range("PivotTable3").PivotTable.RefreshTable
    Range("PivotTable100").PivotTable.RefreshTable

    ThisWorkbook.Worksheets("Heatmap").Activate

End Sub
</code>```

Let me know if it works

Body:
Hello I recorded a macro in excel to refresh these pivot tables that I want selected, however when I try to run the Macro it gives me this error "application-defined or object-defined error". I'm not really sure why it's working as all I did was hit record Macro, refreshed the tables I wanted and use this to refresh the tables specified.

Sub Refresh()
'
' Refresh Macro
'

'
    Sheets("F-Pivots").Select
    ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("P-Pivots").Select
    ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("F-Y-Reject P.").Select
    ActiveSheet.PivotTables("PivotTable3").PivotCache.Refresh
    Sheets("P-Y-Reject P.").Select
    ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("F-Y-DT P.").Select
    ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("P-Y-DT P.").Select
    ActiveSheet.PivotTables("PivotTable2").PivotCache.Refresh
    ActiveWindow.ScrollWorkbookTabs Sheets:=1
    ActiveWindow.ScrollWorkbookTabs Sheets:=1
    Sheets("Monthly Data").Select
    ActiveSheet.PivotTables("PivotTable2").PivotCache.Refresh
    Range("B4").Select
    ActiveSheet.PivotTables("PivotTable100").PivotCache.Refresh
    ActiveWindow.ScrollWorkbookTabs Sheets:=-1
    ActiveWindow.ScrollWorkbookTabs Sheets:=-1
    ActiveWindow.ScrollWorkbookTabs Sheets:=-1
    Sheets("Heatmap").Select
End Sub

Body:
I realized that some of the pivot tables have the same name and are located in different sheets, so I believe something is wrong.

The following code refers to the Pivot Tables by their name and refreshes their cache. The cache (source data) should be refreshed by all tables using them.

Code:
EDIT: Use refresh table method on the PivotTable

Public Sub Refresh()

    Range("PivotTable1").PivotTable.RefreshTable
    Range("PivotTable2").PivotTable.RefreshTable
    Range("PivotTable3").PivotTable.RefreshTable
    Range("PivotTable100").PivotTable.RefreshTable

    ThisWorkbook.Worksheets("Heatmap").Activate

End Sub

Let me know if it works


问:
Looking for the likely better way to get at nested data with glom?
I have a particularly nasty stats object from a system that I need to retrieve data from (two of the many stats entries shown for brevity).

```<code> 'https://localhost/mgmt/tm/sys/performance/all-stats/TMM%20Memory%20Used': {'nestedStats': {'entries': {'Average': {'description': '5'},
                                                                                'Current': {'description': '5'},
                                                                                'Max(since 2019_11_12T02:47:10Z)': {'description': '5'},
                                                                                'Memory Used': {'description': 'TMM '
                                                                                'Memory '
                                                                                'Used'}}}},
 'https://localhost/mgmt/tm/sys/performance/all-stats/Utilization': {'nestedStats': {'entries': {'Average': {'description': '9'},
                                                                                'Current': {'description': '10'},
                                                                                'Max(since 2019_11_12T02:47:10Z)': {'description': '53'},
                                                                                'System CPU Usage': {'description': 'Utilization'}}}}}
</code>```

Currently I use the .get method multiple times in the nested stacks, but I was listening to the author of the glom module on Talk Python this weekend and thought that might be a far cleaner solution for me. And it is, as this code makes it so that I have all the data in a loop without crazy layers of get methods (first example pictured above that I'm working on tonight). The outer key is the long URL, the inner key is the avg/current/max/desc.

```<code>stats = b.tm.sys.performances.all_stats.load()
for k, v in stats.entries.items():
    print('\n')
    spec = f'entries.{k}.nestedStats.entries'
    v_stats = glom(stats, spec)
    for k, v, in v_stats.items():
        spec = f'{k}.description'
        stat_vals = glom(v_stats, spec)
        print(f'{k}: {stat_vals}')
</code>```

Which results the data I need:

```<code>Average: 5
Current: 5
Max(since 2019_11_12T02:47:10Z): 5
Memory Used: TMM Memory Used
</code>```

That said, I don't really have control of the data at this point, I'm just printing it. I don't think I'm grokking the power of glom just yet and was curious if someone could point me to an example that'll help my understanding? End goal is to flatten all this data into a single list of 4 item dictionaries.

答:
First, before you try this, make sure glom is updated to the current version 19.11.0 or better.

What you ask for, is called Data-Driven-Assignment by glom's docs and not a strength of glom.

See the glom docs here

To get it to work, you may need lambdas and/or regular Python code.

Below is my working attempt, copy your example lines into the variable d.

```<code>from glom import glom, Call, T, Iter

d = { ... }  # put your example lines into this dictionary.

def get_desc(subdict):
    return {k: v.get('description', None)
            for k,v in subdict[1]['nestedStats']['entries'].items()}

spec = (Call(list, args=(T.items(),) ), Iter().map(get_desc).all())

result = glom(d, spec)

print(result)
</code>```

results in

```<code>[
{'Average': '5', 'Current': '5', 'Max(since 2019_11_12T02:47:10Z)': '5', 'Memory Used': 'TMM Memory Used'},
{'Average': '9', 'Current': '10', 'Max(since 2019_11_12T02:47:10Z)': '53', 'System CPU Usage': 'Utilization'}
]
</code>```

UPDATE

The version below gets the same result, but avoids the need for a helper function.

What the spec does:

Call turns outer dict into a list of tuples

Iter loops over the list. For each item:

Take second element of tuple

get nestedStats.entries (which is another dict)

Call turns this dict into a list of tuples

Turn this list into a list of dicts with key and description

merge the list of dicts into one dict

take all the results from the iteration

I recommend trying this and removing parts of the spec to see what happens...

```<code>from glom import glom, Call, T, Iter, merge

# d = { ... }  # put your example lines into this dictionary.

spec = (
    Call(list, args=(T.items(),)),
    Iter(
        (
            T[1],
            "nestedStats.entries",
            Call(list, args=(T.items(),)),
            [{T[0]: (T[1], "description")}],
            merge,
        )
    ).all(),
)

result = glom(d, spec)

print(result)
</code>```

Body:
I have a particularly nasty stats object from a system that I need to retrieve data from (two of the many stats entries shown for brevity).

 'https://localhost/mgmt/tm/sys/performance/all-stats/TMM%20Memory%20Used': {'nestedStats': {'entries': {'Average': {'description': '5'},
                                                                                'Current': {'description': '5'},
                                                                                'Max(since 2019_11_12T02:47:10Z)': {'description': '5'},
                                                                                'Memory Used': {'description': 'TMM '
                                                                                'Memory '
                                                                                'Used'}}}},
 'https://localhost/mgmt/tm/sys/performance/all-stats/Utilization': {'nestedStats': {'entries': {'Average': {'description': '9'},
                                                                                'Current': {'description': '10'},
                                                                                'Max(since 2019_11_12T02:47:10Z)': {'description': '53'},
                                                                                'System CPU Usage': {'description': 'Utilization'}}}}}

Currently I use the .get method multiple times in the nested stacks, but I was listening to the author of the glom module on Talk Python this weekend and thought that might be a far cleaner solution for me. And it is, as this code makes it so that I have all the data in a loop without crazy layers of get methods (first example pictured above that I'm working on tonight). The outer key is the long URL, the inner key is the avg/current/max/desc.

stats = b.tm.sys.performances.all_stats.load()
for k, v in stats.entries.items():
    print('\n')
    spec = f'entries.{k}.nestedStats.entries'
    v_stats = glom(stats, spec)
    for k, v, in v_stats.items():
        spec = f'{k}.description'
        stat_vals = glom(v_stats, spec)
        print(f'{k}: {stat_vals}')

Which results the data I need:

Average: 5
Current: 5
Max(since 2019_11_12T02:47:10Z): 5
Memory Used: TMM Memory Used

That said, I don't really have control of the data at this point, I'm just printing it. I don't think I'm grokking the power of glom just yet and was curious if someone could point me to an example that'll help my understanding? End goal is to flatten all this data into a single list of 4 item dictionaries.

Body:
First, before you try this, make sure glom is updated to the current version 19.11.0 or better.

What you ask for, is called Data-Driven-Assignment by glom's docs and not a strength of glom.

See the glom docs here

To get it to work, you may need lambdas and/or regular Python code.

Below is my working attempt, copy your example lines into the variable d.

from glom import glom, Call, T, Iter

d = { ... }  # put your example lines into this dictionary.

def get_desc(subdict):
    return {k: v.get('description', None)
            for k,v in subdict[1]['nestedStats']['entries'].items()}

spec = (Call(list, args=(T.items(),) ), Iter().map(get_desc).all())

result = glom(d, spec)

print(result)

results in

[
{'Average': '5', 'Current': '5', 'Max(since 2019_11_12T02:47:10Z)': '5', 'Memory Used': 'TMM Memory Used'},
{'Average': '9', 'Current': '10', 'Max(since 2019_11_12T02:47:10Z)': '53', 'System CPU Usage': 'Utilization'}
]

UPDATE

The version below gets the same result, but avoids the need for a helper function.

What the spec does:

Call turns outer dict into a list of tuples

Iter loops over the list. For each item:

Take second element of tuple

get nestedStats.entries (which is another dict)

Call turns this dict into a list of tuples

Turn this list into a list of dicts with key and description

merge the list of dicts into one dict

take all the results from the iteration

I recommend trying this and removing parts of the spec to see what happens...

from glom import glom, Call, T, Iter, merge

# d = { ... }  # put your example lines into this dictionary.

spec = (
    Call(list, args=(T.items(),)),
    Iter(
        (
            T[1],
            "nestedStats.entries",
            Call(list, args=(T.items(),)),
            [{T[0]: (T[1], "description")}],
            merge,
        )
    ).all(),
)

result = glom(d, spec)

print(result)


问:
Combine arrays of identical length into array of objects
I have 10 arrays of data that look like this:

```<code>var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays
</code>```

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

```<code>overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]
</code>```

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

答:
Just iterate all arrays with 1 loop counter:</p>

```<code>    var dataArrayOne = [1, 2, 3, 4 ];
    var dataArrayTwo = ["hello", "hello1", "hello2", "hello3" ];
...

    var resultArray = [];

    for (var i = 0; i < 4; i++)
    {
        var combined = {
            arr1: dataArrayOne[I],
            arr2: dataArrayTwo[i]
...
        };

        resultArray.push(combined);
    }
</code>```

Body:
I have 10 arrays of data that look like this:

var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

Body:
Just iterate all arrays with 1 loop counter:

    var dataArrayOne = [1, 2, 3, 4 ];
    var dataArrayTwo = ["hello", "hello1", "hello2", "hello3" ];
...

    var resultArray = [];

    for (var i = 0; i < 4; i++)
    {
        var combined = {
            arr1: dataArrayOne[I],
            arr2: dataArrayTwo[i]
...
        };

        resultArray.push(combined);
    }


问:
Deploying an app on Google Cloud Platform - ImportError for pyzbar
I am deploying an app with Flask that uses the library pyzbar (and more specifically the function pyzbar.pyzbar.decode)

It works perfectly on my machine; but when I deploy it, I have the error: ImportError: Unable to find zbar shared library.

This is because pyzbar.pyzbar runs find_library('zbar') (find_library is from ctypes.util) and nothing is returned.

Do you know what I should do?

答:
Create this files app.yaml, main.py, requirements.txt:

1.app.yaml

```<code>runtime: python37
</code>```

2.requirements.txt

```<code>Flask==1.1.1
pyzbar
</code>```

3.main.py

```<code># [START gae_python37_app]
from flask import Flask
import pyzbar

app = Flask(__name__)

@app.route('/')
def hello():
   """Return a friendly HTTP greeting."""
   return 'Hello World!'
</code>```

Then:

```<code>gcloud app deploy -q
gcloud app browse

#Hello Word
</code>```

Everything worked as expected!

Body:
Create this files app.yaml, main.py, requirements.txt:

1.app.yaml

runtime: python37

2.requirements.txt

Flask==1.1.1
pyzbar

3.main.py

# [START gae_python37_app]
from flask import Flask
import pyzbar

app = Flask(__name__)

@app.route('/')
def hello():
   """Return a friendly HTTP greeting."""
   return 'Hello World!'

Then:

gcloud app deploy -q
gcloud app browse

#Hello Word

Everything worked as expected!


问:
Ran 0 tests in 0.000s
I have a pet project in which I use django-rest framework and docker-compose. Everything seems to be working fine except tests.py.Test runner just doesn't see them. docker-compose acts like I don't have any. Here are my files:

docker-compose:

```<code>version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: bash -c 'python3 taskmanager/manage.py makemigrations && taskmanager/manage.py migrate && taskmanager/manage.py test && taskmanager/manage.py runserver 0.0.0.0:5000'
    volumes:
      - .:/code
    ports:
      - "5000:5000"
    depends_on:
      - db
</code>```

tests.py:

```<code>from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .models import Task

class TaskTests(APITestCase):

def setUp(self):
    Task.objects.create(name='Run marathon', description='Need to run a marathon')
    Task.objects.create(name='Lie on the beach', description='Need some more sunlight')

def test_create_task(self):
    url = reverse('tasks_list_url')
    data = {'name': 'Buy milk', 'description': 'Need some milk'}
    response = self.client.post(url, data, format='json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
    self.assertEqual(Task.objects.get(id=3).name, 'Buy milk')

def test_get_single_task(self):
    url = reverse('task_detail_url', args=[2])
    response = self.client.get(url, format='json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)

def test_get_tasks_list(self):
    url = reverse('tasks_list_url')
    response = self.client.get(url, format='json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
</code>```

location of tests.py:
1

答:
This is a wild guess, because there isn't enough information. Are you running pytest? What is your command to run the test? What is the traceback. Please update your question for everyone else to understand this better.

Sometimes, the test runner assumes that the test file is of the form test_***.py. Maybe that's what's happening? Do try to change the test file to something like test_example.py and run the command again.

Title: Ran 0 tests in 0.000s

Body:
I have a pet project in which I use django-rest framework and docker-compose. Everything seems to be working fine except tests.py.Test runner just doesn't see them. docker-compose acts like I don't have any. Here are my files:

docker-compose:

version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: bash -c 'python3 taskmanager/manage.py makemigrations && taskmanager/manage.py migrate && taskmanager/manage.py test && taskmanager/manage.py runserver 0.0.0.0:5000'
    volumes:
      - .:/code
    ports:
      - "5000:5000"
    depends_on:
      - db

tests.py:

from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .models import Task

class TaskTests(APITestCase):

def setUp(self):
    Task.objects.create(name='Run marathon', description='Need to run a marathon')
    Task.objects.create(name='Lie on the beach', description='Need some more sunlight')

def test_create_task(self):
    url = reverse('tasks_list_url')
    data = {'name': 'Buy milk', 'description': 'Need some milk'}
    response = self.client.post(url, data, format='json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
    self.assertEqual(Task.objects.get(id=3).name, 'Buy milk')

def test_get_single_task(self):
    url = reverse('task_detail_url', args=[2])
    response = self.client.get(url, format='json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)

def test_get_tasks_list(self):
    url = reverse('tasks_list_url')
    response = self.client.get(url, format='json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)

location of tests.py:
1


问:
Script finds the necessary file when running through IDLE, but cannot find the file when running through terminal
I have a python script that uses Selenium to get my grades for my classes every hour and sends me an email if my grades have been changed.

I have an external file that gets referenced to see if there has been any change since the last write.

When I test the program by pressing F5 when in the IDLE, it works just as intended. But when I go to my terminal and type python3 /home/pi/Desktop/gradesNotification/script.py it works all the way up until it needs to open the text file with my grades. I get the error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'grades'
</code>```

The text file is in the same folder as the script. The program works when ran through IDLE, but does not work when started from terminal.

答:
I suppose the easiest fix to your problem would be specifying an absolute path to the grades file in your code:

```<code>"/home/pi/Desktop/gradesNotification/grades"
</code>```

However, it would not be very pretty or flexible - here is a great article on handling file system access from Python using pathlib library.

Body:
I have a python script that uses Selenium to get my grades for my classes every hour and sends me an email if my grades have been changed.

I have an external file that gets referenced to see if there has been any change since the last write.

When I test the program by pressing F5 when in the IDLE, it works just as intended. But when I go to my terminal and type python3 /home/pi/Desktop/gradesNotification/script.py it works all the way up until it needs to open the text file with my grades. I get the error:

FileNotFoundError: [Errno 2] No such file or directory: 'grades'

The text file is in the same folder as the script. The program works when ran through IDLE, but does not work when started from terminal.

Body:
I suppose the easiest fix to your problem would be specifying an absolute path to the grades file in your code:

"/home/pi/Desktop/gradesNotification/grades"

However, it would not be very pretty or flexible - here is a great article on handling file system access from Python using pathlib library.


问:
How to change a text in JSON that has quotes in it?
The following code works on python without any issue. It opens the JSON file, and replace all bananas to apples:

```<code>import json

replacements = "banana" : "apple"

with open(mycodepath, 'r') as file:
    data = file.read()
for old, new in replacements.items():
    data = data.replace(old, new)
</code>```

However, I want to replace "ArmReoriented", "visible": true with "ArmReoriented", "visible": false,

I tried using triple quotes, but it does not work.

```<code>replacements = """ArmReoriented", "visible": true""" : """ArmReoriented", "visible": false,"""
</code>```

How I replace a text containing quotes on JSON using Python?

答:
Using """ is basically a comment or a doc-string and would not work.

Put double quote between a single quote string like below.

```<code>replacements = {'"ArmReoriented", "visible": true' : '"ArmReoriented", "visible": false'}
</code>```

Body:
The following code works on python without any issue. It opens the JSON file, and replace all bananas to apples:

import json

replacements = "banana" : "apple"

with open(mycodepath, 'r') as file:
    data = file.read()
for old, new in replacements.items():
    data = data.replace(old, new)

However, I want to replace "ArmReoriented", "visible": true with "ArmReoriented", "visible": false,

I tried using triple quotes, but it does not work.

replacements = """ArmReoriented", "visible": true""" : """ArmReoriented", "visible": false,"""

How I replace a text containing quotes on JSON using Python?

Body:
Using """ is basically a comment or a doc-string and would not work.

Put double quote between a single quote string like below.

replacements = {'"ArmReoriented", "visible": true' : '"ArmReoriented", "visible": false'}


问:
How to format ZonedDateTime to yyyy-MM-ddZ
I need to turn ZonedDateTime to XML Date data type, of format yyyy-MM-ddZ. For example: 2020-02-14Z. I try to use DateTimeFormatter.ofPattern("yyyy-MM-ddZ") but the output is: 2020-02-14+0000. Which DateTimeFormatter pattern should I use to get the desired result?

答:
DateTimeFormatter.ISO_OFFSET_DATE

Use the built-in DateTimeFormatter.ISO_OFFSET_DATE.

```<code>    ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Fortaleza"));
    String dateForXml = dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE);
    System.out.println(dateForXml);
</code>```

When I ran this snippet just now, the output was:

2020-02-14-03:00

If you want a string in UTC with a trailing Z, use ZoneOffset.UTC:

```<code>    ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);
</code>```

2020-02-14Z

If you have got a ZonedDateTime that is not in UTC, convert:

```<code>    ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Fortaleza"));
    OffsetDateTime odt = dateTime.toOffsetDateTime()
            .withOffsetSameInstant(ZoneOffset.UTC);
    String dateForXml = odt.format(DateTimeFormatter.ISO_OFFSET_DATE);
</code>```

2020-02-14Z

Body:
DateTimeFormatter.ISO_OFFSET_DATE

Use the built-in DateTimeFormatter.ISO_OFFSET_DATE.

    ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Fortaleza"));
    String dateForXml = dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE);
    System.out.println(dateForXml);

When I ran this snippet just now, the output was:

2020-02-14-03:00

If you want a string in UTC with a trailing Z, use ZoneOffset.UTC:

    ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);

2020-02-14Z

If you have got a ZonedDateTime that is not in UTC, convert:

    ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Fortaleza"));
    OffsetDateTime odt = dateTime.toOffsetDateTime()
            .withOffsetSameInstant(ZoneOffset.UTC);
    String dateForXml = odt.format(DateTimeFormatter.ISO_OFFSET_DATE);

2020-02-14Z


问:
Install pymssql 2.1.3 in Pycharm
I'm working with Pycharm in a project to read SQL DBs ,I'm working in a windows 10 64bits workstation and I'm trying to install the module pymssql, I have already installed VS2015 to get all requirements but now each time that i try to install i got the message:

error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe' failed with exit status 2

I saw on message details the error in:
  _mssql.c(266): fatal error C1083: Cannot open include file: 'sqlfront.h': No such file or directory

How can i figured it out?  thanks

答:
I had the same problem and I fixed this way.

Download pymssql module from https://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql. place the .whl file in the C:\Python38-32 folder.

Open cmd.exe

Run

cd C:\Python38-32

  pip install pymssql-2.1.4-cp38-cp38-win32.whl

Title: Install pymssql 2.1.3 in Pycharm


问:
How can I check if the time is more than an hour later?
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.

Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?

Example:

```<code>DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing
</code>```

答:
Hello Schmaniel at first i think you should use Carbon()
https://carbon.nesbot.com/docs/ to get the right results. It's a great way to work with timeformats and timestamps.

$now = Carbon::now();
$dbtime = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:10:22');

$totalDuration = $now->diffForHumans($dbtime);
dd($totalDuration);```

Body:
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.

Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?

Example:

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing


问:
Dynamic Include statements for eager loading in a query - EF 4.3.1
I have this method:

```<code>public CampaignCreative GetCampaignCreativeById(int id)
        {
            using (var db = GetContext())
            {
                return db.CampaignCreatives
                    .Include("Placement")
                    .Include("CreativeType")
                    .Include("Campaign")
                    .Include("Campaign.Handshake")
                    .Include("Campaign.Handshake.Agency")
                    .Include("Campaign.Product")
                    .AsNoTracking()
                    .Where(x => x.Id.Equals(id)).FirstOrDefault();
            }
        }
</code>```

I would like to make the list of Includes dynamic. I tried:

```<code>public CampaignCreative GetCampaignCreativeById(int id, string[] includes)
        {
            using (var db = GetContext())
            {
                var query = db.CampaignCreatives;

                foreach (string include in includes)
                {
                    query = query.Include(include);
                }

                return query.AsNoTracking()
                    .Where(x => x.Id.Equals(id)).FirstOrDefault();
            }
        }
</code>```

But it didn't compile. I got this error:

Cannot implicitly convert type 'System.Data.Entity.Infrastructure.DbQuery' to 'System.Data.Entity.DbSet'. An explicit conversion exists (are you missing a cast?)

Does anyone know how to make the list of Includes dynamic?

Thanks

答:
I wrote this method to retrieve any set of entity dynamically based on their types. I used the IDbEntity interface to provide a valid key to search the userId in all the classes.
The Util.GetInverseProperties<T>() method is used to get the properties needed in the Include statement.

public IEnumerable<T> GetItems<T>(string userId) where T : class, IDbEntity
{
    var query = db.Set<T>().Where(l => l.UserId==userId);

    var props = Util.GetInverseProperties<T>();
    foreach (var include in props)
        query = query.Include(include.Name);

    return query
        .AsNoTracking()
        .ToList();
}
```

<pre class="lang-cs prettyprint-override"><code>public interface IDbEntity
{
    public string UserId { get; set; }
}
</code>```

public static List<PropertyInfo> GetInverseProperties<T>()
{
    return typeof(T)
        .GetProperties()
        .Where(p => Attribute.IsDefined(p, typeof(InversePropertyAttribute)))
        .ToList();
}
```

Body:
I have this method:

public CampaignCreative GetCampaignCreativeById(int id)
        {
            using (var db = GetContext())
            {
                return db.CampaignCreatives
                    .Include("Placement")
                    .Include("CreativeType")
                    .Include("Campaign")
                    .Include("Campaign.Handshake")
                    .Include("Campaign.Handshake.Agency")
                    .Include("Campaign.Product")
                    .AsNoTracking()
                    .Where(x => x.Id.Equals(id)).FirstOrDefault();
            }
        }

I would like to make the list of Includes dynamic. I tried:

public CampaignCreative GetCampaignCreativeById(int id, string[] includes)
        {
            using (var db = GetContext())
            {
                var query = db.CampaignCreatives;

                foreach (string include in includes)
                {
                    query = query.Include(include);
                }

                return query.AsNoTracking()
                    .Where(x => x.Id.Equals(id)).FirstOrDefault();
            }
        }

But it didn't compile. I got this error:

Cannot implicitly convert type 'System.Data.Entity.Infrastructure.DbQuery' to 'System.Data.Entity.DbSet'. An explicit conversion exists (are you missing a cast?)

Does anyone know how to make the list of Includes dynamic?

Thanks

Body:
I wrote this method to retrieve any set of entity dynamically based on their types. I used the IDbEntity interface to provide a valid key to search the userId in all the classes.
The Util.GetInverseProperties<T>() method is used to get the properties needed in the Include statement.

public IEnumerable<T> GetItems<T>(string userId) where T : class, IDbEntity
{
    var query = db.Set<T>().Where(l => l.UserId==userId);

    var props = Util.GetInverseProperties<T>();
    foreach (var include in props)
        query = query.Include(include.Name);

    return query
        .AsNoTracking()
        .ToList();
}

public interface IDbEntity
{
    public string UserId { get; set; }
}

public static List<PropertyInfo> GetInverseProperties<T>()
{
    return typeof(T)
        .GetProperties()
        .Where(p => Attribute.IsDefined(p, typeof(InversePropertyAttribute)))
        .ToList();
}


答:
File names are given with respect to cwd, the current working directory.  It's possible that your cwd in IDLE is the directory where the grades reside, but that your terminal window is elsewhere.  Try changing to the proper directory, or specify the full path of the grades file.

Another way is to have your program check its own location, and try to open grades from there.

Title: Script finds the necessary file when running through IDLE, but cannot find the file when running through terminal