问:
Run-time error -2147023170 (800706be) when copy-pasting images from Excel to Word
I am trying to copy/paste some images from my Excel sheet to a word file. Sometimes, it works flawlessly, but often I run into the great Run-time error '-2147023170 (800706be)': Automation error. The remote procedure call failed. message. Google showed my that I'm not alone with this error and that it often results from the fact that e.g. ranges are not precisely defined.I think they are in my project, however.

Here's my code:

```<code>Dim wdDoc As Object
Dim wdApp As Object
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Add
Dim wdImg As Object
ThisWorkbook.Worksheets("Backup - Do not change").Shapes("companyLogo").Copy
With wdDoc.Sections(1).Headers(2).Range
    .PageSetup.DifferentFirstPageHeaderFooter = True
    .Paste
    Set wdImg = .InlineShapes(.InlineShapes.Count).ConvertToShape
    With wdImg
       'some specifications
    End With
End With
ThisWorkbook.Worksheets("Backup - Do not change").Shapes("projectLogo").Copy
With wdDoc.Sections(1).Headers(2).Range
    .Paste
    Set wdImg = .InlineShapes(.InlineShapes.Count).ConvertToShape
    With wdImg
       'some specifications
    End With
End With
Application.CutCopyMode = False
</code>```

The error always occurs at .Paste. I already tried .PasteSpecial DataType:=8 and various other things but it didn't help. Any help is very welcome!

答: Okay so instead of pasting directly to the header range, I now created a table within the header and paste the images into two different cells. Since then I've successfully run the code for more than 10x so it seems like this fixed the issue (I hope it stays like this). Still not sure what caused it, though.</p>

Body:
I am trying to copy/paste some images from my Excel sheet to a word file. Sometimes, it works flawlessly, but often I run into the great Run-time error '-2147023170 (800706be)': Automation error. The remote procedure call failed. message. Google showed my that I'm not alone with this error and that it often results from the fact that e.g. ranges are not precisely defined.I think they are in my project, however.

Here's my code:

Dim wdDoc As Object
Dim wdApp As Object
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Add
Dim wdImg As Object
ThisWorkbook.Worksheets("Backup - Do not change").Shapes("companyLogo").Copy
With wdDoc.Sections(1).Headers(2).Range
    .PageSetup.DifferentFirstPageHeaderFooter = True
    .Paste
    Set wdImg = .InlineShapes(.InlineShapes.Count).ConvertToShape
    With wdImg
       'some specifications
    End With
End With
ThisWorkbook.Worksheets("Backup - Do not change").Shapes("projectLogo").Copy
With wdDoc.Sections(1).Headers(2).Range
    .Paste
    Set wdImg = .InlineShapes(.InlineShapes.Count).ConvertToShape
    With wdImg
       'some specifications
    End With
End With
Application.CutCopyMode = False

The error always occurs at .Paste. I already tried .PasteSpecial DataType:=8 and various other things but it didn't help. Any help is very welcome!


来源: stackexchange

问:
fgets() gets more than it should in file reading - C
Currently I'm doing a practical work to collage in witch I have to read data from a file.

The file data structure is: "id name sex"

example:

```
nm0025630   Vikas Anand M
nm0418131   Victor Janson   M
nm0411451   Dick Israel M
nm0757820   Leopoldo Salcedo    M
```

To read the currently I'm using this code:

```<code>    fh = NULL;
    fh = fopen(ACTORS, "r");
    if (!fh) {
        exit(1);
    }
    while (!feof(fh)) {
        char sex, name[100], id[10];

        fgets(id, 10, fh);
        fgets(name, 100, fh);
        fgetc(sex);

        if (!feof(fh)) {
            hash_update_node(hash, get_id_num(id), name, sex);
            count++;
        }
    }
</code>```

The problem is that it reads the name and the sex together.
Any help is appreciated.

答:
fgets(name, 100, fh); reads up to 99 character, when the name has less than 98 character the sex is also read if it has onlt one space before.

Because the name is may be composed of several words separated by spaces one way is to read all the line then extract the sex.

Warning the first time you do while (!feof(fh)) { this is without any read before so feof cannot know if the file is empty or not then if you reach EOF or not. I encourage you to detect the EOF looking at read result.

Also because you only save the read data when if (!feof(fh)){ you do not memorize the information from the last line.

Note also fgets saves the newline if there is enough place for it, it is more practical to use fscanf.

So one way can be :

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define ACTORS "/tmp/actors"

int main()
{
  FILE * fh = fopen(ACTORS, "r");

  if (!fh) {
    perror("cannot read " ACTORS);
    exit(1);
  }

  char name[100],id[10];

  while (fscanf(fh, "%9s %99[^\n]", id, name) == 2) {
    size_t sz = strlen(name);
    char sex = name[--sz];

    for (;;) {
      if (sz == 0) {
        puts("empty name");
        exit(2);
      }
      if (!isspace((unsigned char) name[--sz]))
        break;
    }

    name[sz+1] = 0;

    /*
    hash_update_node(hash, get_id_num(id) , name, sex);
    count++;
    */
    printf("id='%s', name='%s', sex=%c\n", id, name, sex);
  }

  fclose(fh);
  return 0;
}
</code>```

Compilation and executions :

```<code>pi@raspberrypi:/tmp $ gcc -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
cannot read /tmp/actors: No such file or directory
pi@raspberrypi:/tmp $ cat > actors
nm0025630 Vikas Anand M
nm0418131 Victor Janson M
nm0411451 Dick Israel M
nm0757820 Leopoldo Salcedo M
pi@raspberrypi:/tmp $ ./a.out
id='nm0025630', name='Vikas Anand', sex=M
id='nm0418131', name='Victor Janson', sex=M
id='nm0411451', name='Dick Israel', sex=M
id='nm0757820', name='Leopoldo Salcedo', sex=M
pi@raspberrypi:/tmp $
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Currently I'm doing a practical work to collage in witch I have to read data from a file.

The file data structure is: "id name sex"

example:

nm0025630   Vikas Anand M
nm0418131   Victor Janson   M
nm0411451   Dick Israel M
nm0757820   Leopoldo Salcedo    M

To read the currently I'm using this code:

    fh = NULL;
    fh = fopen(ACTORS, "r");
    if (!fh) {
        exit(1);
    }
    while (!feof(fh)) {
        char sex, name[100], id[10];

        fgets(id, 10, fh);
        fgets(name, 100, fh);
        fgetc(sex);

        if (!feof(fh)) {
            hash_update_node(hash, get_id_num(id), name, sex);
            count++;
        }
    }

The problem is that it reads the name and the sex together.
Any help is appreciated.

Body:
fgets(name, 100, fh); reads up to 99 character, when the name has less than 98 character the sex is also read if it has onlt one space before.

Because the name is may be composed of several words separated by spaces one way is to read all the line then extract the sex.

Warning the first time you do while (!feof(fh)) { this is without any read before so feof cannot know if the file is empty or not then if you reach EOF or not. I encourage you to detect the EOF looking at read result.

Also because you only save the read data when if (!feof(fh)){ you do not memorize the information from the last line.

Note also fgets saves the newline if there is enough place for it, it is more practical to use fscanf.

So one way can be :

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define ACTORS "/tmp/actors"

int main()
{
  FILE * fh = fopen(ACTORS, "r");

  if (!fh) {
    perror("cannot read " ACTORS);
    exit(1);
  }

  char name[100],id[10];

  while (fscanf(fh, "%9s %99[^\n]", id, name) == 2) {
    size_t sz = strlen(name);
    char sex = name[--sz];

    for (;;) {
      if (sz == 0) {
        puts("empty name");
        exit(2);
      }
      if (!isspace((unsigned char) name[--sz]))
        break;
    }

    name[sz+1] = 0;

    /*
    hash_update_node(hash, get_id_num(id) , name, sex);
    count++;
    */
    printf("id='%s', name='%s', sex=%c\n", id, name, sex);
  }

  fclose(fh);
  return 0;
}

Compilation and executions :

pi@raspberrypi:/tmp $ gcc -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
cannot read /tmp/actors: No such file or directory
pi@raspberrypi:/tmp $ cat > actors
nm0025630 Vikas Anand M
nm0418131 Victor Janson M
nm0411451 Dick Israel M
nm0757820 Leopoldo Salcedo M
pi@raspberrypi:/tmp $ ./a.out
id='nm0025630', name='Vikas Anand', sex=M
id='nm0418131', name='Victor Janson', sex=M
id='nm0411451', name='Dick Israel', sex=M
id='nm0757820', name='Leopoldo Salcedo', sex=M
pi@raspberrypi:/tmp $


问:
Modern OpenGL: Object picking (C#, OpenTK)
I am trying to implement object picking in OpenGL using C# and OpenTK. I have written a class for this purpose based on two sources:

OpenGL ray casting (picking): account for object's transform

https://www.bfilipek.com/2012/06/select-mouse-opengl.html

Currently my code is only for calculating the distance of the mouse pointer from an arbitrary test coordinate of (0,0,0), but once working it would not take much to iterate through objects in a scene to find a match.

The method is to define a ray underneath the mouse pointer between the near and far clipping planes. Then find the point on that ray which is closest to the point being tested and return the distance between the two. This should be zero when the mouse pointer is directly over (0,0,0) and increase as it moves away in any direction.

Can anyone help troubleshoot this? It executes without errors but the distance being returned clearly isn't correct. I understand the principles but not the finer points of the calculations.

Although I have found various examples online which almost do it, they are generally in a different language or framework and/or use deprecated methods and/or are incomplete or not working.

```<code>public class ObjectPicker{

    public static float DistanceFromPoint(Point mouseLocation, Vector3 testPoint, Matrix4 modelView, Matrix4 projection)
    {
        Vector3 near = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 0), modelView, projection); // start of ray
        Vector3 far = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 1), modelView, projection); // end of ray
        Vector3 pt = ClosestPoint(near, far, testPoint); // find point on ray which is closest to test point
        return Vector3.Distance(pt, testPoint); // return the distance
    }
    private static Vector3 ClosestPoint(Vector3 A, Vector3 B, Vector3 P)
    {
        Vector3 AB = B - A;
        float ab_square = Vector3.Dot(AB, AB);
        Vector3 AP = P - A;
        float ap_dot_ab = Vector3.Dot(AP, AB);
        // t is a projection param when we project vector AP onto AB
        float t = ap_dot_ab / ab_square;
        // calculate the closest point
        Vector3 Q = A + Vector3.Multiply(AB, t);
        return Q;
    }
    private static Vector3 UnProject(Vector3 screen, Matrix4 modelView, Matrix4 projection)
    {
        int[] viewport = new int[4];
        OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.Viewport, viewport);

        Vector4 pos = new Vector4();

        // Map x and y from window coordinates, map to range -1 to 1
        pos.X = (screen.X - (float)viewport[0]) / (float)viewport[2] * 2.0f - 1.0f;
        pos.Y = 1 - (screen.Y - (float)viewport[1]) / (float)viewport[3] * 2.0f;
        pos.Z = screen.Z * 2.0f - 1.0f;
        pos.W = 1.0f;

        Vector4 pos2 = Vector4.Transform( pos, Matrix4.Invert(modelView) * projection );
        Vector3 pos_out = new Vector3(pos2.X, pos2.Y, pos2.Z);

        return pos_out / pos2.W;
    }
}
</code>```

It is called like this:

```<code>    private void GlControl1_MouseMove(object sender, MouseEventArgs e)
    {

        float dist = ObjectPicker.DistanceFromPoint(new Point(e.X,e.Y), new Vector3(0,0,0), model, projection);
        this.Text = dist.ToString(); // display in window caption for debugging

    }
</code>```

I know how the matrices are being passed in (as per above code). I'm fairly sure that the contents of those matrices must be correct, since the rendering works fine, and I can rotate/zoom successfully. This is the vertex shader FWIW:

```<code>        string vertexShaderSource =
            "# version 330 core\n" +
            "layout(location = 0) in vec3 aPos;" +
            "layout(location = 1) in vec3 aNormal;" +
            "uniform mat4 model;    " +
            "uniform mat4 view;" +
            "uniform mat4 projection;" +
            "out vec3 FragPos;" +
            "out vec3 Normal;" +
            "void main()" +
            "{" +
            "gl_Position = projection * view * model * vec4(aPos, 1.0);" +
            "FragPos = vec3(model * vec4(aPos, 1.0));" +
            "Normal = vec3(model * vec4(aNormal, 1.0))";
            "}";
</code>```

I use an implementation of Arcball for rotation. Zooming is done using a translation, like this:

```<code>private void glControl1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        zoom += (float)e.Delta / 240;
        view = Matrix4.CreateTranslation(0.0f, 0.0f, zoom);
        SetMatrix4(Handle, "view", view);
        glControl1.Invalidate();
    }
</code>```

答:
Each vertex coordinate is transformed by the model view matrix. This transforms the coordinates from model space to view space. Then each vertex coordinate is transformed by the projection matrix. This transforms from view space to clip space. The perspective divide converts a clip space coordinate to normalized device space.

If you want to convert from normalized device space to model space you have to do the reverse operations. That means you have to transform by the inverse projection matrix and the inverse model view matrix:

Vector4 pos2 = Vector4.Transform(pos, Matrix4.Invert(projection) * Matrix4.Invert(modelView));
```

<p>respectively</p>

<pre class="lang-cs prettyprint-override"><code>Vector4 pos2 = Vector4.Transform(pos, Matrix4.Invert(modelView * projection));
</code>```

Note, that OpenTK matrices have to be multiplied from the left to the right. See the answer to OpenGL 4.2 LookAt matrix only works with -z value for eye position.

Body:
I am trying to implement object picking in OpenGL using C# and OpenTK. I have written a class for this purpose based on two sources:

OpenGL ray casting (picking): account for object's transform

https://www.bfilipek.com/2012/06/select-mouse-opengl.html

Currently my code is only for calculating the distance of the mouse pointer from an arbitrary test coordinate of (0,0,0), but once working it would not take much to iterate through objects in a scene to find a match.

The method is to define a ray underneath the mouse pointer between the near and far clipping planes. Then find the point on that ray which is closest to the point being tested and return the distance between the two. This should be zero when the mouse pointer is directly over (0,0,0) and increase as it moves away in any direction.

Can anyone help troubleshoot this? It executes without errors but the distance being returned clearly isn't correct. I understand the principles but not the finer points of the calculations.

Although I have found various examples online which almost do it, they are generally in a different language or framework and/or use deprecated methods and/or are incomplete or not working.

public class ObjectPicker{

    public static float DistanceFromPoint(Point mouseLocation, Vector3 testPoint, Matrix4 modelView, Matrix4 projection)
    {
        Vector3 near = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 0), modelView, projection); // start of ray
        Vector3 far = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 1), modelView, projection); // end of ray
        Vector3 pt = ClosestPoint(near, far, testPoint); // find point on ray which is closest to test point
        return Vector3.Distance(pt, testPoint); // return the distance
    }
    private static Vector3 ClosestPoint(Vector3 A, Vector3 B, Vector3 P)
    {
        Vector3 AB = B - A;
        float ab_square = Vector3.Dot(AB, AB);
        Vector3 AP = P - A;
        float ap_dot_ab = Vector3.Dot(AP, AB);
        // t is a projection param when we project vector AP onto AB
        float t = ap_dot_ab / ab_square;
        // calculate the closest point
        Vector3 Q = A + Vector3.Multiply(AB, t);
        return Q;
    }
    private static Vector3 UnProject(Vector3 screen, Matrix4 modelView, Matrix4 projection)
    {
        int[] viewport = new int[4];
        OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.Viewport, viewport);

        Vector4 pos = new Vector4();

        // Map x and y from window coordinates, map to range -1 to 1
        pos.X = (screen.X - (float)viewport[0]) / (float)viewport[2] * 2.0f - 1.0f;
        pos.Y = 1 - (screen.Y - (float)viewport[1]) / (float)viewport[3] * 2.0f;
        pos.Z = screen.Z * 2.0f - 1.0f;
        pos.W = 1.0f;

        Vector4 pos2 = Vector4.Transform( pos, Matrix4.Invert(modelView) * projection );
        Vector3 pos_out = new Vector3(pos2.X, pos2.Y, pos2.Z);

        return pos_out / pos2.W;
    }
}

It is called like this:

    private void GlControl1_MouseMove(object sender, MouseEventArgs e)
    {

        float dist = ObjectPicker.DistanceFromPoint(new Point(e.X,e.Y), new Vector3(0,0,0), model, projection);
        this.Text = dist.ToString(); // display in window caption for debugging

    }

I know how the matrices are being passed in (as per above code). I'm fairly sure that the contents of those matrices must be correct, since the rendering works fine, and I can rotate/zoom successfully. This is the vertex shader FWIW:

        string vertexShaderSource =
            "# version 330 core\n" +
            "layout(location = 0) in vec3 aPos;" +
            "layout(location = 1) in vec3 aNormal;" +
            "uniform mat4 model;    " +
            "uniform mat4 view;" +
            "uniform mat4 projection;" +
            "out vec3 FragPos;" +
            "out vec3 Normal;" +
            "void main()" +
            "{" +
            "gl_Position = projection * view * model * vec4(aPos, 1.0);" +
            "FragPos = vec3(model * vec4(aPos, 1.0));" +
            "Normal = vec3(model * vec4(aNormal, 1.0))";
            "}";

I use an implementation of Arcball for rotation. Zooming is done using a translation, like this:

private void glControl1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        zoom += (float)e.Delta / 240;
        view = Matrix4.CreateTranslation(0.0f, 0.0f, zoom);
        SetMatrix4(Handle, "view", view);
        glControl1.Invalidate();
    }

Body:
Each vertex coordinate is transformed by the model view matrix. This transforms the coordinates from model space to view space. Then each vertex coordinate is transformed by the projection matrix. This transforms from view space to clip space. The perspective divide converts a clip space coordinate to normalized device space.

If you want to convert from normalized device space to model space you have to do the reverse operations. That means you have to transform by the inverse projection matrix and the inverse model view matrix:

Vector4 pos2 = Vector4.Transform(pos, Matrix4.Invert(projection) * Matrix4.Invert(modelView));

respectively

Vector4 pos2 = Vector4.Transform(pos, Matrix4.Invert(modelView * projection));

Note, that OpenTK matrices have to be multiplied from the left to the right. See the answer to OpenGL 4.2 LookAt matrix only works with -z value for eye position.


问:
How to display items inline using angular's *ngFor
I am trying to display items inline instead of appearing in different row. Please see code and picture below. I have tried to look online for solutions but everyone else is asking a different use case. Please let me know. Thanks!

```<code><!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Document</title>
 </head>
 <body>
    <div>
        <div class="pimg1">
           <div class="ptext">
               <span class="borderStyle">
                   Kenny's Site
               </span>
           </div>
        </div>
        <section class="section section-light">
            <h2>Skills</h2>
            <p class="skills" *ngFor="let skill of skills">{{skill.skill}}</p>
        </section>
        <div class="pimg2">
           <div class="ptext">
               <span class="borderStyle">
                   Image2 Text
               </span>
           </div>
        </div>
        <section class="section section-dark">
           <h2>Section 1</h2>
           <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, saepe.</p>
       </section>
       <div class="pimg3">
           <div class="ptext">
               <span class="borderStyle">
                   Image3 Text
               </span>
           </div>
        </div>
        <section class="section section-dark">
           <h2>Section 3</h2>
           <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, saepe.</p>
       </section>
       <div class="pimg1">
           <div class="ptext">
               <span class="borderStyle">
                   Kenny's Site
               </span>
           </div>
        </div>
    </div>
 </body>
 </html>
</code>```

答:
```<code>    if you don't want to mess around that much with CSS attributes you should have a look at [@angular/flex-layout][1]

          [1]: https://github.com/angular/flex-layout

        1. Rows made like this:
        <div fxLayout="row wrap">
          <div fxFlex="50%" [fxFlex.lt-md]="100%" fxLayoutAlign="start center">

          </div>
          <div fxFlex="50%" [fxFlex.lt-md]="100%" fxLayoutAlign="end center">

          </div>
        </div>

        2. Columns made like this:

        <div fxLayout="column wrap">
          <div fxFlex="50%" fxLayoutAlign="start center">

          </div>
          <div fxFlex="50%" fxLayoutAlign="end center">

          </div>
        </div>

    [fxFlex.lt-md] makes the styling responsive, depending on your current user's viewport. There are *.lt-sm, *.lt-md and also *.gt-sm and so on...

And you may use on any flexLayout directives like "fxLayoutAlign" and others...
</code>```

Body:
I am trying to display items inline instead of appearing in different row. Please see code and picture below. I have tried to look online for solutions but everyone else is asking a different use case. Please let me know. Thanks!

<!DOCTYPE html>

     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Document</title>

                   Kenny's Site

Skills

{{skill.skill}}

                   Image2 Text

Section 1

Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, saepe.

                   Image3 Text

Section 3

Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, saepe.

                   Kenny's Site


问:
I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017

I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017. This code is written to overload the operator *, ">>" & "<<" through the friend functions. one constructor initializes the vector elements to zero while the other constructor is used to initialize the elements of vector through the array.

My code is as below:

```<code> //vector.h

#pragma once
const int SIZE = 3;
#include<iostream>
using namespace std;
class vector
{
    int v[SIZE];
public:
    vector();
    vector(int *x);
    friend vector operator *(vector a, int b);
    friend vector operator *(int b,vector a);
    friend istream & operator >>(istream &input, vector &x);
    friend ostream & operator <<(ostream &output, vector &y);

};

    //vector.cpp

#include "vector.h"
#include<iostream>
using namespace std;

vector::vector()
{
    for (int i = 0; i < SIZE; i++)
        v[i] = 0;

}
vector::vector(int *x)
{
    for (int i = 0; i < SIZE; i++)
        v[i] = x[i];

}
vector operator *(vector a, int b) {
    vector temp;
    for (int i = 0; i < SIZE; i++)
        temp.v[i] = a.v[i]*b;
    return temp;

}
vector operator *(int a, vector b) {
    vector temp;
    for (int i = 0; i < SIZE; i++)
        temp.v[i] = a * b.v[i];
    return temp;
}
istream & operator >>(istream &input, vector &x) {
    for (int i = 0; i < SIZE; i++)
        input >> x.v[i];
    return (input);

}
ostream & operator <<(ostream &output, vector &y) {
    output << "(" << y.v[0];
    for (int i = 1; i < SIZE; i++)
        output <<","<< y.v[i];
    output << ")";
    return (output);

}

    //main.cpp

#include "vector.h"
#include<iostream>
using namespace std;
int x[SIZE] = { 2,4,6 };
int main() {

    vector m;
    vector v2 = x;
    cout << "Enter the elements of vector m:" << "\n";
    cin >> m;
    cout << "\n";
    vector m1, m2;
    m1 = m * 2;
    m2 = 2 * v2;
    cout << "m= "<<m<<"\n";
    cout << "\n";
    cout << "m1= " << m1 << "\n";
    cout << "m2= " << m2 << "\n";
    cin.get();

    return 0;

}
</code>```

答:
Your code assumes you must enter 3 number. If you enter less numbers you see no output.

Some comments:

Your cin.get() doesn't stop execution.
Using std (like using namespace std) and definition own vector class - it's very bad idea.

Body:
I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017. This code is written to overload the operator *, ">>" & "<<" through the friend functions. one constructor initializes the vector elements to zero while the other constructor is used to initialize the elements of vector through the array.

My code is as below:

 //vector.h

#pragma once
const int SIZE = 3;
#include<iostream>
using namespace std;
class vector
{
    int v[SIZE];
public:
    vector();
    vector(int *x);
    friend vector operator *(vector a, int b);
    friend vector operator *(int b,vector a);
    friend istream & operator >>(istream &input, vector &x);
    friend ostream & operator <<(ostream &output, vector &y);

};

    //vector.cpp

#include "vector.h"
#include<iostream>
using namespace std;

vector::vector()
{
    for (int i = 0; i < SIZE; i++)
        v[i] = 0;

}
vector::vector(int *x)
{
    for (int i = 0; i < SIZE; i++)
        v[i] = x[i];

}
vector operator *(vector a, int b) {
    vector temp;
    for (int i = 0; i < SIZE; i++)
        temp.v[i] = a.v[i]*b;
    return temp;

}
vector operator *(int a, vector b) {
    vector temp;
    for (int i = 0; i < SIZE; i++)
        temp.v[i] = a * b.v[i];
    return temp;
}
istream & operator >>(istream &input, vector &x) {
    for (int i = 0; i < SIZE; i++)
        input >> x.v[i];
    return (input);

}
ostream & operator <<(ostream &output, vector &y) {
    output << "(" << y.v[0];
    for (int i = 1; i < SIZE; i++)
        output <<","<< y.v[i];
    output << ")";
    return (output);

}

    //main.cpp

#include "vector.h"
#include<iostream>
using namespace std;
int x[SIZE] = { 2,4,6 };
int main() {

    vector m;
    vector v2 = x;
    cout << "Enter the elements of vector m:" << "\n";
    cin >> m;
    cout << "\n";
    vector m1, m2;
    m1 = m * 2;
    m2 = 2 * v2;
    cout << "m= "<<m<<"\n";
    cout << "\n";
    cout << "m1= " << m1 << "\n";
    cout << "m2= " << m2 << "\n";
    cin.get();

    return 0;

}


问:
How do I determine if I need to annotate with @Bean
How do I determine in spring integration, that I need to annotate with @Bean?

For example lets look at a @Transformer annotation.

Consider the following code snippets:

1.

```<code>    @AllArgsConstructor
    @Getter
    @Setter
    @ToString
    private static class Person {
        private String firstName;
        private String lastName;
        private String phone;
    }

    @Override
    public void run(ApplicationArguments args) {
        firstChannel.send(MessageBuilder.withPayload(new Person("s", "f", null)).build());
    }

    // without bean
    @Transformer(inputChannel = FIRST_CHANNEL, outputChannel = SECOND_CHANNEL)
    public ContentEnricher contentEnricher() {
        ContentEnricher contentEnricher = new ContentEnricher();
        contentEnricher.setPropertyExpressions(ImmutableMap.of("phone", new ValueExpression("123")));
        return contentEnricher;
    }

    @ServiceActivator(inputChannel = SECOND_CHANNEL)
    private void fromSecondChannel(Message<?> message) {
        System.out.println(message.getPayload());
    }
</code>```

and

2.

```<code>    // with bean
    @Bean
    @Transformer(inputChannel = FIRST_CHANNEL, outputChannel = SECOND_CHANNEL)
    public HeaderEnricher headerEnricher() {
        return new HeaderEnricher(ImmutableMap.of("key1", new StaticHeaderValueMessageProcessor<>("value1")));
    }
</code>```

The output for the code snippet nr 2 without @Bean is :

```<code>GenericMessage [payload=org.springframework.integration.transformer.HeaderEnricher@15a3b42, headers={id=76d24f2c-8b64-a254-8733-8b5911871cce, timestamp=1590856526985}]
</code>```

and with @Bean is :

```<code>GenericMessage [payload=DemoApplication11.Person(firstName=s, lastName=f, phone=null), headers={key1=value1, id=55e5b4b7-9a4b-8822-4398-b42755bc7697, timestamp=1590856617667}]
</code>```

答:
@Bean on a class means the Context Dependency Injection (CDI) container will automatically create an instance of that class and then use that instance to resolve @Autowired dependencies.

@Bean on a function means the Context Dependency Injection container will automatically call that function and use the object returned by that function to resolve @Autowired dependencies.

In most cases, Spring Boot will automatically create a default implementation of any configuration classes it needs, which will then be autowired anywhere it is needed. Defining your own @Bean function means you can pass a customized version of that class (either a subclass, or just an instance of the same class with some different parameters) into the Spring Boot framework.

I recommend you read up on what Context Dependency Injection means, and how Spring Boot actually implements it. There is no general answer to "when do i need @Bean" that doesn't require understanding CDI first.

Body:
How do I determine in spring integration, that I need to annotate with @Bean?

For example lets look at a @Transformer annotation.

Consider the following code snippets:

1.

    @AllArgsConstructor
    @Getter
    @Setter
    @ToString
    private static class Person {
        private String firstName;
        private String lastName;
        private String phone;
    }

    @Override
    public void run(ApplicationArguments args) {
        firstChannel.send(MessageBuilder.withPayload(new Person("s", "f", null)).build());
    }

    // without bean
    @Transformer(inputChannel = FIRST_CHANNEL, outputChannel = SECOND_CHANNEL)
    public ContentEnricher contentEnricher() {
        ContentEnricher contentEnricher = new ContentEnricher();
        contentEnricher.setPropertyExpressions(ImmutableMap.of("phone", new ValueExpression("123")));
        return contentEnricher;
    }

    @ServiceActivator(inputChannel = SECOND_CHANNEL)
    private void fromSecondChannel(Message<?> message) {
        System.out.println(message.getPayload());
    }

and

2.

    // with bean
    @Bean
    @Transformer(inputChannel = FIRST_CHANNEL, outputChannel = SECOND_CHANNEL)
    public HeaderEnricher headerEnricher() {
        return new HeaderEnricher(ImmutableMap.of("key1", new StaticHeaderValueMessageProcessor<>("value1")));
    }

The output for the code snippet nr 2 without @Bean is :

GenericMessage [payload=org.springframework.integration.transformer.HeaderEnricher@15a3b42, headers={id=76d24f2c-8b64-a254-8733-8b5911871cce, timestamp=1590856526985}]

and with @Bean is :

GenericMessage [payload=DemoApplication11.Person(firstName=s, lastName=f, phone=null), headers={key1=value1, id=55e5b4b7-9a4b-8822-4398-b42755bc7697, timestamp=1590856617667}]


问:
Download large file with node.js avoiding high memory consumption
I`m trying to create a file downloader as a background service but when a large file is scheduled, it's first put in memory and then, at the end of the download the file is written to disk.

How can I make the file be wrote gradually to the disk preserving memory considering that I may have lots of files being downloaded at the same time?

Here's the code I`m using:

```<code>var sys = require("sys"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    events = require("events");

var downloadfile = "http://nodejs.org/dist/node-v0.2.6.tar.gz";

var host = url.parse(downloadfile).hostname
var filename = url.parse(downloadfile).pathname.split("/").pop()

var theurl = http.createClient(80, host);
var requestUrl = downloadfile;
sys.puts("Downloading file: " + filename);
sys.puts("Before download request");
var request = theurl.request('GET', requestUrl, {"host": host});
request.end();

var dlprogress = 0;

setInterval(function () {
   sys.puts("Download progress: " + dlprogress + " bytes");
}, 1000);

request.addListener('response', function (response) {
    response.setEncoding('binary')
    sys.puts("File size: " + response.headers['content-length'] + " bytes.")
    var body = '';
    response.addListener('data', function (chunk) {
        dlprogress += chunk.length;
        body += chunk;
    });
    response.addListener("end", function() {
        fs.writeFileSync(filename, body, 'binary');
        sys.puts("After download finished");
    });

});
</code>```

答:
When downloading large file please use fs.write and not writeFile as it will override the previous content.

```<code>function downloadfile(res) {
    var requestserver = http.request(options, function(r) {
        console.log('STATUS: ' + r.statusCode);
        console.log('HEADERS: ' + JSON.stringify(r.headers));

        var fd = fs.openSync('sai.tar.gz', 'w');

        r.on('data', function (chunk) {
            size += chunk.length;
            console.log(size+'bytes received');
            sendstatus(res,size);
            fs.write(fd, chunk, 0, chunk.length, null, function(er, written) {
            });
        });
        r.on('end',function(){
            console.log('\nended from server');
            fs.closeSync(fd);
            sendendstatus(res);
        });
    });
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I`m trying to create a file downloader as a background service but when a large file is scheduled, it's first put in memory and then, at the end of the download the file is written to disk.

How can I make the file be wrote gradually to the disk preserving memory considering that I may have lots of files being downloaded at the same time?

Here's the code I`m using:

var sys = require("sys"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    events = require("events");

var downloadfile = "http://nodejs.org/dist/node-v0.2.6.tar.gz";

var host = url.parse(downloadfile).hostname
var filename = url.parse(downloadfile).pathname.split("/").pop()

var theurl = http.createClient(80, host);
var requestUrl = downloadfile;
sys.puts("Downloading file: " + filename);
sys.puts("Before download request");
var request = theurl.request('GET', requestUrl, {"host": host});
request.end();

var dlprogress = 0;

setInterval(function () {
   sys.puts("Download progress: " + dlprogress + " bytes");
}, 1000);

request.addListener('response', function (response) {
    response.setEncoding('binary')
    sys.puts("File size: " + response.headers['content-length'] + " bytes.")
    var body = '';
    response.addListener('data', function (chunk) {
        dlprogress += chunk.length;
        body += chunk;
    });
    response.addListener("end", function() {
        fs.writeFileSync(filename, body, 'binary');
        sys.puts("After download finished");
    });

});

Body:
When downloading large file please use fs.write and not writeFile as it will override the previous content.

function downloadfile(res) {
    var requestserver = http.request(options, function(r) {
        console.log('STATUS: ' + r.statusCode);
        console.log('HEADERS: ' + JSON.stringify(r.headers));

        var fd = fs.openSync('sai.tar.gz', 'w');

        r.on('data', function (chunk) {
            size += chunk.length;
            console.log(size+'bytes received');
            sendstatus(res,size);
            fs.write(fd, chunk, 0, chunk.length, null, function(er, written) {
            });
        });
        r.on('end',function(){
            console.log('\nended from server');
            fs.closeSync(fd);
            sendendstatus(res);
        });
    });
}

ContentLicense: CC BY-SA 3.0


问:
ubuntu18.04 vscode kernel module program ERROR: identifier "KBUILD_MODNAME" is undefine
My environment: Ubuntu 18.04, kernel: linux-5.3.0-53 vscode: lastest

Command for fixing linux/module.h not find asm/xxx.h

cd /usr/src/linux-headers-5.3.0-53/include

sudo ln -s asm-generic/ asm
```

<p>My <em>c_cpp_properties.json</em></p>

<pre class="lang-json prettyprint-override"><code>{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include",
                "/usr/local/include",
                "/usr/src/linux-headers-5.3.0-53/include",
                "/usr/src/linux-headers-5.3.0-53-generic/include",
                "/usr/src/linux-headers-5.3.0-53/arch/x86/include",
                "/usr/src/linux-headers-5.3.0-53/include/uapi",
                "/usr/lib/gcc/x86_64-linux-gnu/7.5.0/include"
            ],
            "defines": [
                "__GNUC__",
                "__KERNEL__"
            ],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}
</code>```

My hello_module.c, a simple Linux kernel module program.

//a simple linux kernel module program.
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

MODULE_LICENSE("GPL");  //error here

static int hello_init(void){
    printk(KERN_ALERT "hello world\n");
    return 0;
}

static void hello_exit(void){
    printk(KERN_ALERT "goodbye world\n");
}

module_init(hello_init);
module_exit(hello_exit);
```

<p><strong>then ERROR：</strong></p>

```identifier "KBUILD_MODNAME" is undefined
```

How to fix? Please help me..

答:
KBUILD_MODNAME is automatically defined by the Makefile when you build your kernel module, so you will not find it anywhere in the kernel header files.

To stop vscode from complaining about undefined KBUILD_MODNAME identifier, just add a dummy definition to your c_cpp_properties.json file in the "defines" section

"defines": [
    "KBUILD_MODNAME=\"hello_module\"",
    "__GNUC__",
    "__KERNEL__",
    "MODULE"
],
```

That should make vscode happy =)

The value you define for KBUILD_MODNAME does not really matter, since it is automatically defined during the make process.

I have not understood if this is your only problem, or if you also have problems to compile the module.  If yes let me know and we will figure out how to solve that too!

Body:
My environment: Ubuntu 18.04, kernel: linux-5.3.0-53 vscode: lastest

Command for fixing linux/module.h not find asm/xxx.h

cd /usr/src/linux-headers-5.3.0-53/include

sudo ln -s asm-generic/ asm

My c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include",
                "/usr/local/include",
                "/usr/src/linux-headers-5.3.0-53/include",
                "/usr/src/linux-headers-5.3.0-53-generic/include",
                "/usr/src/linux-headers-5.3.0-53/arch/x86/include",
                "/usr/src/linux-headers-5.3.0-53/include/uapi",
                "/usr/lib/gcc/x86_64-linux-gnu/7.5.0/include"
            ],
            "defines": [
                "__GNUC__",
                "__KERNEL__"
            ],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}

My hello_module.c, a simple Linux kernel module program.

//a simple linux kernel module program.
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

MODULE_LICENSE("GPL");  //error here

static int hello_init(void){
    printk(KERN_ALERT "hello world\n");
    return 0;
}

static void hello_exit(void){
    printk(KERN_ALERT "goodbye world\n");
}

module_init(hello_init);
module_exit(hello_exit);

then ERROR：

identifier "KBUILD_MODNAME" is undefined

How to fix? Please help me..

Body:
KBUILD_MODNAME is automatically defined by the Makefile when you build your kernel module, so you will not find it anywhere in the kernel header files.

To stop vscode from complaining about undefined KBUILD_MODNAME identifier, just add a dummy definition to your c_cpp_properties.json file in the "defines" section

"defines": [
    "KBUILD_MODNAME=\"hello_module\"",
    "__GNUC__",
    "__KERNEL__",
    "MODULE"
],

That should make vscode happy =)

The value you define for KBUILD_MODNAME does not really matter, since it is automatically defined during the make process.

I have not understood if this is your only problem, or if you also have problems to compile the module.  If yes let me know and we will figure out how to solve that too!


问:
Why won't this JSON file parse into my object with __dict__ = json.load(f)?
I have a json file which contains this text:

```<code>{"_firstName": "John", "_lastName": "Baker", "_middleName": null, "_mobile": "7609984356", "_education": "Harvard", "_skills": null, "_email": "john@baker.com"}
</code>```

I am trying to load it in to this Python object:

```<code>class Profile():
    def __init__(self):
        self._firstName = None
        self._lastName = None
        self._middleName = None
        self._mobile = None
        self._education = None
        self._skills = []
        self._email = None
</code>```

I am using:

```<code>def profileImport(self):
    with open("../tests/profile.json", "r") as f:
        self._prof.__dict__ = json.load(f)
</code>```

the line self._prof.__dict__ = json.load(f) is not properly loading the JSON data. I do not get an error from that line, but the object has all None types, indicating that the line didn't successfully load the json data. However, if I use json.loads(), I do get the valid json data as a string, which shows me that the proper file is being accessed. Why is self._prof.__dict__ = json.load(f) failing to parse the data into my object? I'm using Python 3.6.9.

答:
I would use a a dataclass with a class method for this.

```<code>from dataclasses import dataclass, field
from typing import List
import json

@dataclass
class Profile:
    _firstName: str
    _lastName: str
    _mobile: str
    _education: str
    _email: str
    _skills: List[str] = field(default_factory=list)
    _middleName: str = ""

    def __post_init__(self):
        if self._skills is None:
            self._skills = []
        if self._middleName is None:
            self._middleName = ""

    @classmethod
    def from_json(cls, f):
        return cls(**json.load(f))

with open("tmp.json") as f:
    profile = Profile.from_json(f)
</code>```

The idea is that the class method handles the work of calling json.load and passing the resulting key/value pairs to __init__, which is automatically generated to set the desired fields. __post_init__ takes care of converting the
None values provided by the JSON object into "real" defaults.

Body:
I have a json file which contains this text:

{"_firstName": "John", "_lastName": "Baker", "_middleName": null, "_mobile": "7609984356", "_education": "Harvard", "_skills": null, "_email": "john@baker.com"}

I am trying to load it in to this Python object:

class Profile():
    def __init__(self):
        self._firstName = None
        self._lastName = None
        self._middleName = None
        self._mobile = None
        self._education = None
        self._skills = []
        self._email = None

I am using:

def profileImport(self):
    with open("../tests/profile.json", "r") as f:
        self._prof.__dict__ = json.load(f)

the line self._prof.__dict__ = json.load(f) is not properly loading the JSON data. I do not get an error from that line, but the object has all None types, indicating that the line didn't successfully load the json data. However, if I use json.loads(), I do get the valid json data as a string, which shows me that the proper file is being accessed. Why is self._prof.__dict__ = json.load(f) failing to parse the data into my object? I'm using Python 3.6.9.

Body:
I would use a a dataclass with a class method for this.

from dataclasses import dataclass, field
from typing import List
import json

@dataclass
class Profile:
    _firstName: str
    _lastName: str
    _mobile: str
    _education: str
    _email: str
    _skills: List[str] = field(default_factory=list)
    _middleName: str = ""

    def __post_init__(self):
        if self._skills is None:
            self._skills = []
        if self._middleName is None:
            self._middleName = ""

    @classmethod
    def from_json(cls, f):
        return cls(**json.load(f))

with open("tmp.json") as f:
    profile = Profile.from_json(f)

The idea is that the class method handles the work of calling json.load and passing the resulting key/value pairs to __init__, which is automatically generated to set the desired fields. __post_init__ takes care of converting the
None values provided by the JSON object into "real" defaults.


问:
difference between mouseReleased and mouseClicked
searching on the JAVA api document, i knew the difference between the mousePressed and mouseClicked. but.. the mouseClicked method involves both pressing and releasing so the action is done after the releasing the mouse, i don't find much difference with mouseReleased.

when i tried myself, i found that pressed and clicked are different because the time of action is different, but it's not the case between clicked and released.

my program is about drawing oval at the selected point in canvas

i'm looking for help in this problem.

答:
mouseClicked work when you press and release the mouse button in the same coordinates, obviously inside the JComponent.

mousePressed work as soon as press the mouse button in the JComponent.

mouseReleased work as soon as release the mouse button, provided that has previously press in the JComponent.

While you press the mouse button in the JComponent, no matter the final coordinate for to release the mouse button, it could even be outside the JComponent.

In all cases no matter the length of time between pressing and releasing.

HCL from Perú


问:
Too many nested async methods. Is that a problem?
The following code gets a list of investments belonging to a customer from 3 different resources. The flow starts with a controller's call and follows the flow described below where all methods are declared as async and called with await operator.

I'm wondering if is there a problem making all methods as async. Is there any performance penalty? Is it a code smell or an anti-pattern?

I know there are things that must be waited like access url, get data from cahce, etc. But I think there are things like filling a list or sum some few values doesn't need to be async.

Below follow the code (some parts where ommited for clearness):

Controller

```<code>    {HttpGet]
    public async Task<IActionResult> Get()
    {
        Client client = await _mediator.Send(new RecuperarInvestimentosQuery());
        return Ok(cliente);
    }
</code>```

QueryHandler

```<code>    public async Task<Client> Handle(RecoverInvestimentsQuery request, CancellationToken cancellationToken)
    {
        Client client;
        List<Investiment> list = await _investimentBuilder.GetInvestiments();
        client = new Cliente(request.Id, list);
        return client;
    }
</code>```

InvestmentBuilder

```<code>    public async Task<List<Investiment>> GetInvestiments()
    {
        ListInvestiments builder = new ListInvestiments();
        await builder.BuildLists(_builder);
        // here I get the List<Investiment> list already fulfilled to return to the controller
        return list;
    }
</code>```

BuildLists

```<code>    public async Task BuildLists(IBuilder builder)
    {
        Task[] tasks = new Task[] {
            builder.GetFundsAsync(),   //****
            builder.ObterTesouro(),
            builder.ObterRendaFixa()
        };
        await Task.WhenAll(tasks);
    }
</code>```

Funds, Bonds and Fixed Income Services (***all 3 methods are equal, only its name vary, so I just put one of them for the sake of saving space)

```<code>    public async Task GetFundsAsync()
    {
        var listOfFunds = await _FundsService.RecoverFundsAsync();
        // listOfFunds will get all items from all types of investments
    }
</code>```

Recover Funds, Bonds and Fixed Incomes methods are equals too, again I just put one of them

```<code>    public async Task<List<Funds>> RecoverFundsAsync()
    {
        var returnCache = await _clientCache.GetValueAsync("fundsService");
        // if not in cache, so go get from url
        if (returnCache == null)
        {
            string url = _configuration.GetValue<string>("Urls:Funds");
            var response = await _clienteHttp.ObterDadosAsync(url);
            if (response != null)
            {
                string funds = JObject.Parse(response).SelectToken("funds").ToString();
                await _clienteCache.SetValueAsync("fundService", funds);
                return JsonConvert.DeserializeObject<List<Funds>>(fundos);
            }
            else
                return null;
        }
        return JsonConvert.DeserializeObject<List<Funds>>(returnCache);
    }
</code>```

HTTP Client

```<code>    public async Task<string> GetDataAsync(string Url)
    {
        using (HttpClient client = _clientFactory.CreateClient())
        {
            var response = await client.GetAsync(Url);
            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsStringAsync();
            else
                return null;
        }
    }
</code>```

Cache Client

```<code>    public async Task<string> GetValueAsync(string key)
    {
        IDatabase cache = Connection.GetDatabase();
        RedisValue value = await cache.StringGetAsync(key);
        if (value.HasValue)
            return value.ToString();
        else
            return null;
    }
</code>```

Could someone give a thought about that?

Thanks in advance.

答:
Your code looks okay for me. You are using async and await just for I/O and web access operations, and it perfectly fits for async and await purposes:

For I/O-bound code, you await an operation that returns a Task or Task inside of an async method.

For CPU-bound code, you await an operation that is started on a background thread with the Task.Run method.

Once you've used async and await, then all pieces of your code tends to become asynchronous too. This fact is described greatly in the  MSDN article - Async/Await - Best Practices in Asynchronous Programming:

Asynchronous code reminds me of the story of a fellow who mentioned
  that the world was suspended in space and was immediately challenged
  by an elderly lady claiming that the world rested on the back of a
  giant turtle. When the man enquired what the turtle was standing on,
  the lady replied, “You’re very clever, young man, but it’s turtles all
  the way down!” As you convert synchronous code to asynchronous code,
  you’ll find that it works best if asynchronous code calls and is
  called by other asynchronous code—all the way down (or “up,” if you
  prefer). Others have also noticed the spreading behavior of
  asynchronous programming and have called it “contagious” or compared
  it to a zombie virus. Whether turtles or zombies, it’s definitely true
  that asynchronous code tends to drive surrounding code to also be
  asynchronous. This behavior is inherent in all types of asynchronous
  programming, not just the new async/await keywords.

Body:
The following code gets a list of investments belonging to a customer from 3 different resources. The flow starts with a controller's call and follows the flow described below where all methods are declared as async and called with await operator.

I'm wondering if is there a problem making all methods as async. Is there any performance penalty? Is it a code smell or an anti-pattern?

I know there are things that must be waited like access url, get data from cahce, etc. But I think there are things like filling a list or sum some few values doesn't need to be async.

Below follow the code (some parts where ommited for clearness):

Controller

    {HttpGet]
    public async Task<IActionResult> Get()
    {
        Client client = await _mediator.Send(new RecuperarInvestimentosQuery());
        return Ok(cliente);
    }

QueryHandler

    public async Task<Client> Handle(RecoverInvestimentsQuery request, CancellationToken cancellationToken)
    {
        Client client;
        List<Investiment> list = await _investimentBuilder.GetInvestiments();
        client = new Cliente(request.Id, list);
        return client;
    }

InvestmentBuilder

    public async Task<List<Investiment>> GetInvestiments()
    {
        ListInvestiments builder = new ListInvestiments();
        await builder.BuildLists(_builder);
        // here I get the List<Investiment> list already fulfilled to return to the controller
        return list;
    }

BuildLists

    public async Task BuildLists(IBuilder builder)
    {
        Task[] tasks = new Task[] {
            builder.GetFundsAsync(),   //****
            builder.ObterTesouro(),
            builder.ObterRendaFixa()
        };
        await Task.WhenAll(tasks);
    }

Funds, Bonds and Fixed Income Services (***all 3 methods are equal, only its name vary, so I just put one of them for the sake of saving space)

    public async Task GetFundsAsync()
    {
        var listOfFunds = await _FundsService.RecoverFundsAsync();
        // listOfFunds will get all items from all types of investments
    }

Recover Funds, Bonds and Fixed Incomes methods are equals too, again I just put one of them

    public async Task<List<Funds>> RecoverFundsAsync()
    {
        var returnCache = await _clientCache.GetValueAsync("fundsService");
        // if not in cache, so go get from url
        if (returnCache == null)
        {
            string url = _configuration.GetValue<string>("Urls:Funds");
            var response = await _clienteHttp.ObterDadosAsync(url);
            if (response != null)
            {
                string funds = JObject.Parse(response).SelectToken("funds").ToString();
                await _clienteCache.SetValueAsync("fundService", funds);
                return JsonConvert.DeserializeObject<List<Funds>>(fundos);
            }
            else
                return null;
        }
        return JsonConvert.DeserializeObject<List<Funds>>(returnCache);
    }

HTTP Client

    public async Task<string> GetDataAsync(string Url)
    {
        using (HttpClient client = _clientFactory.CreateClient())
        {
            var response = await client.GetAsync(Url);
            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsStringAsync();
            else
                return null;
        }
    }

Cache Client

    public async Task<string> GetValueAsync(string key)
    {
        IDatabase cache = Connection.GetDatabase();
        RedisValue value = await cache.StringGetAsync(key);
        if (value.HasValue)
            return value.ToString();
        else
            return null;
    }

Could someone give a thought about that?

Thanks in advance.


问:
How are macros finally determined in configure?
```<code>#if (NGX_SOLARIS)

    ngx_int_t   i;
    size_t      size;

#endif
</code>```

I know that NGX_SOLARIS is finally determined when we run ./configure,but how are these macros actually defined,can you provide a detailed example that demonstrates how most ./configure works?

答:
./configure runs through all the checks for what your system's platform is, what capabilities your compiler has, etc. and then it uses automake to generate Makefiles with stuff like CPPFLAGS which define the macros it needs to pass to the preprocessor during compilation.

This is all part of the GNU build system: http://developers.sun.com/solaris/articles/gnu.html

Body:
#if (NGX_SOLARIS)

    ngx_int_t   i;
    size_t      size;

#endif

I know that NGX_SOLARIS is finally determined when we run ./configure,but how are these macros actually defined,can you provide a detailed example that demonstrates how most ./configure works?


问:
Render local html file in React Native
I run React Native using Expo for android and I'm trying to render html file (it shows a map image) in local directory, but it doesn't work properly.

I followed several references, installed webview dependencies in expo and npm both.

The problem is that the result is just html code view, not a map image

Please see my result below:

And my react native code is this (very simple) :

```<code>import React, { Component } from 'react';
import { WebView } from 'react-native-webview';

const testHtml = require('./arcgis/arc1.html');

export default function App() {

  return (
    <WebView source={testHtml} startInLoadingState
    scalesPageToFit
    javaScriptEnabled
    style={{ flex: 1 }}/>
  );

}
</code>```

When I compile the html file in online html website, it appears like this:

left - html code, right - result

This html file is just sample file from official gis website so my react native code must be wrong I guess.

How can I fix the problem ?

Thanks.

答:
You have to use this module for rendering html.

https://github.com/archriss/react-native-render-html

Edit: Instead of using HTML file store your HTML into a .js file and export like this

```<code>export const MyHTML =
    `<p>Here is an <em>ul</em> tag</p>
    <ul>
        <li>Easy</li>
        <li>Peasy</li>
        <li><div style="background-color:red;width:50px;height:50px;"></div></li>
        <li>Lemon</li>
        <li>Squeezy</li>
    </ul>
    <br />
    <p>Here is an <em>ol</em> tag</p>
    <ol>
        <li>Sneaky</li>
        <li>Beaky</li>
        <li>Like</li>
    </ol>
`;
</code>```

and then pass MyHTML to yoru HTML renderer.

Title: Render local html file in React Native

Body:
I run React Native using Expo for android and I'm trying to render html file (it shows a map image) in local directory, but it doesn't work properly.

I followed several references, installed webview dependencies in expo and npm both.

The problem is that the result is just html code view, not a map image

Please see my result below:

And my react native code is this (very simple) :

import React, { Component } from 'react';
import { WebView } from 'react-native-webview';

const testHtml = require('./arcgis/arc1.html');

export default function App() {

  return (
    <WebView source={testHtml} startInLoadingState
    scalesPageToFit
    javaScriptEnabled
    style={{ flex: 1 }}/>
  );

}

When I compile the html file in online html website, it appears like this:

left - html code, right - result

This html file is just sample file from official gis website so my react native code must be wrong I guess.

How can I fix the problem ?

Thanks.

Body:
You have to use this module for rendering html.

https://github.com/archriss/react-native-render-html

Edit: Instead of using HTML file store your HTML into a .js file and export like this

export const MyHTML =
    `<p>Here is an <em>ul</em> tag</p>
    <ul>
        <li>Easy</li>
        <li>Peasy</li>
        <li><div style="background-color:red;width:50px;height:50px;"></div></li>
        <li>Lemon</li>
        <li>Squeezy</li>
    </ul>
    <br />
    <p>Here is an <em>ol</em> tag</p>
    <ol>
        <li>Sneaky</li>
        <li>Beaky</li>
        <li>Like</li>
    </ol>
`;

and then pass MyHTML to yoru HTML renderer.


问:
`ld` error when installing hdp package in R
I am try to install the hdp package by Nicola Robers using the following command in R:

```<code>devtools::install_github("nicolaroberts/hdp", build_vignettes = TRUE)
</code>```

This used to get compiled and installed fine when I had the R version 3.6.2 and gcc version 9.2.1 on an (Arch) Linux machine. After updating the system to R 4.0.0 and gcc 10.1.0, the installation fails with the following message:

```
* installing *source* package ‘hdp’ ...
** using staged installation
** libs
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-base.c -o R-base.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-conparam.c -o R-conparam.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-dp.c -o R-dp.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-hdp.c -o R-hdp.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-hdpMultinomial_iterate.c -o R-hdpMultinomial_iterate.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-multinomial.c -o R-multinomial.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-utils.c -o R-utils.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c randutils.c -o randutils.o
gcc -shared -L/usr/lib64/R/lib -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -o hdp.so R-base.o R-conparam.o R-dp.o R-hdp.o R-hdpMultinomial_iterate.o R-multinomial.o R-utils.o randutils.o -L/usr/lib64/R/lib -lR
/usr/bin/ld: R-conparam.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-dp.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-hdp.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-hdpMultinomial_iterate.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-multinomial.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-utils.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: randutils.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [/usr/share/R//make/shlib.mk:6: hdp.so] Error 1
ERROR: compilation failed for package ‘hdp’
```

The individual files are compiling fine, but the linking seems to fail. Any idea on how to go about debugging what is missing?

答: In case someone else runs into this issue: I manged to compile it by commenting all the references to the debug printing code. I commented all lines with rdebug* and DEBUG. These functions are mainly defined in R-utils.h. It still would be nice to find a better solution. There seems to be a circular definition of the DEBUG?

Body:
I am try to install the hdp package by Nicola Robers using the following command in R:

devtools::install_github("nicolaroberts/hdp", build_vignettes = TRUE)

This used to get compiled and installed fine when I had the R version 3.6.2 and gcc version 9.2.1 on an (Arch) Linux machine. After updating the system to R 4.0.0 and gcc 10.1.0, the installation fails with the following message:

* installing *source* package ‘hdp’ ...
** using staged installation
** libs
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-base.c -o R-base.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-conparam.c -o R-conparam.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-dp.c -o R-dp.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-hdp.c -o R-hdp.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-hdpMultinomial_iterate.c -o R-hdpMultinomial_iterate.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-multinomial.c -o R-multinomial.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c R-utils.c -o R-utils.o
gcc -I"/usr/include/R/" -DNDEBUG   -D_FORTIFY_SOURCE=2   -fpic  -march=x86-64 -mtune=generic -O2 -pipe -fno-plt  -c randutils.c -o randutils.o
gcc -shared -L/usr/lib64/R/lib -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -o hdp.so R-base.o R-conparam.o R-dp.o R-hdp.o R-hdpMultinomial_iterate.o R-multinomial.o R-utils.o randutils.o -L/usr/lib64/R/lib -lR
/usr/bin/ld: R-conparam.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-dp.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-hdp.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-hdpMultinomial_iterate.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-multinomial.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: R-utils.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
/usr/bin/ld: randutils.o:(.bss+0x0): multiple definition of `DEBUG'; R-base.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [/usr/share/R//make/shlib.mk:6: hdp.so] Error 1
ERROR: compilation failed for package ‘hdp’

The individual files are compiling fine, but the linking seems to fail. Any idea on how to go about debugging what is missing?


问:
Groupby apply makes an unwanted transpose when there is only one group
Pandas has an inconsistent behavior when doing a groupby-apply with one group :

```<code>(
    pd.DataFrame({'c1': [0, 0, 0],
                  'c2': [1, 2, 3]})
    .groupby('c1')
    .apply(lambda df: df['c2']).shape
)
</code>```

is equal to (1, 3)

while

```<code>(
    pd.DataFrame({'c1': [0, 0, 1],
                  'c2': [1, 2, 3]})
    .groupby('c1')
    .apply(lambda df: df['c2']).shape
)
</code>```

is equal to (3, ).

When there only one unique value in the groupby variable, the resulting Serie is transposed from what I expect.

I need a consistent behavior : the number of rows must be kept at 3 no matter the number of groups.

答:
You can specify squeeze=True in the .groupby(...) when you are grouping by a column that only has one value, like this:

```<code>(
    pd.DataFrame({'c1': [0, 0, 0],
                  'c2': [1, 2, 3]})
    .groupby('c1', squeeze=True)
    .apply(lambda df: df['c2']).shape
)
</code>```

See the documentation here.

Body:
Pandas has an inconsistent behavior when doing a groupby-apply with one group :

(
    pd.DataFrame({'c1': [0, 0, 0],
                  'c2': [1, 2, 3]})
    .groupby('c1')
    .apply(lambda df: df['c2']).shape
)

is equal to (1, 3)

while

(
    pd.DataFrame({'c1': [0, 0, 1],
                  'c2': [1, 2, 3]})
    .groupby('c1')
    .apply(lambda df: df['c2']).shape
)

is equal to (3, ).

When there only one unique value in the groupby variable, the resulting Serie is transposed from what I expect.

I need a consistent behavior : the number of rows must be kept at 3 no matter the number of groups.

Body:
You can specify squeeze=True in the .groupby(...) when you are grouping by a column that only has one value, like this:

(
    pd.DataFrame({'c1': [0, 0, 0],
                  'c2': [1, 2, 3]})
    .groupby('c1', squeeze=True)
    .apply(lambda df: df['c2']).shape
)

See the documentation here.


问:
Need to compare two arrays with a callback and return an object in Javascript
Construct a function objOfMatches that accepts two arrays and a callback. objOfMatches will build an object and return it. To build the object, objOfMatches will test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value. I got this so far:

```<code>const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
 //Don't know how to check each element using the callback
}
return result
}

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }
</code>```

答:
Try this:

const objOfMatches = (arr1,arr2,call) => {
     let result = {};
     for(let i = 0; i < arr1.length; i++){
          let upper = call(arr1[i]);
          if(arr2[i] && upper == arr2[i])
               result[arr1[i]] = arr2[i];
     }
     return result
}
const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));```

Body:
Construct a function objOfMatches that accepts two arrays and a callback. objOfMatches will build an object and return it. To build the object, objOfMatches will test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value. I got this so far:

const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
 //Don't know how to check each element using the callback
}
return result
}

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }


问:
Javascript modified array before group by
i am trying to modified array before groupBy

i have this array

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

i am trying to modified as per count value has in object value count 3 + 2 = 5 object should in array

witch function i use ? for output array like this

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

答:
Here's a more concise way to use .reduce().

const boxes = [{"name":"BoxOne","count":3},{"name":"BoxTwo","count":2}]

const newBoxes = boxes.reduce((acc, o) =>
  [...acc, ...new Array(o.count).fill(o)]
, [])

console.log(JSON.stringify(newBoxes, null, 2))```

It assumes you don't mind using the same object reference.

It uses spread syntax to always fill the return value with the current content of the accumulator, and the content of a new array containing the desired number of objects for the current iteration, using .fill().

Body:
i am trying to modified array before groupBy

i have this array

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

i am trying to modified as per count value has in object value count 3 + 2 = 5 object should in array

witch function i use ? for output array like this

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

Body:
Here's a more concise way to use .reduce().

const boxes = [{"name":"BoxOne","count":3},{"name":"BoxTwo","count":2}]

const newBoxes = boxes.reduce((acc, o) =>
  [...acc, ...new Array(o.count).fill(o)]
, [])

console.log(JSON.stringify(newBoxes, null, 2))

It assumes you don't mind using the same object reference.

It uses spread syntax to always fill the return value with the current content of the accumulator, and the content of a new array containing the desired number of objects for the current iteration, using .fill().


问:
File Picker for Android
Is there any picker available to pick file from the SDCard or Device memory,like FilePicker available in Blackberry?
If not ,then any alternative for doing this?

Please help me.
Thanks in advance.

答:
There is no standard file picker for Android - which is sad... Nevertheless there are lots of implementations of file browser/picker Intents, applications and sources. You can Google them around and find what meets to your requirements.

I have written file picker for myself and it tooks several hours and Google browsing and some coding.

Title: File Picker for Android


问:
How to take unique IDs and convert each row of another column into another column in R and Python
My data has the form:

```<code>groups <- c("4","4.2","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1")
x <- data.frame(ID = c(rep("samp_1", 4), rep("samp_2", 5)), Group = groups)
</code>```

How do I get this?:

```<code>ID       col_1   col_2   col_3   col_4     col_5
samp_1   4       4.2     4.2.1   4.2.1.1   NA
samp_2   1       1.2     1.2.1   1.2.1.2   1.2.1.2.1
</code>```

Each column will be determined by the length of the string, so all data in column 4 will have length 4 (or length 7 including the dots).

I am looking for the most general solution to this (e.g. using loops; using as few packages as possible) because I need to implement this in both R and Python.

答:
In R, we can create a column for new names with rowid (from data.table) and pivot to 'wide' format

```<code>library(dplyr)
library(data.table)
library(stringr)
x %>%
   mutate(name = str_c('col_', rowid(ID))) %>%
   pivot_wider(names_from = name, values_from = Group)
# A tibble: 2 x 6
#  ID     col_1 col_2 col_3 col_4   col_5
#  <chr>  <chr> <chr> <chr> <chr>   <chr>
#1 samp_1 4     4.2   4.2.1 4.2.1.1 <NA>
#2 samp_2 1     1.2   1.2.1 1.2.1.2 1.2.1.2.1
</code>```

Or using data.table

```<code>library(data.table)
dcast(setDT(x), ID ~ paste0('col_', rowid(ID)), value.var = 'Group')
#       ID col_1 col_2 col_3   col_4     col_5
#1: samp_1     4   4.2 4.2.1 4.2.1.1      <NA>
#2: samp_2     1   1.2 1.2.1 1.2.1.2 1.2.1.2.1
</code>```

Or using base R with reshape

```<code>reshape(transform(x, name = paste0('col_', ave(seq_along(ID), ID,
    FUN = seq_along))), idvar = 'ID', direction = 'wide', timevar = 'name')
</code>```

Body:
My data has the form:

groups <- c("4","4.2","4.2.1","4.2.1.1", "1", "1.2", "1.2.1", "1.2.1.2","1.2.1.2.1")
x <- data.frame(ID = c(rep("samp_1", 4), rep("samp_2", 5)), Group = groups)

How do I get this?:

ID       col_1   col_2   col_3   col_4     col_5
samp_1   4       4.2     4.2.1   4.2.1.1   NA
samp_2   1       1.2     1.2.1   1.2.1.2   1.2.1.2.1

Each column will be determined by the length of the string, so all data in column 4 will have length 4 (or length 7 including the dots).

I am looking for the most general solution to this (e.g. using loops; using as few packages as possible) because I need to implement this in both R and Python.

Body:
In R, we can create a column for new names with rowid (from data.table) and pivot to 'wide' format

library(dplyr)
library(data.table)
library(stringr)
x %>%
   mutate(name = str_c('col_', rowid(ID))) %>%
   pivot_wider(names_from = name, values_from = Group)
# A tibble: 2 x 6
#  ID     col_1 col_2 col_3 col_4   col_5
#  <chr>  <chr> <chr> <chr> <chr>   <chr>
#1 samp_1 4     4.2   4.2.1 4.2.1.1 <NA>
#2 samp_2 1     1.2   1.2.1 1.2.1.2 1.2.1.2.1

Or using data.table

library(data.table)
dcast(setDT(x), ID ~ paste0('col_', rowid(ID)), value.var = 'Group')
#       ID col_1 col_2 col_3   col_4     col_5
#1: samp_1     4   4.2 4.2.1 4.2.1.1      <NA>
#2: samp_2     1   1.2 1.2.1 1.2.1.2 1.2.1.2.1

Or using base R with reshape

reshape(transform(x, name = paste0('col_', ave(seq_along(ID), ID,
    FUN = seq_along))), idvar = 'ID', direction = 'wide', timevar = 'name')


问:
Fix coin change brute force solution
I am starting to write and understand coin change problem and couldn't get intuition so I have started to write a brute force solution. I want to understand the brute force solution before moving to memoization.

```<code>coins = [2, 3, 7]
change = 12

def coin_change(c):
    print(c)
    if c <= 0:
        return 0
    else:
        for i in coins:
            if c - i >= 0:
                coin_change(c - i)

coin_change(change)
</code>```

It prints out couple of changes left but I don't know how to store each path in an array.

I also want to understand how recursion can be used to track path. I can think of adding an extra argument in coin_change but maybe there is an alternate way.

I am confused about its complexity. It has a number of coins call at every step but many online resources mention it's 2n.

Edit: Please note that the coin supply is unlimited, The answer is 4

```<code>[2, 2, 2, 2, 2, 2]
[3, 3, 3, 3]
[2, 2, 2, 3, 3]
[2, 3, 7]
</code>```

答:
Understanding the coin change problem:

Assuming you're referring to the problem of calculating change with the least number of coins, the key idea here is to think of the problem as making a choice at each step - which in this case is 'what coin to dispense next?'

You can break down the problem as coin_change(score) = 1 + min{coin_change(score - c1), coin_change(score - c2), ...} where c1, c2... are the coins you have.

Tracking the pathways:

This is fairly straightforward. Instead of returning the solution (minimum coin combination), simply return all possibilities (all coin combinations). So when you make the recursive call for (score-c1) say, then you get all combinations of coins that make (score-c1) and you just add c1 to them.

The code

```<code>coins = [2, 3, 7]
change = 12

def coin_change(c):
  if c == 0:
    return [[]]     # the only combo possible is no coins
  if c < 0:
    return []      # no combos possible
  else:
    all_combos = []
    for i in coins:
      recursive_result = coin_change(c-i)
      for combo in recursive_result:
        combo.append(i)
      all_combos.extend(recursive_result)

    return all_combos

result = coin_change(change)
for combo in result:
  print(combo)
</code>```

Note: this will give you all permutations. If order doesn't matter, you can use sets to remove duplicates

Edit: Following comments, here's the code that removes duplicates

```<code>coins = [2, 3, 7]
change = 12

def removeDuplicates(combos):
  filtered = set()
  for combo in combos:
    combo.sort()
    filtered.add(tuple(combo))
  return [list(i) for i in filtered]

def coin_change(c):
  if c == 0:
    return [[]]     # the only combo possible is no coins
  if c < 0:
    return []      # no combos possible
  else:
    all_combos = []
    for i in coins:
      recursive_result = coin_change(c-i)
      for combo in recursive_result:
        combo.append(i)
      all_combos.extend(recursive_result)

    return removeDuplicates(all_combos)

result = coin_change(change)
for combo in result:
  print(combo)
</code>```

Title: Fix coin change brute force solution

Body:
I am starting to write and understand coin change problem and couldn't get intuition so I have started to write a brute force solution. I want to understand the brute force solution before moving to memoization.

coins = [2, 3, 7]
change = 12

def coin_change(c):
    print(c)
    if c <= 0:
        return 0
    else:
        for i in coins:
            if c - i >= 0:
                coin_change(c - i)

coin_change(change)

It prints out couple of changes left but I don't know how to store each path in an array.

I also want to understand how recursion can be used to track path. I can think of adding an extra argument in coin_change but maybe there is an alternate way.

I am confused about its complexity. It has a number of coins call at every step but many online resources mention it's 2n.

Edit: Please note that the coin supply is unlimited, The answer is 4

[2, 2, 2, 2, 2, 2]
[3, 3, 3, 3]
[2, 2, 2, 3, 3]
[2, 3, 7]

Body:
Understanding the coin change problem:

Assuming you're referring to the problem of calculating change with the least number of coins, the key idea here is to think of the problem as making a choice at each step - which in this case is 'what coin to dispense next?'

You can break down the problem as coin_change(score) = 1 + min{coin_change(score - c1), coin_change(score - c2), ...} where c1, c2... are the coins you have.

Tracking the pathways:

This is fairly straightforward. Instead of returning the solution (minimum coin combination), simply return all possibilities (all coin combinations). So when you make the recursive call for (score-c1) say, then you get all combinations of coins that make (score-c1) and you just add c1 to them.

The code

coins = [2, 3, 7]
change = 12

def coin_change(c):
  if c == 0:
    return [[]]     # the only combo possible is no coins
  if c < 0:
    return []      # no combos possible
  else:
    all_combos = []
    for i in coins:
      recursive_result = coin_change(c-i)
      for combo in recursive_result:
        combo.append(i)
      all_combos.extend(recursive_result)

    return all_combos

result = coin_change(change)
for combo in result:
  print(combo)

Note: this will give you all permutations. If order doesn't matter, you can use sets to remove duplicates

Edit: Following comments, here's the code that removes duplicates

coins = [2, 3, 7]
change = 12

def removeDuplicates(combos):
  filtered = set()
  for combo in combos:
    combo.sort()
    filtered.add(tuple(combo))
  return [list(i) for i in filtered]

def coin_change(c):
  if c == 0:
    return [[]]     # the only combo possible is no coins
  if c < 0:
    return []      # no combos possible
  else:
    all_combos = []
    for i in coins:
      recursive_result = coin_change(c-i)
      for combo in recursive_result:
        combo.append(i)
      all_combos.extend(recursive_result)

    return removeDuplicates(all_combos)

result = coin_change(change)
for combo in result:
  print(combo)


问:
C code for converting decimal to any base (from 2 to 36)
I have just recently started learning C. I wrote a very short program that converts between decimal and binary. I wanted to try and write a code that converts between decimal and any base (up until 36). However, my code just prints out garbage.

```<code>#include <stdio.h>
#include <string.h>

void printBase(int n, int k, int i, char a[])
{
    int placeholder;
    if (n != 0)
    {
        //return n % 2 + 10 * printBinary(n / 2);
        placeholder=(char)(n%k);
        if(placeholder>=10)
        {
            a[i] = (char)(placeholder - 10) + 'A';
        } else {
            a[i] = (char)placeholder;
        }
        i++;
        printBase(n/2, k, i, a);
    }
    for (i=0; a[i]!='\0'; i++)
    {
        printf("%c", a[i]);
    }
    return;
}

void reverse(char fromStr[], char toStr[])
{
    int i, j=0;
    i=getchar();
    for (i=0; fromStr[i]!='\0'; i++)
    {
        j++;
    }
    i=0;
    while (j>=0)
    {
        toStr[i]=fromStr[j];
        i++;
        j--;
    }
    printf("%s", toStr);
}

int main()
{
    int n, k;
    char a[81], b[81];
    setvbuf(stdout, NULL, _IONBF, 0);
    printf("Enter a deicmal number you want to convert to binary: ");
    scanf("%i", &n);
    fflush(stdout);
    printf("Enter a base: ");
    scanf("%i", &k);
    printBase(n, k, 0, a);
    //printf("%s", a);
    //reverse(a, b);
    return 0;
}
</code>```

I thought the problem was with my reverse function but it works fine outside of this code. Even when I print out string a inside the printBase function it prints out garbage. What is the problem here?

答:
```<code>    Try this one.

#include<stdio.h>
    int main()
    {
        int n,b,t1,i=0;
        float t2,t3,t4;
        int a[10];
        scanf("%d%d",&n,&b);
        for( i=0; n!=0; i++)
        {
            t1=n/b;
            t2=(float)n/b;
            t3=(float)t2-t1;
            t1=t3*b;
            t2=(float)t3*b;
            t4=(float)t2-t1;
            if(t4>=0.5)
            {
                a[i]=t3*b+1;

            }
            else
            {
                a[i]=t3*b;
            }
            n=n/b;
        }
        for(int j=i; j>0; j--)
        {
            printf("%d",a[j-1]);
        }

    return 0;
    }
</code>```

Body:
I have just recently started learning C. I wrote a very short program that converts between decimal and binary. I wanted to try and write a code that converts between decimal and any base (up until 36). However, my code just prints out garbage.

#include <stdio.h>
#include <string.h>

void printBase(int n, int k, int i, char a[])
{
    int placeholder;
    if (n != 0)
    {
        //return n % 2 + 10 * printBinary(n / 2);
        placeholder=(char)(n%k);
        if(placeholder>=10)
        {
            a[i] = (char)(placeholder - 10) + 'A';
        } else {
            a[i] = (char)placeholder;
        }
        i++;
        printBase(n/2, k, i, a);
    }
    for (i=0; a[i]!='\0'; i++)
    {
        printf("%c", a[i]);
    }
    return;
}

void reverse(char fromStr[], char toStr[])
{
    int i, j=0;
    i=getchar();
    for (i=0; fromStr[i]!='\0'; i++)
    {
        j++;
    }
    i=0;
    while (j>=0)
    {
        toStr[i]=fromStr[j];
        i++;
        j--;
    }
    printf("%s", toStr);
}

int main()
{
    int n, k;
    char a[81], b[81];
    setvbuf(stdout, NULL, _IONBF, 0);
    printf("Enter a deicmal number you want to convert to binary: ");
    scanf("%i", &n);
    fflush(stdout);
    printf("Enter a base: ");
    scanf("%i", &k);
    printBase(n, k, 0, a);
    //printf("%s", a);
    //reverse(a, b);
    return 0;
}

I thought the problem was with my reverse function but it works fine outside of this code. Even when I print out string a inside the printBase function it prints out garbage. What is the problem here?


答:
You may not need to have an __init__ in your class to create a class instance with the values inside the json file.

Just have a @classmethod to do a load from a json file into a class instance, like so:

import json

class Profile:
    @classmethod
    def from_json(cls, json_file):
        for key, value in json.load(open(json_file)).items():
            setattr(cls, key, value)
        return cls
```

<p>Now you can create an instance like this:</p>

<pre class="lang-py prettyprint-override"><code>profile = Profile.from_json('/path/to/file.json')
profile._email  # --> "john@baker.com"
</code>```

Title: Why won't this JSON file parse into my object with __dict__ = json.load(f)?

Body:
I have a json file which contains this text:

{"_firstName": "John", "_lastName": "Baker", "_middleName": null, "_mobile": "7609984356", "_education": "Harvard", "_skills": null, "_email": "john@baker.com"}

I am trying to load it in to this Python object:

class Profile():
    def __init__(self):
        self._firstName = None
        self._lastName = None
        self._middleName = None
        self._mobile = None
        self._education = None
        self._skills = []
        self._email = None

I am using:

def profileImport(self):
    with open("../tests/profile.json", "r") as f:
        self._prof.__dict__ = json.load(f)

the line self._prof.__dict__ = json.load(f) is not properly loading the JSON data. I do not get an error from that line, but the object has all None types, indicating that the line didn't successfully load the json data. However, if I use json.loads(), I do get the valid json data as a string, which shows me that the proper file is being accessed. Why is self._prof.__dict__ = json.load(f) failing to parse the data into my object? I'm using Python 3.6.9.

Body:
You may not need to have an __init__ in your class to create a class instance with the values inside the json file.

Just have a @classmethod to do a load from a json file into a class instance, like so:

import json

class Profile:
    @classmethod
    def from_json(cls, json_file):
        for key, value in json.load(open(json_file)).items():
            setattr(cls, key, value)
        return cls

Now you can create an instance like this:

profile = Profile.from_json('/path/to/file.json')
profile._email  # --> "john@baker.com"


问:
Nodejs express promise.all().then() is not synchronous
I'm building a little app using Nodejs express where I update/delete some data. After it did the update/delete, I want to return the data from the database again. I'm using promise.all() because I want to either have everything succeed or fail together.

My problem is that it's not being run synchronously. Every now and then my code returns the data before the update/delete has happend.

Here is an example:

const save = async (houseId, personIds, pets, petsToDelete) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    await Promise.all(dbActions)
    let promiseResult = await Promise.all([
           PetRepository.findByHouse({ houseId: houseId })
    ])

    return promiseResult
}

```

<p>The issue is that PetRepository.findByHouse is sometimes returning data before all dbActions in the loop were executed/completed.</p>

<p>I thought adding them to an array and using that array in a Promise.all outside the loop would fix the issue, but it didn't. Any ideas?</p>

<p>How save() is called: </p>

<pre class="lang-js prettyprint-override"><code>    const promiseResponseHandler = (req, res, promise) => {
        promise.then(successResponse(req, res)).catch(...errorhandling...)
    }

    App.put('save/:houseId', (req, res) => {
        promiseResponseHandler(req, res, PetService.save(req.params.houseId, req.body[0], req.body[1], req.body[2]))
    })
</code>```

Update: repository functions

const Mongoose = require('mongoose')
Mongoose.Promise = global.Promise

Mongoose.connection.on('open', () => Logger.info('Db connection established'))
let connectionString

connectionString = `mongodb+srv://${Config.MONGO_HOST}?retryWrites=true`

connection = Mongoose.connect(
    connectionString,
    {
        user: Config.MONGO_USER,
        pass: Config.MONGO_PW,
        dbName: Config.MONGO_DB,
        reconnectTries: 3,
        useNewUrlParser: true
    }
).catch((err) => {
    Logger.error(err)
})

const deletePets = async (personId, petsToDelete) => {
    if (petsToDelete.length > 0) {
        await Pet.bulkWrite(
            petsToDelete.map((petId) => {
                deleteMany: {
                    filter: { personId: personId, petId: petId}
                }
            })
        )
    }
}

const updatePets = async (personId, pets) => {
    if (pets.length > 0) {
        await Pet.bulkWrite(
            pets.map((pet) => ({
                updateOne: {
                    filter: { personId: pet.personId, petId: petId },
                    update: {
                        $set: { name: pet.name },
                        $setOnInsert: {
                            petId: pet.petId,
                            personId: personId,
                            houseId: pet.houseId
                        }
                    }
                }
            }))
        )
    }
}

module.exports = { deletePets, updatePets }
```

答:
I believe I have found what has been causing PetRepository.findByHouse to return prematurely.

const save = (houseId, personIds, pets, petsToDelete) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    return Promise.all(dbActions).then(() => { // this is the correct way to wait for dbActions
                                               // and then return findByHouse(...)
            return PetRepository.findByHouse({ houseId: houseId })
    })
}
```

Body:
I'm building a little app using Nodejs express where I update/delete some data. After it did the update/delete, I want to return the data from the database again. I'm using promise.all() because I want to either have everything succeed or fail together.

My problem is that it's not being run synchronously. Every now and then my code returns the data before the update/delete has happend.

Here is an example:

const save = async (houseId, personIds, pets, petsToDelete) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    await Promise.all(dbActions)
    let promiseResult = await Promise.all([
           PetRepository.findByHouse({ houseId: houseId })
    ])

    return promiseResult
}

The issue is that PetRepository.findByHouse is sometimes returning data before all dbActions in the loop were executed/completed.

I thought adding them to an array and using that array in a Promise.all outside the loop would fix the issue, but it didn't. Any ideas?

How save() is called:

    const promiseResponseHandler = (req, res, promise) => {
        promise.then(successResponse(req, res)).catch(...errorhandling...)
    }

    App.put('save/:houseId', (req, res) => {
        promiseResponseHandler(req, res, PetService.save(req.params.houseId, req.body[0], req.body[1], req.body[2]))
    })

Update: repository functions

const Mongoose = require('mongoose')
Mongoose.Promise = global.Promise

Mongoose.connection.on('open', () => Logger.info('Db connection established'))
let connectionString

connectionString = `mongodb+srv://${Config.MONGO_HOST}?retryWrites=true`

connection = Mongoose.connect(
    connectionString,
    {
        user: Config.MONGO_USER,
        pass: Config.MONGO_PW,
        dbName: Config.MONGO_DB,
        reconnectTries: 3,
        useNewUrlParser: true
    }
).catch((err) => {
    Logger.error(err)
})

const deletePets = async (personId, petsToDelete) => {
    if (petsToDelete.length > 0) {
        await Pet.bulkWrite(
            petsToDelete.map((petId) => {
                deleteMany: {
                    filter: { personId: personId, petId: petId}
                }
            })
        )
    }
}

const updatePets = async (personId, pets) => {
    if (pets.length > 0) {
        await Pet.bulkWrite(
            pets.map((pet) => ({
                updateOne: {
                    filter: { personId: pet.personId, petId: petId },
                    update: {
                        $set: { name: pet.name },
                        $setOnInsert: {
                            petId: pet.petId,
                            personId: personId,
                            houseId: pet.houseId
                        }
                    }
                }
            }))
        )
    }
}

module.exports = { deletePets, updatePets }


问:
What data structure do I need or how to implement a "LIFO-like" queue?
I'm looking for a data structure that behaves like this:

Last in, first out

Upon iteration the first item is the item that was last in (LCFS - last come, first served)

When max capacity is reached, the 'oldest' item(s) need(s) to be dropped

It sounds like a Queue would do the trick, but that structure is FIFO. Sounds like I need a LIFO-like queue.

Any ideas what I should use?

答:
Use LinkedList<T>:

```<code>public class LifoBuffer<T> : LinkedList<T>
{
    private int capacity;

    public LifoBuffer(int capacity)
    {
        this.capacity = capacity;
    }

    public void Add(T item)
    {
        if (Count == capacity) RemoveLast();
        AddFirst(item);
    }
}

void Main()
{
    var lifoBuffer = new LifoBuffer<int>(3);
    lifoBuffer.Add(1);
    lifoBuffer.Add(2);
    lifoBuffer.Add(3);
    lifoBuffer.Add(4);
    lifoBuffer.Add(5);
    foreach (var item in lifoBuffer) Console.WriteLine(item); // outputs: 5, 4, 3
}
</code>```

Body:
Use LinkedList<T>:

public class LifoBuffer<T> : LinkedList<T>
{
    private int capacity;

    public LifoBuffer(int capacity)
    {
        this.capacity = capacity;
    }

    public void Add(T item)
    {
        if (Count == capacity) RemoveLast();
        AddFirst(item);
    }
}

void Main()
{
    var lifoBuffer = new LifoBuffer<int>(3);
    lifoBuffer.Add(1);
    lifoBuffer.Add(2);
    lifoBuffer.Add(3);
    lifoBuffer.Add(4);
    lifoBuffer.Add(5);
    foreach (var item in lifoBuffer) Console.WriteLine(item); // outputs: 5, 4, 3
}


问:
Excel Save As Button Macro
I would like to create a VB "Save As" macro for Excel that would utilize the data from cell B7,B5 and =NOW as the file name. This new file name would then be saved to a particular directory. (Ex. User clicks "Save" button. File name = (B5)ABCD_(B7)EFGH_=NOW is created and then saved to a directory of my choosing.

I have found scripts that offer some of the singular options, but have had no luck finding or creating a script of my own with these options. Any help would be greatly appreciated.

答:
You need to substitute for the invalid characters in the filename (they can't contain / or :) with periods or something else.

```<code>Sub DateFile()
    Dim str As String
    str = Range("B5").Value & "ABCD_" & Range("B7").Value & "EFGH" & Now()
    str = Replace(str, "/", ".")
    str = Replace(str, ":", ".")
    ActiveWorkbook.SaveAs (str)
End Sub
</code>```

This can then be integrated into your push button code.

Title: Excel Save As Button Macro

Body:
You need to substitute for the invalid characters in the filename (they can't contain / or :) with periods or something else.

Sub DateFile()
    Dim str As String
    str = Range("B5").Value & "ABCD_" & Range("B7").Value & "EFGH" & Now()
    str = Replace(str, "/", ".")
    str = Replace(str, ":", ".")
    ActiveWorkbook.SaveAs (str)
End Sub

This can then be integrated into your push button code.