问:
Left-hand operand of comma has no effect vs Right-hand operand of comma has no effect
I'm very beginner in C++ and I'm currently reading a book to get better in it. While reading a section about C++'s only ternary operator, I played around some code and got a question:

So, when I do this:

```<code>std::cout << "Hello ", "Mars";
</code>```

I get a warning:

warning: right operand of comma operator has no effect [-Wunused-value]

And when I do this:

```<code>std::cout << (5 > 4 ? "Hello ", "Mars" : "Bye ", "World");
</code>```

for the second operand of ?: I get:

warning: left operand of comma operator has no effect [-Wunused-value]

for the third operand of ?: I get:

warning: left operand of comma operator has no effect [-Wunused-value]

So my question is, why do I get the first warning for the second operand of ?:, while I get the second warning for the third operand of ?:?

答:
From cppreference:

In a comma expression E1, E2, the expression E1 is evaluated, its
  result is discarded (although if it has class type, it won't be
  destroyed until the end of the containing full expression), and its
  side effects are completed before evaluation of the expression E2
  begins (note that a user-defined operator, cannot guarantee
  sequencing) (until C++17).

It is the result of left operand that is discarded. However, if you consider operator precedence, where the comma operator is always last, then

```<code>std::cout << "Hello ", "Mars";
</code>```

is the same as

```<code>(std::cout << "Hello ") , ( "Mars" ) ;
</code>```

and the compiler is trying to be clever. This

```<code>std::cout << "Hello "
</code>```

does have an effect even if you ignore the returned value. Note that operator<< returns a reference to the stream and you typically ignore that value. Hence, discarding it via the comma operator does not prevent it to print something on the screen.

On the other hand

```<code>"Mars";
</code>```

as a statement has no effect and that is what the compiler is trying to tell in that case.

Body:
I'm very beginner in C++ and I'm currently reading a book to get better in it. While reading a section about C++'s only ternary operator, I played around some code and got a question:

So, when I do this:

std::cout << "Hello ", "Mars";

I get a warning:

warning: right operand of comma operator has no effect [-Wunused-value]

And when I do this:

std::cout << (5 > 4 ? "Hello ", "Mars" : "Bye ", "World");

for the second operand of ?: I get:

warning: left operand of comma operator has no effect [-Wunused-value]

for the third operand of ?: I get:

warning: left operand of comma operator has no effect [-Wunused-value]

So my question is, why do I get the first warning for the second operand of ?:, while I get the second warning for the third operand of ?:?

Body:
From cppreference:

In a comma expression E1, E2, the expression E1 is evaluated, its
  result is discarded (although if it has class type, it won't be
  destroyed until the end of the containing full expression), and its
  side effects are completed before evaluation of the expression E2
  begins (note that a user-defined operator, cannot guarantee
  sequencing) (until C++17).

It is the result of left operand that is discarded. However, if you consider operator precedence, where the comma operator is always last, then

std::cout << "Hello ", "Mars";

is the same as

(std::cout << "Hello ") , ( "Mars" ) ;

and the compiler is trying to be clever. This

std::cout << "Hello "

does have an effect even if you ignore the returned value. Note that operator<< returns a reference to the stream and you typically ignore that value. Hence, discarding it via the comma operator does not prevent it to print something on the screen.

On the other hand

"Mars";

as a statement has no effect and that is what the compiler is trying to tell in that case.


来源: stackexchange

问:
Angular displays only ID number from Java REST
I am making CRUD app with SpringBoot and Angular. I am using MySQL to this, and when I make POST request in Postman I can see all my date displayed in JSON file. So in Angular I have service with:

```<code>export class GetdataService {
  constructor(private http: HttpClient) {}

  getAllTodos() {
    return this.http.get < Todo[] > ('http://wwww.localhost:8081/todos');
  }
}
</code>```

My Component where I am saving data:

```<code>export class TaskListComponent implements OnInit {
  todos: Todo[];

  constructor(private getDataService: GetdataService) {}

  ngOnInit() {
    this.refreshTodos();
  }

  refreshTodos() {
    console.log(this.getDataService.getAllTodos().subscribe(
      response => {
        console.log(response);
        this.todos = response;
      }
    ));
  }
}

export class Todo {
  constructor(
    public id: number,
    public description: string,
    public status: boolean,
    public date: Date
  ) {}
}
</code>```

In console.log I am able to see my JSON format with correct data from database. When I start angular application I do not have any errors in console but on my browser I can see only id numbers. Do not know what might be wrong in this case.

```<code><div class="container">
  <table class="table">
    <thead>
    <tr>
      <th>Id</th>
      <th>Target Date</th>
      <th>is Completed?</th>
      <th>Update</th>
      <th>Delete</th>
    </tr>
    </thead>
    <tbody>

    <tr *ngFor="let todo of todos">
      <td>{{todo.description}}</td>
      <td>{{todo.id}}</td>
      <td>{{todo.status}}</td>
      <td>{{todo.date}}</td>
    </tr>

    </tbody>
  </table>
</div>
</code>```

答: You might have the incorrect property name, which is causing this issue. </p>

ContentLicense: CC BY-SA 4.0

Body:
I am making CRUD app with SpringBoot and Angular. I am using MySQL to this, and when I make POST request in Postman I can see all my date displayed in JSON file. So in Angular I have service with:

export class GetdataService {
  constructor(private http: HttpClient) {}

  getAllTodos() {
    return this.http.get < Todo[] > ('http://wwww.localhost:8081/todos');
  }
}

My Component where I am saving data:

export class TaskListComponent implements OnInit {
  todos: Todo[];

  constructor(private getDataService: GetdataService) {}

  ngOnInit() {
    this.refreshTodos();
  }

  refreshTodos() {
    console.log(this.getDataService.getAllTodos().subscribe(
      response => {
        console.log(response);
        this.todos = response;
      }
    ));
  }
}

export class Todo {
  constructor(
    public id: number,
    public description: string,
    public status: boolean,
    public date: Date
  ) {}
}

In console.log I am able to see my JSON format with correct data from database. When I start angular application I do not have any errors in console but on my browser I can see only id numbers. Do not know what might be wrong in this case.

      Id
      Target Date
      is Completed?
      Update
      Delete

      {{todo.description}}
      {{todo.id}}
      {{todo.status}}
      {{todo.date}}


问:
How to do operator++ overloading with heap allocation
I want to overload the ++ operator but it isn't working. The example I found in the book I'm using used stack memory allocation and I tried to do it through heap memory allocation. It isn't crashing but it isn't incrementing either.

I tried returning the pointer, making a reference, all sorts of stuff that I don't quite understand yet and nothing really worked.

```<code>#include <iostream>

using namespace std;

class MyObject{
public:
  MyObject(int initVal = 0):value(initVal){cout << "Constructor called..." << endl;}
  ~MyObject(){cout << "Destructor called..." << endl;}
  const MyObject& operator++();
  int getValue(){return value;}
private:
  int value = 0;

};

int main(){
  int initVal = 0;
  char done = 'N';

  cout << "initVal?" << endl;
  cin >> initVal;
  MyObject *obj = new MyObject(initVal);
  while(done == 'N'){
    cout << "Current value of obj :" << obj->getValue() << ". Want to stop? (Y/N)" << endl;
    cin >> done;
    //cout << "value of done :" << done << endl;
    //cin.get();
    if(done != 'Y' || done != 'N'){
      continue;
    }
    *obj++;
  }
  cout << "";
  cin.get();
}

const MyObject& MyObject::operator++(){
  cout << "OVERLOADER CALLED val:" << value << endl;
  value++;
  return *this;
}
</code>```

Actual:

```<code>initVal?
10
Constructor called...
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)

Expected:initVal?
10
Constructor called...
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :11. Want to stop? (Y/N)
N
Current value of obj :12. Want to stop? (Y/N)
N
Current value of obj :13. Want to stop? (Y/N)
Y
</code>```

Also, my test to see if the response was not either Y or N stops the program when true instead of iterating at the beginning of the while loop. Help on that is also appreciated.

答:
You've fallen victim to operator precedence. The expression *pointer++ dereferences the pointer, returns that reference and increments the pointer, not the value. It's equivalent to *(pointer++).

The solution is to add a pair of parentheses: (*pointer)++.

Don't use new, std::unique_ptr is the correct way to handle dynamic memory.

Also you overloaded the prefix operator, you probably wanted postfix. Both operators should look something like this:

```<code>MyObject MyObjects::operator++(int)//Post-fix accepts unused int argument
{
    MyObject copy{*this};
    ++*this; // Use prefix++ to avoid redundant code.
    return copy;
}

MyObject& MyObjects::operator++()
{
    //Put incrementing logic here
    ++this->value;
    return *this;
}
</code>```

Body:
I want to overload the ++ operator but it isn't working. The example I found in the book I'm using used stack memory allocation and I tried to do it through heap memory allocation. It isn't crashing but it isn't incrementing either.

I tried returning the pointer, making a reference, all sorts of stuff that I don't quite understand yet and nothing really worked.

#include <iostream>

using namespace std;

class MyObject{
public:
  MyObject(int initVal = 0):value(initVal){cout << "Constructor called..." << endl;}
  ~MyObject(){cout << "Destructor called..." << endl;}
  const MyObject& operator++();
  int getValue(){return value;}
private:
  int value = 0;

};

int main(){
  int initVal = 0;
  char done = 'N';

  cout << "initVal?" << endl;
  cin >> initVal;
  MyObject *obj = new MyObject(initVal);
  while(done == 'N'){
    cout << "Current value of obj :" << obj->getValue() << ". Want to stop? (Y/N)" << endl;
    cin >> done;
    //cout << "value of done :" << done << endl;
    //cin.get();
    if(done != 'Y' || done != 'N'){
      continue;
    }
    *obj++;
  }
  cout << "";
  cin.get();
}

const MyObject& MyObject::operator++(){
  cout << "OVERLOADER CALLED val:" << value << endl;
  value++;
  return *this;
}

Actual:

initVal?
10
Constructor called...
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)

Expected:initVal?
10
Constructor called...
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :11. Want to stop? (Y/N)
N
Current value of obj :12. Want to stop? (Y/N)
N
Current value of obj :13. Want to stop? (Y/N)
Y

Also, my test to see if the response was not either Y or N stops the program when true instead of iterating at the beginning of the while loop. Help on that is also appreciated.

Body:
You've fallen victim to operator precedence. The expression *pointer++ dereferences the pointer, returns that reference and increments the pointer, not the value. It's equivalent to *(pointer++).

The solution is to add a pair of parentheses: (*pointer)++.

Don't use new, std::unique_ptr is the correct way to handle dynamic memory.

Also you overloaded the prefix operator, you probably wanted postfix. Both operators should look something like this:

MyObject MyObjects::operator++(int)//Post-fix accepts unused int argument
{
    MyObject copy{*this};
    ++*this; // Use prefix++ to avoid redundant code.
    return copy;
}

MyObject& MyObjects::operator++()
{
    //Put incrementing logic here
    ++this->value;
    return *this;
}


问:
Restrict access to images in bucket to authenticated users
Looking for instructions on how to setup Google Cloud Storage bucket with images that only authenticated users can access.

Our application uses Firstore and Cloud Storage. We store images in GCS buckets which we do not want publicly visible on the NET.
We have setup storage rules

```<code>allow read: if request.auth.uid != null;
</code>```

We have also configured the bucket in our Firebase config settings.
We then use the storage API to getDownloadURL() for the target path.
This works and we are able to see the images. However, if we copy the Image URL from the page and go to another browser (that is not logged in) that browser is able to download the image.

Question: what is the correct (and most efficient) way to configure and access a GCS bucket such that only authenticated users authenticated using Firebase signInWithEmailAndPassword() can view the images.

Here is what we do currently (Angular and AngularFire)

```<code>// Assumes storage is an instance of the AngularFireStorage service
this.storage.getDownloadURL('/thumbs/imagename.jpg')
  .subscribe(path => {
     this.imgSrc = path;
});
</code>```

As described above, the resulting path is public and the above process is very slow - images take a long time to appear on the screen.

I am guessing this is not the right approach?

答:
As Doug said, you would have to use the client SDK to accomplish that, depending on the level of control you need you can choose one of the options listed on the official documentation [1] and to only let authenticated users have access with Firebase Authentication SDK [2].

[1] https://cloud.google.com/storage/docs/access-control/

[2] https://firebase.google.com/docs/storage/security/user-security

Body:
Looking for instructions on how to setup Google Cloud Storage bucket with images that only authenticated users can access.

Our application uses Firstore and Cloud Storage. We store images in GCS buckets which we do not want publicly visible on the NET.
We have setup storage rules

allow read: if request.auth.uid != null;

We have also configured the bucket in our Firebase config settings.
We then use the storage API to getDownloadURL() for the target path.
This works and we are able to see the images. However, if we copy the Image URL from the page and go to another browser (that is not logged in) that browser is able to download the image.

Question: what is the correct (and most efficient) way to configure and access a GCS bucket such that only authenticated users authenticated using Firebase signInWithEmailAndPassword() can view the images.

Here is what we do currently (Angular and AngularFire)

// Assumes storage is an instance of the AngularFireStorage service
this.storage.getDownloadURL('/thumbs/imagename.jpg')
  .subscribe(path => {
     this.imgSrc = path;
});

As described above, the resulting path is public and the above process is very slow - images take a long time to appear on the screen.

I am guessing this is not the right approach?


问:
Batch File to Loop Over Files In a Folder and Run Exe for Info
I am writing a *.BAT file to count the frames in every GIF file in a folder. Writing all that to TXT files would be nice, but I haven't gotten that far yet.

I can do this from the command line for single files.

This does what I want, but it does not output the number of frames to the window.
The next line is a sample of what it should do for a single file.

```<code>"c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n 14215349.gif
</code>```

These two lines should do the same for every file in the folder.
But, they just echo the command, rather than show its output.

```<code>set "frames=^0x22c:\program^ files\ImageMagick-6.8.9-Q8\identify.exe^0x22^ -format^ %%n"
forfiles /m *.gif /c "cmd /c echo %frames% @file"
</code>```

The only thing I can see wrong is the double quotes, but this shows that's not it:

```<code>"c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n "14215349.gif"
pause
</code>```

It should output an integer for each file. Line 1 does this. Lines 2 and 3 do not; they just echo the command.

答:
I would suggest you use something like this:

@Echo Off
For %%K In (*.gif)Do If /I "%%~xK"==".gif" (
    "%ProgramFiles%\ImageMagick-6.8.9-Q8\identify.exe" -format "%%[n] %%[f]" "%%K"
)>>"FramesList.txt"
```

In the example above, I have used %%K for safety, because there are no short form attributes which use %K and it is a distinct character, for recognition purposes. In addition, I have decided to use the long form attributes percent escapes for the number of images, and filename, i.e. %[n] and %[f], for the same reason, because, from a batch file, %%n and %%f could be confused with For metavariables.

The If statement was included because *.gif does not loop through files with .gif extensions, it loops all extensions which begin with .gif. Whilst you may not have any which match this scenario, there's no real reason not to add in the additional safety.

Body:
I am writing a *.BAT file to count the frames in every GIF file in a folder. Writing all that to TXT files would be nice, but I haven't gotten that far yet.

I can do this from the command line for single files.

This does what I want, but it does not output the number of frames to the window.
The next line is a sample of what it should do for a single file.

"c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n 14215349.gif

These two lines should do the same for every file in the folder.
But, they just echo the command, rather than show its output.

set "frames=^0x22c:\program^ files\ImageMagick-6.8.9-Q8\identify.exe^0x22^ -format^ %%n"
forfiles /m *.gif /c "cmd /c echo %frames% @file"

The only thing I can see wrong is the double quotes, but this shows that's not it:

"c:\program files\ImageMagick-6.8.9-Q8\identify.exe" -format %%n "14215349.gif"
pause

It should output an integer for each file. Line 1 does this. Lines 2 and 3 do not; they just echo the command.

Body:
I would suggest you use something like this:

@Echo Off
For %%K In (*.gif)Do If /I "%%~xK"==".gif" (
    "%ProgramFiles%\ImageMagick-6.8.9-Q8\identify.exe" -format "%%[n] %%[f]" "%%K"
)>>"FramesList.txt"

In the example above, I have used %%K for safety, because there are no short form attributes which use %K and it is a distinct character, for recognition purposes. In addition, I have decided to use the long form attributes percent escapes for the number of images, and filename, i.e. %[n] and %[f], for the same reason, because, from a batch file, %%n and %%f could be confused with For metavariables.

The If statement was included because *.gif does not loop through files with .gif extensions, it loops all extensions which begin with .gif. Whilst you may not have any which match this scenario, there's no real reason not to add in the additional safety.


问:
mysql rand with condition
Could someone help me out with the correct syntax for this query please.

I have, table1:

```<code>id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)
</code>```

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?

答:
Try this: </p>

```<code>SELECT id,name FROM table1 WHERE `on`=1 ORDER BY RAND() LIMIT 0,10
</code>```

ContentLicense: CC BY-SA 3.0

Title: mysql rand with condition

Body:
Could someone help me out with the correct syntax for this query please.

I have, table1:

id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?

Body:
Try this:

SELECT id,name FROM table1 WHERE `on`=1 ORDER BY RAND() LIMIT 0,10


问:
Why will a move closure not capture a value with a generic type?
I'm trying to create a ScopeRunner type that can store method calls to a method of types implementing the Scope trait like this:

trait Scope {
    fn run(&self) -> String;
}

struct ScopeImpl;

impl Scope for ScopeImpl {
    fn run(&self) -> String {
        "Some string".to_string()
    }
}

struct ScopeRunner {
    runner: Box<dyn Fn() -> String>,
}

impl ScopeRunner {
    fn new<S: Scope>(scope: S) -> Self {
        ScopeRunner {
            runner: Box::new(move || scope.run())
        }
    }

    pub fn run(self) -> String {
        (self.runner)()
    }

}

fn main() {
    let scope = ScopeImpl {};
    let scope_runner = ScopeRunner::new(scope);

    dbg!(scope_runner.run());
}
```

<p>I would expect that since <code>ScopeRunner::new</code> creates a move closure this would cause scope to be moved into the closure. But instead the borrow checker gives me this error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0310]: the parameter type `S` may not live long enough
  --> src/main.rs:21:30
   |
20 |     fn new<S: Scope>(scope: S) -> Self {
   |            -- help: consider adding an explicit lifetime bound `S: 'static`...
21 |         ScopeRunner {runner: Box::new(move || scope.run())}
   |                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: ...so that the type `[closure@src/main.rs:21:39: 21:58 scope:S]` will meet its required lifetime bounds
  --> src/main.rs:21:30
   |
21 |         ScopeRunner {runner: Box::new(move || scope.run())}
   |
</code>```

When I replace ScopeRunner::new with a non generic version that just takes a ScopeImpl this code does work.

fn new(scope: ScopeImpl) -> Self {
    ScopeRunner {
        runner: Box::new(move || scope.run())
    }
}
```

I don't understand why this is different. To me it seems the lifetime of the generic Scope would be the same as the concrete version.

答:
The problem is that S could be any type with a Scope impl, which includes all kinds of not-yet-existing types that carry references to other types. For example you could have an implementation like this:

```<code>struct AnotherScope<'a> {
    reference: &'str,
}

impl Scope for ScopeImpl {
    fn run(&self) -> String {
        self.reference.to_string()
    }
}
</code>```

Rust is cautious and wants to make sure that this will work for any qualifying S, including if it contains references.

The easiest fix is to do as the error note suggests and just disallow S from having any non-static references:

```<code>fn new<S: Scope + 'static>(scope: S) -> Self {
    ScopeRunner {
        runner: Box::new(move || scope.run())
    }
}
</code>```

Bounding S with 'static effectively means that S can contain either references to values with a 'static lifetime or no references at all.

If you want to be a bit more flexible, you can broaden that to references that outlive the ScopeRunner itself:

```<code>struct ScopeRunner<'s> {
    runner: Box<dyn Fn() -> String + 's>,
}

impl<'s> ScopeRunner<'s> {
    fn new<S: Scope + 's>(scope: S) -> Self {
        ScopeRunner {
            runner: Box::new(move || scope.run())
        }
    }

    pub fn run(self) -> String {
        (self.runner)()
    }
}
</code>```

Body:
I'm trying to create a ScopeRunner type that can store method calls to a method of types implementing the Scope trait like this:

trait Scope {
    fn run(&self) -> String;
}

struct ScopeImpl;

impl Scope for ScopeImpl {
    fn run(&self) -> String {
        "Some string".to_string()
    }
}

struct ScopeRunner {
    runner: Box<dyn Fn() -> String>,
}

impl ScopeRunner {
    fn new<S: Scope>(scope: S) -> Self {
        ScopeRunner {
            runner: Box::new(move || scope.run())
        }
    }

    pub fn run(self) -> String {
        (self.runner)()
    }

}

fn main() {
    let scope = ScopeImpl {};
    let scope_runner = ScopeRunner::new(scope);

    dbg!(scope_runner.run());
}

I would expect that since ScopeRunner::new creates a move closure this would cause scope to be moved into the closure. But instead the borrow checker gives me this error:

error[E0310]: the parameter type `S` may not live long enough
  --> src/main.rs:21:30
   |
20 |     fn new<S: Scope>(scope: S) -> Self {
   |            -- help: consider adding an explicit lifetime bound `S: 'static`...
21 |         ScopeRunner {runner: Box::new(move || scope.run())}
   |                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: ...so that the type `[closure@src/main.rs:21:39: 21:58 scope:S]` will meet its required lifetime bounds
  --> src/main.rs:21:30
   |
21 |         ScopeRunner {runner: Box::new(move || scope.run())}
   |

When I replace ScopeRunner::new with a non generic version that just takes a ScopeImpl this code does work.

fn new(scope: ScopeImpl) -> Self {
    ScopeRunner {
        runner: Box::new(move || scope.run())
    }
}

I don't understand why this is different. To me it seems the lifetime of the generic Scope would be the same as the concrete version.

Body:
The problem is that S could be any type with a Scope impl, which includes all kinds of not-yet-existing types that carry references to other types. For example you could have an implementation like this:

struct AnotherScope<'a> {
    reference: &'str,
}

impl Scope for ScopeImpl {
    fn run(&self) -> String {
        self.reference.to_string()
    }
}

Rust is cautious and wants to make sure that this will work for any qualifying S, including if it contains references.

The easiest fix is to do as the error note suggests and just disallow S from having any non-static references:

fn new<S: Scope + 'static>(scope: S) -> Self {
    ScopeRunner {
        runner: Box::new(move || scope.run())
    }
}

Bounding S with 'static effectively means that S can contain either references to values with a 'static lifetime or no references at all.

If you want to be a bit more flexible, you can broaden that to references that outlive the ScopeRunner itself:

struct ScopeRunner<'s> {
    runner: Box<dyn Fn() -> String + 's>,
}

impl<'s> ScopeRunner<'s> {
    fn new<S: Scope + 's>(scope: S) -> Self {
        ScopeRunner {
            runner: Box::new(move || scope.run())
        }
    }

    pub fn run(self) -> String {
        (self.runner)()
    }
}


问:
C# convert monochrome image (1bpp) to grayscale one (8bpp)

I've tried to convert an image from 1bpp to 8bpp:

```<code>    BitmapData dstData = dstImage.LockBits(
    new Rectangle(0, 0, dstImage.Width, dstImage.Height),
    ImageLockMode.ReadWrite, dstImage.PixelFormat);

    try
    {
    int width = srcData.Width;
    int height = srcData.Height;

    unsafe
    {
        byte* srcBase = (byte*)srcData.Scan0.ToPointer();
        byte* dstBase = (byte*)dstData.Scan0.ToPointer();
        int srcStride = srcData.Stride;
        int dstStride = dstData.Stride;

        for (int y = 0; y < height; y++)
        {
            ushort* src = (ushort*)(srcBase + y * srcStride);
            ushort* dst = (ushort*)(dstBase + y * dstStride);

            for (int x = 0; x < width; x++)
            {
                byte mask = (byte)(0x80 >> (x & 0x07));
                *dst = ((*src) & mask) != 0 ? (ushort)255 : (ushort)0;
                if (mask == 1)
                {
                    src++;
                }

                dst++;
            }
        }
    }
}
finally
{
    dstImage.UnlockBits(dstData);
}
</code>```

The new image is not the expected gray-scale one. The algho for setting the pixel value seems to be wrong.

答:
var src = srcBase + y * srcStride;
                        var dst = dstBase + y * dstStride;</p>

```<code>                    for (int x = 0; x < width; x++, dst++)
                    {
                        byte mask = (byte)(0x80 >> (x & 0x07));
                        *dst = ((*src) & mask) != 0 ? (byte)255 : (byte)0;
                        if (mask == 1)
                        {
                            src++;
                        }
                    }
</code>```

Body:
I've tried to convert an image from 1bpp to 8bpp:

    BitmapData dstData = dstImage.LockBits(
    new Rectangle(0, 0, dstImage.Width, dstImage.Height),
    ImageLockMode.ReadWrite, dstImage.PixelFormat);

    try
    {
    int width = srcData.Width;
    int height = srcData.Height;

    unsafe
    {
        byte* srcBase = (byte*)srcData.Scan0.ToPointer();
        byte* dstBase = (byte*)dstData.Scan0.ToPointer();
        int srcStride = srcData.Stride;
        int dstStride = dstData.Stride;

        for (int y = 0; y < height; y++)
        {
            ushort* src = (ushort*)(srcBase + y * srcStride);
            ushort* dst = (ushort*)(dstBase + y * dstStride);

            for (int x = 0; x < width; x++)
            {
                byte mask = (byte)(0x80 >> (x & 0x07));
                *dst = ((*src) & mask) != 0 ? (ushort)255 : (ushort)0;
                if (mask == 1)
                {
                    src++;
                }

                dst++;
            }
        }
    }
}
finally
{
    dstImage.UnlockBits(dstData);
}

The new image is not the expected gray-scale one. The algho for setting the pixel value seems to be wrong.

Body:
var src = srcBase + y * srcStride;
                        var dst = dstBase + y * dstStride;

                    for (int x = 0; x < width; x++, dst++)
                    {
                        byte mask = (byte)(0x80 >> (x & 0x07));
                        *dst = ((*src) & mask) != 0 ? (byte)255 : (byte)0;
                        if (mask == 1)
                        {
                            src++;
                        }
                    }


问:
Can the vanilla JS date object be used normally in React.js?
I'm trying to get the last date of the current month so I can accurately display calendar days so I'm using the vanilla JS date object. However, from what I've seen by console logging the date object, it seems as though it's a completely different object, presumably a react object. So how can I access the date object?

I've tried using the toString method to unwrap the date object into a string which didn't work because it turns into an array with the object in it.

```<code>componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    console.log(date)
}
</code>```

I expect the date object to be outputted instead of the unknown object

EDIT:

The unknown object looks like this in the console:

```<code>{$$typeof: Symbol(react.element), type: "div", key: null, ref: null,
props: {…}, …}
</code>```

DOUBLE EDIT:

Here's the  minimum reproducible code.

So while doing this I figured out that the date changes from the default
date structure
Ex. Mon May 27 2019 16:00:56 etc. to the other object when I import in the Date component for some reason.

File App.js

```<code>import React from "react";
import Calendar from "./Calendar"

function App() {
    return (
        <div>
            <Calendar />
        </div>

    )
}

export default App;
</code>```

File Calendar.js

```<code>import React from "react";
import Date from "./Date";

class Calendar extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        let date = new Date();
        console.log(date)
    }

    render() {
        return (
            <Date />
        )
    }
}

export default Calendar;
</code>```

File Date.js

```<code>import React from "react";

function Date() {
    return (
        <div className="grid date">
            <p>1</p>
        </div>
    )
}

export default Date;
</code>```

答:
Yes Dates are used normally in React. </p>

<p>One way to work with dates would be the moment.js library. So you can do something like: </p>

```<code>componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    let formatted_date = moment(date).format('MMMM Do, YYYY | h:mm a')
    console.log(formatted_date)
}
</code>```

Body:
I'm trying to get the last date of the current month so I can accurately display calendar days so I'm using the vanilla JS date object. However, from what I've seen by console logging the date object, it seems as though it's a completely different object, presumably a react object. So how can I access the date object?

I've tried using the toString method to unwrap the date object into a string which didn't work because it turns into an array with the object in it.

componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    console.log(date)
}

I expect the date object to be outputted instead of the unknown object

EDIT:

The unknown object looks like this in the console:

{$$typeof: Symbol(react.element), type: "div", key: null, ref: null,
props: {…}, …}

DOUBLE EDIT:

Here's the  minimum reproducible code.

So while doing this I figured out that the date changes from the default
date structure
Ex. Mon May 27 2019 16:00:56 etc. to the other object when I import in the Date component for some reason.

File App.js

import React from "react";
import Calendar from "./Calendar"

function App() {
    return (

            <Calendar />

    )
}

export default App;

File Calendar.js

import React from "react";
import Date from "./Date";

class Calendar extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        let date = new Date();
        console.log(date)
    }

    render() {
        return (
            <Date />
        )
    }
}

export default Calendar;

File Date.js

import React from "react";

function Date() {
    return (

1

    )
}

export default Date;

Body:
Yes Dates are used normally in React.

One way to work with dates would be the moment.js library. So you can do something like:

componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    let formatted_date = moment(date).format('MMMM Do, YYYY | h:mm a')
    console.log(formatted_date)
}


问:
Duplicate data when testing with nodejs/mocha/mongoose
I'm running asynchronous tests with nodeJS/mocha/mongoose and I keep getting duplicate documents in my collection when I run a test like the following.

```<code>const assert = require('assert');
const User = require('../src/user');

describe('Duplicates records test', () => {

    beforeEach((done) => {
        let user = new User({ name: 'Bob'});
        user.save()
            .then(() => done());
    });

    it('Return users named Bob', (done) => {
        User.find({ name: 'Bob' })
            .then((users) => {
                console.log(users);
                done();
            });

    });
});
</code>```

The following is the model I'm using:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: String
});

const User = mongoose.model('user', UserSchema);

module.exports = User;
</code>```

The following is the output from running the test:

```<code>[ { _id: 5c918ca6d4b6eb4416312226, name: 'Bob', __v: 0 },
{ _id: 5c918ca6c2589d4415a4317a, name: 'Bob', __v: 0 } ]

1 passing (2s)
</code>```

And finally the output from mongodb:

```<code>> db.users.find().pretty()
{ "_id" : ObjectId("5c918ca6d4b6eb4416312226"), "name" : "Bob", "__v" : 0 }
{ "_id" : ObjectId("5c918ca6c2589d4415a4317a"), "name" : "Bob", "__v" : 0 }
</code>```

I have several tests like this in my suite and this only seems to happen when I save records inside of a beforeEach statement. Any insight as to why this is happening would be greatly appreciated.

答:
This is probably happening because you have no logic to drop the previous record saved when you fire off the next test.

To avoid duplicate records when you are testing with NodeJS/Mocha/mongoose you want to add some logic to drop the collections at least when running your server for testing.

You have not shared your package.json file, but I would recommend a script that looks like this:

```<code>"scripts": {
    "test": "NODE_ENV=test nodemon --exec 'mocha --recursive -R min'"
  },
</code>```

So NODE_ENV is an environment variable and environment variables are used to customize the behavior or encode some constants to access inside an application and you can use NODE_ENV variable to specify if the server is running in development, production or whatever.

So this will help you in seeing if it needs to empty out the collection of users.

To do so, you can make a reference to the variable process.env.NODE_ENV.

Wherever you are making your connection to Mongo, you want to add an if statement like so:

```<code>if (process.env.NODE_ENV !== "test") {
  mongoose.connect("mongodb://localhost/user", { useMongoClient: true });
}
</code>```

So what you are saying here is, when running in development just start up the sever and connect to the database but when running in test, start up the server, connect to the database and drop the collections, but that is not the solution in and of itself.

What I would recommend is creating a separate database that would be called user_test and then create a separate helper file with the logic for connecting to that database.

So you are going to have two separate databases.

So in the if statement above you are saying if I am running in a development or production environment, if its not equal to test, then connect to this database. If I am running in test do not connect to this database.

Then you add that test helper file to the application that will be used to connect to mongoose. Why a separate test helper file? because it will make it easier to ensure the test suite only starts up once the connection to the test database has been achieved.

Keep in mind that Mocha and Mongoose don't really play well together or at least not in my opinion.

This is also helpful because you do not have to wrap the connection string with an if statement to check if you are in the test environment. If the test helper file is executed then yeah you are in the test environment so you don’t have to make it explicit. That logic would look something like this:

```<code>const mongoose = require(‘mongoose’);

before((done) => {
    mongoose.connect("mongodb://localhost/user_test”, { useMongoClient: true });
});
</code>```

So now the user_test database can get dropped all day long and nothing bad is going to happen, you won’t be touching the development data and so later you can even customize that development database to have some data that you might want to have stick around.

You also place handlers for looking at the connection status and once the connection is open you can use a done callback like so:

```<code>const mongoose = require(‘mongoose’);

before((done) => {
    mongoose.connect("mongodb://localhost/user_test”, { useMongoClient: true });
    mongoose.connection.once(‘open’, () => done())
});
</code>```

If there is ever an error you can launch a console.warn() like so:

```<code>const mongoose = require(‘mongoose’);

before((done) => {
    mongoose.connect("mongodb://localhost/muber_test”, { useMongoClient: true });
    mongoose.connection.once(‘open’, () => done()).on(‘error’, (err) => {
        console.warn(‘Warning’, error);
    });
});
</code>```

I like this solution because if you locate all the logic inside of the test itself, sometimes Mocha will execute the test before the connection has been made to the database which means all the tests will fail as a result.

Almost forgot the most important part, dropping the collection:

```<code>const mongoose = require(‘mongoose’);

    before((done) => {
        mongoose.connect("mongodb://localhost/muber_test”, { useMongoClient: true });
        mongoose.connection.once(‘open’, () => done()).on(‘error’, (err) => {
            console.warn(‘Warning’, error);
        });
    });

beforeEach((done) => {
    const { users } = mongoose.connection.collections;
    users.drop().then(() => done()).catch(() => done());
});
</code>```

The reason we have that catch() in there for done() is that it handles the very first time your database runs, you do not have yet a users collection in existence and that would throw an error and that's why we add that to handle the case.

Body:
I'm running asynchronous tests with nodeJS/mocha/mongoose and I keep getting duplicate documents in my collection when I run a test like the following.

const assert = require('assert');
const User = require('../src/user');

describe('Duplicates records test', () => {

    beforeEach((done) => {
        let user = new User({ name: 'Bob'});
        user.save()
            .then(() => done());
    });

    it('Return users named Bob', (done) => {
        User.find({ name: 'Bob' })
            .then((users) => {
                console.log(users);
                done();
            });

    });
});

The following is the model I'm using:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: String
});

const User = mongoose.model('user', UserSchema);

module.exports = User;

The following is the output from running the test:

[ { _id: 5c918ca6d4b6eb4416312226, name: 'Bob', __v: 0 },
{ _id: 5c918ca6c2589d4415a4317a, name: 'Bob', __v: 0 } ]

1 passing (2s)

And finally the output from mongodb:

> db.users.find().pretty()
{ "_id" : ObjectId("5c918ca6d4b6eb4416312226"), "name" : "Bob", "__v" : 0 }
{ "_id" : ObjectId("5c918ca6c2589d4415a4317a"), "name" : "Bob", "__v" : 0 }

I have several tests like this in my suite and this only seems to happen when I save records inside of a beforeEach statement. Any insight as to why this is happening would be greatly appreciated.

Body:
This is probably happening because you have no logic to drop the previous record saved when you fire off the next test.

To avoid duplicate records when you are testing with NodeJS/Mocha/mongoose you want to add some logic to drop the collections at least when running your server for testing.

You have not shared your package.json file, but I would recommend a script that looks like this:

"scripts": {
    "test": "NODE_ENV=test nodemon --exec 'mocha --recursive -R min'"
  },

So NODE_ENV is an environment variable and environment variables are used to customize the behavior or encode some constants to access inside an application and you can use NODE_ENV variable to specify if the server is running in development, production or whatever.

So this will help you in seeing if it needs to empty out the collection of users.

To do so, you can make a reference to the variable process.env.NODE_ENV.

Wherever you are making your connection to Mongo, you want to add an if statement like so:

if (process.env.NODE_ENV !== "test") {
  mongoose.connect("mongodb://localhost/user", { useMongoClient: true });
}

So what you are saying here is, when running in development just start up the sever and connect to the database but when running in test, start up the server, connect to the database and drop the collections, but that is not the solution in and of itself.

What I would recommend is creating a separate database that would be called user_test and then create a separate helper file with the logic for connecting to that database.

So you are going to have two separate databases.

So in the if statement above you are saying if I am running in a development or production environment, if its not equal to test, then connect to this database. If I am running in test do not connect to this database.

Then you add that test helper file to the application that will be used to connect to mongoose. Why a separate test helper file? because it will make it easier to ensure the test suite only starts up once the connection to the test database has been achieved.

Keep in mind that Mocha and Mongoose don't really play well together or at least not in my opinion.

This is also helpful because you do not have to wrap the connection string with an if statement to check if you are in the test environment. If the test helper file is executed then yeah you are in the test environment so you don’t have to make it explicit. That logic would look something like this:

const mongoose = require(‘mongoose’);

before((done) => {
    mongoose.connect("mongodb://localhost/user_test”, { useMongoClient: true });
});

So now the user_test database can get dropped all day long and nothing bad is going to happen, you won’t be touching the development data and so later you can even customize that development database to have some data that you might want to have stick around.

You also place handlers for looking at the connection status and once the connection is open you can use a done callback like so:

const mongoose = require(‘mongoose’);

before((done) => {
    mongoose.connect("mongodb://localhost/user_test”, { useMongoClient: true });
    mongoose.connection.once(‘open’, () => done())
});

If there is ever an error you can launch a console.warn() like so:

const mongoose = require(‘mongoose’);

before((done) => {
    mongoose.connect("mongodb://localhost/muber_test”, { useMongoClient: true });
    mongoose.connection.once(‘open’, () => done()).on(‘error’, (err) => {
        console.warn(‘Warning’, error);
    });
});

I like this solution because if you locate all the logic inside of the test itself, sometimes Mocha will execute the test before the connection has been made to the database which means all the tests will fail as a result.

Almost forgot the most important part, dropping the collection:

const mongoose = require(‘mongoose’);

    before((done) => {
        mongoose.connect("mongodb://localhost/muber_test”, { useMongoClient: true });
        mongoose.connection.once(‘open’, () => done()).on(‘error’, (err) => {
            console.warn(‘Warning’, error);
        });
    });

beforeEach((done) => {
    const { users } = mongoose.connection.collections;
    users.drop().then(() => done()).catch(() => done());
});

The reason we have that catch() in there for done() is that it handles the very first time your database runs, you do not have yet a users collection in existence and that would throw an error and that's why we add that to handle the case.


问:
Why does mutate not act like I expect in this code?
I have a confusion regarding how the mutate in tidyverse/ dplyr works. I have included a reproducible example here. One uses mutate and one uses a loop. I would expect both to give the same result, but they do not. I have no idea why. Any help would be appreciated.

```<code>library(tidyverse)
d <- data.frame(x = c('a,a,b,b,b','a,a','a,b,b,b,c,c,c'))
# Approach 1 (mutate)
d %>%
  mutate(y = paste(unique(str_split(x, ',')[[1]]), collapse = ','))
d
# Approach 2 (loop)
for (i in 1:nrow(d))
{
  d$y[i] <- paste(unique(str_split(d$x[i], ',')[[1]]), collapse = ',')
}
d
</code>```

I expect output to be the same for both approaches, but they are not.

答:
Issue is that we are subsetting only first list element with [[1]] and then the unique is only on that element.  Instead, we need to loop through the list (from str_split output)

```<code>library(tidyverse)
d %>%
     mutate(y = str_split(x, ',') %>%  # output is a list
                   map_chr(~ unique(.x) %>% # loop with map, get the unique elements
                    toString)) # paste the strings together
#             x       y
#1     a,a,b,b,b    a, b
#2           a,a       a
#3 a,b,b,b,c,c,c a, b, c
</code>```

In the for loop, it was not the case because the splitting was done one element at a time str_split(d$x[i]

To understand better, the str_split (strsplit base R) is vectorized.  They can take multiple strings and split into alistofvector`s equal to the length of the intial vector

```<code>str_split(d$x, ',') # list of length 3
#[[1]]
#[1] "a" "a" "b" "b" "b"

#[[2]]
#[1] "a" "a"

#[[3]]
#[1] "a" "b" "b" "b" "c" "c" "c"
</code>```

Extracting the first [[1]]

```<code>str_split(d$x, ',')[[1]]
#[1] "a" "a" "b" "b" "b"
</code>```

In the for loop, we are individually splitting the elements and extract the list (length 1) element

```<code>str_split(d$x[1], ',')[[1]]
#[1] "a" "a" "b" "b" "b"
str_split(d$x[2], ',')[[1]]
#[1] "a" "a"
</code>```

That is the reason, we need to loop over the list and then get the unique from each of the elements

Body:
I have a confusion regarding how the mutate in tidyverse/ dplyr works. I have included a reproducible example here. One uses mutate and one uses a loop. I would expect both to give the same result, but they do not. I have no idea why. Any help would be appreciated.

library(tidyverse)
d <- data.frame(x = c('a,a,b,b,b','a,a','a,b,b,b,c,c,c'))
# Approach 1 (mutate)
d %>%
  mutate(y = paste(unique(str_split(x, ',')[[1]]), collapse = ','))
d
# Approach 2 (loop)
for (i in 1:nrow(d))
{
  d$y[i] <- paste(unique(str_split(d$x[i], ',')[[1]]), collapse = ',')
}
d

I expect output to be the same for both approaches, but they are not.

Body:
Issue is that we are subsetting only first list element with [[1]] and then the unique is only on that element.  Instead, we need to loop through the list (from str_split output)

library(tidyverse)
d %>%
     mutate(y = str_split(x, ',') %>%  # output is a list
                   map_chr(~ unique(.x) %>% # loop with map, get the unique elements
                    toString)) # paste the strings together
#             x       y
#1     a,a,b,b,b    a, b
#2           a,a       a
#3 a,b,b,b,c,c,c a, b, c

In the for loop, it was not the case because the splitting was done one element at a time str_split(d$x[i]

To understand better, the str_split (strsplit base R) is vectorized.  They can take multiple strings and split into alistofvector`s equal to the length of the intial vector

str_split(d$x, ',') # list of length 3
#[[1]]
#[1] "a" "a" "b" "b" "b"

#[[2]]
#[1] "a" "a"

#[[3]]
#[1] "a" "b" "b" "b" "c" "c" "c"

Extracting the first [[1]]

str_split(d$x, ',')[[1]]
#[1] "a" "a" "b" "b" "b"

In the for loop, we are individually splitting the elements and extract the list (length 1) element

str_split(d$x[1], ',')[[1]]
#[1] "a" "a" "b" "b" "b"
str_split(d$x[2], ',')[[1]]
#[1] "a" "a"

That is the reason, we need to loop over the list and then get the unique from each of the elements


答:
The JavaScript Date object has built-in methods you can use to format the date into a string:</p>

```<code>componentDidMount() {
    let date = new Date();
    console.log(date.toLocaleDateString()) // "5/27/2019"
}
</code>```

Title: Can the vanilla JS date object be used normally in React.js?

Body:
The JavaScript Date object has built-in methods you can use to format the date into a string:

componentDidMount() {
    let date = new Date();
    console.log(date.toLocaleDateString()) // "5/27/2019"
}


问:
How to read variable values in Python cplex api?
I have modeled a MIP problem in Python Cplex API. Is there any way to read variable values - variable-wise?

Currently I am reading variable values into a list and mapping those from the LP file"

```<code>    for i, j in zip(cpx.variables.get_names(), cpx.solution.get_values()):
        cplex_details_inp.append((i, j))
</code>```

By this method, I am able to read all variable values at a time,
but this method is causing memory issue due to the fact that there are 500k variables.

How to read values variable wise?  I don't find any specific document or examples for this.

答:
Looking at the reference documentation we can see that there are various options to call this function:

solution.get_values()
return the values of all variables from the problem.

solution.get_values(i)
i must be a variable name or index. Returns the value of the variable whose index or name is i.

solution.get_values(s)
s must be a sequence of variable names or indices. Returns the values of the variables with indices the members of s. Equivalent to [solution.get_values(i) for i in s]

solution.get_values(begin, end)
begin and end must be variable indices or variable names. Returns the values of the variables with indices between begin and end, inclusive of end. Equivalent to solution.get_values(range(begin, end + 1)).

So you can specify as argument to the function just the variables for which you want to read the variables. Either specify variables one by one or read variables in chunks.

Body:
I have modeled a MIP problem in Python Cplex API. Is there any way to read variable values - variable-wise?

Currently I am reading variable values into a list and mapping those from the LP file"

    for i, j in zip(cpx.variables.get_names(), cpx.solution.get_values()):
        cplex_details_inp.append((i, j))

By this method, I am able to read all variable values at a time,
but this method is causing memory issue due to the fact that there are 500k variables.

How to read values variable wise?  I don't find any specific document or examples for this.


问:
Alphabetically enumerate files in directories with attributes
I'm trying to enumerate in alphabetical order two lists of files based on different directories.

One list is the files in my directory using the following code:

```<code>import os
file_list = os.listdir('./')
for x in file_list:
    print(x)
</code>```

which will return

```<code>file_b.py
file_c.py
file_d.txt
</code>```

Issue being one list is coming from a github repository

```<code>from github import Github
g = Github("token")
repo = g.get_repo("Name/Repo")
for content in repo.get_contents("files"):
    print(content.name)
</code>```

Which will return

```<code>File_a.py
File_b.c
File_c.txt
File_d.py
</code>```

For now I'm using zip to do as follows:

```<code>from github import Github
import os
g = Github("token")
repo = g.get_repo("Name/Repo")
content = repo.get_contents("files")

for elt, (x, y) in enumerate(zip(content, os.listdir('./'))):
    if x.name.endswith('.py'):
        print('[{}] {}'.center(79).format(str(elt), x.name))
    if y.endswith('.py'):
        print('[{}] {}'.center(79).format(str(elt), y))
</code>```

Now issue is that in my content list has a ".name" attribute while my os dirlist doesn't

So what I'd like to get is:

```<code>                                    [0] file_a.py
                                    [1] file_b.py
                                    [2] file_c.py
                                    [3] file_d.py
</code>```

However what I get is:

```<code>                                    [0] file_a.py
                                    [0] file_b.py
                                    [1] file_d.py
                                    [1] file_c.py

</code>```

I'm not sure how I would go to fix this? Is there anyway to sort and enumerate two lists with attributes while keeping the number consistent? And at the same time order it alphabetically?

答:
You should create and sort your list of file names before iteration</p>

```<code>import os
g = Github("token")
repo = g.get_repo("Name/Repo")
file_names = repo.get_contents("files")
file_names.extend([f.name for f in os.listdir('./')])

for index, file_name in enumerate(sorted(file_names)):
    if file_name.endswith('.py'):
        print('[{}] {}'.center(79).format(str(index), file_name))
</code>```

Body:
I'm trying to enumerate in alphabetical order two lists of files based on different directories.

One list is the files in my directory using the following code:

import os
file_list = os.listdir('./')
for x in file_list:
    print(x)

which will return

file_b.py
file_c.py
file_d.txt

Issue being one list is coming from a github repository

from github import Github
g = Github("token")
repo = g.get_repo("Name/Repo")
for content in repo.get_contents("files"):
    print(content.name)

Which will return

File_a.py
File_b.c
File_c.txt
File_d.py

For now I'm using zip to do as follows:

from github import Github
import os
g = Github("token")
repo = g.get_repo("Name/Repo")
content = repo.get_contents("files")

for elt, (x, y) in enumerate(zip(content, os.listdir('./'))):
    if x.name.endswith('.py'):
        print('[{}] {}'.center(79).format(str(elt), x.name))
    if y.endswith('.py'):
        print('[{}] {}'.center(79).format(str(elt), y))

Now issue is that in my content list has a ".name" attribute while my os dirlist doesn't

So what I'd like to get is:

                                    [0] file_a.py
                                    [1] file_b.py
                                    [2] file_c.py
                                    [3] file_d.py

However what I get is:

                                    [0] file_a.py
                                    [0] file_b.py
                                    [1] file_d.py
                                    [1] file_c.py

I'm not sure how I would go to fix this? Is there anyway to sort and enumerate two lists with attributes while keeping the number consistent? And at the same time order it alphabetically?

Body:
You should create and sort your list of file names before iteration

import os
g = Github("token")
repo = g.get_repo("Name/Repo")
file_names = repo.get_contents("files")
file_names.extend([f.name for f in os.listdir('./')])

for index, file_name in enumerate(sorted(file_names)):
    if file_name.endswith('.py'):
        print('[{}] {}'.center(79).format(str(index), file_name))


问:
R Setter method in class
When I write a setter method in a class, the setter method does not change the value. I just cannot find the error here.</p>

```<code>point <- function(x,y){
  structure(class = "point", list(
    # attributes
    x = x,
    y = y,
    # methods
    get_x = function() paste("(", x,",",y,")"),
    set_x = function(x,y){ self.x = x; self.y =  y}

  ))}

> p <- point(0,1)
> p$get_x()
[1] "( 0 , 1 )"

> p$set_x(6,5)
> p$get_x()

[1] "( 0 , 1 )"
</code>```

答:
Try to follow this change to your code.

In function set_x, it is the values of variables x and y created in function point that are assigned new values with <<-, not the x and y that exist in the .GlobalEnv.

```<code>point <- function(x, y){
  structure(class = "point", list(
    x = x,
    y = y,
    get_x = function() paste("(", x,",",y,")"),
    set_x = function(x, y){
      x <<- x
      y <<- y
    }
  ))
}

x <- 0
y <- 1

p <- point(0,1)
p$get_x()
#[1] "( 0 , 1 )"

p$set_x(6,5)
p$get_x()
#[1] "( 6 , 5 )"

x
#[1] 0

y
#[1] 1
</code>```

Title: R Setter method in class

Body:
When I write a setter method in a class, the setter method does not change the value. I just cannot find the error here.

point <- function(x,y){
  structure(class = "point", list(
    # attributes
    x = x,
    y = y,
    # methods
    get_x = function() paste("(", x,",",y,")"),
    set_x = function(x,y){ self.x = x; self.y =  y}

  ))}

> p <- point(0,1)
> p$get_x()
[1] "( 0 , 1 )"

> p$set_x(6,5)
> p$get_x()

[1] "( 0 , 1 )"

Body:
Try to follow this change to your code.

In function set_x, it is the values of variables x and y created in function point that are assigned new values with <<-, not the x and y that exist in the .GlobalEnv.

point <- function(x, y){
  structure(class = "point", list(
    x = x,
    y = y,
    get_x = function() paste("(", x,",",y,")"),
    set_x = function(x, y){
      x <<- x
      y <<- y
    }
  ))
}

x <- 0
y <- 1

p <- point(0,1)
p$get_x()
#[1] "( 0 , 1 )"

p$set_x(6,5)
p$get_x()
#[1] "( 6 , 5 )"

x
#[1] 0

y
#[1] 1


问:
How to call callback provided by render prop from its parent component using hooks between renders
I'm trying to close a popover that can only be closed via a close callback in its render props. I was wondering how I can use hooks or some other strategy to save this callback function between renders to call it in a useEffect.  I tried using useContext to no avail: https://codesandbox.io/s/popover-close-from-content-y637f</p>

答:
You could use a ref to save the close function for use in useEffect. Here is a working codesandbox: https://codesandbox.io/s/popover-close-from-content-sgmgs

```<code>import React, { useEffect, useState, useRef } from "react";
import { Block } from "baseui/block";
import { Button } from "baseui/button";
import { StatefulPopover } from "baseui/popover";

export default () => {
  const closeRef = useRef();
  const [state, setState] = useState({ isSaving: false });
  useEffect(() => {
    if (state.isSaving) {
      const timeout = setTimeout(() => {
        console.log("closing", closeRef.current);
        // close popover from here
        closeRef.current && closeRef.current();
        setState({ isSaving: false });
      }, 5000);

      return () => {
        clearTimeout(timeout);
      };
    }
  }, [state.isSaving]);
  const onSave = () => {
    console.log("save btn clicked");
    setState({ isSaving: true });
  };
  return (
    <div>
      <StatefulPopover
        content={(
          { close } // I need to call close per this library's API to close
        ) => {
          closeRef.current = close;
          return (
            <Block padding="scale500" maxWidth="300px">
              <Block paddingBottom="scale400">
                content render prop is passed a <code>close()</code> callback so
                it you can manually trigger popover close from within
              </Block>
              <Button isLoading={state.isSaving} onClick={onSave}>
                Save
              </Button>
            </Block>
          );
        }}
      >
        <Button>Click Me</Button>
      </StatefulPopover>
    </div>
  );
};
</code>```

Context isn't working as you expect because you are attempting to access the context using useContext outside of the Provider. In order to access the value from the Provider, the useContext hooks must be utilized inside of a child component of the context Provider. Otherwise, the useContext will just get the default value passed into createContext.

Body:
You could use a ref to save the close function for use in useEffect. Here is a working codesandbox: https://codesandbox.io/s/popover-close-from-content-sgmgs

import React, { useEffect, useState, useRef } from "react";
import { Block } from "baseui/block";
import { Button } from "baseui/button";
import { StatefulPopover } from "baseui/popover";

export default () => {
  const closeRef = useRef();
  const [state, setState] = useState({ isSaving: false });
  useEffect(() => {
    if (state.isSaving) {
      const timeout = setTimeout(() => {
        console.log("closing", closeRef.current);
        // close popover from here
        closeRef.current && closeRef.current();
        setState({ isSaving: false });
      }, 5000);

      return () => {
        clearTimeout(timeout);
      };
    }
  }, [state.isSaving]);
  const onSave = () => {
    console.log("save btn clicked");
    setState({ isSaving: true });
  };
  return (
    <div>
      <StatefulPopover
        content={(
          { close } // I need to call close per this library's API to close
        ) => {
          closeRef.current = close;
          return (
            <Block padding="scale500" maxWidth="300px">
              <Block paddingBottom="scale400">
                content render prop is passed a <code>close()</code> callback so
                it you can manually trigger popover close from within
              </Block>
              <Button isLoading={state.isSaving} onClick={onSave}>
                Save
              </Button>
            </Block>
          );
        }}
      >
        <Button>Click Me</Button>
      </StatefulPopover>
    </div>
  );
};

Context isn't working as you expect because you are attempting to access the context using useContext outside of the Provider. In order to access the value from the Provider, the useContext hooks must be utilized inside of a child component of the context Provider. Otherwise, the useContext will just get the default value passed into createContext.


问:
Remove White Spaces Between HTML Sections
Please how do I remove the white spaces in between the html sections when page is rendered on the browser.

Get the freedom you deserve.

        Support

        Terms of Use

```

答:
Two of the HTML elements you used have margin by default. Both h1 and ul tags come with margin-top and margin-bottom by default. You must either use a reset/normalize stylesheet or remember to account for the margins in your own CSS.

#product-overview {
  background: #eee; /* just for demo so you can see the layout better */
}

#product-overview h1 {
  margin: 0;
}

.main-footer {
  background: #ddd; /* just for demo so you can see the layout better */
}

.footer-ul__list {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="product-overview">
  <h1>Get the freedom you deserve.</h1>
</section>

<footer class="main-footer">
  <nav>
    <ul class="footer-ul__list">
      <li class="footer__link">
        Support
      </li>
      <li class="footer__link">
        Terms of Use
      </li>
    </ul>
  </nav>
</footer></code>```

Body:
Two of the HTML elements you used have margin by default. Both h1 and ul tags come with margin-top and margin-bottom by default. You must either use a reset/normalize stylesheet or remember to account for the margins in your own CSS.

#product-overview {
  background: #eee; /* just for demo so you can see the layout better */
}

#product-overview h1 {
  margin: 0;
}

.main-footer {
  background: #ddd; /* just for demo so you can see the layout better */
}

.footer-ul__list {
  margin: 0;
}

<section id="product-overview">
  <h1>Get the freedom you deserve.</h1>
</section>

<footer class="main-footer">
  <nav>
    <ul class="footer-ul__list">
      <li class="footer__link">
        <a href="#">Support</a>
      </li>
      <li class="footer__link">
        <a href="#">Terms of Use</a>
      </li>
    </ul>
  </nav>
</footer>


问:
Ruby : How to record an object and reuse it for tests?
In Ruby-on-Rails, how to record an object and its state (in development mode) so that I can use it for testing purpose ? For example the request object, but more generally any complicated object, whether I own the class definition or not.</p>

答:
One option is to use Marshal, which is built into ruby natively (i.e., not specific to Rails). You can use Marshal to serialize objects to strings via serialized_obj = Marshal.dump(my_object). You can store those strings in files and then deserialize them in your test suite via my_obj = Marshal.load(serialized_obj). Here's an example from this great writeup by Mehdi Farsi, https://blog.appsignal.com/2019/03/26/object-marshalling-in-ruby.html.

```<code>hello_world = 'hello world!'

serialized_string = Marshal.dump(hello_world) # => "\x04\bI\"\x11hello world!\x06:\x06ET"
serialized_string.class                       # => String

deserialized_hello_world = Marshal.load(serialized_string) # => "hello world!"

hello_world.object_id              # => 70204420126020
deserialized_hello_world.object_id # => 70204419825700
</code>```

Body:
One option is to use Marshal, which is built into ruby natively (i.e., not specific to Rails). You can use Marshal to serialize objects to strings via serialized_obj = Marshal.dump(my_object). You can store those strings in files and then deserialize them in your test suite via my_obj = Marshal.load(serialized_obj). Here's an example from this great writeup by Mehdi Farsi, https://blog.appsignal.com/2019/03/26/object-marshalling-in-ruby.html.

hello_world = 'hello world!'

serialized_string = Marshal.dump(hello_world) # => "\x04\bI\"\x11hello world!\x06:\x06ET"
serialized_string.class                       # => String

deserialized_hello_world = Marshal.load(serialized_string) # => "hello world!"

hello_world.object_id              # => 70204420126020
deserialized_hello_world.object_id # => 70204419825700


问:
How to append script tag/JS to textarea as text (non executeable)
How would I go about printing out html tags / javascript as text in a textarea? (non-executeable)

I tried appending the JS/script tags, but that doesn't seem to append as text (= doesn't show anything in the textarea)

Jquery

```<code>  $('#textarea').append('' +
    '<script type="text/javascript">' +
        'adf.Params.PageName = encodeURIComponent("[hello]");' +
        'adf.Params.Divider = encodeURIComponent("|");' +
    '</script>' +
  '');
</code>```

HTML

```<code><textarea rows="12" cols="50" name="textarea" id="textarea"></textarea>
</code>```

JSFiddle here

答:
It appears to be having an issue related to the script tags.  One option is to encode the < character on the open and close script tags so that they will not be evaluated as actual tags.

var text = '';

$('#textarea').append(text);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="12" cols="50" name="textarea" id="textarea"></textarea></code>```

Body:
How would I go about printing out html tags / javascript as text in a textarea? (non-executeable)

I tried appending the JS/script tags, but that doesn't seem to append as text (= doesn't show anything in the textarea)

Jquery

  $('#textarea').append('' +
    '' +
  '');

HTML

<textarea rows="12" cols="50" name="textarea" id="textarea"></textarea>

JSFiddle here

Body:
It appears to be having an issue related to the script tags.  One option is to encode the < character on the open and close script tags so that they will not be evaluated as actual tags.

var text = '&lt;script type="text/javascript">\n\t' +
  'adf.Params.PageName = encodeURIComponent("[hello]");\n\t' +
  'adf.Params.Divider = encodeURIComponent("|");\n' +
  '&lt;/script>';

$('#textarea').append(text);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="12" cols="50" name="textarea" id="textarea"></textarea>


问:
Optimal way of creating object from two objects
I built this, which is working fine, it takes about 7-9 seconds to run and display.
I'm wondering, is there a faster/optimal way of building this custom object?

As you can see, I want all the drivers information from Win32_PNPsigneddriver but to that, I add two other properties from Win32_PNPentity (configmanagererrorcode and status) based on the DeviceID.

This way, the final object contains all drivers and shows if there is an error for the device using that driver.

```<code>$poste = "COMPUTER1234"

$DriversUp = Get-WmiObject -computername $poste Win32_PNPsigneddriver |
             Where-Object {$_.DeviceName -ne $null}
$Devices = Get-WmiObject -computername $poste Win32_PNPentity

$DriversDevices = foreach ($driver in $DriversUp) {
    $driver |
        Select-Object DeviceClass, Manufacturer, DeviceName,
            FriendlyName, DriverName, InfName,
            @{name='Status';expression={$Devices | Where-Object {$_.DeviceID -eq "$($driver.DeviceID)"} | Select-Object -ExpandProperty status}},
            @{name='ConfigManagerErrorCode';expression={$Devices | Where-Object {$_.DeviceID -eq "$($driver.DeviceID)"} | Select-Object -ExpandProperty ConfigManagerErrorCode}},
            @{name='DriverDate';expression={[DateTime]::ParseExact(($_.DriverDate).Split('.')[0], "yyyyMMddHHmmss", [System.Globalization.CultureInfo]::InvariantCulture)}},
            DriverVersion
}

$DriversDevices |
    Sort-Object DeviceClass |
    Out-GridView -Title "$poste - Drivers utilisés"
</code>```

Like I said everything works fine already. However, I'm curious to know if there's a faster way!

答:
This is how I would do it, not big difference in performance, but more clear IMO:
Used an ArrayList for the results, also replaced the Where-Object on the Get-WmiObject with -Filter, it's a bit faster...

```<code>$poste = "COMPUTER1234"
$DriversUp = Get-WmiObject -computername $poste Win32_PNPsigneddriver -Filter "DeviceName != NULL"
$Devices = Get-WmiObject -computername $poste Win32_PNPentity

$DriversDevices = New-Object System.Collections.ArrayList

    foreach ($driver in $DriversUp) {

    $row = "" | Select DeviceClass,Manufacturer,DeviceName,FriendlyName,DriverName,
    InfName,Status,ConfigManagerErrorCode,DriverDate,DriverVersion

    $row.DeviceClass = $driver.DeviceClass
    $row.Manufacturer = $driver.Manufacturer
    $row.DeviceName = $driver.DeviceName
    $row.DriverName = $driver.DriverName
    $row.InfName = $driver.InfName
    $row.Status = ($Devices | ? {$_.DeviceID -eq $driver.DeviceID}).Status
    $row.ConfigManagerErrorCode = ($Devices | ? {$_.DeviceID -eq $driver.DeviceID}).ConfigManagerErrorCode
    $row.DriverDate = [datetime]::ParseExact(($driver.DriverDate.Split('.')[0]),"yyyyMMddHHmmss",$null)
    $row.DriverVersion = $driver.DriverVersion
    [void]$DriversDevices.Add($row)
    }

    $DriversDevices | Sort-Object DeviceClass | Out-GridView -Title "$poste - Drivers utilisés"
</code>```

Body:
I built this, which is working fine, it takes about 7-9 seconds to run and display.
I'm wondering, is there a faster/optimal way of building this custom object?

As you can see, I want all the drivers information from Win32_PNPsigneddriver but to that, I add two other properties from Win32_PNPentity (configmanagererrorcode and status) based on the DeviceID.

This way, the final object contains all drivers and shows if there is an error for the device using that driver.

$poste = "COMPUTER1234"

$DriversUp = Get-WmiObject -computername $poste Win32_PNPsigneddriver |
             Where-Object {$_.DeviceName -ne $null}
$Devices = Get-WmiObject -computername $poste Win32_PNPentity

$DriversDevices = foreach ($driver in $DriversUp) {
    $driver |
        Select-Object DeviceClass, Manufacturer, DeviceName,
            FriendlyName, DriverName, InfName,
            @{name='Status';expression={$Devices | Where-Object {$_.DeviceID -eq "$($driver.DeviceID)"} | Select-Object -ExpandProperty status}},
            @{name='ConfigManagerErrorCode';expression={$Devices | Where-Object {$_.DeviceID -eq "$($driver.DeviceID)"} | Select-Object -ExpandProperty ConfigManagerErrorCode}},
            @{name='DriverDate';expression={[DateTime]::ParseExact(($_.DriverDate).Split('.')[0], "yyyyMMddHHmmss", [System.Globalization.CultureInfo]::InvariantCulture)}},
            DriverVersion
}

$DriversDevices |
    Sort-Object DeviceClass |
    Out-GridView -Title "$poste - Drivers utilisés"

Like I said everything works fine already. However, I'm curious to know if there's a faster way!

Body:
This is how I would do it, not big difference in performance, but more clear IMO:
Used an ArrayList for the results, also replaced the Where-Object on the Get-WmiObject with -Filter, it's a bit faster...

$poste = "COMPUTER1234"
$DriversUp = Get-WmiObject -computername $poste Win32_PNPsigneddriver -Filter "DeviceName != NULL"
$Devices = Get-WmiObject -computername $poste Win32_PNPentity

$DriversDevices = New-Object System.Collections.ArrayList

    foreach ($driver in $DriversUp) {

    $row = "" | Select DeviceClass,Manufacturer,DeviceName,FriendlyName,DriverName,
    InfName,Status,ConfigManagerErrorCode,DriverDate,DriverVersion

    $row.DeviceClass = $driver.DeviceClass
    $row.Manufacturer = $driver.Manufacturer
    $row.DeviceName = $driver.DeviceName
    $row.DriverName = $driver.DriverName
    $row.InfName = $driver.InfName
    $row.Status = ($Devices | ? {$_.DeviceID -eq $driver.DeviceID}).Status
    $row.ConfigManagerErrorCode = ($Devices | ? {$_.DeviceID -eq $driver.DeviceID}).ConfigManagerErrorCode
    $row.DriverDate = [datetime]::ParseExact(($driver.DriverDate.Split('.')[0]),"yyyyMMddHHmmss",$null)
    $row.DriverVersion = $driver.DriverVersion
    [void]$DriversDevices.Add($row)
    }

    $DriversDevices | Sort-Object DeviceClass | Out-GridView -Title "$poste - Drivers utilisés"


问:
Call to snprintf and vsnprintf inside a variadic function
I'm trying to use variadic functions inside a variadic function. I check many examples on Internet and Stack Overflow but I can't find my mistake.

When I'm running my program using Visual Studio, I have an access violation when it's calling snprintf.

Here the header:

```<code>#pragma once
#include <cstdarg>
class Console
{
   public:
     static void writeLine(const char *s, ...);

   private:
     Console() = delete;
    ~Console() = delete;
};
</code>```

The class:

```<code>#include "Console.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>

void Console::writeLine(const char *s...)
{
    va_list arg1, arg2;

    // Search the total length
    va_start(arg1, s);
    va_copy(arg2, arg1);
    int length = snprintf(nullptr, 0, s, arg1);
    va_end(arg1);

    size_t size = length + 1;
    char *szBuff = new char[size]; // note +1 for terminating null byte

    // Format the string
    vsnprintf(szBuff, size, s, arg2);
    va_end(arg2);

    std::cout << (const char*)szBuff << std::endl;

   delete(szBuff);
}
</code>```

And the main program:

```<code>#include "Console.h"
#include <iostream>

int main()
{
   Console::writeLine("Example with an int (%d) and a string(%s)", 10, "my string");
}
</code>```

I'm sure I did a stupidity, but I can't see why it's not working.

EDIT

The cout call is just un example, I'm using a function from Windows to write to the console of Visual Studio. It's why, I'm doing this class: to format the data before to write the result to the console.

答:
You are using the wrong function to calculate the size of your buffer.  snprintf() does not take a va_list as input. Also, Microsoft's implementation of vsnprintf() is not defined as accepting a NULL buffer as input, like snprintf() does. You need to use _vscprintf() instead:

_vscprintf returns the number of characters that would be generated if the string pointed to by the list of arguments was printed or sent to a file or buffer using the specified formatting codes. The value returned does not include the terminating null character.

Also, you are not freeing your buffer correctly. Since you use new[] to allocate it, you need to use delete[] to free it.

Try this instead:

void Console::writeLine(const char *s, ...)
{
    va_list arg1, arg2;

    va_start(arg1, s);

    // Search the total length
    va_copy(arg2, arg1);
    size_t size = _vscprintf(s, arg2) + 1; // note +1 for terminating null byte
    va_end(arg2);

    char *szBuff = new char[size];

    // Format the string
    vsnprintf(szBuff, size, s, arg1);

    va_end(arg1);

    std::cout << szBuff << std::endl;

    delete[] szBuff;
}
```

Body:
I'm trying to use variadic functions inside a variadic function. I check many examples on Internet and Stack Overflow but I can't find my mistake.

When I'm running my program using Visual Studio, I have an access violation when it's calling snprintf.

Here the header:

#pragma once
#include <cstdarg>
class Console
{
   public:
     static void writeLine(const char *s, ...);

   private:
     Console() = delete;
    ~Console() = delete;
};

The class:

#include "Console.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>

void Console::writeLine(const char *s...)
{
    va_list arg1, arg2;

    // Search the total length
    va_start(arg1, s);
    va_copy(arg2, arg1);
    int length = snprintf(nullptr, 0, s, arg1);
    va_end(arg1);

    size_t size = length + 1;
    char *szBuff = new char[size]; // note +1 for terminating null byte

    // Format the string
    vsnprintf(szBuff, size, s, arg2);
    va_end(arg2);

    std::cout << (const char*)szBuff << std::endl;

   delete(szBuff);
}

And the main program:

#include "Console.h"
#include <iostream>

int main()
{
   Console::writeLine("Example with an int (%d) and a string(%s)", 10, "my string");
}

I'm sure I did a stupidity, but I can't see why it's not working.

EDIT

The cout call is just un example, I'm using a function from Windows to write to the console of Visual Studio. It's why, I'm doing this class: to format the data before to write the result to the console.


问:
MongoDB Aggregation to $group and conditionnally $addToSet
Given the following dummy collection, I want to extract exporting and importing countries for a given resource:

```<code>[{
    country: "France",
    exchange: {
        export: [{
            resource: "MILK",
            origin: ["Toulouse", "Bordeaux"]
        }],
        import: [{
            resource: "BEEF",
            origin: ["Lyon", "Marseille"]
        }]
    }
}, {
    country: "Spain",
    exchange: {
        export: [{
            resource: "PORK",
            origin: ["Madrid", "Barcelona"]
        }],
        import: [{
            resource: "MILK",
            origin: ["Valencia", "Bilbao"]
        }]
    }
}]
</code>```

Expected result:

```<code>{
    resource: "MILK",
    exportingCountries: ["France"],
    importingCountries: ["Spain"]
}
</code>```

I've been playing with $group but I can't find a way to conditionnally $addToSet countries.

答:
You can use $concatArrays to combine exchange.export and exchange.import arrays. This allows you to $group by country and then you need to get back import and export using $filter and $map operators, try:

```<code>db.col.aggregate([
    {
        $project: {
            country: 1,
            resources: {
                $concatArrays: [
                    { $map: { input: "$exchange.export", in: { resource: "$$this.resource", exchange: "export" } } },
                    { $map: { input: "$exchange.import", in: { resource: "$$this.resource", exchange: "import" } } },
                ]
            }
        }
    },
    {
        $unwind: "$resources"
    },
    {
        $group: {
            _id: "$resources.resource",
            resources: { $addToSet: { country: "$country", exchange: "$resources.exchange" } }
        }
    },
    {
        $project: {
            _id: 0,
            resource: "$_id",
            importingCountries: {
                $map: {
                    input: { $filter: { input: "$resources", as: "r", cond: { $eq: [ "$$r.exchange", "import" ] } } },
                    in: "$$this.country"
                }
            },
            exportingCountries: {
                $map: {
                    input: { $filter: { input: "$resources", as: "r", cond: { $eq: [ "$$r.exchange", "export" ] } } },
                    in: "$$this.country"
                }
            }
        }
    }
])
</code>```

Output:

```<code>{ "resource" : "PORK", "importingCountries" : [ ], "exportingCountries" : [ "Spain" ] }
{ "resource" : "BEEF", "importingCountries" : [ "France" ], "exportingCountries" : [ ] }
{ "resource" : "MILK", "importingCountries" : [ "Spain" ], "exportingCountries" : [ "France" ] }
</code>```

Body:
Given the following dummy collection, I want to extract exporting and importing countries for a given resource:

[{
    country: "France",
    exchange: {
        export: [{
            resource: "MILK",
            origin: ["Toulouse", "Bordeaux"]
        }],
        import: [{
            resource: "BEEF",
            origin: ["Lyon", "Marseille"]
        }]
    }
}, {
    country: "Spain",
    exchange: {
        export: [{
            resource: "PORK",
            origin: ["Madrid", "Barcelona"]
        }],
        import: [{
            resource: "MILK",
            origin: ["Valencia", "Bilbao"]
        }]
    }
}]

Expected result:

{
    resource: "MILK",
    exportingCountries: ["France"],
    importingCountries: ["Spain"]
}

I've been playing with $group but I can't find a way to conditionnally $addToSet countries.

Body:
You can use $concatArrays to combine exchange.export and exchange.import arrays. This allows you to $group by country and then you need to get back import and export using $filter and $map operators, try:

db.col.aggregate([
    {
        $project: {
            country: 1,
            resources: {
                $concatArrays: [
                    { $map: { input: "$exchange.export", in: { resource: "$$this.resource", exchange: "export" } } },
                    { $map: { input: "$exchange.import", in: { resource: "$$this.resource", exchange: "import" } } },
                ]
            }
        }
    },
    {
        $unwind: "$resources"
    },
    {
        $group: {
            _id: "$resources.resource",
            resources: { $addToSet: { country: "$country", exchange: "$resources.exchange" } }
        }
    },
    {
        $project: {
            _id: 0,
            resource: "$_id",
            importingCountries: {
                $map: {
                    input: { $filter: { input: "$resources", as: "r", cond: { $eq: [ "$$r.exchange", "import" ] } } },
                    in: "$$this.country"
                }
            },
            exportingCountries: {
                $map: {
                    input: { $filter: { input: "$resources", as: "r", cond: { $eq: [ "$$r.exchange", "export" ] } } },
                    in: "$$this.country"
                }
            }
        }
    }
])

Output:

{ "resource" : "PORK", "importingCountries" : [ ], "exportingCountries" : [ "Spain" ] }
{ "resource" : "BEEF", "importingCountries" : [ "France" ], "exportingCountries" : [ ] }
{ "resource" : "MILK", "importingCountries" : [ "Spain" ], "exportingCountries" : [ "France" ] }


问:
How do i get the HTML from a MockMVC?
In spring, I have found my MockMVC for a given url:

```<code>MvcResult result = this.mockMvc.perform( get(urlToFetch).sessionAttrs(sessionAttr))
            .andExpect(status().isOk())
            .andReturn();
</code>```

Great. Now I want to see what the html that this would return is. How do I do that? I want a string representation of it (ie String theHtml = ...) so I can parse it and check it in my test.

答:
Oh.

There is no rendering of jsp content. So that's why I'm not getting anything.

Title: How do i get the HTML from a MockMVC?

Body:
In spring, I have found my MockMVC for a given url:

MvcResult result = this.mockMvc.perform( get(urlToFetch).sessionAttrs(sessionAttr))
            .andExpect(status().isOk())
            .andReturn();

Great. Now I want to see what the html that this would return is. How do I do that? I want a string representation of it (ie String theHtml = ...) so I can parse it and check it in my test.


问:
beautifulsoup select method not selecting results as expected
Following the automate the boring stuff tutorial in chapter 11, the I’m Feeling Lucky Google Search project. It's downloading the HTML data correctly seemingly but when I use beautifulsoup to select the result links I get nothing. According to the book it said use soup.select('.r a') and it didn't select anything.

Reading the documentation I tried using differing syntax soup.select('[class~=r]') to hopefully get beautifulsoup to select something but it didn't. I've also tried selecting different classes and it didn't do that either so I assume I'm doing something fundamentally wrong.

```<code>SEARCHVAR = sys.argv[1:]

res = requests.get('http://google.com/search?q=' + ' '.join(SEARCHVAR))
res.raise_for_status()
print('Searching ' + ' '.join(SEARCHVAR[:]) + ' on Google')
soup = bs4.BeautifulSoup(res.text, 'html.parser')
print('Parsing')
linkElems = soup.select('.r a')
print(str(linkElems))
</code>```

I used the print(str(linkElems)) to check what beautifulsoup is selecting but I keep getting nothing, just [].

答:
This doesn't work because of your get request to Google. If I use developer tools in chrome on Google the div class r does exist. However, when I download the query with request.get it's no longer there. However, there's now a div class called 'jfp3ef'. I was able to get the a tags associated with the search results with the following

```<code>soup = soup.find_all("div", {"class": "jfp3ef"})
for div in soup:
    print(div.select("a"))
</code>```

If you want you can download the entire page with the divs in the r class by using urllib.request, but Google blocks this behavior so you have to change the header information.

```<code>SEARCHVAR = sys.argv[1:]
query = 'http://google.com/search?q=' + ' '.join(SEARCHVAR)
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17
(KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib.request.Request(query, headers= headers)
html = urllib.request.urlopen(req).read()
print('Searching ' + ' '.join(SEARCHVAR[:]) + ' on Google')
soup = bs4.BeautifulSoup(html, 'html.parser')
print('Parsing')
linkElems = soup.select('.r a')
print(str(linkElems)
</code>```

The example in the book is out of date. I assume my top example with class "jfp3ef" is randomized from google and will break soon or may not work for you at all. The bottom example does work well.

Body:
Following the automate the boring stuff tutorial in chapter 11, the I’m Feeling Lucky Google Search project. It's downloading the HTML data correctly seemingly but when I use beautifulsoup to select the result links I get nothing. According to the book it said use soup.select('.r a') and it didn't select anything.

Reading the documentation I tried using differing syntax soup.select('[class~=r]') to hopefully get beautifulsoup to select something but it didn't. I've also tried selecting different classes and it didn't do that either so I assume I'm doing something fundamentally wrong.

SEARCHVAR = sys.argv[1:]

res = requests.get('http://google.com/search?q=' + ' '.join(SEARCHVAR))
res.raise_for_status()
print('Searching ' + ' '.join(SEARCHVAR[:]) + ' on Google')
soup = bs4.BeautifulSoup(res.text, 'html.parser')
print('Parsing')
linkElems = soup.select('.r a')
print(str(linkElems))

I used the print(str(linkElems)) to check what beautifulsoup is selecting but I keep getting nothing, just [].

Body:
This doesn't work because of your get request to Google. If I use developer tools in chrome on Google the div class r does exist. However, when I download the query with request.get it's no longer there. However, there's now a div class called 'jfp3ef'. I was able to get the a tags associated with the search results with the following

soup = soup.find_all("div", {"class": "jfp3ef"})
for div in soup:
    print(div.select("a"))

If you want you can download the entire page with the divs in the r class by using urllib.request, but Google blocks this behavior so you have to change the header information.

SEARCHVAR = sys.argv[1:]
query = 'http://google.com/search?q=' + ' '.join(SEARCHVAR)
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17
(KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib.request.Request(query, headers= headers)
html = urllib.request.urlopen(req).read()
print('Searching ' + ' '.join(SEARCHVAR[:]) + ' on Google')
soup = bs4.BeautifulSoup(html, 'html.parser')
print('Parsing')
linkElems = soup.select('.r a')
print(str(linkElems)

The example in the book is out of date. I assume my top example with class "jfp3ef" is randomized from google and will break soon or may not work for you at all. The bottom example does work well.


问:
What is the difference between Amazon SNS and Amazon SQS?
When would I use SNS versus SQS, and why are they always coupled together?</p>

答:
In simple terms,

SNS - sends messages to the subscriber using push mechanism and no need of pull.

SQS - it is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components.

A common pattern is to use SNS to publish messages to Amazon SQS queues to reliably send messages to one or many system components asynchronously.

Reference from Amazon SNS FAQs.


问:
How do I process posts and export them as CSV before output?
I am trying to export as CSV a list of custom type posts directly from Wordpress' dashboard (edit.php). This is my code so far:

```<code>add_filter('pre_get_posts', 'yri_export_csv');

function yri_export_csv($query) {
    if(is_admin() && $query->get('post_type') == 'kohde' && isset($_GET['export_csv'])) {
        $kunta = $query->get('kunta');
        $osasto = $query->get('osasto');
        $time = time();

        $args = $query->query;
        $posts = get_posts($args);

        header('Content-type: application/csv');
        header("Content-Disposition: attachment; filename=kohteet_{$kunta}_{$osasto}_{$time}.csv");

        foreach ($posts as $post) {
            // Do CSV stuff here
        }

        die();
    }
}
</code>```

The problem is that when I query the posts using get_posts or new WP_Query Wordpress for some reason redirects me to the frontend, to a 404 page. Why does it do that?

答:
This solved it:

```<code>...
if(is_main_query() && is_admin() && $query->get('post_type') == 'kohde' && isset($_GET['export_csv'])) {
...
</code>```

I'm not exactly sure why. There seems to be some kind of redirecting mechanic in Wordpress here and I don't exactly understand how it works. However, testing for main query, is_main_query(), was the missing piece.

Body:
I am trying to export as CSV a list of custom type posts directly from Wordpress' dashboard (edit.php). This is my code so far:

add_filter('pre_get_posts', 'yri_export_csv');

function yri_export_csv($query) {
    if(is_admin() && $query->get('post_type') == 'kohde' && isset($_GET['export_csv'])) {
        $kunta = $query->get('kunta');
        $osasto = $query->get('osasto');
        $time = time();

        $args = $query->query;
        $posts = get_posts($args);

        header('Content-type: application/csv');
        header("Content-Disposition: attachment; filename=kohteet_{$kunta}_{$osasto}_{$time}.csv");

        foreach ($posts as $post) {
            // Do CSV stuff here
        }

        die();
    }
}

The problem is that when I query the posts using get_posts or new WP_Query Wordpress for some reason redirects me to the frontend, to a 404 page. Why does it do that?

Body:
This solved it:

...
if(is_main_query() && is_admin() && $query->get('post_type') == 'kohde' && isset($_GET['export_csv'])) {
...

I'm not exactly sure why. There seems to be some kind of redirecting mechanic in Wordpress here and I don't exactly understand how it works. However, testing for main query, is_main_query(), was the missing piece.


问:
AWS S3 List Objects Inconsistency
I'm trying to list the objects with a given prefix using the AWS S3 cli. However, it sometimes returns different results for seemingly identical folder structures.

Ok so here is command #1

```<code>aws s3api list-objects --bucket b --prefix 38d2f2e0-8091-11e9-aaa9-03fd73386354/raw

38d2f2e0-8091-11e9-aaa9-03fd73386354/raw/Pogonocherus_hispidus_Max.1001.png
38d2f2e0-8091-11e9-aaa9-03fd73386354/raw/Pogonocherus_hispidus_Max.mtl
38d2f2e0-8091-11e9-aaa9-03fd73386354/raw/Pogonocherus_hispidus_Max.obj
</code>```

and here #2

```<code>aws s3api list-objects --bucket b --prefix 5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw

5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/
5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/Pogonocherus_hispidus_Max.1001.png
5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/Pogonocherus_hispidus_Max.mtl
5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/Pogonocherus_hispidus_Max.obj
</code>```

I have no idea why it's doing that. Ideally, i want the output to always look like #1.

What's going on here?

答:
The difference between the two listings is the presence in the second list of a raw/ subfolder object. With S3, it's not necessary to create a folder before writing a object to that folder. And, when you create an object such as folder1/folder2/image.jpg, S3 does not create the folder1/folder2/ structure; it simply writes the object.

So, some process that you are using is deliberately creating an object at 5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/ to represent the raw/ subfolder. There's no need to create this folder typically but some clients do. As you can see, things work just fine in the first example without the raw/ subfolder.

So, see if you can identify some difference in the way you are populating S3 that might cause the uuid/raw/ subfolder to be created. One common cause is that someone used the AWS S3 Console to create a folder.

Title: AWS S3 List Objects Inconsistency

Body:
I'm trying to list the objects with a given prefix using the AWS S3 cli. However, it sometimes returns different results for seemingly identical folder structures.

Ok so here is command #1

aws s3api list-objects --bucket b --prefix 38d2f2e0-8091-11e9-aaa9-03fd73386354/raw

38d2f2e0-8091-11e9-aaa9-03fd73386354/raw/Pogonocherus_hispidus_Max.1001.png
38d2f2e0-8091-11e9-aaa9-03fd73386354/raw/Pogonocherus_hispidus_Max.mtl
38d2f2e0-8091-11e9-aaa9-03fd73386354/raw/Pogonocherus_hispidus_Max.obj

and here #2

aws s3api list-objects --bucket b --prefix 5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw

5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/
5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/Pogonocherus_hispidus_Max.1001.png
5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/Pogonocherus_hispidus_Max.mtl
5d5c3abe-1a95-4e92-a03d-11fbf37d7851/raw/Pogonocherus_hispidus_Max.obj

I have no idea why it's doing that. Ideally, i want the output to always look like #1.

What's going on here?


问:
how separate the mouse click event and the courser click event in Aframe
I'm creating a VR Editor using AFRAME...
I need to create an event when the user clicks on an element by mouse and to do deferent action when clicking by Aframe camera cursor.

I found the  but this would do the same click event on both mouse and cursor click.
 is that possible in AFRAME?

答:
Discriminate by the cursor element:

```<code>AFRAME.registerComponent('on-click', {
    init: function () {
      var self = this;
      this.el.addEventListener('click', function (evt) {
        if (self.el.sceneEl === evt.detail.cursorEl) {
          console.log("MOUSE");
        } else {
          console.log("CURSOR");
        }
      });
    }
  });
</code>```

Example: https://glitch.com/edit/#!/winter-sagittarius

Body:
Discriminate by the cursor element:

AFRAME.registerComponent('on-click', {
    init: function () {
      var self = this;
      this.el.addEventListener('click', function (evt) {
        if (self.el.sceneEl === evt.detail.cursorEl) {
          console.log("MOUSE");
        } else {
          console.log("CURSOR");
        }
      });
    }
  });

Example: https://glitch.com/edit/#!/winter-sagittarius


问:
Import a function in every .py
Aloha!
I want to make an import for every .py file I have like:

maincode.py

import generalimports

# somecode
```

<p>generalimports.py</p>

<pre class="lang-py prettyprint-override"><code>import math
import x
import y
# ...
</code>```

答:
Your idea seems to work as-is. The problem is accessing these imported modules. When you have

```<code>import generalimports
# (in maincode.py)
</code>```

You access the modules with:

```<code>generalimports.math
generalimports.x
...
</code>```

Although this method is discouraged, a wildcard import may suit your needs.

```<code>from generalimports import *
# now access modules normally
math.sqrt(6)
x.y()
</code>```

Title: Import a function in every .py

Body:
Aloha!
I want to make an import for every .py file I have like:

maincode.py

import generalimports

# somecode

generalimports.py

import math
import x
import y
# ...

Body:
Your idea seems to work as-is. The problem is accessing these imported modules. When you have

import generalimports
# (in maincode.py)

You access the modules with:

generalimports.math
generalimports.x
...

Although this method is discouraged, a wildcard import may suit your needs.

from generalimports import *
# now access modules normally
math.sqrt(6)
x.y()