问:
Segementation fault whilst trying to deep copy struct
I have this piece of code, where I have an array of Constituencies and I wish to deep copy the whole array into a new array. Now too me, it seems I'm doing this correctly but I keep getting a segmentation fault for this code. Is anybody able to spot what I'm doing wrong?

From what I can tell is going wrong is that when freeing the heap memory in the old array, this is somehow freeing the new heap memory stored in the new array. But I'm really not sure how this is the case?

main.c

```<code>int main() {
    const int numConstituencies = 5;
    struct Constituency constituencies[numConstituencies];

    constructConstituency(
        &constituencies[0], "London",
        (unsigned int[]){1, 2, 3, 4}, 4);
    constructConstituency(
        &constituencies[1], "Manchester",
        (unsigned int[]){0, 2}, 2);
    constructConstituency(
        &constituencies[2], "Leeds",
        (unsigned int[]){0, 1, 3}, 3);
    constructConstituency(
        &constituencies[3], "Liverpool",
        (unsigned int[]){0, 2, 4}, 3);
    constructConstituency(
        &constituencies[4], "Newcastle",
        (unsigned int[]){0, 3}, 2);

    struct Constituency * copy = copyConstituencies(constituencies,
                                                    numConstituencies);

    int i;
    for (i = 0; i < numConstituencies; i++) {
        destructConstituency(&constituencies[i]);
    }

    for (i = 0; i < numConstituencies; i++) {
        destructConstituency(&copy[i]);
    }
    return 0;
</code>```

constituency.c

```<code>struct Constituency {
    char *name;
    unsigned int *neighbours;
    unsigned int numNeighbours;
};

void clearValues(struct Constituency * const constituency) {
    constituency->name = NULL;
    constituency->neighbours = NULL;
    constituency->numNeighbours = 0;
}

void constructConstituency(struct Constituency * const constituency,
                           char * const name,
                           unsigned int * const neighbours,
                           unsigned int numNeighbours) {

    clearValues(constituency);

    int nameLength = strlen(name) + 1; // \0 terminated string

    constituency->numNeighbours = numNeighbours;
    constituency->name = (char *) malloc(sizeof(char) * nameLength);
    constituency->neighbours = (unsigned int *) malloc(sizeof(unsigned int) * numNeighbours);
   if (constituency->name == NULL || constituency->neighbours == NULL) {
       printf("Unable to allocate for constituency: %s\n", name);
       exit(1);
   }

    memcpy(constituency->name, name, sizeof(char) * nameLength);
    memcpy(constituency->neighbours, neighbours, sizeof(unsigned int) * numNeighbours);
}

struct Constituency * copyConstituencies(struct Constituency * const constituencies,
                                         unsigned int const numConstituencies) {

    struct Constituency newConstituencies[numConstituencies];

    int i;
    for (i = 0; i < numConstituencies; i++) {
        constructConstituency(&newConstituencies[i],
                              constituencies[i].name,
                              constituencies[i].neighbours,
                              constituencies[i].numNeighbours);
    }

    return newConstituencies;
}

void destructConstituency(struct Constituency * const constituency) {
    free(constituency->name);
    free(constituency->neighbours);

    clearValues(constituency);
}
</code>```

答:
In this functipn

```<code>struct Constituency * copyConstituencies(struct Constituency * const constituencies,
                                         unsigned int const numConstituencies) {

    struct Constituency newConstituencies[numConstituencies];

    int i;
    for (i = 0; i < numConstituencies; i++) {
        constructConstituency(&newConstituencies[i],
                              constituencies[i].name,
                              constituencies[i].neighbours,
                              constituencies[i].numNeighbours);
    }

    return newConstituencies;
}
</code>```

you are returning a pointer to a local array that will not be alive after exiting the function. So the returned pointer is invalid and dereferencing the pointer invokes undefined behavior.

You need to allocate the array dynamically:

```<code>
    struct Constituency *newConstituencies = malloc(sizeof(struct Constituency) * numConstituencies);

</code>```

Body:
I have this piece of code, where I have an array of Constituencies and I wish to deep copy the whole array into a new array. Now too me, it seems I'm doing this correctly but I keep getting a segmentation fault for this code. Is anybody able to spot what I'm doing wrong?

From what I can tell is going wrong is that when freeing the heap memory in the old array, this is somehow freeing the new heap memory stored in the new array. But I'm really not sure how this is the case?

main.c

int main() {
    const int numConstituencies = 5;
    struct Constituency constituencies[numConstituencies];

    constructConstituency(
        &constituencies[0], "London",
        (unsigned int[]){1, 2, 3, 4}, 4);
    constructConstituency(
        &constituencies[1], "Manchester",
        (unsigned int[]){0, 2}, 2);
    constructConstituency(
        &constituencies[2], "Leeds",
        (unsigned int[]){0, 1, 3}, 3);
    constructConstituency(
        &constituencies[3], "Liverpool",
        (unsigned int[]){0, 2, 4}, 3);
    constructConstituency(
        &constituencies[4], "Newcastle",
        (unsigned int[]){0, 3}, 2);

    struct Constituency * copy = copyConstituencies(constituencies,
                                                    numConstituencies);

    int i;
    for (i = 0; i < numConstituencies; i++) {
        destructConstituency(&constituencies[i]);
    }

    for (i = 0; i < numConstituencies; i++) {
        destructConstituency(&copy[i]);
    }
    return 0;

constituency.c

struct Constituency {
    char *name;
    unsigned int *neighbours;
    unsigned int numNeighbours;
};

void clearValues(struct Constituency * const constituency) {
    constituency->name = NULL;
    constituency->neighbours = NULL;
    constituency->numNeighbours = 0;
}

void constructConstituency(struct Constituency * const constituency,
                           char * const name,
                           unsigned int * const neighbours,
                           unsigned int numNeighbours) {

    clearValues(constituency);

    int nameLength = strlen(name) + 1; // \0 terminated string

    constituency->numNeighbours = numNeighbours;
    constituency->name = (char *) malloc(sizeof(char) * nameLength);
    constituency->neighbours = (unsigned int *) malloc(sizeof(unsigned int) * numNeighbours);
   if (constituency->name == NULL || constituency->neighbours == NULL) {
       printf("Unable to allocate for constituency: %s\n", name);
       exit(1);
   }

    memcpy(constituency->name, name, sizeof(char) * nameLength);
    memcpy(constituency->neighbours, neighbours, sizeof(unsigned int) * numNeighbours);
}

struct Constituency * copyConstituencies(struct Constituency * const constituencies,
                                         unsigned int const numConstituencies) {

    struct Constituency newConstituencies[numConstituencies];

    int i;
    for (i = 0; i < numConstituencies; i++) {
        constructConstituency(&newConstituencies[i],
                              constituencies[i].name,
                              constituencies[i].neighbours,
                              constituencies[i].numNeighbours);
    }

    return newConstituencies;
}

void destructConstituency(struct Constituency * const constituency) {
    free(constituency->name);
    free(constituency->neighbours);

    clearValues(constituency);
}

Body:
In this functipn

struct Constituency * copyConstituencies(struct Constituency * const constituencies,
                                         unsigned int const numConstituencies) {

    struct Constituency newConstituencies[numConstituencies];

    int i;
    for (i = 0; i < numConstituencies; i++) {
        constructConstituency(&newConstituencies[i],
                              constituencies[i].name,
                              constituencies[i].neighbours,
                              constituencies[i].numNeighbours);
    }

    return newConstituencies;
}

you are returning a pointer to a local array that will not be alive after exiting the function. So the returned pointer is invalid and dereferencing the pointer invokes undefined behavior.

You need to allocate the array dynamically:

    struct Constituency *newConstituencies = malloc(sizeof(struct Constituency) * numConstituencies);


来源: stackexchange

问:
How to overwrite the folder in s3 bucket when using sam deploy for lamda deployment
I am using the below command to deploy lambda. It always create a new folder(.template and 1 more) in s3 bucket when there is change in my lamda project files. I want to overwrite the folder, so at any point in time, I will be having only 1 folder. How to do that?</p>
```<code> sam deploy --no-fail-on-empty-changeset --s3-bucket bucketName --capabilities CAPABILITY_IAM --stack-name stackName --parameter-overrides "ParameterKey=Stage,ParameterValue=staging"
</code>```

答:
The easiest way to keep deployment artefact buckets "tidy" is to add a Bucket Lifecycle Rule that expires (deletes) objects after an arbitrary number of days.

You can create the rule in the S3 Console (Management > Lifecyle rules). You can safely expire all the objects, including the "current" version. Artefacts are read only at deploy-time and will be re-created with the next sam deploy.

ContentLicense: CC BY-SA 4.0

Body:
I am using the below command to deploy lambda. It always create a new folder(.template and 1 more) in s3 bucket when there is change in my lamda project files. I want to overwrite the folder, so at any point in time, I will be having only 1 folder. How to do that?

 sam deploy --no-fail-on-empty-changeset --s3-bucket bucketName --capabilities CAPABILITY_IAM --stack-name stackName --parameter-overrides "ParameterKey=Stage,ParameterValue=staging"


问:
Get the position of points on a line segment with constraints
I am designing a layout engine for ZenUML. One requirement (after simplification) is this:

There a line segment;

There are n (n < 100, it can be reduced to n < 30 if that makes difference in performance) points on this line segment, the order is fixed; (e.g. P1 ~ Pn)

There are known minimum distances between some points; (e.g. m_d(P2,P4)=500)

The length of the line segment should be as small as possible;

(nice to have) The gaps between neighbour points should be as even as possible (measured by standard deviation^, and must not violate 1~4).

(newly added) it must give result in no longer than 1s for 30 points in worst case (more or less constraints).

^ standard deviation is used as a best alternative that I can precisely describe with my limited math knowledge. However as Roman and David pointed out, there is more appealing result in some cases that does not satisfy lowest standard deviation. See this comment

A sister questions is asked at https://math.stackexchange.com/q/4377433. It is the same problem described with math language (matrix).

For example, for a line segment that has 4 points on it (P1 ~ P4).

m_d(P1, P3) = 200, m_d(P1, P4) = 900.

a. One solution would be P1 = 0, P2 = 0, P3 = 200, P4 = 900.

b. A better solution would be P1 = 0, P2 = 100, P3 = 200, P4 = 900. (put P3 at the middle)

c. A even better solution would be P1 = 0, P2 = 300, P3 = 600, P4 = 900. (evenly distribute P2 and P3).

Some background of this problem. Have a look at the following diagram.

We need to create a layout for all the lifelines (vertical lines). #1, #2

The gap between those line are decided by the length of messages. #3

We need to make sure the total width of the diagram is small (to save space when there are many participants). #4

In this diagram, B should be moved to closer to C. #5

I have implemented the following which satisfies constraints #1~#4. Can some please help with constraint #5? It can be partially met (like b in the example) or fully met (like c in the example). We can use standard deviation to measure the quality of the solution.
Updated: thanks to Roman Svistunov, the base implementation to get non-optimal position is dramatically simplified.

```<code>// Known minimum distance is stored in a matrix
// e.g.
//    m = [
//      [0, 100, 0, 900],
//      [0, 0,   0, 0],
//      [0, 0,   0, 0],
//      [0, 0,   0, 0],
//    ]

let f = function (n: number, m: Array<Array<number>>): number {
  let array = Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    array[i] = f(i, m) + m[i][n];
  }
  return Math.max(0, ...array);
}
</code>```

答:
Since you indicated that an approximation would be OK, here’s a simple code that computes approximately the same result as my other answer. The adjacency list version is longer but likely significantly faster on sparse constraint matrices.</p>
```<code>// Increase for faster but less accurate results.
const PIXEL = 1;

// Returns a layout where each gap is within PIXEL of optimal.
function layOut(n, m) {
  let positions = Array(n).fill(0);
  let gaps = Array(n).fill(0);
  while (true) {
    // Compute the leftmost layout.
    for (let j = 1; j < n; j++) {
      positions[j] = positions[j - 1] + gaps[j - 1];
      for (let i = 0; i < j; i++) {
        positions[j] = Math.max(positions[j], positions[i] + m[i][j]);
      }
    }
    // Compute the rightmost layout. As we do so, each gap that can grow, grows.
    let stillGrowing = false;
    for (let i = n - 2; i > -1; i--) {
      let proposedGap = gaps[i] + PIXEL;
      // i + 1 is rightmost; i is leftmost.
      let maxGap = positions[i + 1] - positions[i];
      if (proposedGap < maxGap) {
        gaps[i] = proposedGap;
        stillGrowing = true;
      } else {
        gaps[i] = maxGap;
      }
      positions[i] = positions[i + 1] - gaps[i];
      for (let j = n - 1; j > i; j--) {
        positions[i] = Math.min(positions[i], positions[j] - m[i][j]);
      }
    }
    if (!stillGrowing) {
      return positions;
    }
  }
}

// Adjacency list version.
function layOut(n, m) {
  let leftArcs = [];
  let rightArcs = [];
  for (let i = 0; i < n; i++) leftArcs.push([]);
  for (let j = 0; j < n; j++) rightArcs.push([]);
  for (let j = 1; j < n; j++) {
    for (let i = 0; i < j; i++) {
      let x = m[i][j];
      if (x > 0) {
        leftArcs[j].push([i, x]);
        rightArcs[i].push([j, x]);
      }
    }
  }
  let positions = Array(n).fill(0);
  let gaps = Array(n).fill(0);
  while (true) {
    // Compute the leftmost layout.
    for (let j = 1; j < n; j++) {
      positions[j] = positions[j - 1] + gaps[j - 1];
      for (let [i, x] of leftArcs[j]) {
        positions[j] = Math.max(positions[j], positions[i] + x);
      }
    }
    // Compute the rightmost layout. As we do so, each gap that can grow, grows.
    let stillGrowing = false;
    for (let i = n - 2; i > -1; i--) {
      let proposedGap = gaps[i] + PIXEL;
      // i + 1 is rightmost; i is leftmost.
      let maxGap = positions[i + 1] - positions[i];
      if (proposedGap < maxGap) {
        gaps[i] = proposedGap;
        stillGrowing = true;
      } else {
        gaps[i] = maxGap;
      }
      positions[i] = positions[i + 1] - gaps[i];
      for (let [j, x] of rightArcs[i]) {
        positions[i] = Math.min(positions[i], positions[j] - x);
      }
    }
    if (!stillGrowing) {
      return positions;
    }
  }
}

// Various test cases.
console.log(
  layOut(4, [
    [0, 200, 0, 900],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(5, [
    [0, 0, 200, 0, 0],
    [0, 0, 0, 550, 0],
    [0, 0, 0, 0, 800],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 150],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 200],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 300],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);
</code>```

Body:
I am designing a layout engine for ZenUML. One requirement (after simplification) is this:

There a line segment;

There are n (n < 100, it can be reduced to n < 30 if that makes difference in performance) points on this line segment, the order is fixed; (e.g. P1 ~ Pn)

There are known minimum distances between some points; (e.g. m_d(P2,P4)=500)

The length of the line segment should be as small as possible;

(nice to have) The gaps between neighbour points should be as even as possible (measured by standard deviation^, and must not violate 1~4).

(newly added) it must give result in no longer than 1s for 30 points in worst case (more or less constraints).

^ standard deviation is used as a best alternative that I can precisely describe with my limited math knowledge. However as Roman and David pointed out, there is more appealing result in some cases that does not satisfy lowest standard deviation. See this comment

A sister questions is asked at https://math.stackexchange.com/q/4377433. It is the same problem described with math language (matrix).

For example, for a line segment that has 4 points on it (P1 ~ P4).

m_d(P1, P3) = 200, m_d(P1, P4) = 900.

a. One solution would be P1 = 0, P2 = 0, P3 = 200, P4 = 900.

b. A better solution would be P1 = 0, P2 = 100, P3 = 200, P4 = 900. (put P3 at the middle)

c. A even better solution would be P1 = 0, P2 = 300, P3 = 600, P4 = 900. (evenly distribute P2 and P3).

Some background of this problem. Have a look at the following diagram.

We need to create a layout for all the lifelines (vertical lines). #1, #2

The gap between those line are decided by the length of messages. #3

We need to make sure the total width of the diagram is small (to save space when there are many participants). #4

In this diagram, B should be moved to closer to C. #5

I have implemented the following which satisfies constraints #1~#4. Can some please help with constraint #5? It can be partially met (like b in the example) or fully met (like c in the example). We can use standard deviation to measure the quality of the solution.
Updated: thanks to Roman Svistunov, the base implementation to get non-optimal position is dramatically simplified.

// Known minimum distance is stored in a matrix
// e.g.
//    m = [
//      [0, 100, 0, 900],
//      [0, 0,   0, 0],
//      [0, 0,   0, 0],
//      [0, 0,   0, 0],
//    ]

let f = function (n: number, m: Array<Array<number>>): number {
  let array = Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    array[i] = f(i, m) + m[i][n];
  }
  return Math.max(0, ...array);
}

Body:
Since you indicated that an approximation would be OK, here’s a simple code that computes approximately the same result as my other answer. The adjacency list version is longer but likely significantly faster on sparse constraint matrices.

// Increase for faster but less accurate results.
const PIXEL = 1;

// Returns a layout where each gap is within PIXEL of optimal.
function layOut(n, m) {
  let positions = Array(n).fill(0);
  let gaps = Array(n).fill(0);
  while (true) {
    // Compute the leftmost layout.
    for (let j = 1; j < n; j++) {
      positions[j] = positions[j - 1] + gaps[j - 1];
      for (let i = 0; i < j; i++) {
        positions[j] = Math.max(positions[j], positions[i] + m[i][j]);
      }
    }
    // Compute the rightmost layout. As we do so, each gap that can grow, grows.
    let stillGrowing = false;
    for (let i = n - 2; i > -1; i--) {
      let proposedGap = gaps[i] + PIXEL;
      // i + 1 is rightmost; i is leftmost.
      let maxGap = positions[i + 1] - positions[i];
      if (proposedGap < maxGap) {
        gaps[i] = proposedGap;
        stillGrowing = true;
      } else {
        gaps[i] = maxGap;
      }
      positions[i] = positions[i + 1] - gaps[i];
      for (let j = n - 1; j > i; j--) {
        positions[i] = Math.min(positions[i], positions[j] - m[i][j]);
      }
    }
    if (!stillGrowing) {
      return positions;
    }
  }
}

// Adjacency list version.
function layOut(n, m) {
  let leftArcs = [];
  let rightArcs = [];
  for (let i = 0; i < n; i++) leftArcs.push([]);
  for (let j = 0; j < n; j++) rightArcs.push([]);
  for (let j = 1; j < n; j++) {
    for (let i = 0; i < j; i++) {
      let x = m[i][j];
      if (x > 0) {
        leftArcs[j].push([i, x]);
        rightArcs[i].push([j, x]);
      }
    }
  }
  let positions = Array(n).fill(0);
  let gaps = Array(n).fill(0);
  while (true) {
    // Compute the leftmost layout.
    for (let j = 1; j < n; j++) {
      positions[j] = positions[j - 1] + gaps[j - 1];
      for (let [i, x] of leftArcs[j]) {
        positions[j] = Math.max(positions[j], positions[i] + x);
      }
    }
    // Compute the rightmost layout. As we do so, each gap that can grow, grows.
    let stillGrowing = false;
    for (let i = n - 2; i > -1; i--) {
      let proposedGap = gaps[i] + PIXEL;
      // i + 1 is rightmost; i is leftmost.
      let maxGap = positions[i + 1] - positions[i];
      if (proposedGap < maxGap) {
        gaps[i] = proposedGap;
        stillGrowing = true;
      } else {
        gaps[i] = maxGap;
      }
      positions[i] = positions[i + 1] - gaps[i];
      for (let [j, x] of rightArcs[i]) {
        positions[i] = Math.min(positions[i], positions[j] - x);
      }
    }
    if (!stillGrowing) {
      return positions;
    }
  }
}

// Various test cases.
console.log(
  layOut(4, [
    [0, 200, 0, 900],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(5, [
    [0, 0, 200, 0, 0],
    [0, 0, 0, 550, 0],
    [0, 0, 0, 0, 800],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 150],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 200],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 300],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);


问:
pass any function parameter which extends a specific base class
I have this base class:

```<code>export class ActVsBudget {
  constructor(
    public budget?: number,
    public actual?: number,
    public monthDiff?: number,
    public cumBudget?: number,
    public cumActual?: number,
    public cumDiff?: number
  ) {}
}
</code>```

And this extended class:

```<code>export class CostOverview extends ActVsBudget {
  constructor(
    public plant?: Plant,
    public plantArea?: PlantArea,
    public costCenter?: CostCenter,
    public costAccType?: CostAccountingType,
    public year?: number,
    public month?: number
  ) {
    super();
  }
}
</code>```

Now, I want a function, which takes a parameter (an array) of any class, which extends the above base class.

With this function signature I can pass the above CostOverview class as a parameter because of the inheritance:

```<code>calculateSums(data: ActVsBudget[])
</code>```

But then what if I need access to any other property of the child class. I can't have acces these properties with this signature.

I tried something like this:

```<code>calculateSums(data: <T extends ActVsBudget>[])
</code>```

But ts complains, that I need some brackets before the [.

What would be the right function signature?

Thanks.

答:
First, you should know that you can not define a type like this:

```<code>calculateSums(data: <T extends ActVsBudget>[])
</code>```

Instead, you should use and define your type before parentheses like:

```<code>caculateSums<TYPE extends ActVsBudget>(data: TYPE[]);
</code>```

When you want to use it you should do something like using other properties of the new inherited class. SomeClass in example

```<code>class SomeClass extends ActVsBudget {}

const similarData = [new SomeClass(), new SomeClass()];

calculateSums<SomeClass>(similarData);
</code>```

Body:
I have this base class:

export class ActVsBudget {
  constructor(
    public budget?: number,
    public actual?: number,
    public monthDiff?: number,
    public cumBudget?: number,
    public cumActual?: number,
    public cumDiff?: number
  ) {}
}

And this extended class:

export class CostOverview extends ActVsBudget {
  constructor(
    public plant?: Plant,
    public plantArea?: PlantArea,
    public costCenter?: CostCenter,
    public costAccType?: CostAccountingType,
    public year?: number,
    public month?: number
  ) {
    super();
  }
}

Now, I want a function, which takes a parameter (an array) of any class, which extends the above base class.

With this function signature I can pass the above CostOverview class as a parameter because of the inheritance:

calculateSums(data: ActVsBudget[])

But then what if I need access to any other property of the child class. I can't have acces these properties with this signature.

I tried something like this:

calculateSums(data: <T extends ActVsBudget>[])

But ts complains, that I need some brackets before the [.

What would be the right function signature?

Thanks.

Body:
First, you should know that you can not define a type like this:

calculateSums(data: <T extends ActVsBudget>[])

Instead, you should use and define your type before parentheses like:

caculateSums<TYPE extends ActVsBudget>(data: TYPE[]);

When you want to use it you should do something like using other properties of the new inherited class. SomeClass in example

class SomeClass extends ActVsBudget {}

const similarData = [new SomeClass(), new SomeClass()];

calculateSums<SomeClass>(similarData);


问:
When to enable application load balancers on AWS
I have an app launched on AWS ELB at the moment. AWS automatically enables an application load balancer which is a significant cost driver to my application. I only have 20 users at the moment, so the load on my application is quite low. When is a good time to enable load balancing?</p>

答:
Use single instance environment in Elastic Beanstalk if you don't want to use load balancer yet.

Ref: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-types.html#single-instance-environ

Quote:

Single-instance environment

A single-instance environment contains one Amazon EC2 instance with an
Elastic IP address. A single-instance environment doesn't have a load
balancer, which can help you reduce costs compared to a load-balanced,
scalable environment. Although a single-instance environment does use
the Amazon EC2 Auto Scaling service, settings for the minimum number
of instances, maximum number of instances, and desired capacity are
all set to 1. Consequently, new instances are not started to
accommodate increasing load on your application.

Use a single-instance environment if you expect your production
application to have low traffic or if you are doing remote
development. If you're not sure which environment type to select, you
can pick one and, if required, you can switch the environment type
later. For more information, see Changing environment type.


问:
How to find all matches of IP v4 addresses and subnets in a text file and print matches line by line with given prefix using only one command?
I would like to replace this pipeline of three commands with one. I think that it is possible to achieve a similar result with only awk or sed.

Current solution with cat, greep and awk

```<code>cat textfile | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}(\/[0-9]{1,2}|)" | awk '{print "prefix "$0}'
</code>```

Text file example:

```<code>192.168.1.1 10.100.20.0/24 some text  2a05:d014:d13:26aa:f493:ef87:bb60:d85f
10.15.12.11, text "10.10.0.0/16" =25.0.0.0/12 etc
</code>```

Output:

```<code>prefix 192.168.1.1
prefix 10.100.20.0/24
prefix 10.15.12.11
prefix 10.10.0.0/16
prefix 25.0.0.0/12
</code>```

答:
For any given shell command, cat file | command can always be replaced with command file if the command can take a file argument or command < file (or the equivalent < file command if you like specifying the file name to the left of the command rather than to the right of it) no matter whether the command can take a file argument or not.

Using GNU awk for multi-char RS and RT:

```<code>$ awk -v RS='([0-9]{1,3}[.]){3}[0-9]{1,3}(/[0-9]{1,2})?' 'RT{print "prefix", RT}' file
prefix 192.168.1.1
prefix 10.100.20.0/24
prefix 10.15.12.11
prefix 10.10.0.0/16
prefix 25.0.0.0/12
</code>```

or with any awk:

```<code>$ awk '{
    while ( match($0,"([0-9]{1,3}[.]){3}[0-9]{1,3}(/[0-9]{1,2})?") ) {
        print "prefix", substr($0,RSTART,RLENGTH)
        $0 = substr($0,RSTART+RLENGTH)
    }
}' file
prefix 192.168.1.1
prefix 10.100.20.0/24
prefix 10.15.12.11
prefix 10.10.0.0/16
prefix 25.0.0.0/12
</code>```

The only changes I made to your regexp were cleanup rather than functional - you don't need to escape . within a bracket expression nor / in a regexp (unless you're using /s as the regexp delimiters which we aren't) and I just think (/[0-9]{1,2})? is clearer than (/[0-9]{1,2}|)

Body:
I would like to replace this pipeline of three commands with one. I think that it is possible to achieve a similar result with only awk or sed.

Current solution with cat, greep and awk

cat textfile | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}(\/[0-9]{1,2}|)" | awk '{print "prefix "$0}'

Text file example:

192.168.1.1 10.100.20.0/24 some text  2a05:d014:d13:26aa:f493:ef87:bb60:d85f
10.15.12.11, text "10.10.0.0/16" =25.0.0.0/12 etc

Output:

prefix 192.168.1.1
prefix 10.100.20.0/24
prefix 10.15.12.11
prefix 10.10.0.0/16
prefix 25.0.0.0/12

Body:
For any given shell command, cat file | command can always be replaced with command file if the command can take a file argument or command < file (or the equivalent < file command if you like specifying the file name to the left of the command rather than to the right of it) no matter whether the command can take a file argument or not.

Using GNU awk for multi-char RS and RT:

$ awk -v RS='([0-9]{1,3}[.]){3}[0-9]{1,3}(/[0-9]{1,2})?' 'RT{print "prefix", RT}' file
prefix 192.168.1.1
prefix 10.100.20.0/24
prefix 10.15.12.11
prefix 10.10.0.0/16
prefix 25.0.0.0/12

or with any awk:

$ awk '{
    while ( match($0,"([0-9]{1,3}[.]){3}[0-9]{1,3}(/[0-9]{1,2})?") ) {
        print "prefix", substr($0,RSTART,RLENGTH)
        $0 = substr($0,RSTART+RLENGTH)
    }
}' file
prefix 192.168.1.1
prefix 10.100.20.0/24
prefix 10.15.12.11
prefix 10.10.0.0/16
prefix 25.0.0.0/12

The only changes I made to your regexp were cleanup rather than functional - you don't need to escape . within a bracket expression nor / in a regexp (unless you're using /s as the regexp delimiters which we aren't) and I just think (/[0-9]{1,2})? is clearer than (/[0-9]{1,2}|)


问:
PDOException SQLSTATE[HY000] [2002] No such file or directory
I believe that I've successfully deployed my (very basic) site to fortrabbit, but as soon as I connect to SSH to run some commands (such as php artisan migrate or php artisan db:seed) I get an error message:

```<code>[PDOException]
SQLSTATE[HY000] [2002] No such file or directory
</code>```

At some point the migration must have worked, because my tables are there - but this doesn't explain why it isn't working for me now.

答:
solved

in my case it was a logic issue in code, the connection values are in a if statement:

```<code>if($_SERVER['HTTP_HOST'] == "localhost")
</code>```

so the solution was to add a pipe and add 127.0.0.1, that solved the problem for me

```<code>if($_SERVER['HTTP_HOST'] == "localhost" || $_SERVER['HTTP_HOST'] == "127.0.0.1")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I believe that I've successfully deployed my (very basic) site to fortrabbit, but as soon as I connect to SSH to run some commands (such as php artisan migrate or php artisan db:seed) I get an error message:

[PDOException]
SQLSTATE[HY000] [2002] No such file or directory

At some point the migration must have worked, because my tables are there - but this doesn't explain why it isn't working for me now.

Body:
solved

in my case it was a logic issue in code, the connection values are in a if statement:

if($_SERVER['HTTP_HOST'] == "localhost")

so the solution was to add a pipe and add 127.0.0.1, that solved the problem for me

if($_SERVER['HTTP_HOST'] == "localhost" || $_SERVER['HTTP_HOST'] == "127.0.0.1")


问:
Break an infinite loop
i have an infinite loop something like that:

```<code>while(true) {
    //do something
}
</code>```

I would like to be able to break the loop using a key for exaple escape key. I think it could be done using events but as i am new to java i cant do that.
Can anyone help me? Thank you in advance!

In the while loop the program reads a value from usb and then send it over the network using sockets. My program is the server and sends bytes to a client. I want to be able to stop that server with a key!

In the while loop the program reads a value from usb and then send it over the network using sockets. My program is the server and sends bytes to a client. I want to be able to stop that server with a key!

答:
You can force quit the console if you are in infinite loops.
Window = Ctrl + Shift + Esc
Mac = Option + Command + Esc</p>

Title: Break an infinite loop

Body:
i have an infinite loop something like that:

while(true) {
    //do something
}

I would like to be able to break the loop using a key for exaple escape key. I think it could be done using events but as i am new to java i cant do that.
Can anyone help me? Thank you in advance!

In the while loop the program reads a value from usb and then send it over the network using sockets. My program is the server and sends bytes to a client. I want to be able to stop that server with a key!

In the while loop the program reads a value from usb and then send it over the network using sockets. My program is the server and sends bytes to a client. I want to be able to stop that server with a key!


问:
Notifications don't seem to be fired from MPMoviePlayerController
I'm trying to get a simple video to play on an iPhone with iOS 4.3 and am running in to issues with dismissing the video player. Below is the code I have set up ... I'm listening for three different notification events to help signal when the movie player and its parent view should exit, but none of those events seem to get fired. My callback method is never invoked. </p>

```<code>NSString* moviePath = [[NSBundle mainBundle] pathForResource:@"sample1" ofType:@"m4v"];
NSLog(@"Here is the movie path: %@", moviePath);
NSURL* movieUrl = [NSURL fileURLWithPath:moviePath];
NSLog(@"Will now try to play movie at the following url: %@", movieUrl);
self.mpvc = [[MPMoviePlayerViewController alloc] initWithContentURL:movieUrl];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.mpvc.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerDidExitFullscreenNotification object:self.mpvc.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerWillExitFullscreenNotification object:self.mpvc.moviePlayer];
[[self.mpvc moviePlayer] prepareToPlay];
[[self.mpvc moviePlayer] setShouldAutoplay:YES];
[[self.mpvc moviePlayer] setFullscreen:YES];

[self.mpvc.view setFrame: self.view.bounds];  // player's frame must match parent's
[self.view addSubview:self.mpvc.view];
</code>```

答:
Are you sure your self.mpvc.moviePlayer is a valid object which is sending the notification.

Are you sure you MPMoviePlayerPlaybackDidFinishNotification MPMoviePlayerDidExitFullscreenNotification MPMoviePlayerWillExitFullscreenNotification same notification name..

Here is the sample code/example of NSNotification

```<code>[[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(manageHistory:) name:@"historyLoaded" object:nil];

[[NSNotificationCenter defaultCenter] postNotificationName:@"historyLoaded"
   object:nil userInfo:jsonReturn];

- (void) manageHistory: (NSNotification *) historyData{
     NSDictionary* _dict = historyData.userInfo;
     NSLog(@"Your information embedded to dictionary obj %@",_dict);
}
</code>```

Body:
I'm trying to get a simple video to play on an iPhone with iOS 4.3 and am running in to issues with dismissing the video player. Below is the code I have set up ... I'm listening for three different notification events to help signal when the movie player and its parent view should exit, but none of those events seem to get fired. My callback method is never invoked.

NSString* moviePath = [[NSBundle mainBundle] pathForResource:@"sample1" ofType:@"m4v"];
NSLog(@"Here is the movie path: %@", moviePath);
NSURL* movieUrl = [NSURL fileURLWithPath:moviePath];
NSLog(@"Will now try to play movie at the following url: %@", movieUrl);
self.mpvc = [[MPMoviePlayerViewController alloc] initWithContentURL:movieUrl];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.mpvc.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerDidExitFullscreenNotification object:self.mpvc.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerWillExitFullscreenNotification object:self.mpvc.moviePlayer];
[[self.mpvc moviePlayer] prepareToPlay];
[[self.mpvc moviePlayer] setShouldAutoplay:YES];
[[self.mpvc moviePlayer] setFullscreen:YES];

[self.mpvc.view setFrame: self.view.bounds];  // player's frame must match parent's
[self.view addSubview:self.mpvc.view];

Body:
Are you sure your self.mpvc.moviePlayer is a valid object which is sending the notification.

Are you sure you MPMoviePlayerPlaybackDidFinishNotification MPMoviePlayerDidExitFullscreenNotification MPMoviePlayerWillExitFullscreenNotification same notification name..

Here is the sample code/example of NSNotification

[[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(manageHistory:) name:@"historyLoaded" object:nil];

[[NSNotificationCenter defaultCenter] postNotificationName:@"historyLoaded"
   object:nil userInfo:jsonReturn];

- (void) manageHistory: (NSNotification *) historyData{
     NSDictionary* _dict = historyData.userInfo;
     NSLog(@"Your information embedded to dictionary obj %@",_dict);
}


问:
Spring create generic service multiple times using generic in constructor
I have a service that uses some object as a generic

@Component
@RequiredArgsConstructor
public class SomeGenericService<T extends Base> {
    private final T base;

    public void someWork(String info) {
        base.someAction(info);
    }
}

```
<p>I also have 3 <code>Base</code> implementations marked with <code>@Component</code>(<code>Base1</code>, <code>Base2</code>, <code>Base3</code>)</p>
<p>I want spring itself to create a service with the generic it needs, for the following example</p>
<pre class="lang-java prettyprint-override"><code>@Component
@RequiredArgsConstructor
public class Runner implements CommandLineRunner {
    private final SomeGenericService<Base1> s1;
    private final SomeGenericService<Base2> s2;
    private final SomeGenericService<Base3> s3;

    @Override
    public void run(String... args) throws Exception {
        String someString = "text";

        s1.someWork(someString);
        s2.someWork(someString);
        s3.someWork(someString);
    }
}
</code>```

But after the launch, the spring does not understand what I want from it.

```<code>Parameter 0 of constructor in SomeGenericService required a single bean, but 3 were found:
    - base1: defined in file [Base1.class]
    - base2: defined in file [Base2.class]
    - base3: defined in file [Base3.class]
</code>```

Is it possible to set this to automatic, without manually configuring it via the @Bean annotation for each service?

答:
You need to define how those beans should be injected. It's a good practice to have some @Configurations for this purpose. Something like:

 @Configuration
 @Import({
            Base1.class,
            Base2.class,
            Base3.class
    })
    public class SomeConfig {
        @Bean
        SomeGenericService<Base1> someGenericService1() {
            return new SomeGenericService(new Base1());
        }
        @Bean
        SomeGenericService<Base2> someGenericService2() {
            return new SomeGenericService(new Base2());
        }
        @Bean
        SomeGenericService<Base3> someGenericService3() {
            return new SomeGenericService(new Base3());
        }
    }
```

Body:
I have a service that uses some object as a generic

@Component
@RequiredArgsConstructor
public class SomeGenericService<T extends Base> {
    private final T base;

    public void someWork(String info) {
        base.someAction(info);
    }
}

I also have 3 Base implementations marked with @Component(Base1, Base2, Base3)

I want spring itself to create a service with the generic it needs, for the following example

@Component
@RequiredArgsConstructor
public class Runner implements CommandLineRunner {
    private final SomeGenericService<Base1> s1;
    private final SomeGenericService<Base2> s2;
    private final SomeGenericService<Base3> s3;

    @Override
    public void run(String... args) throws Exception {
        String someString = "text";

        s1.someWork(someString);
        s2.someWork(someString);
        s3.someWork(someString);
    }
}

But after the launch, the spring does not understand what I want from it.

Parameter 0 of constructor in SomeGenericService required a single bean, but 3 were found:
    - base1: defined in file [Base1.class]
    - base2: defined in file [Base2.class]
    - base3: defined in file [Base3.class]

Is it possible to set this to automatic, without manually configuring it via the @Bean annotation for each service?


问:
Getting the different elements from 2 lists in groovy
i have 2 lists in groovy and im trying to 'filter' one list from the other,and get them into a new list .I'm also doing that in a groovy function for a jenkins pipeline I'm writing. Many thank.</p>
```<code>l1 = ['abc','def','ghi','jkl']
l2 = ['def','jkl']
def sum = []
for (y in l1) {
  for (x in l2) {
     if (x != y){
       sum = sum + x
     }
  }
}
print sum
</code>```

答:
eventually I did this and it worked</p>
```<code>sum = l1 - l2

print "${sum}" //prints the elements in the array
</code>```

Body:
i have 2 lists in groovy and im trying to 'filter' one list from the other,and get them into a new list .I'm also doing that in a groovy function for a jenkins pipeline I'm writing. Many thank.

l1 = ['abc','def','ghi','jkl']
l2 = ['def','jkl']
def sum = []
for (y in l1) {
  for (x in l2) {
     if (x != y){
       sum = sum + x
     }
  }
}
print sum

Body:
eventually I did this and it worked

sum = l1 - l2

print "${sum}" //prints the elements in the array


问:
php post request is empty when posting to url with nginx and switch router
So nginx send all the request of the site to the index.php

```<code>location / {
            try_files $uri $uri/ /index.php;
}
</code>```

So when I send mine post request to the /login-post as a post request and try to get the post data. The array is always empty and I dont understand what I am missing cause Im posting towards the correct URL? but the post data is not there?

the Form:

```<code><form class="form-signin text-center" action="/login-post" enctype="multipart/form-data" method="post" style="max-width: 400px">
    <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
    <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>

    <div style="width: 100%; display: flex; align-content: end; flex-direction: row-reverse;">
    <button class="btn btn-lg btn-primary btn-block" style="width: 100px" type="submit">Sign in</button>
    </div>
    <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
</form>
</code>```

the php code that should log the post data from (index.php)

```<code>$request = $_SERVER['REQUEST_URI'];
echo $request;

switch ($request) {
    case '/' :
        (new HomeController)->index(); // this works
        break;
    case '/login' :
        (new LoginController())->index(); // this works
        break;
    case '/login-post':
        print_r($_POST); <---- this is always empty
        break;
    default:
        http_response_code(404);
        echo "404";
        break;
}
</code>```

I dont see whats going wrong? or why I cant see the post data.

答:
I had the same issue and I could perform a good solution, the problem is related with the htaccess configuration, so lets try adding this in it

```<code>RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|OPTIONS|POST|PROPFIND|PUT) [NC]
RewriteRule .* - [F,L]
</code>```

It will allow you to preserve the information that you send thru a form

If it does not work please try to change the whole htaccess for something like this

```<code>RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*) $1.html

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|OPTIONS|POST|PROPFIND|PUT) [NC]
RewriteRule .* - [F,L]
RewriteRule ^(.+)$ index.php [QSA,L]

ErrorDocument 404 /404.php
</code>```

Body:
So nginx send all the request of the site to the index.php

location / {
            try_files $uri $uri/ /index.php;
}

So when I send mine post request to the /login-post as a post request and try to get the post data. The array is always empty and I dont understand what I am missing cause Im posting towards the correct URL? but the post data is not there?

the Form:

<form class="form-signin text-center" action="/login-post" enctype="multipart/form-data" method="post" style="max-width: 400px">

Please sign in

    <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>

    <button class="btn btn-lg btn-primary btn-block" style="width: 100px" type="submit">Sign in</button>

© 2017-2018

</form>

the php code that should log the post data from (index.php)

$request = $_SERVER['REQUEST_URI'];
echo $request;

switch ($request) {
    case '/' :
        (new HomeController)->index(); // this works
        break;
    case '/login' :
        (new LoginController())->index(); // this works
        break;
    case '/login-post':
        print_r($_POST); <---- this is always empty
        break;
    default:
        http_response_code(404);
        echo "404";
        break;
}

I dont see whats going wrong? or why I cant see the post data.

Body:
I had the same issue and I could perform a good solution, the problem is related with the htaccess configuration, so lets try adding this in it

RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|OPTIONS|POST|PROPFIND|PUT) [NC]
RewriteRule .* - [F,L]

It will allow you to preserve the information that you send thru a form

If it does not work please try to change the whole htaccess for something like this

RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*) $1.html

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|OPTIONS|POST|PROPFIND|PUT) [NC]
RewriteRule .* - [F,L]
RewriteRule ^(.+)$ index.php [QSA,L]

ErrorDocument 404 /404.php


问:
Monitoring bundle exec unicorn_rails with bluepill
Due to unicorn_rails complaining about different gem versions we moved to running bundle exec unicorn_rails... in our bluepill files. This change solved that particular problem and things start and stop but when we try sudo bluepill status we now get

unicorn(pix: XXXXXX): unmonitored

Which looks like bluepill is not monitoring the unicorn processes now. It will restart the child processes if I stop them but won't restart the parent process.

I've searched around but can't find much about this issue and was hoping someone could shed some light on it. The bluepill config file is

```<code>app_dir = "/opt/local/share/httpd/apps/xyz"
Bluepill.application('xyz', :log_file => "#{app_dir}/current/log/bluepill.log") do |app|
  app.process('unicorn') do |process|
    process.pid_file    = "#{app_dir}/shared/pids/unicorn.pid"
    process.working_dir = "#{app_dir}/current"

    process.stdout = process.stderr = "#{app_dir}/shared/log/unicorn.err.log"
    process.start_command = "bundle exec unicorn_rails -D -c #{app_dir}/current/config/environments/production/unicorn.rb -E production"
    process.stop_command = "kill -QUIT {{PID}}"
    process.restart_command = "kill -USR2 {{PID}}"

    process.start_grace_time = 8.seconds
    process.stop_grace_time = 5.seconds
    process.restart_grace_time = 13.seconds

    process.monitor_children do |child_process|
      child_process.stop_command = "kill -QUIT {{PID}}"

      child_process.checks :mem_usage, :every => 10.seconds, :below => 200.megabytes, :times => [3,5]
      child_process.checks :cpu_usage, :every => 10.seconds, :below => 50, :times => [3,5]
    end
  end

end
</code>```

答:
When you run bundle exec, it sets up an environment and forks the unicorn_rails process.  Bluepill ends up monitoring the original bundle exec process instead of unicorn which is why you see unmonitored.

I set up my bundler environment directly in bluepill and then execute unicorn_rails directly:

```<code>Bluepill.application('xyz') do |app|
  app.environment = `env -i BUNDLE_GEMFILE=#{app_dir}/Gemfile bundle exec env`.lines.inject({}) do |env_hash,l|
    kv = l.chomp.split('=',2)
    env_hash[kv[0] = kv[1]
    env_hash
  end

  app.process('unicorn') do |process|
    process.start_command = "unicorn_rails -D -c #{app_dir}/current/config/environments/production/unicorn.rb -E production"
  end
end
</code>```

(Note: I omitted part of the above config file for clarity.  Your config file looks good, just try adding the app.environment stuff above and removing bundle exec from your start command.)

This sets up the environment in bluepill by capturing the bundler environment variables using backticks, parsing the returned string into a hash and assigning it to app.environment.

Body:
Due to unicorn_rails complaining about different gem versions we moved to running bundle exec unicorn_rails... in our bluepill files. This change solved that particular problem and things start and stop but when we try sudo bluepill status we now get

unicorn(pix: XXXXXX): unmonitored

Which looks like bluepill is not monitoring the unicorn processes now. It will restart the child processes if I stop them but won't restart the parent process.

I've searched around but can't find much about this issue and was hoping someone could shed some light on it. The bluepill config file is

app_dir = "/opt/local/share/httpd/apps/xyz"
Bluepill.application('xyz', :log_file => "#{app_dir}/current/log/bluepill.log") do |app|
  app.process('unicorn') do |process|
    process.pid_file    = "#{app_dir}/shared/pids/unicorn.pid"
    process.working_dir = "#{app_dir}/current"

    process.stdout = process.stderr = "#{app_dir}/shared/log/unicorn.err.log"
    process.start_command = "bundle exec unicorn_rails -D -c #{app_dir}/current/config/environments/production/unicorn.rb -E production"
    process.stop_command = "kill -QUIT {{PID}}"
    process.restart_command = "kill -USR2 {{PID}}"

    process.start_grace_time = 8.seconds
    process.stop_grace_time = 5.seconds
    process.restart_grace_time = 13.seconds

    process.monitor_children do |child_process|
      child_process.stop_command = "kill -QUIT {{PID}}"

      child_process.checks :mem_usage, :every => 10.seconds, :below => 200.megabytes, :times => [3,5]
      child_process.checks :cpu_usage, :every => 10.seconds, :below => 50, :times => [3,5]
    end
  end

end

Body:
When you run bundle exec, it sets up an environment and forks the unicorn_rails process.  Bluepill ends up monitoring the original bundle exec process instead of unicorn which is why you see unmonitored.

I set up my bundler environment directly in bluepill and then execute unicorn_rails directly:

Bluepill.application('xyz') do |app|
  app.environment = `env -i BUNDLE_GEMFILE=#{app_dir}/Gemfile bundle exec env`.lines.inject({}) do |env_hash,l|
    kv = l.chomp.split('=',2)
    env_hash[kv[0] = kv[1]
    env_hash
  end

  app.process('unicorn') do |process|
    process.start_command = "unicorn_rails -D -c #{app_dir}/current/config/environments/production/unicorn.rb -E production"
  end
end

(Note: I omitted part of the above config file for clarity.  Your config file looks good, just try adding the app.environment stuff above and removing bundle exec from your start command.)

This sets up the environment in bluepill by capturing the bundler environment variables using backticks, parsing the returned string into a hash and assigning it to app.environment.


问:
fitting on X_train and y_train
For somebody super beginner how can one remember what to pass into model.fit?
I have to keep on looking up that we are supposed to pass X_train, y_train.
But I guess I don't fully understand why we don't pass in something else such as:
X_train, y_test.

Thank you!
Josh

答:
X are your features and y are your associated labels. Your model may only see the test data in the evaluation step.

https://machinelearningmastery.com/train-test-split-for-evaluating-machine-learning-algorithms/

Title: fitting on X_train and y_train


问:
Source Code html doesn't download completly
I try to get HTML content, everything works find except 1 thing. It doesn't download whole code and skip the content which I want to extract(urls to images, names) and I have just blank classes 'obrazek'.

Here is the code i use to get source code:

```<code>     String SourceCode(String adres) throws IllegalStateException, IOException
{

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(adres);
    HttpResponse response = null;
    try {
         response = httpClient.execute(httpGet, localContext);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()
                    )
            );
    String result = "";
    while(reader.readLine() != null)
    {
        result += reader.readLine();
    }
    reader.close();
    return result;
</code>```

Thank you for help:)

答:
You skip one line each time. should be

```<code>StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
    result.append(line);
}
reader.close();
return result.toString();
</code>```

BTW - I used StringBuilder to avoid creation of new String object each iteration - very recommended.

Body:
I try to get HTML content, everything works find except 1 thing. It doesn't download whole code and skip the content which I want to extract(urls to images, names) and I have just blank classes 'obrazek'.

Here is the code i use to get source code:

     String SourceCode(String adres) throws IllegalStateException, IOException
{

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(adres);
    HttpResponse response = null;
    try {
         response = httpClient.execute(httpGet, localContext);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()
                    )
            );
    String result = "";
    while(reader.readLine() != null)
    {
        result += reader.readLine();
    }
    reader.close();
    return result;

Thank you for help:)

Body:
You skip one line each time. should be

StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
    result.append(line);
}
reader.close();
return result.toString();

BTW - I used StringBuilder to avoid creation of new String object each iteration - very recommended.


问:
Github Actions: using workflow_run based on new tags
I have two workflows: CI (for continuous integration) and CD (for continuous delivery). Both are working fine individually. My goal is to run the CD workflow only when:

A new tag like v1.1.1 is created on the master branch

The CI workflow is finished

To achieve my goal I'm using the workflow_run event. These are the snippets of my workflows files:

ci.yml:

```<code>name: CI

on:
  push:
    tags: v[1-9]+.[0-9]+.[0-9]+

  pull_request:
    branches: [develop, hotfix*]
</code>```

cd.yml

```<code>name: CD

on:
  workflow_run:
    workflows: [CI]
    branches: [master]
    types:
      - completed
</code>```

The current behavior is: when a tag is created in the master branch only the CI workflow run. I've tried putting tags: v[1-9]+.[0-9]+.[0-9]+ in the workflow_run but the behavior is the same.

My question is: how can I achieve my goal? Is it possible?

答:
According to docs you can only use branches option and not tags for workflow_run so I'm afraid that's why your current setting doesn't work.

You have some alternatives though:

You can turn your CD workflow into action and run it as part of your CI with condition:
.github/actiond/cd/action.yml:

name: CD
description: Run CD
runs:
  using: composite
  steps:
    - run: echo "Success!"
      shell: bash
```
<p>CI:</p>
<pre class="lang-yaml prettyprint-override"><code>name: CI

on:
  push:
    tags: v[1-9]+.[0-9]+.[0-9]+
  pull_request:
    branches: [develop, hotfix*]

jobs:
  sucess:
    name: Log success
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: echo "Success!"
      - name: Run CD
        if: github.event_name == 'push' && contains(github.event.ref, '/tags/')
        uses: ./.github/actions/cd
</code>```

Have it as a separate job that is dependant on CI job using needs option

Converting it to action makes for better encapsulation IMO although requires some work.

Body:
I have two workflows: CI (for continuous integration) and CD (for continuous delivery). Both are working fine individually. My goal is to run the CD workflow only when:

A new tag like v1.1.1 is created on the master branch

The CI workflow is finished

To achieve my goal I'm using the workflow_run event. These are the snippets of my workflows files:

ci.yml:

name: CI

on:
  push:
    tags: v[1-9]+.[0-9]+.[0-9]+

  pull_request:
    branches: [develop, hotfix*]

cd.yml

name: CD

on:
  workflow_run:
    workflows: [CI]
    branches: [master]
    types:
      - completed

The current behavior is: when a tag is created in the master branch only the CI workflow run. I've tried putting tags: v[1-9]+.[0-9]+.[0-9]+ in the workflow_run but the behavior is the same.

My question is: how can I achieve my goal? Is it possible?

Body:
According to docs you can only use branches option and not tags for workflow_run so I'm afraid that's why your current setting doesn't work.

You have some alternatives though:

You can turn your CD workflow into action and run it as part of your CI with condition:
.github/actiond/cd/action.yml:

name: CD
description: Run CD
runs:
  using: composite
  steps:
    - run: echo "Success!"
      shell: bash

CI:

name: CI

on:
  push:
    tags: v[1-9]+.[0-9]+.[0-9]+
  pull_request:
    branches: [develop, hotfix*]

jobs:
  sucess:
    name: Log success
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: echo "Success!"
      - name: Run CD
        if: github.event_name == 'push' && contains(github.event.ref, '/tags/')
        uses: ./.github/actions/cd

Have it as a separate job that is dependant on CI job using needs option

Converting it to action makes for better encapsulation IMO although requires some work.


问:
503 error from cloudfront cdn when loading video from s3 using lambda
I'm getting an error when fetching videos from s3 as part of the origin-response trigger. This is my code:

const getVidS3 = (s3, bucketName, fileName) =>
    new Promise((res, rej) => {
        const start = Date.now();
        s3.listObjects(
            {
                Bucket: bucketName,
                Delimiter: '/',
                Prefix: `${fileName}/`,
                MaxKeys: 1,
            },
            function (err, data) {
                console.log(
                    '================ milliseconds to list objects:',
                    Date.now() - start
                );
                if (err) return rej(err);
                if (!Array.isArray(data.Contents) || data.Contents.length < 1) {
                    return rej('original raw video not found');
                }
                console.log('============= s3 objects:', data);
                const rawVidFileKey = data.Contents[0].Key;
                s3.getObject(
                    {
                        Bucket: bucketName,
                        Key: rawVidFileKey,
                    },
                    (err, data) => {
                        console.log(
                            '================ milliseconds to get video object:',
                            Date.now() - start
                        );
                        if (err) {
                            return rej(err);
                        }

                        const contentType = data.ContentType;
                        const video = data.Body;
                        console.log('=============== S3 video data', data);
                        return res({ video, contentType });
                    }
                );
            }
        );
    });
                const videoFile = await getVidS3(fileName);
                response.status = 200;
                response.headers['Content-Type'] = [
                    { key: 'Content-Type', value: videoFile.contentType },
                ];
                response.headers['Content-Disposition'] = [
                    { key: 'Content-Disposition', value: 'inline' },
                ];

                response.headers['Cache-Control'] = [
                    { key: 'Cache-Control', value: 'public,max-age=1' },
                ];
                response.headers['Access-Control-Allow-Methods'] = [
                    {
                        key: 'Access-Control-Allow-Methods',
                        value: 'GET,PUT,POST,DELETE',
                    },
                ];
                response.statusDescription = 'OK';
                response.body = videoFile.video;
```
<p>From this article it seems that binary files should be sent as base64 encoded strings, so I tried changing the last line of code to</p>
<pre class="lang-js prettyprint-override"><code>                const base64Vid = videoFile.video.toString('base64');
                response.body = base64Vid;
                response.bodyEncoding = 'base64';
</code>```

But the problem hasn't gone away. I've confirmed that the video is getting fetched from s3, so it seems that I'm setting the body incorrectly. This is the error from the lambda: ERROR Validation error: The Lambda function returned an invalid json output, json is not parsable.

What am I missing? Thanks.

答:
Considering you're getting videos, the probable issue is that your response payload is too large.

You can check other limitations in the official documentation but for the request and response payload, the max allowed size is 6 MB. I assume you have a video that is bigger than 6 MB.

Body:
I'm getting an error when fetching videos from s3 as part of the origin-response trigger. This is my code:

const getVidS3 = (s3, bucketName, fileName) =>
    new Promise((res, rej) => {
        const start = Date.now();
        s3.listObjects(
            {
                Bucket: bucketName,
                Delimiter: '/',
                Prefix: `${fileName}/`,
                MaxKeys: 1,
            },
            function (err, data) {
                console.log(
                    '================ milliseconds to list objects:',
                    Date.now() - start
                );
                if (err) return rej(err);
                if (!Array.isArray(data.Contents) || data.Contents.length < 1) {
                    return rej('original raw video not found');
                }
                console.log('============= s3 objects:', data);
                const rawVidFileKey = data.Contents[0].Key;
                s3.getObject(
                    {
                        Bucket: bucketName,
                        Key: rawVidFileKey,
                    },
                    (err, data) => {
                        console.log(
                            '================ milliseconds to get video object:',
                            Date.now() - start
                        );
                        if (err) {
                            return rej(err);
                        }

                        const contentType = data.ContentType;
                        const video = data.Body;
                        console.log('=============== S3 video data', data);
                        return res({ video, contentType });
                    }
                );
            }
        );
    });
                const videoFile = await getVidS3(fileName);
                response.status = 200;
                response.headers['Content-Type'] = [
                    { key: 'Content-Type', value: videoFile.contentType },
                ];
                response.headers['Content-Disposition'] = [
                    { key: 'Content-Disposition', value: 'inline' },
                ];

                response.headers['Cache-Control'] = [
                    { key: 'Cache-Control', value: 'public,max-age=1' },
                ];
                response.headers['Access-Control-Allow-Methods'] = [
                    {
                        key: 'Access-Control-Allow-Methods',
                        value: 'GET,PUT,POST,DELETE',
                    },
                ];
                response.statusDescription = 'OK';
                response.body = videoFile.video;

From this article it seems that binary files should be sent as base64 encoded strings, so I tried changing the last line of code to

                const base64Vid = videoFile.video.toString('base64');
                response.body = base64Vid;
                response.bodyEncoding = 'base64';

But the problem hasn't gone away. I've confirmed that the video is getting fetched from s3, so it seems that I'm setting the body incorrectly. This is the error from the lambda: ERROR Validation error: The Lambda function returned an invalid json output, json is not parsable.

What am I missing? Thanks.


问:
How can I update my backgroud image url by the image I got from random client
I'm trying to make a function which allows my user to customize the whole background of my site. so I made a form for image upload but I don't know what to do next to do with this image I got from a user. Where this image or images are stored and how to access to this image and make this images as a background image. below is my html

```<code><div class="crossfade">
  <figure></figure>
  <figure></figure>
  <figure></figure>
  <figure></figure>
  <figure></figure>
</div>
</code>```

and I gave animation using css

```<code>.crossfade figure {
  animation: imageAnimation 60s linear infinite 0s;
  backface-visibility: hidden;
  background-size: cover;
  background-position: center;
  color: transparent;
  height: 100%;
  width: 100%;
  left: 0px;
  opacity: 0;
  position: absolute;
  top: 0px;
  z-index: -1;
  margin: 0;
}

.crossfade > figure:nth-child(1) {
  background-image: url(../img/0.jpeg);
}

.crossfade > figure:nth-child(2) {
  animation-delay: 12s;
  background-image: url(../img/1.jpeg);
}
.crossfade > figure:nth-child(3) {
  animation-delay: 24s;
  background-image: url(../img/2.jpeg);
}
.crossfade > figure:nth-child(4) {
  animation-delay: 36s;
  background-image: url(../img/0.jpeg);
}
.crossfade > figure:nth-child(5) {
  animation-delay: 48s;
  background-image: url(../img/1.jpeg);
}

@keyframes imageAnimation {
  0% {
    animation-timing-function: ease-in;
    opacity: 0;
  }
  8% {
    animation-timing-function: ease-out;
    opacity: 1;
  }
  17% {
    opacity: 1;
  }
  45% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}
</code>```

and get image from user by form

```<code><form id="background-form" method="get">
  <div>
    <label for="custom-file" class="form-label">Choose Images to upload(jpg, jpeg, or png) up to 5MB</label>
      <input
        required
        type="file"
        class="form-control"
        id="custom-file"
        accept=".jpg, .jpeg, .png"
        multiple/>
  </div>
</form>
</code>```

And javascript file to handle submit

```<code>const submit = document.querySelector("form#background-form")

function handleSubmit() {
  //How should I access to the image I got from form
  //I tried to access by using URL.createObjectURL(file) API but didn't work
  //Or is there a way to store this image in localstorage or sessionstorage?
  //If it is possible how can I access to the image URL?

}
</code>```

答:
There is way to store your image using local and session storage based on your needs and take in count, that localStorage have size limit of 5mb and limit can be increased by the user when needed, however, only a few browsers support this but on other hand sessionStorage size is limited only by system memory.

To save image in localStorage you can do following.

```<code>const fileInput = document.querySelector('#fileInput');
</code>```

when input is changed - when image is chosen or changed this function executes

```<code>fileInput.addEventListener('change', function () {
    const reader = new FileReader(); -- read content of files
</code>```

when content of files is loaded

```<code>    reader.addEventListener('load', function () {
</code>```

save result ( image ) in local storage

```<code>        localStorage.setItem('image', reader.result)
    })
</code>```

read content of blob or file

```<code>    reader.readAsDataURL(this.files[0]);
})
</code>```

Body:
I'm trying to make a function which allows my user to customize the whole background of my site. so I made a form for image upload but I don't know what to do next to do with this image I got from a user. Where this image or images are stored and how to access to this image and make this images as a background image. below is my html

and I gave animation using css

.crossfade figure {
  animation: imageAnimation 60s linear infinite 0s;
  backface-visibility: hidden;
  background-size: cover;
  background-position: center;
  color: transparent;
  height: 100%;
  width: 100%;
  left: 0px;
  opacity: 0;
  position: absolute;
  top: 0px;
  z-index: -1;
  margin: 0;
}

.crossfade > figure:nth-child(1) {
  background-image: url(../img/0.jpeg);
}

.crossfade > figure:nth-child(2) {
  animation-delay: 12s;
  background-image: url(../img/1.jpeg);
}
.crossfade > figure:nth-child(3) {
  animation-delay: 24s;
  background-image: url(../img/2.jpeg);
}
.crossfade > figure:nth-child(4) {
  animation-delay: 36s;
  background-image: url(../img/0.jpeg);
}
.crossfade > figure:nth-child(5) {
  animation-delay: 48s;
  background-image: url(../img/1.jpeg);
}

@keyframes imageAnimation {
  0% {
    animation-timing-function: ease-in;
    opacity: 0;
  }
  8% {
    animation-timing-function: ease-out;
    opacity: 1;
  }
  17% {
    opacity: 1;
  }
  45% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

and get image from user by form

<form id="background-form" method="get">

    Choose Images to upload(jpg, jpeg, or png) up to 5MB
      <input
        required
        type="file"
        class="form-control"
        id="custom-file"
        accept=".jpg, .jpeg, .png"
        multiple/>

</form>

And javascript file to handle submit

const submit = document.querySelector("form#background-form")

function handleSubmit() {
  //How should I access to the image I got from form
  //I tried to access by using URL.createObjectURL(file) API but didn't work
  //Or is there a way to store this image in localstorage or sessionstorage?
  //If it is possible how can I access to the image URL?

}

Body:
There is way to store your image using local and session storage based on your needs and take in count, that localStorage have size limit of 5mb and limit can be increased by the user when needed, however, only a few browsers support this but on other hand sessionStorage size is limited only by system memory.

To save image in localStorage you can do following.

const fileInput = document.querySelector('#fileInput');

when input is changed - when image is chosen or changed this function executes

fileInput.addEventListener('change', function () {
    const reader = new FileReader(); -- read content of files

when content of files is loaded

    reader.addEventListener('load', function () {

save result ( image ) in local storage

        localStorage.setItem('image', reader.result)
    })

read content of blob or file

    reader.readAsDataURL(this.files[0]);
})


问:
Javascript matching objects of an array
I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.

Any way to do this with map? And present in a list?
I've come this far:

```<code>const allaOrter = orter.map((allOrt) =>
<li>{allOrt.url}</li>
)
</code>```

What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how...
The real array I'm working with is much bigger and contains loads of urls.
Maybe even make new arrays which contains those elements that have a common url.
I hope my provided example is enough for someone of you guys to help me out. :)

```<code>orter.json
[{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]
</code>```

答:
Working Demo :

const data = [{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/alpha/beta"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/abc/def"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }];

const res = data.filter((obj) => obj.url.indexOf('/blekinge') !== -1);

console.log(res);```

Title: Javascript matching objects of an array

Body:
I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.

Any way to do this with map? And present in a list?
I've come this far:

const allaOrter = orter.map((allOrt) =>

{allOrt.url}

)

What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how...
The real array I'm working with is much bigger and contains loads of urls.
Maybe even make new arrays which contains those elements that have a common url.
I hope my provided example is enough for someone of you guys to help me out. :)

orter.json
[{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]


问:
Why isn't the C# inequality operator !==?
In C#, == is used to check equality, whereas = is for assignment.

Does this mean that checking for inequality should really be !==.

Why isn't this the case? Os it for historical reasons?

The rise of != has seen it establish itself in most SQL variations now too.

答: C# had a lot of influence from Java and C/C++ both of which use == and !=.  I imagine they simply chose to stick with the existing predominant pattern instead of reinventing the wheel. Choosing another syntax say === for equality and !=== for inequality would've been a stumbling block for the vast majority of developers they were targeting


问:
iOS app rejected because of a Unity IAP issue
I recently submitted one of my Unity games for App Review today and it got rejected. The rejection was related to an In-App Purchase issue in iOS 15.3 (which, at the time of writing, is the latest version). Their response is below:

We found that your in-app purchase products exhibited one or more bugs when reviewed on iPhone running iOS 15.3 on Wi-Fi.

Next Steps

When validating receipts on your server, your server needs to be able to handle a production-signed app getting its receipts from Apple’s test environment. The recommended approach is for your production server to always validate receipts against the production App Store first. If validation fails with the error code "Sandbox receipt used in production," you should validate against the test environment instead.

A couple things to note. I'm not even using server-side validation for my IAPs. For this particular game, I'm using local validation. My IAPs also worked in the sandbox environment. Both the test builds and production builds are running identical code. Any ideas on what could be causing this?

I'm using the most recent version of the IAP package (4.1.2 at the time of writing) with Unity 2020.1.15f1.

答: Turns out Unity made a patch for the IAP package that fixed the problem. My game got approved!</p>


问:
I don't understand the golang channel well
Goroutines and channels are bothering me these days. I'm looking at the memo5 code at https://github.com/adonovan/gopl.io/tree/master/ch9.
If you look at memo.go of memo5, there are func (e *entry) call(f Func, key string) and func (e *entry) deliver(response chan<- result) parts.

```<code>// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/

// See page 278.

// Package memo provides a concurrency-safe non-blocking memoization
// of a function.  Requests for different keys proceed in parallel.
// Concurrent requests for the same key block until the first completes.
// This implementation uses a monitor goroutine.
package memo

//!+Func

// Func is the type of the function to memoize.
type Func func(key string) (interface{}, error)

// A result is the result of calling a Func.
type result struct {
    value interface{}
    err   error
}

type entry struct {
    res   result
    ready chan struct{} // closed when res is ready
}

//!-Func

//!+get

// A request is a message requesting that the Func be applied to key.
type request struct {
    key      string
    response chan<- result // the client wants a single result
}

type Memo struct{ requests chan request }

// New returns a memoization of f.  Clients must subsequently call Close.
func New(f Func) *Memo {
    memo := &Memo{requests: make(chan request)}
    go memo.server(f)
    return memo
}

func (memo *Memo) Get(key string) (interface{}, error) {
    response := make(chan result)
    memo.requests <- request{key, response}
    res := <-response
    return res.value, res.err
}

func (memo *Memo) Close() { close(memo.requests) }

//!-get

//!+monitor

func (memo *Memo) server(f Func) {
    cache := make(map[string]*entry)
    for req := range memo.requests {
        e := cache[req.key]
        if e == nil {
            // This is the first request for this key.
            e = &entry{ready: make(chan struct{})}
            cache[req.key] = e
            go e.call(f, req.key) // call f(key)
        }
        go e.deliver(req.response)
    }
}

func (e *entry) call(f Func, key string) {
    // Evaluate the function.
    e.res.value, e.res.err = f(key)
    // Broadcast the ready condition.
    close(e.ready)
}

func (e *entry) deliver(response chan<- result) {
    // Wait for the ready condition.
    <-e.ready
    // Send the result to the client.
    response <- e.res
}

//!-monitor
</code>```

I don't understand how  close(e.ready) and  <-e.ready synchronize here. Even after reading the book, I don't understand. Please tell me what the mechanism is.

答:
e.ready is more known as done  channel. this is a way to tell your ref functions that domething is ready by closing done (e.ready chan). <-e.ready is going to block until its done (closed).

so... reading this code it means next.

deliver waits for rediness signal.

call gets data for e.res (e.res.value, e.res.err = f(key)`)

call releas done channel by closing it (close(e.ready))

deliver can move throu block reading from <-e.ready and send data to response

Body:
Goroutines and channels are bothering me these days. I'm looking at the memo5 code at https://github.com/adonovan/gopl.io/tree/master/ch9.
If you look at memo.go of memo5, there are func (e *entry) call(f Func, key string) and func (e *entry) deliver(response chan<- result) parts.

// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/

// See page 278.

// Package memo provides a concurrency-safe non-blocking memoization
// of a function.  Requests for different keys proceed in parallel.
// Concurrent requests for the same key block until the first completes.
// This implementation uses a monitor goroutine.
package memo

//!+Func

// Func is the type of the function to memoize.
type Func func(key string) (interface{}, error)

// A result is the result of calling a Func.
type result struct {
    value interface{}
    err   error
}

type entry struct {
    res   result
    ready chan struct{} // closed when res is ready
}

//!-Func

//!+get

// A request is a message requesting that the Func be applied to key.
type request struct {
    key      string
    response chan<- result // the client wants a single result
}

type Memo struct{ requests chan request }

// New returns a memoization of f.  Clients must subsequently call Close.
func New(f Func) *Memo {
    memo := &Memo{requests: make(chan request)}
    go memo.server(f)
    return memo
}

func (memo *Memo) Get(key string) (interface{}, error) {
    response := make(chan result)
    memo.requests <- request{key, response}
    res := <-response
    return res.value, res.err
}

func (memo *Memo) Close() { close(memo.requests) }

//!-get

//!+monitor

func (memo *Memo) server(f Func) {
    cache := make(map[string]*entry)
    for req := range memo.requests {
        e := cache[req.key]
        if e == nil {
            // This is the first request for this key.
            e = &entry{ready: make(chan struct{})}
            cache[req.key] = e
            go e.call(f, req.key) // call f(key)
        }
        go e.deliver(req.response)
    }
}

func (e *entry) call(f Func, key string) {
    // Evaluate the function.
    e.res.value, e.res.err = f(key)
    // Broadcast the ready condition.
    close(e.ready)
}

func (e *entry) deliver(response chan<- result) {
    // Wait for the ready condition.
    <-e.ready
    // Send the result to the client.
    response <- e.res
}

//!-monitor

I don't understand how  close(e.ready) and  <-e.ready synchronize here. Even after reading the book, I don't understand. Please tell me what the mechanism is.


问:
Qcubed 2.xx How do you extend the year range in the Qdatepicker dropdown
We are working with a CMS system built with qCubed 2.xx   The Year range in the QDatepicker dropdown ended at year 2020.   I cannot seem to find where to set or extend the date year range.  Is there nyone out there who can help?

Thanks
David

答:
Glad to see someone else still using qcubed 2.xx :-)

Try to check this file:

```<code>includes/qcubed/_core/base_controls/QDateTimePicker.class.php
</code>```

Look for these lines:

```<code>protected $intMinimumYear =
protected $intMaximumYear =
</code>```

Body:
Glad to see someone else still using qcubed 2.xx :-)

Try to check this file:

includes/qcubed/_core/base_controls/QDateTimePicker.class.php

Look for these lines:

protected $intMinimumYear =
protected $intMaximumYear =


问:
How to delete todo item with js typescript (NOT ONLY BY NAME OF THE TASK)
I'm new to ts, so I've created a to-do list, but when I'm completing the task with the same name as others, they all disappear.
It looks like I just need to add one more criteria to filter or smth, but I don't know how to do it.
I've pinned 3 different code files that I use.

```<code>import React, {FC, useState, ChangeEvent} from 'react';
import './App.css';
import TodoTask from './Components/TodoTask'
import { ITask } from './Interfaces';

const taskInitialState = {taskName: "", deadline: 0, description: ""};

const App: FC = () => {
  const [task, setTask] = useState<ITask>(taskInitialState);
  const [todoList, setTodoList] = useState<ITask[]>([]);

  const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
    setTask({...task, [event.target.name]: event.target.value});
  };

  const addTask = (): void => {
    setTodoList([...todoList, task])
    setTask(taskInitialState);
  }

  const completeTask = (taskNameToDelete: string): void => {
    setTodoList(todoList.filter((task) => {
      return task.taskName != taskNameToDelete
    }))
  }

  return (
    <div className="App">
      <div className="header">
        <div className='inputContainer'>
        <input type="text" placeholder="Your task" name="taskName" value={task.taskName} onChange={handleChange} />
        <input type="number" placeholder="Deadline in days" name="deadline" value={task.deadline} onChange={handleChange} />
        <input type="text" placeholder="Description" name="description" value={task.description} onChange={handleChange} />
        </div>
        <button onClick={addTask}>Add Task</button>
      </div>
      <div className='todoList'>
        {todoList.map((task: ITask, key: number) => {
          return <TodoTask key={key} task={task} completeTask={completeTask} />;
        })}
      </div>
    </div>
  );
}

export default App;
</code>```

TodoTask.tsx

```<code>import React from 'react';
import { ITask } from '../Interfaces';

interface ITodoTask {
    task: ITask;
    completeTask(taskNameToDelete: string): void;
}

const TodoTask = ({ task, completeTask }: ITodoTask) => {
    return (
    <div className='task'>
        <div className='content'>
            <span className='taskName'>{task.taskName}</span>
            <span className='duration'>{task.deadline}</span>
            <span>{task.description}</span>
        </div>
        <button onClick={() => {completeTask(task.taskName)}} >Complete</button>
    </div>

    )
}

export default TodoTask;
</code>```

Interfaces.tsx

```<code>export interface ITask {
    taskName: string;
    deadline: number;
    description: string;
}
</code>```

答:
You need change parameters of your function completeTask is object type ITask.

Passing a value to your function completeTask is a task.

use JSON.stringify() and compare with your task in filter function.
Hope my answer helpful.

Body:
I'm new to ts, so I've created a to-do list, but when I'm completing the task with the same name as others, they all disappear.
It looks like I just need to add one more criteria to filter or smth, but I don't know how to do it.
I've pinned 3 different code files that I use.

import React, {FC, useState, ChangeEvent} from 'react';
import './App.css';
import TodoTask from './Components/TodoTask'
import { ITask } from './Interfaces';

const taskInitialState = {taskName: "", deadline: 0, description: ""};

const App: FC = () => {
  const [task, setTask] = useState<ITask>(taskInitialState);
  const [todoList, setTodoList] = useState<ITask[]>([]);

  const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
    setTask({...task, [event.target.name]: event.target.value});
  };

  const addTask = (): void => {
    setTodoList([...todoList, task])
    setTask(taskInitialState);
  }

  const completeTask = (taskNameToDelete: string): void => {
    setTodoList(todoList.filter((task) => {
      return task.taskName != taskNameToDelete
    }))
  }

  return (

        <input type="text" placeholder="Your task" name="taskName" value={task.taskName} onChange={handleChange} />
        <input type="number" placeholder="Deadline in days" name="deadline" value={task.deadline} onChange={handleChange} />
        <input type="text" placeholder="Description" name="description" value={task.description} onChange={handleChange} />

        <button onClick={addTask}>Add Task</button>

        {todoList.map((task: ITask, key: number) => {
          return <TodoTask key={key} task={task} completeTask={completeTask} />;
        })}

  );
}

export default App;

TodoTask.tsx

import React from 'react';
import { ITask } from '../Interfaces';

interface ITodoTask {
    task: ITask;
    completeTask(taskNameToDelete: string): void;
}

const TodoTask = ({ task, completeTask }: ITodoTask) => {
    return (

            {task.taskName}
            {task.deadline}
            {task.description}

        <button onClick={() => {completeTask(task.taskName)}} >Complete</button>

    )
}

export default TodoTask;

Interfaces.tsx

export interface ITask {
    taskName: string;
    deadline: number;
    description: string;
}


问:
imgs get value from data-src

File "C:\Users\86134\PycharmProjects\pythonProject\strip-spam.py", line 15, in <module>

print(imgs.get_attribute("data-src"))

AttributeError: 'list' object has no attribute 'get_attribute'.

Did you mean: '__getattribute__'?

Above is an error from my code. Can anyone help to fix it?

The len() of imgs is 60, as the chrome xpath, but imgs.get_attribute("data-src") is wrong.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
import  time

browser = webdriver.Chrome()
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(options=chrome_options)

browser.get('https://prediger.de/runde-wandleuchten.html')
print(browser.title)
imgs = browser.find_elements(By.XPATH,'//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img')
print(len(imgs))
print(imgs.get_attribute("data-src"))
</code>```

答:
browser.find_elements(By.XPATH,'//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img') gives you a list of 60 elements.  The get_attribute method can be allied on a single we element.

So, to make your code working you should iterate over each web element in the list to extract it attribute, as following:

imgs = browser.find_elements(By.XPATH,'//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img')
print(len(imgs))
for img in imgs:
    print(img.get_attribute("data-src"))
```
<p>Also, your code is missing a wait. You have to wait for all the elements to loaded before extracting their attributes. The preferred way to do it is with the use of expected conditions explicit waits, as following</p>
<pre class="lang-py prettyprint-override"><code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(browser, 20)
wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img')))
#short additional delay to make sure all the elements are loaded after the first element is become visible
time.sleep(0.5)
#now get the list of images
imgs = browser.find_elements(By.XPATH,'//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img')
print(len(imgs))
for img in imgs:
    print(img.get_attribute("data-src"))
</code>```

Title: imgs get value from data-src

Body:
File "C:\Users\86134\PycharmProjects\pythonProject\strip-spam.py", line 15, in <module>

print(imgs.get_attribute("data-src"))

AttributeError: 'list' object has no attribute 'get_attribute'.

Did you mean: '__getattribute__'?

Above is an error from my code. Can anyone help to fix it?

The len() of imgs is 60, as the chrome xpath, but imgs.get_attribute("data-src") is wrong.

from selenium import webdriver
from selenium.webdriver.common.by import By
import  time

browser = webdriver.Chrome()
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(options=chrome_options)

browser.get('https://prediger.de/runde-wandleuchten.html')
print(browser.title)
imgs = browser.find_elements(By.XPATH,'//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img')
print(len(imgs))
print(imgs.get_attribute("data-src"))

Body:
browser.find_elements(By.XPATH,'//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img') gives you a list of 60 elements.  The get_attribute method can be allied on a single we element.

So, to make your code working you should iterate over each web element in the list to extract it attribute, as following:

imgs = browser.find_elements(By.XPATH,'//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img')
print(len(imgs))
for img in imgs:
    print(img.get_attribute("data-src"))

Also, your code is missing a wait. You have to wait for all the elements to loaded before extracting their attributes. The preferred way to do it is with the use of expected conditions explicit waits, as following

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(browser, 20)
wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img')))
#short additional delay to make sure all the elements are loaded after the first element is become visible
time.sleep(0.5)
#now get the list of images
imgs = browser.find_elements(By.XPATH,'//*[@id="maincontent"]/div[3]/div[2]/section/article/div/div[1]/div/picture/img')
print(len(imgs))
for img in imgs:
    print(img.get_attribute("data-src"))