问:
How to cancel valueChanges in Angular and set the old value again?
I subscribed to valueChanges of a mat-selection-list to be notified when the user selects a new list item. In some cases I ask the user if he/she really wants to select the new item via a confirmation dialog. If the user clicks "No" in this dialog, I need to cancel the selection of the new item. This is how I attempted to do this:

```<code>this.createForm.controls.selectionList.valueChanges.subscribe((value: number[]) => {
  const prevValue = this.createForm.controls.selectionList.value;

  if (<condition>) {
    const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: "Do you really want to do this?",
    });

    confirmDialogRef.afterClosed().subscribe((confirmResult) => {
      if (confirmResult === true) {
        // User clicked yes, continue...
      } else {
        // User clicked no, set the previous value again...
        this.createForm.controls.selectionList.setValue(prevValue, { emitEvent: false });
      }
    });
  } else {
    // No user confirmation required, just continue...
  }
});
</code>```

Unfortunately, this does not seem to work because prevValue seems to already be the new value when I try to set it as current value. What can I do instead to set the previous value again and basically just pretend that the user never even selected a new list item to begin with? Do I really have to cache the previous value manually, or is there a better way to do this?

答:
Probably this could be the better one. Also, Set this.prevValue after creating the form with the value you are getting initially otherwise it's [].

Try to avoid subscriptions inside the subscription for good performance.

```<code>private prevValue: number[] = [];

this.createForm.controls.selectionList.valueChanges.pipe(mergeMap((value: number[]) => {
    if (<condition>) {
    const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: "Do you really want to do this?",
    });

    return confirmDialogRef.afterClosed();
  } else {
    // No user confirmation required, just continue...
    this.prevValue = value;
    return of(undefined);
  }
})).subscribe((confirmResult) => {
    if(confirmResult != undefined) {
      if (confirmResult === true) {
        // User clicked yes, continue...
        this.prevValue = this.createForm.controls.selectionList.value;
       } else {
        // User clicked no, set the previous value again...
        this.createForm.controls.selectionList.setValue(prevValue, { emitEvent: false });
      }
  }
});
</code>```

Body:
I subscribed to valueChanges of a mat-selection-list to be notified when the user selects a new list item. In some cases I ask the user if he/she really wants to select the new item via a confirmation dialog. If the user clicks "No" in this dialog, I need to cancel the selection of the new item. This is how I attempted to do this:

this.createForm.controls.selectionList.valueChanges.subscribe((value: number[]) => {
  const prevValue = this.createForm.controls.selectionList.value;

  if (<condition>) {
    const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: "Do you really want to do this?",
    });

    confirmDialogRef.afterClosed().subscribe((confirmResult) => {
      if (confirmResult === true) {
        // User clicked yes, continue...
      } else {
        // User clicked no, set the previous value again...
        this.createForm.controls.selectionList.setValue(prevValue, { emitEvent: false });
      }
    });
  } else {
    // No user confirmation required, just continue...
  }
});

Unfortunately, this does not seem to work because prevValue seems to already be the new value when I try to set it as current value. What can I do instead to set the previous value again and basically just pretend that the user never even selected a new list item to begin with? Do I really have to cache the previous value manually, or is there a better way to do this?

Body:
Probably this could be the better one. Also, Set this.prevValue after creating the form with the value you are getting initially otherwise it's [].

Try to avoid subscriptions inside the subscription for good performance.

private prevValue: number[] = [];

this.createForm.controls.selectionList.valueChanges.pipe(mergeMap((value: number[]) => {
    if (<condition>) {
    const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: "Do you really want to do this?",
    });

    return confirmDialogRef.afterClosed();
  } else {
    // No user confirmation required, just continue...
    this.prevValue = value;
    return of(undefined);
  }
})).subscribe((confirmResult) => {
    if(confirmResult != undefined) {
      if (confirmResult === true) {
        // User clicked yes, continue...
        this.prevValue = this.createForm.controls.selectionList.value;
       } else {
        // User clicked no, set the previous value again...
        this.createForm.controls.selectionList.setValue(prevValue, { emitEvent: false });
      }
  }
});


来源: stackexchange

问:
How to copy a file to a new file with a new name in same directory but across multiple directories in bash?
I am trying to copy an existing file (that is found in across directories) to a new file with a new name in Bash.  For example, 'Preview.json' to 'Performance.json'.  I have tried using

```<code>find * -type f -name 'Preview.json' -exec cp {} {}"QA" \;
</code>```

But ended up with 'Preview.jsonQA'.  (I am new to Bash.)  I have tried moving the "QA" in front of the {} but I got errors because of an invalid path.

答:
In an -exec predicate, the symbol {} represents a path that is being considered, starting at one of the starting-point directories designated in the command.  Example: start/dir2/Preview.json.  You can form other file names by either prepending or appending characters, but whether that makes sense depends on the details.  In your case, appending produces commands such as

```<code>cp start/dir2/Preview.json start/dir2/Preview.jsonQA
</code>```

which is a plausible command in the event that start/dir2/Preview.json exists. But cp does not automatically create directories in the destination path, so the result of prepending characters ...

```<code>cp start/dir2/Preview.json QAstart/dir2/Preview.json
</code>```

... is not as likely to be accepted -- it depends on directory QAstart/dir2 existing.

I think what you're actually looking for may be cp commands of the form ...

```<code>cp start/dir2/Preview.json start/dir2/QAPreview.json
</code>```

... but find cannot do this by itself.

For more flexibility in handling the file names discovered by find, pipe its output into another command.  If you want to pass them as command-line arguments to another command, then you can interpose the xargs command to achieve that.  The command on the receiving end of the pipe can be a shell function or a compound command if you wish.

For example,

```<code># Using ./* instead of * ensures that file names beginning with - will not
# be misinterpreted as options:
find ./* -type f -name 'Preview.json' |
  while IFS= read -r name; do  # Read one line and store it in variable $name
    # the destination name needs to be computed differently if the name
    # contains a / character (the usual case) than if it doesn't:
    case "${name}" in
      */*) cp "${name}" "${name%/*}/QA${name##*/}" ;;
      *)   cp "${name}" "QA${name}" ;;
    esac
  done
</code>```

Note that that assumes that none of your directory names contain newline characters (the read command would split up newline-containing filenames).  That's a reasonably safe assumption, but not absolutely safe.

Of course, you would generally want to have that in a script, not to try to type it on the fly on the command line.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to copy an existing file (that is found in across directories) to a new file with a new name in Bash.  For example, 'Preview.json' to 'Performance.json'.  I have tried using

find * -type f -name 'Preview.json' -exec cp {} {}"QA" \;

But ended up with 'Preview.jsonQA'.  (I am new to Bash.)  I have tried moving the "QA" in front of the {} but I got errors because of an invalid path.

Body:
In an -exec predicate, the symbol {} represents a path that is being considered, starting at one of the starting-point directories designated in the command.  Example: start/dir2/Preview.json.  You can form other file names by either prepending or appending characters, but whether that makes sense depends on the details.  In your case, appending produces commands such as

cp start/dir2/Preview.json start/dir2/Preview.jsonQA

which is a plausible command in the event that start/dir2/Preview.json exists. But cp does not automatically create directories in the destination path, so the result of prepending characters ...

cp start/dir2/Preview.json QAstart/dir2/Preview.json

... is not as likely to be accepted -- it depends on directory QAstart/dir2 existing.

I think what you're actually looking for may be cp commands of the form ...

cp start/dir2/Preview.json start/dir2/QAPreview.json

... but find cannot do this by itself.

For more flexibility in handling the file names discovered by find, pipe its output into another command.  If you want to pass them as command-line arguments to another command, then you can interpose the xargs command to achieve that.  The command on the receiving end of the pipe can be a shell function or a compound command if you wish.

For example,

# Using ./* instead of * ensures that file names beginning with - will not
# be misinterpreted as options:
find ./* -type f -name 'Preview.json' |
  while IFS= read -r name; do  # Read one line and store it in variable $name
    # the destination name needs to be computed differently if the name
    # contains a / character (the usual case) than if it doesn't:
    case "${name}" in
      */*) cp "${name}" "${name%/*}/QA${name##*/}" ;;
      *)   cp "${name}" "QA${name}" ;;
    esac
  done

Note that that assumes that none of your directory names contain newline characters (the read command would split up newline-containing filenames).  That's a reasonably safe assumption, but not absolutely safe.

Of course, you would generally want to have that in a script, not to try to type it on the fly on the command line.


问:
Iterate through array of objects using javascript
I am trying to iterate through the array of objects but somehow not getting it right. Can somone please let me know where i am going wrong.

Here is the data

```<code>const response = {
    "pass": 1,
    "fail": 2,
    "projects_all": [
        {
            "projects": [
                {
                    "name": "Project1",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        },
        {
            "projects": [
                {
                    "name": "Project2",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "FAIL",
                    }
                },
                {
                    "name": "Project3",
                    "status": "LIVE",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        }
    ]
}
</code>```

And here is the code i tried

```<code>if(response) {
  response?.projects_all?.forEach((projects) => {
     projects.forEach(project) => {
       if(project.previous !== null) {
         //do something here
       }
    });
 });
}
</code>```

I am trying to iterate through this array of objects but it says projects not iterable. Any help is appreciated to make me understand where i am going wrong.

答:
First, determine what shape your response object currently has.
By using the ?. operator your essentially muting JS built in error reporting.

From the context, I assume your response actually looks like this:

console.log(response);
{
   data: {
      projects_all: [ ... ]
   }
}
```
<p>Therefore your existing code using <code>response?.projects_all</code> doesn't actually hit the <code>projects_all</code> property inside your response.</p>
<p>Can you try the following:</p>
<pre class="lang-js prettyprint-override"><code>response.data.projects_all.forEach((project) => {
   console.info("Project: ", project);
   project.projects.forEach((project) => {
      console.log(project, project?.name);
   });
});
</code>```

Alternatively, if you don't have a data key inside your response object, you can omit it in the loop:

response.data.projects_all.forEach((project) => {
   console.info("Project: ", project);
   project.projects.forEach((project) => {
      console.log(project, project?.name);
   });
});
```

Body:
I am trying to iterate through the array of objects but somehow not getting it right. Can somone please let me know where i am going wrong.

Here is the data

const response = {
    "pass": 1,
    "fail": 2,
    "projects_all": [
        {
            "projects": [
                {
                    "name": "Project1",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        },
        {
            "projects": [
                {
                    "name": "Project2",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "FAIL",
                    }
                },
                {
                    "name": "Project3",
                    "status": "LIVE",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        }
    ]
}

And here is the code i tried

if(response) {
  response?.projects_all?.forEach((projects) => {
     projects.forEach(project) => {
       if(project.previous !== null) {
         //do something here
       }
    });
 });
}

I am trying to iterate through this array of objects but it says projects not iterable. Any help is appreciated to make me understand where i am going wrong.

Body:
First, determine what shape your response object currently has.
By using the ?. operator your essentially muting JS built in error reporting.

From the context, I assume your response actually looks like this:

console.log(response);
{
   data: {
      projects_all: [ ... ]
   }
}

Therefore your existing code using response?.projects_all doesn't actually hit the projects_all property inside your response.

Can you try the following:

response.data.projects_all.forEach((project) => {
   console.info("Project: ", project);
   project.projects.forEach((project) => {
      console.log(project, project?.name);
   });
});

Alternatively, if you don't have a data key inside your response object, you can omit it in the loop:

response.data.projects_all.forEach((project) => {
   console.info("Project: ", project);
   project.projects.forEach((project) => {
      console.log(project, project?.name);
   });
});


问:
How to copy file from one location to another location?
I want to copy a file from one location to another location in Java. What is the best way to do this?

Here is what I have so far:

```<code>import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
    public static void main(String[] args) {
        File f = new File(
            "D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
        List<String>temp=new ArrayList<String>();
        temp.add(0, "N33");
        temp.add(1, "N1417");
        temp.add(2, "N331");
        File[] matchingFiles = null;
        for(final String temp1: temp){
            matchingFiles = f.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.startsWith(temp1);
                }
            });
            System.out.println("size>>--"+matchingFiles.length);

        }
    }
}
</code>```

This does not copy the file, what is the best way to do this?

答:
I modified one of the answers to make it a bit more efficient.</p>
```<code>public void copy(){
    InputStream in = null;
    try {
        in = new FileInputStream(Files);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        OutputStream out = new FileOutputStream();
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            while (true) {
                int len = 0;
                try {
                    if (!((len = in.read(buf)) > 0)) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.write(buf, 0, len);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void moveFile() {
    copy();
    File dir = getFilesDir();
    File file = new File(dir, "my_filename");
    boolean deleted = file.delete();
}
</code>```

Body:
I want to copy a file from one location to another location in Java. What is the best way to do this?

Here is what I have so far:

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
    public static void main(String[] args) {
        File f = new File(
            "D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
        List<String>temp=new ArrayList<String>();
        temp.add(0, "N33");
        temp.add(1, "N1417");
        temp.add(2, "N331");
        File[] matchingFiles = null;
        for(final String temp1: temp){
            matchingFiles = f.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.startsWith(temp1);
                }
            });
            System.out.println("size>>--"+matchingFiles.length);

        }
    }
}

This does not copy the file, what is the best way to do this?

Body:
I modified one of the answers to make it a bit more efficient.

public void copy(){
    InputStream in = null;
    try {
        in = new FileInputStream(Files);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        OutputStream out = new FileOutputStream();
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            while (true) {
                int len = 0;
                try {
                    if (!((len = in.read(buf)) > 0)) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.write(buf, 0, len);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void moveFile() {
    copy();
    File dir = getFilesDir();
    File file = new File(dir, "my_filename");
    boolean deleted = file.delete();
}


问:
How to add data on nested array in Firestore with react-native
I would like to ask if is it possible to add data in a nested array.The result i want is this

But i get this when i add a new rating with the code i use

```<code>async function getAll(){
    const userEmail= firebase.firestore().collection('users')
    const snapshot=await userEmail.where('email','==',index.email).get()
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }

    snapshot.forEach(doc => {
      userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({parking:[markerName]})},{merge:true})
      userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({rating:[currentRating]})},{merge:true})

     console.log(userEmail.doc(doc.id));
    });
  }
  getAll()
</code>```

答:
I've managed to do it by using forEach function to an array of image path

```<code>  const [imageUri, setImageUri] = useState([]);
  const [uploading, setUploading] = useState(false);

  const UploadImage = () => {
    setUploading(true);
    imageUri.forEach(async (image, index) => {
      // setTransferred(0);

      const pathToFile = image;
      let filename = pathToFile.substring(pathToFile.lastIndexOf('-') + 1);
      const extension = filename.split('.').pop();
      const name = filename.split('.').slice(0, -1).join('.');
      filename = name + Date.now() + '.' + extension;

      const reference = storage().ref().child(`/userprofile/${filename}`);
      // path to existing file on filesystem

      // uploads file
      const task = reference.putFile(pathToFile);
      try {
        await task;

        const url = await reference.getDownloadURL();
        downloadableURI.push(url);
        if (index == imageUri.length - 1) {
          setUploading(false);
          Alert.alert(
            'Image uploaded!',
            'Your image has been uploaded to the Firebase Cloud Storage Successfully!',
          );
        }
      } catch (e) {
        console.log(e);
      }
    });
  };

</code>```

whenever the function is called, then the array of images is uploaded to firebase storage,

Body:
I would like to ask if is it possible to add data in a nested array.The result i want is this

But i get this when i add a new rating with the code i use

async function getAll(){
    const userEmail= firebase.firestore().collection('users')
    const snapshot=await userEmail.where('email','==',index.email).get()
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }

    snapshot.forEach(doc => {
      userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({parking:[markerName]})},{merge:true})
      userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({rating:[currentRating]})},{merge:true})

     console.log(userEmail.doc(doc.id));
    });
  }
  getAll()

Body:
I've managed to do it by using forEach function to an array of image path

  const [imageUri, setImageUri] = useState([]);
  const [uploading, setUploading] = useState(false);

  const UploadImage = () => {
    setUploading(true);
    imageUri.forEach(async (image, index) => {
      // setTransferred(0);

      const pathToFile = image;
      let filename = pathToFile.substring(pathToFile.lastIndexOf('-') + 1);
      const extension = filename.split('.').pop();
      const name = filename.split('.').slice(0, -1).join('.');
      filename = name + Date.now() + '.' + extension;

      const reference = storage().ref().child(`/userprofile/${filename}`);
      // path to existing file on filesystem

      // uploads file
      const task = reference.putFile(pathToFile);
      try {
        await task;

        const url = await reference.getDownloadURL();
        downloadableURI.push(url);
        if (index == imageUri.length - 1) {
          setUploading(false);
          Alert.alert(
            'Image uploaded!',
            'Your image has been uploaded to the Firebase Cloud Storage Successfully!',
          );
        }
      } catch (e) {
        console.log(e);
      }
    });
  };

whenever the function is called, then the array of images is uploaded to firebase storage,


问:
Sum is not computed over groups (always gives the absolute total)
I'm creating some summary tables and I'm having a hard time with simple sums...

While the count of records is correct, the variables with sums always compute the same value for all groups.

This is the code:

```<code>SummarybyCallContext <- PSTNRecords %>%
                            group_by (PSTNRecords$destinationContext) %>%
                                summarize(
                                  Calls = n(),
                                  Minutes = sum(PSTNRecords$durationMinutes),
                                  Charges = sum(PSTNRecords$charge),
                                  Fees = sum(PSTNRecords$connectionCharge)
                                )

SummarybyCallContext
</code>```

And this is the result:

Minutes and Charges should be different for each group (Fees is always zero, but I need to display it anyway in the table).

Setting na.rm to TRUE or FALSE doesn't seem to change the result.

What am I doing wrong?

Thanks in advance!

~Alienvolm

答:
(Almost) Never use PSTNRecords$ within dplyr verb functions in a pipeline starting from PSTNRecords. Why? With the $-indexing, every reference is to the original data, before any grouping or filtering or adding/changing columns or rearranging is done. Without the $-referencing, it is using the columns as they appear at that point in the pipeline.

SummarybyCallContext <- PSTNRecords %>%
                            group_by (destinationContext) %>%
                                summarize(
                                  Calls = n(),
                                  Minutes = sum(durationMinutes),
                                  Charges = sum(charge),
                                  Fees = sum(connectionCharge)
                                )
```
<p>There are exceptions to this, but they are rare and, for the vast majority of new dplyr users, generally done better via other mechanisms.</p>
<p>Demonstration:</p>
<pre class="lang-r prettyprint-override"><code>dat <- data.frame(x=1:5)
dat %>%
  filter(dat$x > 2) %>%      # this still works okay, since `dat` and "data now" are same
  summarize(x2 = dat$x[1])   # however, `dat` has 5 rows but data in pipe only has 3 rows
#   x2
# 1  1
dat %>%
  filter(x > 2) %>%
  summarize(x2 = x[1])
#   x2
# 1  3
</code>```

Body:
I'm creating some summary tables and I'm having a hard time with simple sums...

While the count of records is correct, the variables with sums always compute the same value for all groups.

This is the code:

SummarybyCallContext <- PSTNRecords %>%
                            group_by (PSTNRecords$destinationContext) %>%
                                summarize(
                                  Calls = n(),
                                  Minutes = sum(PSTNRecords$durationMinutes),
                                  Charges = sum(PSTNRecords$charge),
                                  Fees = sum(PSTNRecords$connectionCharge)
                                )

SummarybyCallContext

And this is the result:

Minutes and Charges should be different for each group (Fees is always zero, but I need to display it anyway in the table).

Setting na.rm to TRUE or FALSE doesn't seem to change the result.

What am I doing wrong?

Thanks in advance!

~Alienvolm

Body:
(Almost) Never use PSTNRecords$ within dplyr verb functions in a pipeline starting from PSTNRecords. Why? With the $-indexing, every reference is to the original data, before any grouping or filtering or adding/changing columns or rearranging is done. Without the $-referencing, it is using the columns as they appear at that point in the pipeline.

SummarybyCallContext <- PSTNRecords %>%
                            group_by (destinationContext) %>%
                                summarize(
                                  Calls = n(),
                                  Minutes = sum(durationMinutes),
                                  Charges = sum(charge),
                                  Fees = sum(connectionCharge)
                                )

There are exceptions to this, but they are rare and, for the vast majority of new dplyr users, generally done better via other mechanisms.

Demonstration:

dat <- data.frame(x=1:5)
dat %>%
  filter(dat$x > 2) %>%      # this still works okay, since `dat` and "data now" are same
  summarize(x2 = dat$x[1])   # however, `dat` has 5 rows but data in pipe only has 3 rows
#   x2
# 1  1
dat %>%
  filter(x > 2) %>%
  summarize(x2 = x[1])
#   x2
# 1  3


问:
How to group the list based on count of previous list odd integer?
I need to group the list based  based on (N -count of previous list odd integer)

Example:

Input

```<code>n=5
l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]
</code>```

Initially the input has nested list at 0th index at the size of n.We need to group the other elements based on this condition

```<code>n - count of odd integers
</code>```

l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]

Initially the nested loop has 1 odd integer:
Therefore
n - count of odd integers = 5-1= 4
so i need to group next four elements.

```<code>>>[[45, 20, 40, 26, 32], [10, 20, 13, 16], 5, 10, 8, 5, 4, 2, 1]
</code>```

then the second nested loop has 1 odd integer:

Therefore
n - count of odd integers = 4-1= 3
so I need to group next three elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], 5, 4, 2, 1]

then the third nested loop has 1 odd integer:

Therefore
n - count of odd integers = 3-1= 2
so I need to group next 2 elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], 2, 1]

...like that I need to do

the final output to be

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], [2], 1]

My code:

l1=[l[i:(i+n)] for i in range(0,len(l),n)]

my output:

```<code>[[45, 20, 40, 26, 32], [10, 20, 13, 16, 5], [10, 8, 5, 4, 2], [1]]
</code>```

What changes I need to do???

Body:
I need to group the list based  based on (N -count of previous list odd integer)

Example:

Input

n=5
l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]

Initially the input has nested list at 0th index at the size of n.We need to group the other elements based on this condition

n - count of odd integers

l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]

Initially the nested loop has 1 odd integer:
Therefore
n - count of odd integers = 5-1= 4
so i need to group next four elements.

>>[[45, 20, 40, 26, 32], [10, 20, 13, 16], 5, 10, 8, 5, 4, 2, 1]

then the second nested loop has 1 odd integer:

Therefore
n - count of odd integers = 4-1= 3
so I need to group next three elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], 5, 4, 2, 1]

then the third nested loop has 1 odd integer:

Therefore
n - count of odd integers = 3-1= 2
so I need to group next 2 elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], 2, 1]

...like that I need to do

the final output to be

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], [2], 1]

My code:

l1=[l[i:(i+n)] for i in range(0,len(l),n)]

my output:

[[45, 20, 40, 26, 32], [10, 20, 13, 16, 5], [10, 8, 5, 4, 2], [1]]

What changes I need to do???

Body:
I'm sure there are many ways to do this:

l = [[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]
n = len(l[0])
r = [l[0]]
k = 1

while k < len(l):
    n -= sum(x % 2 for x in r[-1])
    r.append(l[k:k+n])
    k += n

print(r)


问:
google maps flutter my location blue dot compass arrow
update question:
I am facing a problem when using google map flutter.
Normally in the google map application, the current position will be displayed with a blue dot and trimmed beam, but in google_maps_flutter, it will display a blue dot and an arrow indicating the direction of the compass. currently when i rotate my phone the beam on google maps app moves in the direction of the phone but the arrow on the app using google_maps_flutter doesn't move or moves very slow and wrong direction. everyone can test it with the example of google maps flutter below. Has anyone encountered this problem can give me advice or a keyword to solve. Thank you everyone for reading.

if anyone wants to try can pull directly from google_maps_flutter example. Install on device -> settings -> enable GPS permission -> open app -> user interface -> mylocation marker. tks

link git hub example:

https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter/google_maps_flutter

blue and compass arrow in google_map_flutter

blue dot and the beam that indicates in Google Maps application

答:
This button is provided by the Google Maps Flutter plugin directly. I think, it is there for compatibility reasons and it does not play well with other widgets wich are overlapping the map and it is not customizable, as far as I know.

My suggestion is to disable this button and use your own buttons to control the GoogleMaps widget. Use Floating Action Buttons for example.


问:
How to copy python from one stage to another during a multi-stage docker build
I'm using nvidia/cudagl:11.4.2-base-ubuntu20.04, which does not include python. This is ok for me, since I need a very specific python version (3.9.9) anyhow. One way should be to compile python myself (e.g. according to https://askubuntu.com/a/890959). However, I thought maybe I could use a multi-stage build and just copy the required python executables from python:3.9.9-slim, so that I don't have to deal with the compilation and its remnants.

Is that a feasible idea? And what exactly would need to be copied over?

答:
It's not really feasible to copy installed binaries from one image to another.  If you know the application is only a static binary, or you know it has very controlled library dependencies, it could work, but Python installs things in many different directories and includes its own library tree.  You'll be much better off using the distribution package manager to install the specific version of Python you need.

Since your base image is based on Ubuntu, there's an add-on Ubuntu repository that contains many different Python versions; also see Python 3.7 on Ubuntu 20.04.  Translating that answer to Dockerfile format, you'd get something like:

FROM nvidia/cudagl:11.4.2-base-ubuntu20.04
...
# USER root (if you're not already root)
RUN apt-add-repository ppa:deadsnakes/ppa \
 && apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      python3.9
```

As of this writing that includes Python 3.9.10 rather than 3.9.9, but this shouldn't be a significant difference for you.

Body:
It's not really feasible to copy installed binaries from one image to another.  If you know the application is only a static binary, or you know it has very controlled library dependencies, it could work, but Python installs things in many different directories and includes its own library tree.  You'll be much better off using the distribution package manager to install the specific version of Python you need.

Since your base image is based on Ubuntu, there's an add-on Ubuntu repository that contains many different Python versions; also see Python 3.7 on Ubuntu 20.04.  Translating that answer to Dockerfile format, you'd get something like:

FROM nvidia/cudagl:11.4.2-base-ubuntu20.04
...
# USER root (if you're not already root)
RUN apt-add-repository ppa:deadsnakes/ppa \
 && apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      python3.9

As of this writing that includes Python 3.9.10 rather than 3.9.9, but this shouldn't be a significant difference for you.


问:
MSK vs SQS + SNS
I am deciding if I should use MSK (managed kafka from AWS) or a combination of SQS + SNS to achieve a pub sub model?

Background

Currently, we have a micro service architecture but we don't use any messaging service and only use REST apis (dont ask why - related to some 3rd party vendors who designed the architecture). Now, I want to revamp it and start using messaging for communication between micro-services.

Initially, the plan is to start publishing entity events for any other micro service to consume - these events will also be stored in data lake in S3 which will also serve as a base for starting data team.

Later, I want to move certain features from REST to async communication.

Anyway, the main question I have is - should I decide to go with MSK or should I use SQS + SNS for the same? ( I already understand the basic concepts but wanted to understand from fellow community if there are some other pros and cons)?

Thanks in advance

答:
MSK VS SQS+SNS is not really 1:1 comparison. The choice depends on various use cases. Please find out some of specific difference between two

Scalability ->
MSK has better scalability option because of inherent design of partitions that allow parallelism and ordering of message.
SNS has limitation of 300 publish/Second, to achieve same performance as MSK, there need to have higher number of SNS topic for same purpose.

Example : Topic: Order Service
in MSK -> one topic+ 10 Partitions
SNS     -> 10 topics

if client/message producer use 10 SNS topic for same purpose, then client needs to have information of all 10 SNS topic and distribution of message.
In MSK, it's pretty straightforward, key needs to send in message and kafka will allocate the partition based on Key value.

Administration/Operation ->
SNS+SQS setup is much simpler compare to MSK.
Operational challenge is much more with MSK( even this is managed service). MSK needs more in depth skills to use optimally.

SNS +SQS VS SQS -> I believe you have multiple subscription(fanout) for same message thats why you have refer SNS +SQS.
If you have One Subscription for one message, then only SQS is also sufficient.

Replay of message -> MSK can be use for replaying the already processed message.
It will be tricky for SQS, though can be achieve by having duplicate queue so that can be use for replay.

Title: MSK vs SQS + SNS


问:
How to add 301 redirect for a request with %20 at end of URL
Hi my site is written in .Net and I've discovered there are a few sites who incorrectly link to my site with a %20 symbol at the end of the URL.  For example their hyperlink is http://www.mysite.com/%20

This will always go to my 404 page and I've noticed that this happens to a lot of other big sites eg http://www.google.com/%20 will hit a 404.

When I try this locally I've put a breakpoint in Application_BeginRequest in global.asax to try and deal with the request however it doesn't even get this far, it just gives me a directory listing on screen and changes the URL in the address bar to "http://www.mysite.com/ /"

答:
Check out the config section from this blog.The part of httpError redirection might be of relevance to you:
http://deepeshsomani.wordpress.com/2011/08/16/how-to-resolve-file-size-error-for-files-whose-size-is-larger-than-specified-in-web-config/</p>

ContentLicense: CC BY-SA 3.0


问:
How to make flex box with limit 2 elements per row?
I need to make a table which will contain up to 4 divs.
But the divs in that table always should use maximum of avaliable space.
And one one row should contain not more then 2 divs
For instance if table contains 2 divs it should look like this

If table has 3 divs then like this:

And if contains 4 then it should look like that

To achieve it i wrote this code:

```<code><div
  style={{
    height: '58vh', border: '1px solid #d9d9d9',
    borderRadius: '0px 0px 2px 2px',
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
  }}
 >
   <div style={{background:'red', flex: 'auto', margin: '5px'}}
   <div style={{background:'green', flex: 'auto', margin: '5px'}}
   <div style={{background:'blue', flex: 'auto', margin: '5px'}}
   <div style={{background:'pink', flex: 'auto', margin: '5px'}}

 </div>
</code>```

But i missing something here.
For 1 div and for 2 divs it works as planned.
But for more..
This is my result for 3 divs

And for 4 divs

Can anyone advice me please what should i change in this code?

PS. Please don't judge my unevenly drawn squeres :)

答:
.container {
  display: flex;
  flex-wrap: wrap;
}

.inner {
  flex-basis: 50%;
  flex-grow: 1;
}

.inner:nth-of-type(1) {
  background: red;
}

.inner:nth-of-type(2) {
  background: gold;
}

.inner:nth-of-type(3) {
  background: green;
}

.inner:nth-of-type(4) {
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="inner">one</div>
  <div class="inner">two</div>
  <div class="inner">three</div>
  <div class="inner">four</div>
</div></code>```

I used the following steps to achieve your result.

Make the container which contains the inner boxes as flex.

Give the container flex-wrap: wrap so that the inner boxes which do not have place on the same line, shift to the next line.

Give flex-basis: 50% to the inner boxes so that they take up 50% of the available space.

Give the inner boxes flex-grow: 1 so that if the last box has any space left, it will take up all of it.

References:

Flexbox

flex-wrap

flex-basis

flex-grow

(Extra) flex-shrink

PS: Try commenting the fourth inner box so that the third box will take up the whole horizontal space.

Body:
I need to make a table which will contain up to 4 divs.
But the divs in that table always should use maximum of avaliable space.
And one one row should contain not more then 2 divs
For instance if table contains 2 divs it should look like this

If table has 3 divs then like this:

And if contains 4 then it should look like that

To achieve it i wrote this code:

   <div style={{background:'red', flex: 'auto', margin: '5px'}}
   <div style={{background:'green', flex: 'auto', margin: '5px'}}
   <div style={{background:'blue', flex: 'auto', margin: '5px'}}
   <div style={{background:'pink', flex: 'auto', margin: '5px'}}

But i missing something here.
For 1 div and for 2 divs it works as planned.
But for more..
This is my result for 3 divs

And for 4 divs

Can anyone advice me please what should i change in this code?

PS. Please don't judge my unevenly drawn squeres :)

Body:
.container {
  display: flex;
  flex-wrap: wrap;
}

.inner {
  flex-basis: 50%;
  flex-grow: 1;
}

.inner:nth-of-type(1) {
  background: red;
}

.inner:nth-of-type(2) {
  background: gold;
}

.inner:nth-of-type(3) {
  background: green;
}

.inner:nth-of-type(4) {
  background: blue;
}

<div class="container">
  <div class="inner">one</div>
  <div class="inner">two</div>
  <div class="inner">three</div>
  <div class="inner">four</div>
</div>

I used the following steps to achieve your result.

Make the container which contains the inner boxes as flex.

Give the container flex-wrap: wrap so that the inner boxes which do not have place on the same line, shift to the next line.

Give flex-basis: 50% to the inner boxes so that they take up 50% of the available space.

Give the inner boxes flex-grow: 1 so that if the last box has any space left, it will take up all of it.

References:

Flexbox

flex-wrap

flex-basis

flex-grow

(Extra) flex-shrink

PS: Try commenting the fourth inner box so that the third box will take up the whole horizontal space.


问:
HTML5 Audio player resizes on mobile device
Straight forward HTML5 Audio player. Looks good on desktop but on mobile it gets a little weird. It keeps its width but repositions and floats over the element it's inside. How do I stop it from repositioning on mobile devices?

Hope you can see the yellow border for reference.

Desktop printscreen:

Mobile printscreen:

When you zoom on the mobile device, the player starts moving towards its intended position (and player controls appear) - the more you zoom, the more it moves upwards, until halting in the middle of the element:

Mobile zoomed printscreen:

Been trying all the position values and done a fair share of googling. I don't understand what causes this, so I don't know where to start trying to solve it. Hope someone can help.

HTML:

```<code><div id="audiowrap">
  <audio controls controlsList="nodownload">
    Your browser does not support HTML5 Audio
  </audio>
</div>
</code>```

CSS:

```<code>audio { margin:0 0 0 5px; width:540px; }
#audiowrap {
  margin:0 auto; border: 1px solid yellow;
}
</code>```

答:
```<code><div id="audiowrap">
  <audio controls controlsList="nodownload">
    Your browser does not support HTML5 Audio
  </audio>http://162.210.197.146:9423/
</div>`enter code here`
</code>```

Blockquote

Body:
Straight forward HTML5 Audio player. Looks good on desktop but on mobile it gets a little weird. It keeps its width but repositions and floats over the element it's inside. How do I stop it from repositioning on mobile devices?

Hope you can see the yellow border for reference.

Desktop printscreen:

Mobile printscreen:

When you zoom on the mobile device, the player starts moving towards its intended position (and player controls appear) - the more you zoom, the more it moves upwards, until halting in the middle of the element:

Mobile zoomed printscreen:

Been trying all the position values and done a fair share of googling. I don't understand what causes this, so I don't know where to start trying to solve it. Hope someone can help.

HTML:

  <audio controls controlsList="nodownload">
    Your browser does not support HTML5 Audio
  </audio>

CSS:

audio { margin:0 0 0 5px; width:540px; }
#audiowrap {
  margin:0 auto; border: 1px solid yellow;
}

Body:
<div id="audiowrap">
  <audio controls controlsList="nodownload">
    Your browser does not support HTML5 Audio
  </audio>http://162.210.197.146:9423/
</div>`enter code here`

Blockquote


问:
One Signal - idsAvailable is deprecated
OneSignal's latest build version generate a warning like 'idsAvailable' is deprecated. How can I get 'playerID' using getPermissionSubscriptionState() instead idsAvailable as I did below?

```<code>    OneSignal.idsAvailable({ (userId, pushToken) in

        if (pushToken != nil) {

            if let playerID = userId {

                // do something

            }
        }
    })
</code>```

答:
Use this code</p>
```<code>public class MainActivity extends Activity implements OSSubscriptionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addSubscriptionObserver(this);
  }

  public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
    if (!stateChanges.getFrom().getSubscribed() &&
        stateChanges.getTo().getSubscribed()) {
         new AlertDialog.Builder(this)
             .setMessage("You've successfully subscribed to push notifications!")
             .show();
        // get player ID
        stateChanges.getTo().getUserId();
      }

      Log.i("Debug", "onOSSubscriptionChanged: " + stateChanges);
  }
}
</code>```

Title: One Signal - idsAvailable is deprecated

Body:
OneSignal's latest build version generate a warning like 'idsAvailable' is deprecated. How can I get 'playerID' using getPermissionSubscriptionState() instead idsAvailable as I did below?

    OneSignal.idsAvailable({ (userId, pushToken) in

        if (pushToken != nil) {

            if let playerID = userId {

                // do something

            }
        }
    })

Body:
Use this code

public class MainActivity extends Activity implements OSSubscriptionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addSubscriptionObserver(this);
  }

  public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
    if (!stateChanges.getFrom().getSubscribed() &&
        stateChanges.getTo().getSubscribed()) {
         new AlertDialog.Builder(this)
             .setMessage("You've successfully subscribed to push notifications!")
             .show();
        // get player ID
        stateChanges.getTo().getUserId();
      }

      Log.i("Debug", "onOSSubscriptionChanged: " + stateChanges);
  }
}


问:
SQL - How do I get values where all of the values in another column are the same?
Given a table like this:

```<code>PROJ| NAME | c_3
----+------+----
 1  | ANN  | 10
 2  | BOB  | 20
 3  | CHAD | 15
 4  | ANN  | 20
 5  | ANN  | 30
 6  | BOB  | 20
 7  | BOB  | 20
</code>```

I need to get the names of those where the value of c_3 is always the same. In this case the result would be CHAD (single entry) and BOB (c_3 is always 20) but not ANN (c_3) varies. I'm completely stuck and nothing I've tried comes close

答:
You wanted to see the names of those where the value of c_3 is always the same. So here is my simple query which will help you to resolve this</p>
```<code> SELECT Name
 FROM
 (
     SELECT
         Name,
         COUNT(DISTINCT C_3) Distinct_Counter
     FROM Table_Name
     GROUP BY Name
 )T WHERE T.Distinct_Counter = 1
</code>```

Body:
Given a table like this:

PROJ| NAME | c_3
----+------+----
 1  | ANN  | 10
 2  | BOB  | 20
 3  | CHAD | 15
 4  | ANN  | 20
 5  | ANN  | 30
 6  | BOB  | 20
 7  | BOB  | 20

I need to get the names of those where the value of c_3 is always the same. In this case the result would be CHAD (single entry) and BOB (c_3 is always 20) but not ANN (c_3) varies. I'm completely stuck and nothing I've tried comes close

Body:
You wanted to see the names of those where the value of c_3 is always the same. So here is my simple query which will help you to resolve this

 SELECT Name
 FROM
 (
     SELECT
         Name,
         COUNT(DISTINCT C_3) Distinct_Counter
     FROM Table_Name
     GROUP BY Name
 )T WHERE T.Distinct_Counter = 1


问:
Read a CSV file in real time using Kafka Connect
how can I integrate Kafka connect with Kafka producer in java so that I can read a CSV file in real time? I am having a hard time finding any source related to this.

Right now I am using scala-ide to run a simple Kafka producer class, but have no idea on how to use it with Kafka connect.

答: The issue with the casual spooldir connector is that you need to have the csv file inside the pod/ container of kafka-connect. It might not be secure for large sized files.</p>


问:
How to remove a specific value that is based on a specific date
Below is a portion of my dataframe:

```<code>    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-14        a wnd       n      n                  1
    2017 2017-08-15        a wnd       n      n                  1
    2017 2017-08-16        a wnd       n      n                  1
    2017 2017-08-17        a wnd       n      n                  1
    2017 2017-08-18        a wnd       n      n                  1
    2017 2017-08-19        a wnd       n      n                  1
    2017 2017-08-20        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-17        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0
</code>```

The column "atDominantLocation" contains "1"s and "0"s. I want to keep all the "0"s but only keep the "1" with the earliest date. So, there should ONLY be one "1" for each tag and year and that "1" should be the earliest date in that year.

Below is my desired output:

```<code>    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0
</code>```

I've tried both the duplicate and unique functions without any success. Thanks for your help.

Body:
Below is a portion of my dataframe:

    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-14        a wnd       n      n                  1
    2017 2017-08-15        a wnd       n      n                  1
    2017 2017-08-16        a wnd       n      n                  1
    2017 2017-08-17        a wnd       n      n                  1
    2017 2017-08-18        a wnd       n      n                  1
    2017 2017-08-19        a wnd       n      n                  1
    2017 2017-08-20        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-17        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0

The column "atDominantLocation" contains "1"s and "0"s. I want to keep all the "0"s but only keep the "1" with the earliest date. So, there should ONLY be one "1" for each tag and year and that "1" should be the earliest date in that year.

Below is my desired output:

    Year Date        Location Tag Section domsec atDominantLocation
    2017 2017-08-13        a wnd       n      n                  1
    2017 2017-08-21        a wnd       b      n                  0
    2017 2017-08-21        a wnd       u      n                  0
    2017 2017-08-23        a wnd       f      n                  0
    2018 2018-08-21        a wnd       f      s                  0
    2018 2018-08-18        a wnd       h      s                  0
    2018 2018-08-19        a wnd       o      s                  0
    2018 2018-08-15        a wnd       s      s                  1
    2018 2018-08-14        c wnd      ss      s                  0
    2018 2018-08-16        a wnd       t      s                  0
    2018 2018-08-21        a wnd       t      s                  0
    2018 2018-08-13        c wnd      ww      s                  0
    2018 2018-08-20        a wnd       y      s                  0

I've tried both the duplicate and unique functions without any success. Thanks for your help.

Body:
We can group by 'Year', 'Tag' and create the logical expression in filter to subset the rows  - create separate logical expressions and join them with | (OR)  i..e. as we want all 0 values (atDominantLocation == 0) and only the row with minimum 'Date' where the 'atDominantLocation' is 1 (Date == min(Date[atDominantLocation == 1]))

library(dplyr)
df1 %>%
   mutate(Date = as.Date(Date)) %>%
   group_by(Year, Tag) %>%
   filter(atDominantLocation == 0|
     ( Date == min(Date[atDominantLocation == 1]))) %>%
   ungroup

-output

# A tibble: 13 × 7
    Year Date       Location Tag   Section domsec atDominantLocation
   <int> <date>     <chr>    <chr> <chr>   <chr>               <int>
 1  2017 2017-08-13 a        wnd   n       n                       1
 2  2017 2017-08-21 a        wnd   b       n                       0
 3  2017 2017-08-21 a        wnd   u       n                       0
 4  2017 2017-08-23 a        wnd   f       n                       0
 5  2018 2018-08-21 a        wnd   f       s                       0
 6  2018 2018-08-18 a        wnd   h       s                       0
 7  2018 2018-08-19 a        wnd   o       s                       0
 8  2018 2018-08-15 a        wnd   s       s                       1
 9  2018 2018-08-14 c        wnd   ss      s                       0
10  2018 2018-08-16 a        wnd   t       s                       0
11  2018 2018-08-21 a        wnd   t       s                       0
12  2018 2018-08-13 c        wnd   ww      s                       0
13  2018 2018-08-20 a        wnd   y       s                       0

data

df1 <- structure(list(Year = c(2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
2017L, 2017L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L), Date = c("2017-08-13",
"2017-08-14", "2017-08-15", "2017-08-16", "2017-08-17", "2017-08-18",
"2017-08-19", "2017-08-20", "2017-08-21", "2017-08-21", "2017-08-23",
"2018-08-21", "2018-08-18", "2018-08-19", "2018-08-15", "2018-08-17",
"2018-08-14", "2018-08-16", "2018-08-21", "2018-08-13", "2018-08-20"
), Location = c("a", "a", "a", "a", "a", "a", "a", "a", "a",
"a", "a", "a", "a", "a", "a", "a", "c", "a", "a", "c", "a"),
    Tag = c("wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd",
    "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd", "wnd",
    "wnd", "wnd", "wnd", "wnd", "wnd"), Section = c("n", "n",
    "n", "n", "n", "n", "n", "n", "b", "u", "f", "f", "h", "o",
    "s", "s", "ss", "t", "t", "ww", "y"), domsec = c("n", "n",
    "n", "n", "n", "n", "n", "n", "n", "n", "n", "s", "s", "s",
    "s", "s", "s", "s", "s", "s", "s"), atDominantLocation = c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
    0L, 0L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-21L))


问:
Installing pandas in docker Alpine
I am having a really hard time trying to install a stable data science package configuration in docker. This should be easier with such mainstream, relevant tools.

The following is the Dockerfile that used to work, with a bit of a hack, removing pandas from the package core and installing it separately, specifying pandas<0.21.0, because, allegedly, higher versions conflict with numpy.

```<code>    FROM alpine:3.6

    ENV PACKAGES="\
    dumb-init \
    musl \
    libc6-compat \
    linux-headers \
    build-base \
    bash \
    git \
    ca-certificates \
    freetype \
    libgfortran \
    libgcc \
    libstdc++ \
    openblas \
    tcl \
    tk \
    libssl1.0 \
    "

ENV PYTHON_PACKAGES="\
    numpy \
    matplotlib \
    scipy \
    scikit-learn \
    nltk \
    "

RUN apk add --no-cache --virtual build-dependencies python3 \
    && apk add --virtual build-runtime \
    build-base python3-dev openblas-dev freetype-dev pkgconfig gfortran \
    && ln -s /usr/include/locale.h /usr/include/xlocale.h \
    && python3 -m ensurepip \
    && rm -r /usr/lib/python*/ensurepip \
    && pip3 install --upgrade pip setuptools \
    && ln -sf /usr/bin/python3 /usr/bin/python \
    && ln -sf pip3 /usr/bin/pip \
    && rm -r /root/.cache \
    && pip install --no-cache-dir $PYTHON_PACKAGES \
    && pip3 install 'pandas<0.21.0' \    #<---------- PANDAS
    && apk del build-runtime \
    && apk add --no-cache --virtual build-dependencies $PACKAGES \
    && rm -rf /var/cache/apk/*

# set working directory
WORKDIR /usr/src/app

# add and install requirements
COPY ./requirements.txt /usr/src/app/requirements.txt # other than data science packages go here
RUN pip install -r requirements.txt

# add entrypoint.sh
COPY ./entrypoint.sh /usr/src/app/entrypoint.sh

RUN chmod +x /usr/src/app/entrypoint.sh

# add app
COPY . /usr/src/app

# run server
CMD ["/usr/src/app/entrypoint.sh"]
</code>```

The configuration above used to work. What happens now is that build does go through, but pandas fails at import with the following error:

```<code>ImportError: Missing required dependencies ['numpy']
</code>```

Since numpy 1.16.1 was installed, I don't know which numpy pandas is trying to find anymore...

Does anyone know how to obtain a stable solution for this?

NOTE: A solution consisting of a pull from a turnkey docker image for data science with at least the packages mentioned above, into Dockerfile above, would be also very welcomed.

EDIT 1:

If I move install of data packages into requirements.txt, as suggested in the comments, like so:

requirements.txt

```<code>(...)
numpy==1.16.1 # or numpy==1.16.0
scikit-learn==0.20.2
scipy==1.2.1
nltk==3.4
pandas==0.24.1 # or pandas== 0.23.4
matplotlib==3.0.2
(...)
</code>```

and Dockerfile:

```<code># add and install requirements
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip install -r requirements.txt
</code>```

It breaks again at pandas, complaining about numpy.

```<code>Collecting numpy==1.16.1 (from -r requirements.txt (line 61))
  Downloading https://files.pythonhosted.org/packages/2b/26/07472b0de91851b6656cbc86e2f0d5d3a3128e7580f23295ef58b6862d6c/numpy-1.16.1.zip (5.1MB)
Collecting scikit-learn==0.20.2 (from -r requirements.txt (line 62))
  Downloading https://files.pythonhosted.org/packages/49/0e/8312ac2d7f38537361b943c8cde4b16dadcc9389760bb855323b67bac091/scikit-learn-0.20.2.tar.gz (10.3MB)
Collecting scipy==1.2.1 (from -r requirements.txt (line 63))
  Downloading https://files.pythonhosted.org/packages/a9/b4/5598a706697d1e2929eaf7fe68898ef4bea76e4950b9efbe1ef396b8813a/scipy-1.2.1.tar.gz (23.1MB)
Collecting nltk==3.4 (from -r requirements.txt (line 64))
  Downloading https://files.pythonhosted.org/packages/6f/ed/9c755d357d33bc1931e157f537721efb5b88d2c583fe593cc09603076cc3/nltk-3.4.zip (1.4MB)
Collecting pandas==0.24.1 (from -r requirements.txt (line 65))
  Downloading https://files.pythonhosted.org/packages/81/fd/b1f17f7dc914047cd1df9d6813b944ee446973baafe8106e4458bfb68884/pandas-0.24.1.tar.gz (11.8MB)
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 359, in get_provider
        module = sys.modules[moduleOrReq]
    KeyError: 'numpy'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-_e5z6o6_/pandas/setup.py", line 732, in <module>
        ext_modules=maybe_cythonize(extensions, compiler_directives=directives),
      File "/tmp/pip-install-_e5z6o6_/pandas/setup.py", line 475, in maybe_cythonize
        numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 1144, in resource_filename
        return get_provider(package_or_requirement).get_resource_filename(
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 361, in get_provider
        __import__(moduleOrReq)
    ModuleNotFoundError: No module named 'numpy'

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-_e5z6o6_/pandas/
</code>```

EDIT 2:

This seems like an open pandas issue. For more details please refer to:

pandas-dev github

"Unfortunately, this means that a requirements.txt file is insufficient for setting up a new environment with pandas installed (like in a docker container)".

```<code>  **ImportError**:

  IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

  Importing the multiarray numpy extension module failed.  Most
  likely you are trying to import a failed build of numpy.
  Here is how to proceed:
  - If you're working with a numpy git repository, try `git clean -xdf`
    (removes all files not under version control) and rebuild numpy.
  - If you are simply trying to use the numpy version that you have installed:
    your installation is broken - please reinstall numpy.
  - If you have already reinstalled and that did not fix the problem, then:
    1. Check that you are using the Python you expect (you're using /usr/local/bin/python),
       and that you have no directories in your PATH or PYTHONPATH that can
       interfere with the Python and numpy versions you're trying to use.
    2. If (1) looks fine, you can open a new issue at
       https://github.com/numpy/numpy/issues.  Please include details on:
       - how you installed Python
       - how you installed numpy
       - your operating system
       - whether or not you have multiple versions of Python installed
       - if you built from source, your compiler versions and ideally a build log
</code>```

EDIT 3

requirements.txt ---> https://pastebin.com/0icnx0iu

EDIT 4

As of 01/12/20, the accepted solution started not to work anymore.
Now, build breaks not at pandas, but at scipy but after numpy, while building scipy's wheel. This is the log:

```<code>  ----------------------------------------
  ERROR: Failed building wheel for scipy
  Running setup.py clean for scipy
  ERROR: Command errored out with exit status 1:
   command: /usr/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s6nahssd/scipy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s6nahssd/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all
       cwd: /tmp/pip-install-s6nahssd/scipy
  Complete output (9 lines):

  `setup.py clean` is not supported, use one of the following instead:

    - `git clean -xdf` (cleans all files)
    - `git clean -Xdf` (cleans all versioned files, doesn't touch
                        files that aren't checked into the git repo)

  Add `--force` to your command to use it anyway if you must (unsupported).

  ----------------------------------------
  ERROR: Failed cleaning build dir for scipy
Successfully built numpy
Failed to build scipy
ERROR: Could not build wheels for scipy which use PEP 517 and cannot be installed directly
</code>```

From the error it seems that building process is using python3.6, while I use FROM alpine:3.7.

Full log here -> https://pastebin.com/Tw4ubxSA

And this is the current Dockerfile:

https://pastebin.com/3SftEufx

答:
FROM python:3.8-alpine

RUN apk --update add gcc build-base freetype-dev libpng-dev openblas-dev

RUN pip install --no-cache-dir matplotlib pandas

Title: Installing pandas in docker Alpine

Body:
I am having a really hard time trying to install a stable data science package configuration in docker. This should be easier with such mainstream, relevant tools.

The following is the Dockerfile that used to work, with a bit of a hack, removing pandas from the package core and installing it separately, specifying pandas<0.21.0, because, allegedly, higher versions conflict with numpy.

    FROM alpine:3.6

    ENV PACKAGES="\
    dumb-init \
    musl \
    libc6-compat \
    linux-headers \
    build-base \
    bash \
    git \
    ca-certificates \
    freetype \
    libgfortran \
    libgcc \
    libstdc++ \
    openblas \
    tcl \
    tk \
    libssl1.0 \
    "

ENV PYTHON_PACKAGES="\
    numpy \
    matplotlib \
    scipy \
    scikit-learn \
    nltk \
    "

RUN apk add --no-cache --virtual build-dependencies python3 \
    && apk add --virtual build-runtime \
    build-base python3-dev openblas-dev freetype-dev pkgconfig gfortran \
    && ln -s /usr/include/locale.h /usr/include/xlocale.h \
    && python3 -m ensurepip \
    && rm -r /usr/lib/python*/ensurepip \
    && pip3 install --upgrade pip setuptools \
    && ln -sf /usr/bin/python3 /usr/bin/python \
    && ln -sf pip3 /usr/bin/pip \
    && rm -r /root/.cache \
    && pip install --no-cache-dir $PYTHON_PACKAGES \
    && pip3 install 'pandas<0.21.0' \    #<---------- PANDAS
    && apk del build-runtime \
    && apk add --no-cache --virtual build-dependencies $PACKAGES \
    && rm -rf /var/cache/apk/*

# set working directory
WORKDIR /usr/src/app

# add and install requirements
COPY ./requirements.txt /usr/src/app/requirements.txt # other than data science packages go here
RUN pip install -r requirements.txt

# add entrypoint.sh
COPY ./entrypoint.sh /usr/src/app/entrypoint.sh

RUN chmod +x /usr/src/app/entrypoint.sh

# add app
COPY . /usr/src/app

# run server
CMD ["/usr/src/app/entrypoint.sh"]

The configuration above used to work. What happens now is that build does go through, but pandas fails at import with the following error:

ImportError: Missing required dependencies ['numpy']

Since numpy 1.16.1 was installed, I don't know which numpy pandas is trying to find anymore...

Does anyone know how to obtain a stable solution for this?

NOTE: A solution consisting of a pull from a turnkey docker image for data science with at least the packages mentioned above, into Dockerfile above, would be also very welcomed.

EDIT 1:

If I move install of data packages into requirements.txt, as suggested in the comments, like so:

requirements.txt

(...)
numpy==1.16.1 # or numpy==1.16.0
scikit-learn==0.20.2
scipy==1.2.1
nltk==3.4
pandas==0.24.1 # or pandas== 0.23.4
matplotlib==3.0.2
(...)

and Dockerfile:

# add and install requirements
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip install -r requirements.txt

It breaks again at pandas, complaining about numpy.

Collecting numpy==1.16.1 (from -r requirements.txt (line 61))
  Downloading https://files.pythonhosted.org/packages/2b/26/07472b0de91851b6656cbc86e2f0d5d3a3128e7580f23295ef58b6862d6c/numpy-1.16.1.zip (5.1MB)
Collecting scikit-learn==0.20.2 (from -r requirements.txt (line 62))
  Downloading https://files.pythonhosted.org/packages/49/0e/8312ac2d7f38537361b943c8cde4b16dadcc9389760bb855323b67bac091/scikit-learn-0.20.2.tar.gz (10.3MB)
Collecting scipy==1.2.1 (from -r requirements.txt (line 63))
  Downloading https://files.pythonhosted.org/packages/a9/b4/5598a706697d1e2929eaf7fe68898ef4bea76e4950b9efbe1ef396b8813a/scipy-1.2.1.tar.gz (23.1MB)
Collecting nltk==3.4 (from -r requirements.txt (line 64))
  Downloading https://files.pythonhosted.org/packages/6f/ed/9c755d357d33bc1931e157f537721efb5b88d2c583fe593cc09603076cc3/nltk-3.4.zip (1.4MB)
Collecting pandas==0.24.1 (from -r requirements.txt (line 65))
  Downloading https://files.pythonhosted.org/packages/81/fd/b1f17f7dc914047cd1df9d6813b944ee446973baafe8106e4458bfb68884/pandas-0.24.1.tar.gz (11.8MB)
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 359, in get_provider
        module = sys.modules[moduleOrReq]
    KeyError: 'numpy'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-_e5z6o6_/pandas/setup.py", line 732, in <module>
        ext_modules=maybe_cythonize(extensions, compiler_directives=directives),
      File "/tmp/pip-install-_e5z6o6_/pandas/setup.py", line 475, in maybe_cythonize
        numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 1144, in resource_filename
        return get_provider(package_or_requirement).get_resource_filename(
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 361, in get_provider
        __import__(moduleOrReq)
    ModuleNotFoundError: No module named 'numpy'

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-_e5z6o6_/pandas/

EDIT 2:

This seems like an open pandas issue. For more details please refer to:

pandas-dev github

"Unfortunately, this means that a requirements.txt file is insufficient for setting up a new environment with pandas installed (like in a docker container)".

  **ImportError**:

  IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

  Importing the multiarray numpy extension module failed.  Most
  likely you are trying to import a failed build of numpy.
  Here is how to proceed:
  - If you're working with a numpy git repository, try `git clean -xdf`
    (removes all files not under version control) and rebuild numpy.
  - If you are simply trying to use the numpy version that you have installed:
    your installation is broken - please reinstall numpy.
  - If you have already reinstalled and that did not fix the problem, then:
    1. Check that you are using the Python you expect (you're using /usr/local/bin/python),
       and that you have no directories in your PATH or PYTHONPATH that can
       interfere with the Python and numpy versions you're trying to use.
    2. If (1) looks fine, you can open a new issue at
       https://github.com/numpy/numpy/issues.  Please include details on:
       - how you installed Python
       - how you installed numpy
       - your operating system
       - whether or not you have multiple versions of Python installed
       - if you built from source, your compiler versions and ideally a build log

EDIT 3

requirements.txt ---> https://pastebin.com/0icnx0iu

EDIT 4

As of 01/12/20, the accepted solution started not to work anymore.
Now, build breaks not at pandas, but at scipy but after numpy, while building scipy's wheel. This is the log:

  ----------------------------------------
  ERROR: Failed building wheel for scipy
  Running setup.py clean for scipy
  ERROR: Command errored out with exit status 1:
   command: /usr/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s6nahssd/scipy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s6nahssd/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all
       cwd: /tmp/pip-install-s6nahssd/scipy
  Complete output (9 lines):

  `setup.py clean` is not supported, use one of the following instead:

    - `git clean -xdf` (cleans all files)
    - `git clean -Xdf` (cleans all versioned files, doesn't touch
                        files that aren't checked into the git repo)

  Add `--force` to your command to use it anyway if you must (unsupported).

  ----------------------------------------
  ERROR: Failed cleaning build dir for scipy
Successfully built numpy
Failed to build scipy
ERROR: Could not build wheels for scipy which use PEP 517 and cannot be installed directly

From the error it seems that building process is using python3.6, while I use FROM alpine:3.7.

Full log here -> https://pastebin.com/Tw4ubxSA

And this is the current Dockerfile:

https://pastebin.com/3SftEufx


问:
Removing a model in rails (reverse of "rails g model Title...")
```<code>rails g model Rating user_id:integer message:string value:integer
</code>```

How can I completely remove this model? Thanks

答:
Try this

```<code>rails destroy model Rating
</code>```

It will remove model, migration, tests and fixtures

Body:
rails g model Rating user_id:integer message:string value:integer

How can I completely remove this model? Thanks

Body:
Try this

rails destroy model Rating

It will remove model, migration, tests and fixtures


问:
How to make if/else chain with lists more efficient
I have a huge dataframe with ~100,000 rows. I have this code but it is taking way too long to execute. Is there any way to make this more efficient?</p>
```<code>df["Grade Band"] = ""
k5 = ["0","1","2","3","4","5"]
ms = ["6", "7" ,"8"]
hs = ["9","10","11","12"]

for x in df["Grade Roll"]:
    if x == "Other":
        df["Grade Band"] == "Undefined"
    elif x in k5:
        df["Grade Band"] == "K5"
    elif x in ms:
        df["Grade Band"] == "MS"
    elif x in hs:
            df["Grade Band"] == "HS"
</code>```

答:
Use a map.

gradeMap = { "Other": "Undefined" }
gradeMap.update(dict.fromkeys(k5, "K5"))
gradeMap.update(dict.fromkeys(ms, "MS"))
gradeMap.update(dict.fromkeys(hs, "HS"))

for x in df["Grade Roll"]:
    if x in gradeMap:
        gradeMapVal = gradeMap[x]
    else:
        raise Exception('The grade ' + x + ' was not found in the grade map.')
```

Body:
I have a huge dataframe with ~100,000 rows. I have this code but it is taking way too long to execute. Is there any way to make this more efficient?

df["Grade Band"] = ""
k5 = ["0","1","2","3","4","5"]
ms = ["6", "7" ,"8"]
hs = ["9","10","11","12"]

for x in df["Grade Roll"]:
    if x == "Other":
        df["Grade Band"] == "Undefined"
    elif x in k5:
        df["Grade Band"] == "K5"
    elif x in ms:
        df["Grade Band"] == "MS"
    elif x in hs:
            df["Grade Band"] == "HS"


问:
How do I fix my source code bindings?
I've installed VB6, I've installed Sourcegear Vault 5.x and now I get this message on every VB6 startup.

And of course, I can't use the built-in source control commands.

I've tried reinstalling SourceGear Vault, to no avail.  What am I missing?

How do I fix it?

答:
I had this same issue using 'SourceSafe 6.0' (not Vault), fixed by installing SourceSafe from the VB6 installation media (I had skipped this originally thinking the 'MSSCCI provider' would handle it).

Note: oddly the 'Source Code Control' add-in was showing 'Startup / Loaded' in VB6 IDE before SourceSafe was installed.

Ref:

w10 (64-bit)

VB6 SP6

Microsoft Visual Studio Team Foundation Server 2013&2015 MSSCCI Provider (32-bit)
(https://marketplace.visualstudio.com/items?itemName=TFSPowerToolsTeam.MicrosoftVisualStudioTeamFoundationServer20132015M)(32-bit even though is w10 64-bit)

TFS 2015 update 4.2

Title: How do I fix my source code bindings?


问:
If it's in a main div with margin, make a div with a width of 100vw
I'm trying to make a div with a width of 100vw to cover all viewing areas, however, it comes in a div with a margin, so I'm having trouble.

I've also included an image link below to help you understand.

* {
    margin: 0%;
    padding: 0%;
}

body {
    background: black;
    margin: 2rem 6rem;
    color: white;
}

/* About Section  */

.about {
    display: block;
    background-color: #2e3038;
    margin-left: -6rem;
    margin-right: 6rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="about">
    <div id="col1">
      <h3>A co-founder at one of the world's largest communities.
      </h3>
      <p>

        The combined experience I have working at the top Fortune 500 companies has allowed me to develop a skill set that helps me in not just development but in every aspect of any business. <br> I'm proud to announce that I am now working at one
        of the world's largest communities teaching young minds about how to sell themselves as a developer and open them to a whole new world of opportunities.
      </p>
    </div>
    <div id="col2">
      <p>As a developer, you have everything available to you and all that's holding you back is yourself. <br> A quote I live by perfectly illustrates what I mean. <br> "How big would you dream, if you knew you wouldn't fail?" You've already gone through
        the hardest parts of being a developer, it's time to elevate your skills and become a leader in something you're passionate about. <br> I'm happy to chat over coffee some time about how I can help your company.</p>
    </div>
  </div>
</body></code>```

As you can see, I attempted to use margin-right, however, it would not work.

I can't use inspect element since the design I'm attempting to replicate is in png format.

答:
You're close - you've just specified the wrong direction for margin-right:

* {
    margin: 0%;
    padding: 0%;
}

body {
    background: black;
    margin: 2rem 6rem;
    color: white;
}

.about {
    background-color: #2e3038;
    margin-left: -6rem;
    margin-right: -6rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="about">
    <div id="col1">
      <h3>A co-founder at one of the world's largest communities.
      </h3>
      <p>

        The combined experience I have working at the top Fortune 500 companies has allowed me to develop a skill set that helps me in not just development but in every aspect of any business. <br> I'm proud to announce that I am now working at one
        of the world's largest communities teaching young minds about how to sell themselves as a developer and open them to a whole new world of opportunities.
      </p>
    </div>
    <div id="col2">
      <p>As a developer, you have everything available to you and all that's holding you back is yourself. <br> A quote I live by perfectly illustrates what I mean. <br> "How big would you dream, if you knew you wouldn't fail?" You've already gone through
        the hardest parts of being a developer, it's time to elevate your skills and become a leader in something you're passionate about. <br> I'm happy to chat over coffee some time about how I can help your company.</p>
    </div>
  </div>
</body></code>```

Full Width Containers in Limited Width Parents | CSS-Tricks

Body:
I'm trying to make a div with a width of 100vw to cover all viewing areas, however, it comes in a div with a margin, so I'm having trouble.

I've also included an image link below to help you understand.

* {
    margin: 0%;
    padding: 0%;
}

body {
    background: black;
    margin: 2rem 6rem;
    color: white;
}

/* About Section  */

.about {
    display: block;
    background-color: #2e3038;
    margin-left: -6rem;
    margin-right: 6rem;
}

A co-founder at one of the world's largest communities.

        The combined experience I have working at the top Fortune 500 companies has allowed me to develop a skill set that helps me in not just development but in every aspect of any business.
 I'm proud to announce that I am now working at one
        of the world's largest communities teaching young minds about how to sell themselves as a developer and open them to a whole new world of opportunities.

As a developer, you have everything available to you and all that's holding you back is yourself.
 A quote I live by perfectly illustrates what I mean.
 "How big would you dream, if you knew you wouldn't fail?" You've already gone through
        the hardest parts of being a developer, it's time to elevate your skills and become a leader in something you're passionate about.
 I'm happy to chat over coffee some time about how I can help your company.

As you can see, I attempted to use margin-right, however, it would not work.

I can't use inspect element since the design I'm attempting to replicate is in png format.

Body:
You're close - you've just specified the wrong direction for margin-right:

* {
    margin: 0%;
    padding: 0%;
}

body {
    background: black;
    margin: 2rem 6rem;
    color: white;
}

.about {
    background-color: #2e3038;
    margin-left: -6rem;
    margin-right: -6rem;
}

<body>
  <div class="about">
    <div id="col1">
      <h3>A co-founder at one of the world's largest communities.
      </h3>
      <p>

        The combined experience I have working at the top Fortune 500 companies has allowed me to develop a skill set that helps me in not just development but in every aspect of any business. <br> I'm proud to announce that I am now working at one
        of the world's largest communities teaching young minds about how to sell themselves as a developer and open them to a whole new world of opportunities.
      </p>
    </div>
    <div id="col2">
      <p>As a developer, you have everything available to you and all that's holding you back is yourself. <br> A quote I live by perfectly illustrates what I mean. <br> "How big would you dream, if you knew you wouldn't fail?" You've already gone through
        the hardest parts of being a developer, it's time to elevate your skills and become a leader in something you're passionate about. <br> I'm happy to chat over coffee some time about how I can help your company.</p>
    </div>
  </div>
</body>

Full Width Containers in Limited Width Parents | CSS-Tricks


问:
Weasy-print convert to pdf with border image
I’m trying to create pdf file for payment receipt, but I’m not able to figure out how I should set border for it.

As border I want to use this image:

But while converting it to pdf, next page gets like this:

How can I make it constant border for all pages?

Python + Django code:

from weasyprint import HTML
html_string = render_to_string('receipt.html', DATA)
html = HTML(string=html_string)
result = html.write_pdf()
f = open(str(os.path.join(MEDIA_URL + "invoice_receipt/", 'temp.pdf')), 'wb')
f.write(result)
file_obj = File(open(MEDIA_URL + "invoice_receipt/" + "temp.pdf", 'rb'))
transaction.receipt_file = file_obj
transaction.save()
```
<p>receipt.html template:</p>
<pre class="lang-html prettyprint-override"><code>    <style>
      table tbody tr td{
        border-top: unset !important;
      }

      table tbody tr:nth-child(7) td,
      table tbody tr:nth-child(8) td,
      table tbody tr:nth-child(9) td,
      table tbody tr:nth-child(10) td,
      table tbody tr:nth-child(11) td,
      table tbody tr:nth-child(12) td
      {
        padding-top: 0;
        padding-bottom: 0;
      }
      .amount-in-words{
        border-bottom:3px solid black;
      }

      .table thead th {
    vertical-align: bottom;
    border-bottom: 4px solid black;
}

      /* .invoice-template{
        padding: 20px;
        border: 20px solid transparent;
        border-image: linear-gradient(to right,#633363 50%,#f3c53d 50%);
        border-image-slice: 1;
      } */

      .logo{
        margin-top: 2rem;
      }
      .logo2{
        margin-top: 2rem;
        height: 160px;
        width:200px;
      }

      .invoice-template{
        padding: 20px;
        background-image: url('https://dev-api.test.com/files/files/DumpData/Frame.png');
        background-repeat: no-repeat;
        background-size: contain;
        break-inside: auto;
      }

      .main-container{
        border: 1px solid black;
        padding: 20px 10px;
        background: white;
      }

      p {
        font-weight: 500;
      }

    </style>
  </head>
<body>
  <div class="container invoice-template">
    <!-- <div class="main-container"> -->
    <div class="row justify-content-center">
      <div class="col-md-5 logo"><img src={{ logo }} class="logo2"></div>
      <div class="col-md-5 text-right">
        <ul style="list-style: none; color: purple; margin-top: 2rem;">
            <li>{{ phone }}<span></span></li>
            <li><p>{{ email }}<br>{{ website }}</p><span></span></li>
          <li>Resource Factory Pvt. Ltd.<br>{{ shop_address|linebreaksbr }}<span></span></li>
          </ul>
      </div>
    </div>

    <div class="row text-center">
      <div class="col-md-12"><h6>INVOICE</h6></div>
    </div>

    <div class="row justify-content-center">
      <div class="col-md-5">
        <p>
          To,<br>
          {{ user_name }}<br>
          {{ user_address|linebreaksbr }}
        </p>
        <p>Client GST Number.:</p>
      </div>
      <div class="col-md-5 text-center">
        <p>Date: {{ order_date|date:"d-m-Y" }}</p>
        <p>Invoice No. {{ invoice }}</p>
      </div>
    </div>
</code>```

I’m giving a short version of my html code. If needed full code please mention.

答:
The behavior of box decorations when a box is split (like your main
 here) is controller by box-decoration-break. Default is slice which breaks the borders after rendering them. clone will compute the borders on each part of the box:

.invoice-template {
    box-decoration-break: clone;
}
```

Body:
I’m trying to create pdf file for payment receipt, but I’m not able to figure out how I should set border for it.

As border I want to use this image:

But while converting it to pdf, next page gets like this:

How can I make it constant border for all pages?

Python + Django code:

from weasyprint import HTML
html_string = render_to_string('receipt.html', DATA)
html = HTML(string=html_string)
result = html.write_pdf()
f = open(str(os.path.join(MEDIA_URL + "invoice_receipt/", 'temp.pdf')), 'wb')
f.write(result)
file_obj = File(open(MEDIA_URL + "invoice_receipt/" + "temp.pdf", 'rb'))
transaction.receipt_file = file_obj
transaction.save()

receipt.html template:

{{ phone }}

{{ email }}
{{ website }}

Resource Factory Pvt. Ltd.
{{ shop_address|linebreaksbr }}

INVOICE

          To,

          {{ user_name }}

          {{ user_address|linebreaksbr }}

Client GST Number.:

Date: {{ order_date|date:"d-m-Y" }}

Invoice No. {{ invoice }}

I’m giving a short version of my html code. If needed full code please mention.

Body:
The behavior of box decorations when a box is split (like your main <div> here) is controller by box-decoration-break. Default is slice which breaks the borders after rendering them. clone will compute the borders on each part of the box:

.invoice-template {
    box-decoration-break: clone;
}


问:
How does CodeBlocks increment variable addresses, specifically for pointers in C?
I am taking an introductory class in C. We just covered pointers, and our current lab is just to change our code from array notation to pointer notation. I know that in Codeblocks, it takes 4 bytes to store an int variable. So, I assigned a pointer to the front of the array, and based on the lecture from class and from experimentation, I know that by incrementing the pointer, I can change what element of the array that the pointer is pointing to. I figure that incrementing by 4 will allow me to go to the next element of the array.

However, whenever I print the pointer, run pointer+=4, and print the pointer again, it actually changes the value of my pointer by 16. In fact, any increment changes by its multiple of 4. Currently, my code runs fine by instead using pointer++.

My code runs fine, so this shouldn't be an issue, but I wanted to know if anyone could give me more information about why this is the case, and any other information about how Codeblocks stores memory?

答:
Pointer arithmetic is always done in the base unit of the pointer. So if you you have a pointer to int (i.e. int *) then doing arithmetic on that pointer will be in the units of int.

So lets say you have

```<code>int arr[] = { 1, 2, 3, 4 };
int *ptr = arr;
</code>```

then ptr will point to the first element in the array, arr[0].

Now if we increase the pointer ptr like ptr = ptr + 1 (or ptr += 1 or ptr++) then ptr will point to the second element of the array arr[1].

Of you need to visualize it, lets "draw" the array arr with the pointer and some pointer arithmetic:

```
+-----+-----+-----+-----+
|  1  |  2  |  3  |  4  |
+-----+-----+-----+-----+
^     ^     ^     ^
|     |     |     |
ptr   ptr+1 ptr+2 ptr+3
```

From this you should start to see a pattern corresponding to array indexing... ptr + 1 points to the second element, just like arr[1] (and ptr[1]) is the value of the second element.

In fact, all this is the underpinnings of why arr[i] is exactly equal to *(arr + i), and the array-to-pointer decay.

Body:
Pointer arithmetic is always done in the base unit of the pointer. So if you you have a pointer to int (i.e. int *) then doing arithmetic on that pointer will be in the units of int.

So lets say you have

int arr[] = { 1, 2, 3, 4 };
int *ptr = arr;

then ptr will point to the first element in the array, arr[0].

Now if we increase the pointer ptr like ptr = ptr + 1 (or ptr += 1 or ptr++) then ptr will point to the second element of the array arr[1].

Of you need to visualize it, lets "draw" the array arr with the pointer and some pointer arithmetic:

+-----+-----+-----+-----+
|  1  |  2  |  3  |  4  |
+-----+-----+-----+-----+
^     ^     ^     ^
|     |     |     |
ptr   ptr+1 ptr+2 ptr+3

From this you should start to see a pattern corresponding to array indexing... ptr + 1 points to the second element, just like arr[1] (and ptr[1]) is the value of the second element.

In fact, all this is the underpinnings of why arr[i] is exactly equal to *(arr + i), and the array-to-pointer decay.


问:
How method hiding works in C#? (Part Two)
The following program prints

```<code>A:C(A,B)
B:C(A,B)
</code>```

(as it should)

```<code>public interface I
{
    string A();
}

public class C : I
{
    public string A()
    {
        return "A";
    }

    public string B()
    {
        return "B";
    }
}

public class A
{
    public virtual void Print(C c)
    {
        Console.WriteLine("A:C(" + c.A() + "," + c.B() + ")");
    }
}

public class B : A
{
    public new void Print(C c)
    {
        Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
    }

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }
}

class Program
{
    public static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();
        a.Print(c);
        b.Print(c);
    }
}
</code>```

however, if I change keyword 'new' to 'override' in class B like so:

```<code>    public override void Print(C c)
</code>```

all of a sudden program starts to print:

```<code>A:C(A,B)
B:I(A)
</code>```

Why?

答:
This is at least as much a question about how method overloading works in C#. I think you've highlighted an interesting situation here...

In the first case (using the new keyword on the method), the compiler decides to use the Print method overload with the parameter of type C because it's type is exactly equivalent to that of the parameter passed (i.e. no implicit conversion is required) whereas an implicit conversion to the interface I would be required if the compiler were to choose the Print method that takes an argument of type I - in other words, it chooses the more "obvious" method overload.

In the second case (using the override keyword on the method), the compiler decides to use the overload of Print with parameter of type I because although you are overriding the Print(C c) method overload in the class B, it is effectively defined in the parent class A, making the Print(I i) method overload in fact the highest-level overload and therefore the most direct one, i.e. the first one the compiler finds.

Hopefully this will help you to understand. Let me know if I need to clairfy any points further...

Note: If I'm wrong about saying that the compiler does these things, then please correct me, though it makes little difference for the sake of the argument whether it's the compiler or CLR/JIT, it would seem.

ContentLicense: CC BY-SA 2.5

Body:
The following program prints

A:C(A,B)
B:C(A,B)

(as it should)

public interface I
{
    string A();
}

public class C : I
{
    public string A()
    {
        return "A";
    }

    public string B()
    {
        return "B";
    }
}

public class A
{
    public virtual void Print(C c)
    {
        Console.WriteLine("A:C(" + c.A() + "," + c.B() + ")");
    }
}

public class B : A
{
    public new void Print(C c)
    {
        Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
    }

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }
}

class Program
{
    public static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();
        a.Print(c);
        b.Print(c);
    }
}

however, if I change keyword 'new' to 'override' in class B like so:

    public override void Print(C c)

all of a sudden program starts to print:

A:C(A,B)
B:I(A)

Why?

OwnerDisplayName: Noldorin


问:
Problem with position:absolute on input
I have this code :

```<code><div class="areaButton">
    <input type="submit" value="Add">
</div>

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
}
</code>```

but as you can see, the Input doesnt "feel" the container (where is the background-color:red;)?

答:
Browsers insert default margin and padding on some elements, that's what CSS resets are for.

As you mark your input element as position: absolute, it gets taken out of the page flow, and the container won't expand to fit the element. You have to add height to the .areaButton element to see the background.

See my update:

http://jsfiddle.net/SZYUe/1/

Title: Problem with position:absolute on input

Body:
I have this code :

    <input type="submit" value="Add">

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
}

but as you can see, the Input doesnt "feel" the container (where is the background-color:red;)?


问:
Sequence `remove()` method not removing
I am learning Python and took on a few CodeWars exercises to get more familiar with its methods.

I have this function that creates the sum of all positive integers, and although I know there might be a "one liner" way to do this, this is approach I am taking as a beginner:

def positive_sum(arr):
    for x in arr:
        if x <= 0:
            arr.remove(x)

    if len(arr) == 0:
        return 0

    print(arr)

    return sum(arr)
```
<p>For some reason this method is not removing -2, and -4 from the array. Why is that?</p>
<pre class="lang-py prettyprint-override"><code>@test.it("returns 0 when all elements are negative")
    def negative_case():
        test.assert_equals(positive_sum([-1,-2,-3,-4,-5]),0)
</code>```

答:
Here is a way you can do it.</p>
```<code>x = [-6, -4, 3, 5]
x = sum([i for i in x if i>0])
print(x)
</code>```

Title: Sequence `remove()` method not removing

Body:
I am learning Python and took on a few CodeWars exercises to get more familiar with its methods.

I have this function that creates the sum of all positive integers, and although I know there might be a "one liner" way to do this, this is approach I am taking as a beginner:

def positive_sum(arr):
    for x in arr:
        if x <= 0:
            arr.remove(x)

    if len(arr) == 0:
        return 0

    print(arr)

    return sum(arr)

For some reason this method is not removing -2, and -4 from the array. Why is that?

@test.it("returns 0 when all elements are negative")
    def negative_case():
        test.assert_equals(positive_sum([-1,-2,-3,-4,-5]),0)

Body:
Here is a way you can do it.

x = [-6, -4, 3, 5]
x = sum([i for i in x if i>0])
print(x)