问:
PermissionError: [Errno 13] Permission denied: 'System Volume Information' when trying to copy files with python
I am trying to create a program that copies files from the USB stick inserted into the computer to a folder within the hard drive. I keep getting this error:
PermissionError: [Errno 13] Permission denied: 'System Volume Information'
The code is

```<code>import os
import shutil
from shutil import copyfile
drives = [ chr(x) + ":" for x in range(65,90) if os.path.exists(chr(x) + ":") ]
print(drives)

if "E:" in drives:
    with open('backupNumbers.txt', 'r') as f:
        f_contents =f.readlines()
        numberofFolders = int(f_contents[0])
        numberofFolders += 1
    with open('backupNumbers.txt', 'w') as wf:
        wf.write(str(numberofFolders))

    def createFolder(directory):
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
        except OSError:
            print ('Error: Creating directory. ' +  directory)
    folderNumber = str(numberofFolders)
    createFolder('./' + "Backup " + folderNumber + '/')
    src = "E:\\"
    dest1 = "Y:\\Documents\\USB Copies\\"
    dest = str(dest1 + "Backup" + folderNumber)
    files = os.listdir(src)
    os.chdir(src)
    for file in files:
        with open(file) as f:
            print(file, f.read())
    for file in files:
        shutil.copy(file, dest)
</code>```

The full traceback is

```<code>File "<ipython-input-4-fb59bc7c32b6>", line 1, in <module>
    runfile('E:/USB Backups/Automation.py', wdir='E:/USB Backups')

  File "C:\Users\Garret Langlois\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Garret Langlois\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "E:/USB Backups/Automation.py", line 30, in <module>
    with open(file) as f:

PermissionError: [Errno 13] Permission denied: 'System Volume Information'
</code>```

答:
System Volume Information is a special folder used by Windows to manage restore points.

You probably don't need to copy it yourself, and I'd suggest you just skip it.

But if you do want to get access to it, you can read about that here: https://support.microsoft.com/en-us/help/309531/how-to-gain-access-to-the-system-volume-information-folder

Body:
I am trying to create a program that copies files from the USB stick inserted into the computer to a folder within the hard drive. I keep getting this error:
PermissionError: [Errno 13] Permission denied: 'System Volume Information'
The code is

import os
import shutil
from shutil import copyfile
drives = [ chr(x) + ":" for x in range(65,90) if os.path.exists(chr(x) + ":") ]
print(drives)

if "E:" in drives:
    with open('backupNumbers.txt', 'r') as f:
        f_contents =f.readlines()
        numberofFolders = int(f_contents[0])
        numberofFolders += 1
    with open('backupNumbers.txt', 'w') as wf:
        wf.write(str(numberofFolders))

    def createFolder(directory):
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
        except OSError:
            print ('Error: Creating directory. ' +  directory)
    folderNumber = str(numberofFolders)
    createFolder('./' + "Backup " + folderNumber + '/')
    src = "E:\\"
    dest1 = "Y:\\Documents\\USB Copies\\"
    dest = str(dest1 + "Backup" + folderNumber)
    files = os.listdir(src)
    os.chdir(src)
    for file in files:
        with open(file) as f:
            print(file, f.read())
    for file in files:
        shutil.copy(file, dest)

The full traceback is

File "<ipython-input-4-fb59bc7c32b6>", line 1, in <module>
    runfile('E:/USB Backups/Automation.py', wdir='E:/USB Backups')

  File "C:\Users\Garret Langlois\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Garret Langlois\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "E:/USB Backups/Automation.py", line 30, in <module>
    with open(file) as f:

PermissionError: [Errno 13] Permission denied: 'System Volume Information'


来源: stackexchange

问:
Sharepoint - Permissions
In the root page, I have web parts - Announcements and Events, and hyperlinks to different Document Libraries and lets say Group X and Y has permissions for this. There is also an image which directs to another page (ex. Manager Sales), which has different document libraries.
I am able to set up different permissions for all document libraries, but I would like the Group X to not have access to the image link. </p>

答:
You could use JavaScript api to check user groups, you could find the script here, then you could hide the image link for Group X users by jQuery or CSS.hide element by jQuery</p>

```<code> function CheckUserGroups() {
            var groups = ["Visitors", "Designers"]
            IsCurrentUserMemberOfGroups(groups, function (isCurrentUserInGroup) {
                if (isCurrentUserInGroup) {
                    //your hide logic
                }
            });

        }
        ExecuteOrDelayUntilScriptLoaded(CheckUserGroups, 'SP.js');
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sharepoint - Permissions

Body:
You could use JavaScript api to check user groups, you could find the script here, then you could hide the image link for Group X users by jQuery or CSS.hide element by jQuery

 function CheckUserGroups() {
            var groups = ["Visitors", "Designers"]
            IsCurrentUserMemberOfGroups(groups, function (isCurrentUserInGroup) {
                if (isCurrentUserInGroup) {
                    //your hide logic
                }
            });

        }
        ExecuteOrDelayUntilScriptLoaded(CheckUserGroups, 'SP.js');


问:
Get the longest ranges per seqnames
I have a GRanges object with different genomic ranges for each seqnames (e.g. chromosomes).

How can I get a GRanges containing only the longest range for each seqname/chromosome?

For example, if gr is a GRanges:

```<code>library(GenomicRanges)

# Make a GRanges object
set.seed(123)
gr <- GRanges(seqnames = rep(c("chr1", "chr2", "chr3"), times=2:4),
              ranges = IRanges(start=sample.int(10000, 9),
                               width = c(3,5,50,20,10,500,100,500,200)))

# Add a column with the width for clarity:
mcols(gr)$width <- width(gr)

gr
#GRanges object with 9 ranges and 1 metadata column:
#      seqnames    ranges strand |     width
#         <Rle> <IRanges>  <Rle> | <integer>
#  [1]     chr1 2463-2465      * |         3
#  [2]     chr1 2511-2515      * |         5
#  [3]     chr2 8718-8767      * |        50
#  [4]     chr2 2986-3005      * |        20
#  [5]     chr2 1842-1851      * |        10
#  [6]     chr3 9334-9833      * |       500
#  [7]     chr3 3371-3470      * |       100
#  [8]     chr3 4761-5260      * |       500
#  [9]     chr3 6746-6945      * |       200
#  -------
#  seqinfo: 3 sequences from an unspecified genome; no seqlengths
</code>```

Then I want to obtain the following GRanges:

```<code>#GRanges object with 3 ranges and 1 metadata column:
#    seqnames      ranges strand |     width
#       <Rle>   <IRanges>  <Rle> | <integer>
#  [1]     chr1 2511-2515      * |         5
#  [2]     chr2 8718-8767      * |        50
#  [3]     chr3 9334-9833      * |       500
</code>```

For my application I'm OK with getting only the first longest range for chr3 but I would appreciate a solution that can also select all ties if any.

答:
I found this solution:

```<code>library(GenomicRanges)

# Make the GRanges object
set.seed(123)
gr <- GRanges(seqnames = rep(c("chr1", "chr2", "chr3"), times=2:4),
              ranges = IRanges(start=sample.int(10000, 9),
                               width = c(3,5,50,20,10,500,100,500,200)))

# Add a column with the width for clarity:
mcols(gr)$width <- width(gr)

# split gr by seqnames
grl <- split(gr, seqnames(gr))

# Get the width of each range organized as an IntegerList
wgr <- width(grl)
# if gr is ordered by seqnames this is equivalent to:
wgr <- splitAsList(width(gr), seqnames(gr))
wgr
#IntegerList of length 3
#[["chr1"]] 3 5
#[["chr2"]] 50 20 10
#[["chr3"]] 500 100 500 200

# Get the ranges with the largest width
# See ?'which.max,NumericList-method' for the global argument
longestRanges <- gr[which.max(wgr, global = TRUE)]

longestRanges
#GRanges object with 3 ranges and 1 metadata column:
#      seqnames      ranges strand |     width
#         <Rle>   <IRanges>  <Rle> | <integer>
#  [1]     chr1 2511-2515      * |         5
#  [2]     chr2 8718-8767      * |        50
#  [3]     chr3 9334-9833      * |       500
#  -------
#  seqinfo: 3 sequences from an unspecified genome; no seqlengths
</code>```

Note that this solution only works if the ranges in gr are initially grouped/ordered by seqnames.

If they are not, it is necessary to start by sorting gr with gr <- sort(gr)

To get all the ties, one can use:

```<code>longestRanges <- unlist(grl[which(wgr == max(wgr))])

longestRanges
#GRanges object with 4 ranges and 1 metadata column:
#       seqnames    ranges strand |     width
#          <Rle> <IRanges>  <Rle> | <integer>
#  chr1     chr1 2511-2515      * |         5
#  chr2     chr2 8718-8767      * |        50
#  chr3     chr3 9334-9833      * |       500
#  chr3     chr3 4761-5260      * |       500
#  -------
#  seqinfo: 3 sequences from an unspecified genome; no seqlengths
</code>```

Title: Get the longest ranges per seqnames

Body:
I have a GRanges object with different genomic ranges for each seqnames (e.g. chromosomes).

How can I get a GRanges containing only the longest range for each seqname/chromosome?

For example, if gr is a GRanges:

library(GenomicRanges)

# Make a GRanges object
set.seed(123)
gr <- GRanges(seqnames = rep(c("chr1", "chr2", "chr3"), times=2:4),
              ranges = IRanges(start=sample.int(10000, 9),
                               width = c(3,5,50,20,10,500,100,500,200)))

# Add a column with the width for clarity:
mcols(gr)$width <- width(gr)

gr
#GRanges object with 9 ranges and 1 metadata column:
#      seqnames    ranges strand |     width
#         <Rle> <IRanges>  <Rle> | <integer>
#  [1]     chr1 2463-2465      * |         3
#  [2]     chr1 2511-2515      * |         5
#  [3]     chr2 8718-8767      * |        50
#  [4]     chr2 2986-3005      * |        20
#  [5]     chr2 1842-1851      * |        10
#  [6]     chr3 9334-9833      * |       500
#  [7]     chr3 3371-3470      * |       100
#  [8]     chr3 4761-5260      * |       500
#  [9]     chr3 6746-6945      * |       200
#  -------
#  seqinfo: 3 sequences from an unspecified genome; no seqlengths

Then I want to obtain the following GRanges:

#GRanges object with 3 ranges and 1 metadata column:
#    seqnames      ranges strand |     width
#       <Rle>   <IRanges>  <Rle> | <integer>
#  [1]     chr1 2511-2515      * |         5
#  [2]     chr2 8718-8767      * |        50
#  [3]     chr3 9334-9833      * |       500

For my application I'm OK with getting only the first longest range for chr3 but I would appreciate a solution that can also select all ties if any.

Body:
I found this solution:

library(GenomicRanges)

# Make the GRanges object
set.seed(123)
gr <- GRanges(seqnames = rep(c("chr1", "chr2", "chr3"), times=2:4),
              ranges = IRanges(start=sample.int(10000, 9),
                               width = c(3,5,50,20,10,500,100,500,200)))

# Add a column with the width for clarity:
mcols(gr)$width <- width(gr)

# split gr by seqnames
grl <- split(gr, seqnames(gr))

# Get the width of each range organized as an IntegerList
wgr <- width(grl)
# if gr is ordered by seqnames this is equivalent to:
wgr <- splitAsList(width(gr), seqnames(gr))
wgr
#IntegerList of length 3
#[["chr1"]] 3 5
#[["chr2"]] 50 20 10
#[["chr3"]] 500 100 500 200

# Get the ranges with the largest width
# See ?'which.max,NumericList-method' for the global argument
longestRanges <- gr[which.max(wgr, global = TRUE)]

longestRanges
#GRanges object with 3 ranges and 1 metadata column:
#      seqnames      ranges strand |     width
#         <Rle>   <IRanges>  <Rle> | <integer>
#  [1]     chr1 2511-2515      * |         5
#  [2]     chr2 8718-8767      * |        50
#  [3]     chr3 9334-9833      * |       500
#  -------
#  seqinfo: 3 sequences from an unspecified genome; no seqlengths

Note that this solution only works if the ranges in gr are initially grouped/ordered by seqnames.

If they are not, it is necessary to start by sorting gr with gr <- sort(gr)

To get all the ties, one can use:

longestRanges <- unlist(grl[which(wgr == max(wgr))])

longestRanges
#GRanges object with 4 ranges and 1 metadata column:
#       seqnames    ranges strand |     width
#          <Rle> <IRanges>  <Rle> | <integer>
#  chr1     chr1 2511-2515      * |         5
#  chr2     chr2 8718-8767      * |        50
#  chr3     chr3 9334-9833      * |       500
#  chr3     chr3 4761-5260      * |       500
#  -------
#  seqinfo: 3 sequences from an unspecified genome; no seqlengths


问:
counting sql rows , adding value of every row to the next
I have a two columns and I want to add the value of every row to the next row.
My table with two columns and 4 rows is like:

```<code>date           users
2011-01-01      1
2011-02-02      1
2011-03-02      2
2011-04-02      4
</code>```

and I want the users to be shown like below , and add every row to it's previous row value:

users:

```<code>1
2
4
8
</code>```

Is there a function in for MS SQL Server to do that?

thanks

答:
This is possible through Cross Join. if your table column is in Asc order.</p>

```<code>select <T1.Text>,sum(T2.Value) AS 'Commulative Value' from <Your Table name>t1
cross JOIN <Your Table name> t2 where t2.value<= t1.value
group BY t1.text
order by value
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a two columns and I want to add the value of every row to the next row.
My table with two columns and 4 rows is like:

date           users
2011-01-01      1
2011-02-02      1
2011-03-02      2
2011-04-02      4

and I want the users to be shown like below , and add every row to it's previous row value:

users:

1
2
4
8

Is there a function in for MS SQL Server to do that?

thanks

Body:
This is possible through Cross Join. if your table column is in Asc order.

select <T1.Text>,sum(T2.Value) AS 'Commulative Value' from <Your Table name>t1
cross JOIN <Your Table name> t2 where t2.value<= t1.value
group BY t1.text
order by value

ContentLicense: CC BY-SA 3.0


问:
Laravel API Response Object formatting
I have created a basic Laravel REST API that will service some JavaScript applications that are using axios to make requests.

My application is using a Base Controller to ensure all responses are sent in the same format:

```<code>class BaseController extends Controller
{
    /**
     * success response method.
     *
     * @param $result
     * @param $message
     *
     * @return JsonResponse
     */
    public function sendResponse($result, $message)
    {
        $response = [
            'success' => true,
            'data' => $result,
            'message' => $message,
        ];

        return response()->json($response, 200);
    }

    /**
     * return error response.
     *
     * @param $error
     * @param  array  $errorMessages
     * @param  int  $code
     *
     * @return JsonResponse
     */
    public function sendError($error, $errorMessages = [], $code = 200)
    {
        $response = [
            'success' => false,
            'message' => $error,
        ];

        if (!empty($errorMessages)) {
            $response['data'] = $errorMessages;
        }

        return response()->json($response, $code);
    }
}
</code>```

When I retrieve the response from the API URL and log it to the console, I get the following output:

Currently, my response object contains its own data object, which then contains another data object. As a result, to access the data I have to use response.data.data.

I am wondering if this is actually the correct way to do this. As the naming convention of response.data.data doesn't seem to be a very clean way to do this. I have seen a couple of guides online where it has been done this way, but I am wondering if there are any typically followed conventions that I am missing. Perhaps this is correct but I just wanted some insight from more experienced programmers.

答:
In my opinion how you are approaching it is fine:

response is the full response object via axios

response.data is the full response body that was returned

response.data.data is the data node of the response body that was returned

Some suggestions:

instead of using success in your response, that can be implied from the returned status code: anything within 200-299 is successful, anything 300-399 is a redirect, anything 400-499 is a client error, and anything 500+ is a server error (see here)

instead of using data in the instance of an error, in my opinion that node should be reserved for successful data and a node such as errors should be used instead

your sendError method should default to a status code of 500 instead of 200, as 200 is a successful status code

Title: Laravel API Response Object formatting

Body:
I have created a basic Laravel REST API that will service some JavaScript applications that are using axios to make requests.

My application is using a Base Controller to ensure all responses are sent in the same format:

class BaseController extends Controller
{
    /**
     * success response method.
     *
     * @param $result
     * @param $message
     *
     * @return JsonResponse
     */
    public function sendResponse($result, $message)
    {
        $response = [
            'success' => true,
            'data' => $result,
            'message' => $message,
        ];

        return response()->json($response, 200);
    }

    /**
     * return error response.
     *
     * @param $error
     * @param  array  $errorMessages
     * @param  int  $code
     *
     * @return JsonResponse
     */
    public function sendError($error, $errorMessages = [], $code = 200)
    {
        $response = [
            'success' => false,
            'message' => $error,
        ];

        if (!empty($errorMessages)) {
            $response['data'] = $errorMessages;
        }

        return response()->json($response, $code);
    }
}

When I retrieve the response from the API URL and log it to the console, I get the following output:

Currently, my response object contains its own data object, which then contains another data object. As a result, to access the data I have to use response.data.data.

I am wondering if this is actually the correct way to do this. As the naming convention of response.data.data doesn't seem to be a very clean way to do this. I have seen a couple of guides online where it has been done this way, but I am wondering if there are any typically followed conventions that I am missing. Perhaps this is correct but I just wanted some insight from more experienced programmers.


问:
How can I solve "TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected"?
How I solve this error, I am trying to train a ticket classification model

I'm trying to make a ticket sorter with the Pytorch library, but I have this error. I can't understand what I've done wrong
Can you help me?

```<code>
data_transforms = {
    'train' : transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val' : transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])

}

data_dir = 'dataset_billete_argentino'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,
                                              shuffle=True, num_workers=4)
               for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_name = image_datasets['train'].classes

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3,6,5)
        self.pool = nn.MaxPool2d(2,2)
        self.conv2 = nn.Conv2d(6,16,5)
        self.fc1 = nn.Linear(16 * 53 * 53, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(x.size(0), 16* 53 * 53)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3
        return x

net = Net()

def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
    since = time.time()

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch, num_epochs - 1))
        print('-' * 10)

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for inputs, labels in dataloaders[phase]:
                inputs = inputs.to(device)
                labels = labels.to(device)

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)
            if phase == 'train':
                scheduler.step()

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())

        print()

    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model

from torch.optim import lr_scheduler

exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)

net = train_model(net, criterion, optimizer, exp_lr_scheduler,
                  num_epochs=25)
</code>```

And give this error
TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected one of:
 * (Tensor input)
 * (Tensor input, name dim, bool keepdim, tuple of Tensors out)
 * (Tensor input, Tensor other, Tensor out)
 * (Tensor input, int dim, bool keepdim, tuple of Tensors out)

```<code>Epoch 0/24
----------
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-29dfe3459d8a> in <module>
      4
      5 net = train_model(net, criterion, optimizer, exp_lr_scheduler,
----> 6                   num_epochs=25)

<ipython-input-19-1a5d4f162548> in train_model(model, criterion, optimizer, scheduler, num_epochs)
     31                 with torch.set_grad_enabled(phase == 'train'):
     32                     outputs = model(inputs)
---> 33                     _, preds = torch.max(outputs, 1)
     34                     loss = criterion(outputs, labels)
     35

TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected one of:
 * (Tensor input)
 * (Tensor input, name dim, bool keepdim, tuple of Tensors out)
 * (Tensor input, Tensor other, Tensor out)
 * (Tensor input, int dim, bool keepdim, tuple of Tensors out)
</code>```

答:
As the error message says the problem is in this line:

```<code>_, preds = torch.max(outputs, 1)
</code>```

There are two problems here:

As @Idodo said, you're giving 2 arguments and neither of them is a tensor. According to the message they are a Linear and a int, respectively.

If you remove the int you still have an error, because you're trying to compute a max value of a nn.Linear, which is not possible. Assessing your code I got the second error. In your model's forward method you have:

```<code>x = self.fc3
</code>```

That's the problem. You must do:

```<code>x = self.fc3(x)
</code>```

Body:
How I solve this error, I am trying to train a ticket classification model

I'm trying to make a ticket sorter with the Pytorch library, but I have this error. I can't understand what I've done wrong
Can you help me?

data_transforms = {
    'train' : transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val' : transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])

}

data_dir = 'dataset_billete_argentino'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,
                                              shuffle=True, num_workers=4)
               for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_name = image_datasets['train'].classes

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3,6,5)
        self.pool = nn.MaxPool2d(2,2)
        self.conv2 = nn.Conv2d(6,16,5)
        self.fc1 = nn.Linear(16 * 53 * 53, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(x.size(0), 16* 53 * 53)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3
        return x

net = Net()

def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
    since = time.time()

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch, num_epochs - 1))
        print('-' * 10)

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for inputs, labels in dataloaders[phase]:
                inputs = inputs.to(device)
                labels = labels.to(device)

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)
            if phase == 'train':
                scheduler.step()

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())

        print()

    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model

from torch.optim import lr_scheduler

exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)

net = train_model(net, criterion, optimizer, exp_lr_scheduler,
                  num_epochs=25)

And give this error
TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected one of:
 * (Tensor input)
 * (Tensor input, name dim, bool keepdim, tuple of Tensors out)
 * (Tensor input, Tensor other, Tensor out)
 * (Tensor input, int dim, bool keepdim, tuple of Tensors out)

Epoch 0/24
----------
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-29dfe3459d8a> in <module>
      4
      5 net = train_model(net, criterion, optimizer, exp_lr_scheduler,
----> 6                   num_epochs=25)

<ipython-input-19-1a5d4f162548> in train_model(model, criterion, optimizer, scheduler, num_epochs)
     31                 with torch.set_grad_enabled(phase == 'train'):
     32                     outputs = model(inputs)
---> 33                     _, preds = torch.max(outputs, 1)
     34                     loss = criterion(outputs, labels)
     35

TypeError: max() received an invalid combination of arguments - got (Linear, int), but expected one of:
 * (Tensor input)
 * (Tensor input, name dim, bool keepdim, tuple of Tensors out)
 * (Tensor input, Tensor other, Tensor out)
 * (Tensor input, int dim, bool keepdim, tuple of Tensors out)

Body:
As the error message says the problem is in this line:

_, preds = torch.max(outputs, 1)

There are two problems here:

As @Idodo said, you're giving 2 arguments and neither of them is a tensor. According to the message they are a Linear and a int, respectively.

If you remove the int you still have an error, because you're trying to compute a max value of a nn.Linear, which is not possible. Assessing your code I got the second error. In your model's forward method you have:

x = self.fc3

That's the problem. You must do:

x = self.fc3(x)


问:
In swift, how do you add button using a for loop in stack view in scroll view?
I have added two scroll views, and two vertical stack views inside them, respectively. The constraints have been set already. I have connect the two stack views as outlet collections in ViewController.swift. Suppose I have an array of strings, say

I wanted to add a few buttons (same as length of labels) in the top stack view using a for loop. How do I do this? And since the stack view is in scroll view, do I need to specify the distance between two buttons?

My code is below.

```<code>    @IBOutlet var topStackView: [UIStackView]!
    @IBOutlet var bottomStackView: [UIStackView]!
    @IBOutlet weak var enterItemTextField: UITextField!
    let labels = ["a", "b", "c", "d", "e"]

    override func viewDidLoad() {
        super.viewDidLoad()
        enterItemTextField.delegate = self

        var buttons = [UIButton()]
        for _ in 0..<labels.count {

            let button = UIButton(type: UIButton.ButtonType.system)
            # some operations on button
            buttons.append(button)
        }
        # what do I do here?

    }
</code>```

The stackview has less freedom to adjust the locations. I have removed the stackview and am putting buttons on the scroll view directly.

答:
You need it after

```<code>buttons.append(button)
topStackView.addArrangedView(button)
</code>```

BTW for single item you don't need a collection so to be

```<code>@IBOutlet var topStackView: UIStackView!
@IBOutlet var bottomStackView: UIStackView!
</code>```

instead of

```<code>@IBOutlet var topStackView: [UIStackView]!
@IBOutlet var bottomStackView: [UIStackView]!
</code>```

Do I need to specify the distance between two buttons?

no you don't have to but you can do this

```<code>topStackView.spacing = 20
</code>```

Body:
I have added two scroll views, and two vertical stack views inside them, respectively. The constraints have been set already. I have connect the two stack views as outlet collections in ViewController.swift. Suppose I have an array of strings, say

I wanted to add a few buttons (same as length of labels) in the top stack view using a for loop. How do I do this? And since the stack view is in scroll view, do I need to specify the distance between two buttons?

My code is below.

    @IBOutlet var topStackView: [UIStackView]!
    @IBOutlet var bottomStackView: [UIStackView]!
    @IBOutlet weak var enterItemTextField: UITextField!
    let labels = ["a", "b", "c", "d", "e"]

    override func viewDidLoad() {
        super.viewDidLoad()
        enterItemTextField.delegate = self

        var buttons = [UIButton()]
        for _ in 0..<labels.count {

            let button = UIButton(type: UIButton.ButtonType.system)
            # some operations on button
            buttons.append(button)
        }
        # what do I do here?

    }

The stackview has less freedom to adjust the locations. I have removed the stackview and am putting buttons on the scroll view directly.

Body:
You need it after

buttons.append(button)
topStackView.addArrangedView(button)

BTW for single item you don't need a collection so to be

@IBOutlet var topStackView: UIStackView!
@IBOutlet var bottomStackView: UIStackView!

instead of

@IBOutlet var topStackView: [UIStackView]!
@IBOutlet var bottomStackView: [UIStackView]!

Do I need to specify the distance between two buttons?

no you don't have to but you can do this

topStackView.spacing = 20


问:
Belphegor prime number problem with Python
I have seen a video about Belphegor prime numbers. The definition of a Belphegor prime is one such that in the expression (10^(n+3)+666)*(10^(n+1)+1) is prime for n being a positive integer.

I tried making a Python program that would determine whether an input number n will produce a prime number in the expression mentioned before but my code said that for all n in the expression would be prime which is not true and it said it indefinitely.

My code:

n = int(input("Enter a positive number n: "))

x =(10**(n+3)+666)*10**(n+1)+1

for i in range(2,x - 1):
    if x % i == 0:
        print("Composite")
    else:
        print("Belphegor prime")
```

Please help me fix this error!

答:
Your problem is that your code prints out either Composite or Prime on every iteration through the loop. Instead, you need to assume the number is prime and if at any time the test fails, set a flag to false; then use the state of the flag at the end of the loop to determine if the number is actually prime:

```<code>from math import sqrt

n = int(input("Enter a positive number n: "))
x =(10**(n+3)+666)*(10**(n+1)+1)
p = True
for i in range(2,int(sqrt(x))+1):
    if x % i == 0:
        p = False
        break
if p:
    print("Belphegor prime")
else:
    print("Composite")
</code>```

Note you can shorten your loop by only iterating as far as sqrt(x) as any number greater than sqrt(x) which is a divisor of x will have a matching divisor less than sqrt(x).

Note also that as @LeoE pointed out in the comments to your question, you are missing some () in your computation of x.

Body:
I have seen a video about Belphegor prime numbers. The definition of a Belphegor prime is one such that in the expression (10^(n+3)+666)*(10^(n+1)+1) is prime for n being a positive integer.

I tried making a Python program that would determine whether an input number n will produce a prime number in the expression mentioned before but my code said that for all n in the expression would be prime which is not true and it said it indefinitely.

My code:

n = int(input("Enter a positive number n: "))

x =(10**(n+3)+666)*10**(n+1)+1

for i in range(2,x - 1):
    if x % i == 0:
        print("Composite")
    else:
        print("Belphegor prime")

Please help me fix this error!

Body:
Your problem is that your code prints out either Composite or Prime on every iteration through the loop. Instead, you need to assume the number is prime and if at any time the test fails, set a flag to false; then use the state of the flag at the end of the loop to determine if the number is actually prime:

from math import sqrt

n = int(input("Enter a positive number n: "))
x =(10**(n+3)+666)*(10**(n+1)+1)
p = True
for i in range(2,int(sqrt(x))+1):
    if x % i == 0:
        p = False
        break
if p:
    print("Belphegor prime")
else:
    print("Composite")

Note you can shorten your loop by only iterating as far as sqrt(x) as any number greater than sqrt(x) which is a divisor of x will have a matching divisor less than sqrt(x).

Note also that as @LeoE pointed out in the comments to your question, you are missing some () in your computation of x.


问:
Why is clang removing an underscore from a function declared as 'extern "C"'?
I'm watching a video in an attempt to better understand object files. The presenter uses the following as an example of a program that produces a very simple object file:

```<code>extern "C" void _start() {
    asm("mov $60, %eax\n"
        "mov $24567837, %edi\n"
        "syscall\n");
}
</code>```

The program is compiled via

```<code>clang++ -c step0.cpp -O1 -o step0.o
</code>```

and linked via

```<code>ld -static step0.o -o step0
</code>```

I get this error message when trying to link:

```<code>Undefined symbols for architecture x86_64:
  "start", referenced from:
     -u command line option
     (maybe you meant: __start)
ld: symbol(s) not found for inferred architecture x86_64
</code>```

I don't pass the -u command line option, so I'm not sure why I'm getting that error message.

答:
clang isn't removing an underscore, it's adding an underscore. Your program is actually exporting a __start symbol, but ld expects you to have a start symbol for your entry point, i.e. ld runs with -u start by default for your architecture.

You could disable this check in ld with -U start (which suppresses the error from the start symbol being undefined) or via -undefined suppress (which suppresses all undefined symbol errors). However, you will end up with an executable that does not have an entry point for your architecture, so the program won't actually work.

Instead of suppressing the error, I suggest controlling the symbol that clang chooses directly. You can tell clang what symbol to generate by using a standalone asm declaration:

```<code>void _start() asm ("start");
</code>```

Make sure this standalone declaration is separate from the function definition.

You can read more about controlling the symbols generated by gcc here: https://stackoverflow.com/a/1035937/12928775

Also, as was pointed out in a comment to a similar answer, you will most likely want to use __attribute__((naked)) on the function definition to prevent clang from generating a stack frame on entry. See: https://stackoverflow.com/a/60311490/12928775

Body:
I'm watching a video in an attempt to better understand object files. The presenter uses the following as an example of a program that produces a very simple object file:

extern "C" void _start() {
    asm("mov $60, %eax\n"
        "mov $24567837, %edi\n"
        "syscall\n");
}

The program is compiled via

clang++ -c step0.cpp -O1 -o step0.o

and linked via

ld -static step0.o -o step0

I get this error message when trying to link:

Undefined symbols for architecture x86_64:
  "start", referenced from:
     -u command line option
     (maybe you meant: __start)
ld: symbol(s) not found for inferred architecture x86_64

I don't pass the -u command line option, so I'm not sure why I'm getting that error message.

Body:
clang isn't removing an underscore, it's adding an underscore. Your program is actually exporting a __start symbol, but ld expects you to have a start symbol for your entry point, i.e. ld runs with -u start by default for your architecture.

You could disable this check in ld with -U start (which suppresses the error from the start symbol being undefined) or via -undefined suppress (which suppresses all undefined symbol errors). However, you will end up with an executable that does not have an entry point for your architecture, so the program won't actually work.

Instead of suppressing the error, I suggest controlling the symbol that clang chooses directly. You can tell clang what symbol to generate by using a standalone asm declaration:

void _start() asm ("start");

Make sure this standalone declaration is separate from the function definition.

You can read more about controlling the symbols generated by gcc here: https://stackoverflow.com/a/1035937/12928775

Also, as was pointed out in a comment to a similar answer, you will most likely want to use __attribute__((naked)) on the function definition to prevent clang from generating a stack frame on entry. See: https://stackoverflow.com/a/60311490/12928775


问:
Using ++ operator leads to unexpected results
I do not understand why the two codes below lead to the same result. Shouldn't the latter print from 6 to 10 since n is incremented first?

Edit: I used both Visual Studio 2019 and repl.it.

```<code>#include <iostream>
using namespace std;

int main() {
    int n=5;
    for (n; n<10; n++)
        cout << n << endl;
    return 0;
}

>>> 5
6
7
8
9

#include <iostream>
using namespace std;

int main() {
    int n=5;
    for (n; n<10; ++n)
        cout << n << endl;
    return 0;
}

>>> 5
6
7
8
9
</code>```

答:
There's Nothing wrong here, its just how its supposed to work

Firstly, you should know a for loop works
for loop, without loss of generality can be written as:

```<code>for(exp1; exp2; exp3)
{
    //body
}
</code>```

here exp1 will be executed only when entering the loop first time, then exp2 will be evaluated, if true loop will continue, otherwise not.
exp3 is evaluated only after each iteration is complete.

also the only difference between i++ and ++i, is when you assign it to something.
say i is 5, then after statement

```<code>i++;
</code>```

i will be 6
which is also true for this statement:

```<code>++i;
</code>```

but say i=5,
but you try something like this:

```<code>a=i++;
</code>```

after this statement, a will be 5, and i will be 6.

but after this statement, with same initial condition(i = 5):

```<code>a=++i;
</code>```

both a and i will be 6.

Body:
I do not understand why the two codes below lead to the same result. Shouldn't the latter print from 6 to 10 since n is incremented first?

Edit: I used both Visual Studio 2019 and repl.it.

#include <iostream>
using namespace std;

int main() {
    int n=5;
    for (n; n<10; n++)
        cout << n << endl;
    return 0;
}

>>> 5
6
7
8
9

#include <iostream>
using namespace std;

int main() {
    int n=5;
    for (n; n<10; ++n)
        cout << n << endl;
    return 0;
}

>>> 5
6
7
8
9

Body:
There's Nothing wrong here, its just how its supposed to work

Firstly, you should know a for loop works
for loop, without loss of generality can be written as:

for(exp1; exp2; exp3)
{
    //body
}

here exp1 will be executed only when entering the loop first time, then exp2 will be evaluated, if true loop will continue, otherwise not.
exp3 is evaluated only after each iteration is complete.

also the only difference between i++ and ++i, is when you assign it to something.
say i is 5, then after statement

i++;

i will be 6
which is also true for this statement:

++i;

but say i=5,
but you try something like this:

a=i++;

after this statement, a will be 5, and i will be 6.

but after this statement, with same initial condition(i = 5):

a=++i;

both a and i will be 6.


问:
How to join multiple repositories with Ecto?
I have two databases, the main databases (PostgreSQL) + the statistics database (ClickHouse). Statistics database contains a subpart of data from the main database which is enough for performing calculations. All ids are similar (:binary_id) across both databases. I need to find a way of joining the results obtained from the statistic database with a query to the main database. In terms of pure SQL solution it could be something like this, where VALUES are data obtained from statistics database:

```<code>SELECT p0."id",
       p0."name",
       f1."average_count"
FROM "persons" AS p0
         JOIN (VALUES (0.0, '906af2c0-cde2-4996-9a98-bdbf986fe687'::uuid),
                      (0.2857142857142857, 'aba7c694-3453-4a55-aab9-4b542dbb4ba9'::uuid),
                      (0.2857142857142857, '2dab3350-6149-4752-a55e-7477a6ad0dd3'::uuid))
               as f1 (average_count, user_id)
              on f1.user_id = p0.id;
</code>```

My project actively uses Ecto and has a lot of on-the-fly constructed queries. That's why I cannot just perform pure SQL queries as I post above and should have Ecto based solution. Is there a way to do such a joining with Ecto?

答:
It's not pretty, but you could take advantage of Postgres' UNNEST:

```<code>users = [
  %{id: "906af2c0-cde2-4996-9a98-bdbf986fe687", average_count: 0.0},
  %{id: "aba7c694-3453-4a55-aab9-4b542dbb4ba9", average_count: 0.2857142857142857},
  %{id: "2dab3350-6149-4752-a55e-7477a6ad0dd3", average_count: 0.2857142857142857}
]

{ids, average_counts} =
  users
  |> Stream.map(&{&1.id, &1.average_count})
  |> Enum.unzip()

dumped_ids =
  for id <- ids do
    {:ok, dumped} = Ecto.UUID.dump(id)
    dumped
  end

query =
  from p in Person,
    join: f in fragment("SELECT UNNEST(?::uuid[]) AS user_id, UNNEST(?::float[]) AS average_count", ^dumped_ids, ^average_counts),
    on: f.user_id == p.id,
    select: %{id: p.id, name: p.name, average_count: f.average_count}

Repo.all(query)
</code>```

Maybe it's not the best way of doing it. I'm no DB expert. But that works for me in IEx.

Body:
I have two databases, the main databases (PostgreSQL) + the statistics database (ClickHouse). Statistics database contains a subpart of data from the main database which is enough for performing calculations. All ids are similar (:binary_id) across both databases. I need to find a way of joining the results obtained from the statistic database with a query to the main database. In terms of pure SQL solution it could be something like this, where VALUES are data obtained from statistics database:

SELECT p0."id",
       p0."name",
       f1."average_count"
FROM "persons" AS p0
         JOIN (VALUES (0.0, '906af2c0-cde2-4996-9a98-bdbf986fe687'::uuid),
                      (0.2857142857142857, 'aba7c694-3453-4a55-aab9-4b542dbb4ba9'::uuid),
                      (0.2857142857142857, '2dab3350-6149-4752-a55e-7477a6ad0dd3'::uuid))
               as f1 (average_count, user_id)
              on f1.user_id = p0.id;

My project actively uses Ecto and has a lot of on-the-fly constructed queries. That's why I cannot just perform pure SQL queries as I post above and should have Ecto based solution. Is there a way to do such a joining with Ecto?

Body:
It's not pretty, but you could take advantage of Postgres' UNNEST:

users = [
  %{id: "906af2c0-cde2-4996-9a98-bdbf986fe687", average_count: 0.0},
  %{id: "aba7c694-3453-4a55-aab9-4b542dbb4ba9", average_count: 0.2857142857142857},
  %{id: "2dab3350-6149-4752-a55e-7477a6ad0dd3", average_count: 0.2857142857142857}
]

{ids, average_counts} =
  users
  |> Stream.map(&{&1.id, &1.average_count})
  |> Enum.unzip()

dumped_ids =
  for id <- ids do
    {:ok, dumped} = Ecto.UUID.dump(id)
    dumped
  end

query =
  from p in Person,
    join: f in fragment("SELECT UNNEST(?::uuid[]) AS user_id, UNNEST(?::float[]) AS average_count", ^dumped_ids, ^average_counts),
    on: f.user_id == p.id,
    select: %{id: p.id, name: p.name, average_count: f.average_count}

Repo.all(query)

Maybe it's not the best way of doing it. I'm no DB expert. But that works for me in IEx.


问:
Why is `git describe -dirty` adding a `-dirty` suffix when describing a clean checkout?
I have just discovered the --dirty option to git describe and it looks like it should do something very useful, i.e. append a suffix to the output of git describe when the working tree is dirty, however that doesn't seem to be the case on some of my repositories:

```<code>$ git status
# On branch 8.30
nothing to commit (working directory clean)
$ git describe --dirty
8.30rel-8-g9c1cbdb-dirty
</code>```

I thought this might be because the working directory is dirty relative to the tag, but that doesn't seem to be the case either:

```<code>$ git status
# On branch 1.4
nothing to commit (working directory clean)
$ git describe --tags --dirty --long
1.4rel-0-gfedfe66-dirty
</code>```

I used to make extensive use of hg id when I used to use Mercurial and liked the fact that it's default behaviour was to add a + suffix to any commit hash it reported for a dirty repository, so have been looking out for a git equivalent since, but git describe --dirty doesn't appear to do what I would expect given the documentation:

```<code>   --dirty[=<mark>]
       Describe the working tree. It means describe HEAD and appends
       <mark> (-dirty by default) if the working tree is dirty.
</code>```

Am I misunderstanding what --dirty should do, or am I not using it correctly?

In case it makes any difference, all of the git repositories are deployed via buckminster so there are no submodules involved and the filesystem is an nfs share.

Update: I have discovered a work around, but I have absolutely no idea how this could possibly be making a difference.

If I run git diff --quiet HEAD on the repo then all of a sudden the git describe works as I expect:

```<code>$ git status
# On branch 8.30
nothing to commit (working directory clean)
$ git describe --dirty
8.30rel-8-g9c1cbdb-dirty
$ git diff --quiet HEAD
$ git describe --dirty
8.30rel-8-g9c1cbdb
</code>```

I also spotted that when git describe was reporting the repository as dirty then gitk also showed "Local uncommitted changes, not checked in to index" and then listed each file in the working directory, but with no diffs against them, just the ---- filename ---- lines.

Further update: As this continued to be a problem, I eventually wrote a git-describe-dirty script, which starts by running git describe --dirty but if it finds the repository to be dirty, runs git update-index -q --refresh before trying again and taking the second result.

When iterating through hundreds of repositories, using git describe-dirty and only running the index update for a repository which initially indicates it is dirty saves a great deal of time compared to running git update-index -q --refresh ; git describe --dirty every time.

答:
Beware that there was another bug fix regarding git describe --dirty, about a year ago: https://github.com/git/git/commit/a1e19004e11dcbc0ceebd92c425ceb1770e52d0b

"git --work-tree=$there --git-dir=$here describe --dirty" did not work correctly as it did not pay attention to the location of the worktree specified by the user

In case of this bug, the workarounds shown here didn't work, so we had to upgrade our installation. There seems to be no fix readily available for Debian buster as of today (2020-02-20), yet the Debian bullseye main git packages are compatible with buster right now.

Body:
I have just discovered the --dirty option to git describe and it looks like it should do something very useful, i.e. append a suffix to the output of git describe when the working tree is dirty, however that doesn't seem to be the case on some of my repositories:

$ git status
# On branch 8.30
nothing to commit (working directory clean)
$ git describe --dirty
8.30rel-8-g9c1cbdb-dirty

I thought this might be because the working directory is dirty relative to the tag, but that doesn't seem to be the case either:

$ git status
# On branch 1.4
nothing to commit (working directory clean)
$ git describe --tags --dirty --long
1.4rel-0-gfedfe66-dirty

I used to make extensive use of hg id when I used to use Mercurial and liked the fact that it's default behaviour was to add a + suffix to any commit hash it reported for a dirty repository, so have been looking out for a git equivalent since, but git describe --dirty doesn't appear to do what I would expect given the documentation:

   --dirty[=]
       Describe the working tree. It means describe HEAD and appends
        (-dirty by default) if the working tree is dirty.

Am I misunderstanding what --dirty should do, or am I not using it correctly?

In case it makes any difference, all of the git repositories are deployed via buckminster so there are no submodules involved and the filesystem is an nfs share.

Update: I have discovered a work around, but I have absolutely no idea how this could possibly be making a difference.

If I run git diff --quiet HEAD on the repo then all of a sudden the git describe works as I expect:

$ git status
# On branch 8.30
nothing to commit (working directory clean)
$ git describe --dirty
8.30rel-8-g9c1cbdb-dirty
$ git diff --quiet HEAD
$ git describe --dirty
8.30rel-8-g9c1cbdb

I also spotted that when git describe was reporting the repository as dirty then gitk also showed "Local uncommitted changes, not checked in to index" and then listed each file in the working directory, but with no diffs against them, just the ---- filename ---- lines.

Further update: As this continued to be a problem, I eventually wrote a git-describe-dirty script, which starts by running git describe --dirty but if it finds the repository to be dirty, runs git update-index -q --refresh before trying again and taking the second result.

When iterating through hundreds of repositories, using git describe-dirty and only running the index update for a repository which initially indicates it is dirty saves a great deal of time compared to running git update-index -q --refresh ; git describe --dirty every time.


问:
Custom TensorFlow Keras optimizer
Suppose I want to write a custom optimizer class that conforms to the tf.keras API (using TensorFlow version>=2.0). I am confused about the documented way to do this versus what's done in implementations.

The documentation for tf.keras.optimizers.Optimizer states,

  ### Write a customized optimizer.
  If you intend to create your own optimization algorithm, simply inherit from
  this class and override the following methods:

    - resource_apply_dense (update variable given gradient tensor is dense)
    - resource_apply_sparse (update variable given gradient tensor is sparse)
    - create_slots (if your optimizer algorithm requires additional variables)
```

However, the current tf.keras.optimizers.Optimizer implementation does not define a resource_apply_dense method, but it does define a private-looking _resource_apply_dense method stub. Similarly, there are no resource_apply_sparse or create_slots methods, but there are a _resource_apply_sparse method stub and a _create_slots method call.

In official tf.keras.optimizers.Optimizer subclasses (using tf.keras.optimizers.Adam as an example), there are _resource_apply_dense, _resource_apply_sparse, and _create_slots methods, and there are no such methods without the leading underscore.

There are similar leading-underscore methods in slightly-less-official tf.keras.optimizers.Optimizer subclasses (e.g., tfa.optimizers.MovingAverage from TensorFlow Addons: _resource_apply_dense, _resource_apply_sparse, _create_slots).

Another confounding point for me is that some of the TensorFlow Addons optimizers also override the apply_gradients method (e.g., tfa.optimizers.MovingAverage), whereas the tf.keras.optimizers optimizers do not.

Moreover, I noticed that the apply_gradients method of tf.keras.optimizers.Optimizer method calls _create_slots, but the base tf.keras.optimizers.Optimizer class does not have a _create_slots method.
So, it seems that a _create_slots method must be defined in an optimizer subclass if that subclass does not override apply_gradients.

Questions

What is the correct way to subclass a tf.keras.optimizers.Optimizer? Specifically,

Does the tf.keras.optimizers.Optimizer documentation listed at the top simply mean to override the leading-underscore versions of the methods they mention (e.g., _resource_apply_dense instead of resource_apply_dense)? If so, are there any API guarantees about these private-looking methods not changing their behavior in future versions of TensorFlow? What are the signatures of these methods?

When would one override apply_gradients in addition to the _apply_resource_[dense|sparse] methods?

Edit. Opened issue on GitHub: #36449

答:
Update: TF2.2 forced me to clean up all implementations - so now they can be used as a reference for TF best practices. Also added a section below on _get_hyper vs. _set_hyper.

I've implemented Keras AdamW in all major TF & Keras versions - I invite you to examine optimizers_v2.py. Several points:

You should inherit OptimizerV2, which is actually what you linked; it's the latest and current base class for tf.keras optimizers

You are correct in (1) - this is a documentation mistake; the methods are private, as they aren't meant to be used by the user directly.

apply_gradients (or any other method) is only overidden if the default doesn't accomplish what's needed for a given optimizer; in your linked example, it's just a one-liner addon to the original

"So, it seems that a _create_slots method must be defined in an optimizer subclass if that subclass does not override apply_gradients" - the two are unrelated; it's coincidental.

What is the difference between _resource_apply_dense and _resource_apply_sparse?

Latter deals with sparse layers - e.g. Embedding - and former with everything else; example.

When should I use _create_slots()?

When defining trainable tf.Variables; example: weights' first and second order moments (e.g. Adam). It uses add_slot().

_get_hyper vs. _set_hyper: they enable setting and getting Python literals (int, str, etc), callables, and tensors. They exist largely for convenience: anything set via _set_hyper can be retrieved via _get_hyper, avoiding repeating boilerplate code. I dedicated a Q&A to it here.

Title: Custom TensorFlow Keras optimizer

Body:
Suppose I want to write a custom optimizer class that conforms to the tf.keras API (using TensorFlow version>=2.0). I am confused about the documented way to do this versus what's done in implementations.

The documentation for tf.keras.optimizers.Optimizer states,

  ### Write a customized optimizer.
  If you intend to create your own optimization algorithm, simply inherit from
  this class and override the following methods:

    - resource_apply_dense (update variable given gradient tensor is dense)
    - resource_apply_sparse (update variable given gradient tensor is sparse)
    - create_slots (if your optimizer algorithm requires additional variables)

However, the current tf.keras.optimizers.Optimizer implementation does not define a resource_apply_dense method, but it does define a private-looking _resource_apply_dense method stub. Similarly, there are no resource_apply_sparse or create_slots methods, but there are a _resource_apply_sparse method stub and a _create_slots method call.

In official tf.keras.optimizers.Optimizer subclasses (using tf.keras.optimizers.Adam as an example), there are _resource_apply_dense, _resource_apply_sparse, and _create_slots methods, and there are no such methods without the leading underscore.

There are similar leading-underscore methods in slightly-less-official tf.keras.optimizers.Optimizer subclasses (e.g., tfa.optimizers.MovingAverage from TensorFlow Addons: _resource_apply_dense, _resource_apply_sparse, _create_slots).

Another confounding point for me is that some of the TensorFlow Addons optimizers also override the apply_gradients method (e.g., tfa.optimizers.MovingAverage), whereas the tf.keras.optimizers optimizers do not.

Moreover, I noticed that the apply_gradients method of tf.keras.optimizers.Optimizer method calls _create_slots, but the base tf.keras.optimizers.Optimizer class does not have a _create_slots method.
So, it seems that a _create_slots method must be defined in an optimizer subclass if that subclass does not override apply_gradients.

Questions

What is the correct way to subclass a tf.keras.optimizers.Optimizer? Specifically,

Does the tf.keras.optimizers.Optimizer documentation listed at the top simply mean to override the leading-underscore versions of the methods they mention (e.g., _resource_apply_dense instead of resource_apply_dense)? If so, are there any API guarantees about these private-looking methods not changing their behavior in future versions of TensorFlow? What are the signatures of these methods?

When would one override apply_gradients in addition to the _apply_resource_[dense|sparse] methods?

Edit. Opened issue on GitHub: #36449


答:
The only difference is this:

```<code>    for (n; n<10; n++)
</code>```

vs. this:

```<code>    for (n; n<10; ++n)
</code>```

The first and third expressions in a for statement are evaluated only for their side effects, with any result discarded. (The second is evaluated and its result used to determine whether to continue the loop.) The only difference between n++ and ++n is their results; their side effects are identical. So in this context n++ and ++n are effectively identical.

I'll also mention that the first expression n has no side effects, so it might well be omitted:

```<code>    for (; n<10; n++)
</code>```

Or, better yet, you could incorporate the declaration and initialization into the loop, replacing the existing declaration int n=5;:

```<code>    for (int n = 5; n < 10; n++)
</code>```

Title: Using ++ operator leads to unexpected results

Body:
The only difference is this:

    for (n; n<10; n++)

vs. this:

    for (n; n<10; ++n)

The first and third expressions in a for statement are evaluated only for their side effects, with any result discarded. (The second is evaluated and its result used to determine whether to continue the loop.) The only difference between n++ and ++n is their results; their side effects are identical. So in this context n++ and ++n are effectively identical.

I'll also mention that the first expression n has no side effects, so it might well be omitted:

    for (; n<10; n++)

Or, better yet, you could incorporate the declaration and initialization into the loop, replacing the existing declaration int n=5;:

    for (int n = 5; n < 10; n++)


问:
How does DiffEqFlux.sciml_train work for Neural ODEs in Julia?
I have a ganeral question about how Neural ODE Nets are trained in Julia. Are data points being sampled from the tspan on which the Nural ODE is defined and on them the parameter updates computed? In other words is there some shuffling and batching happening during training or is the loss computed over all data points in the tspan?</p>

答:
parameters are optimized according to minimizing the loss function.  So it's up to you to define how the sampling occurs in the loss function.  Typically one may be comparing the output to discrete data points, in whcih case those become your discrete points.

But neuralODE isn't handling this--- you are.  It's the loss function


问:
What's the different between ASP.NET AJAX pageLoad() and JavaScript window.onload?
I'm working with ASP.NET AJAX and want to understand the difference between these two snippets:

```<code>function pageLoad(sender, eventArgs) { }
</code>```

and

```<code>window.onload = function() { }
</code>```

Do they act the same?

Or is one called before the other?

Or will one be called automatically and the another not?

答:
A couple things to note first. MS invented a sort of "clientside runtime object" called Sys.Application. It handles raising init, load, and unload events throughout the [clientside] lifespan of the page, as follows:

Sys.Application.initialize() begins the init part of the life cycle. This initialize()s all clientside AJAX controls, after which they're ready to be interacted with programatically

Sys.Application begins the load part of the life cycle, calling all handlers that have subscribed to this event

Finally, it calls the global function pageLoad (if one is defined)

Step 2) and 3) are repeated for every partial (ie AJAX + UpdatePanel) postback.

So finally the answer: pageLoad is just a handy shortcut to Sys.Application.add_load().

With regards to its relationship to window.onload however, things start to get interesting. Essentially, MS needed window.onload to fire only after the init phase was complete. But you can't control when the browser will fire onload, as it's tied to "content loaded". This is known as "the window.onload problem":

onload event fires after all page
  content has loaded (including images
  and other binary content). If your
  page includes lots of images then you
  may see a noticeable lag before the
  page becomes active.

So, they just invented their own "special" function to fire at just the right time in their event life cycle and called it "pageLoad". And the trick that they used to kickoff this custom event life cycle was to place the call to Sys.Application.initialize() just before the closing </form> tag. The serverside runtime does this. Astute readers will note that this trick allowed MS to solve the window.onload problem, since any code you put into pageLoad will fire independent of binary content (w/ one rare catch for IE).

> Do they act the same?

Conceptually yes, in practice not at all due to said window.onload problem. The only rule is that you should put code that interacts with your AJAX controls in pageLoad only, since window.onload follows its own event trajectory.

> Or is one called before the other?

They are completely, 100% independent.

> Or will one be called automatically and the another not?

They will both be called if you have them defined.

OwnerDisplayName: amrelgarhy

Body:
I'm working with ASP.NET AJAX and want to understand the difference between these two snippets:

function pageLoad(sender, eventArgs) { }

and

window.onload = function() { }

Do they act the same?

Or is one called before the other?

Or will one be called automatically and the another not?

LastEditorDisplayName: Fabian Steeg


问:
Control other app over gui from my program
I would like to write a simple C++ program for Linux (Ubuntu) to control other GUI programs. For example, to be able to read text labels and put text into entry boxes of other programs written using gtkmm. I have looked at X11 but I don't seem to find any relevant information or examples.

Thank you very much for any information.

答:
One way of doing it is via the XTEST (pdf) extension.

An example usage for key events is here: X11 Fake Key Event Generation using XTest Extension.


问:
How to call a method only after another method completes in ViewDidLoad
I'm trying to make an app where at the start Object A begins to fades.

Immediately after Object A completely fades, I'd like Object B to begin to fade.

I tried putting the below code in the ViewDidLoad method but they both run at the same time. Any idea on how to make one run after the other starting after the initial load?

```<code>ObjectA.isHidden = false
    UIView.animate(withDuration: 5.0, animations: { () -> Void in
         self.Fader.alpha = 0
        })

ObjectB.isHidden = false
    UIView.animate(withDuration: 1.0, animations: { () -> Void in
         self.Intro.alpha = 0
        })
</code>```

答:
You can nest them </p>

```<code>UIView.animate(withDuration: 5.0, delay: 0.0, options: [.curveLinear,.allowUserInteraction], animations: {
    self.fader.alpha = 0
 }) { (fin) in
      self.objectB.isHidden = false
      UIView.animate(withDuration: 1.0, animations: { () -> Void in
        self.Intro.alpha = 0
      })
}
</code>```

Body:
I'm trying to make an app where at the start Object A begins to fades.

Immediately after Object A completely fades, I'd like Object B to begin to fade.

I tried putting the below code in the ViewDidLoad method but they both run at the same time. Any idea on how to make one run after the other starting after the initial load?

ObjectA.isHidden = false
    UIView.animate(withDuration: 5.0, animations: { () -> Void in
         self.Fader.alpha = 0
        })

ObjectB.isHidden = false
    UIView.animate(withDuration: 1.0, animations: { () -> Void in
         self.Intro.alpha = 0
        })

Body:
You can nest them

UIView.animate(withDuration: 5.0, delay: 0.0, options: [.curveLinear,.allowUserInteraction], animations: {
    self.fader.alpha = 0
 }) { (fin) in
      self.objectB.isHidden = false
      UIView.animate(withDuration: 1.0, animations: { () -> Void in
        self.Intro.alpha = 0
      })
}


问:
Can I add arguments to python code when I submit spark job?
I'm trying to use spark-submit to execute my python code in spark cluster.

Generally we run spark-submit with python code like below.

```<code># Run a Python application on a cluster
./bin/spark-submit \
  --master spark://207.184.161.138:7077 \
  my_python_code.py \
  1000
</code>```

But I wanna run my_python_code.pyby passing several arguments Is there smart way to pass arguments?

答:
Aniket Kulkarni's spark-submit args.py a b c d e seems to suffice, but it's worth mentioning we had issues with optional/named args (e.g --param1).

It appears that double dashes -- will help signal that python optional args follow:

```<code>spark-submit --sparkarg xxx yourscript.py -- --scriptarg 1 arg1 arg2
</code>```

Body:
I'm trying to use spark-submit to execute my python code in spark cluster.

Generally we run spark-submit with python code like below.

# Run a Python application on a cluster
./bin/spark-submit \
  --master spark://207.184.161.138:7077 \
  my_python_code.py \
  1000

But I wanna run my_python_code.pyby passing several arguments Is there smart way to pass arguments?

Body:
Aniket Kulkarni's spark-submit args.py a b c d e seems to suffice, but it's worth mentioning we had issues with optional/named args (e.g --param1).

It appears that double dashes -- will help signal that python optional args follow:

spark-submit --sparkarg xxx yourscript.py -- --scriptarg 1 arg1 arg2


问:
Using xpath with c#, help
I'm trying to select the content of MINRANGE of the below XML. This is the code I'm using, the string min just gives me a long block of text not the node i wanted.

```<code>XPathDocument _BTCall = new XPathDocument(callUrl);
XPathNavigator nav = _BTCall.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//MAX/MINRANGE");
XPathNodeIterator iterator = nav.Select(exp);
iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
string min = nav.Value;
return int.Parse(min);
</code>```

```<code><ADSL_CHECKER>
  <ERRORID>0</ERRORID>
  <INPUT>01491410786</INPUT>
  <INPUTTYPE>TELNO</INPUTTYPE>
  <FIXEDRATE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </FIXEDRATE>
  <RATEADAPTIVE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </RATEADAPTIVE>
  <MAX>
    <RAG>G</RAG>
    <SPEED>4500</SPEED>
    <MINRANGE>3500</MINRANGE>
    <MAXRANGE>5500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </MAX>
  <WBC>
    <RAG>G</RAG>
    <SPEED>5500</SPEED>
    <MINRANGE>4500</MINRANGE>
    <MAXRANGE>6500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBC>
  <WBCFTTC>
    <RAG>G</RAG>
    <DOWNSPEED>32500</DOWNSPEED>
    <UPSPEED>7200</UPSPEED>
    <MINRANGE />
    <MAXRANGE />
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBCFTTC>
  <EXCHANGECODE>THHT</EXCHANGECODE>
  <EXCHANGENAME>HENLEY-ON-THAMES</EXCHANGENAME>
  <REASONCODE>L</REASONCODE>
  <VPCONTENTION>N</VPCONTENTION>
  <SPNAME />
  <CAD />
  <CPNAME>BE UN LIMITED</CPNAME>
  <CPCONTACTNO>02074795000</CPCONTACTNO>
  <POSTCODE>RG9 1LT</POSTCODE>
  <SUGGESTEDMSG>Your exchange is ADSL enabled, and our initial test on your line indicates that your line should be able to have an ADSL broadband service that provides a fixed line speed up to 2Mbps.

    Our test also indicates that your line currently supports an estimated ADSL Max broadband line speed of 4.5Mbps. Similar lines predicted with this speed have achieved ADSL Max line speeds in the range of 3.5 to 5.5Mbps.
    Our test also indicates that your line currently supports an estimated ADSL2+ broadband line speed of 5.5Mbps. Similar lines predicted with this speed have achieved ADSL2+ line speed in the range of 4.5 to 6.5Mbps.
    Our test also indicates that your line currently supports a fibre technology with an estimated WBC FTTC Broadband where consumers have received downstream line speed of 32.5Mbps and upstream line speed of 7.2Mbps.
    The actual stable line speed supportable will be determined during the first 10 days of use. This speed may change over time, to ensure line stability is maintained.
    If you decide to place an order, a further test will be performed to confirm if your line is suitable for the service you wish to purchase.
    Thank you for your interest.
    Please note that postcode and address check results are indicative only. Most accurate results can be obtained from a telephone number check.
  </SUGGESTEDMSG>
  <SUPPLEMENTARYMSG>Note: If you already have a Broadband service enabled on this line and you want to switch service providers, you will need to contact both your current provider and your new provider to get your service changed over new and existing service provider to have this service transferred.
  </SUPPLEMENTARYMSG>
</ADSL_CHECKER>
</code>```

Text in XML was modified slightly for formatting purposes.  See previous version for exact.

答:
You need to capture the result of iterator.MoveNext().

```<code>XPathNodeIterator iterator = nav.Select(exp);
if (iterator.MoveNext())
{
   XPathNavigator res = iterator.Current;
   string min = res.Value;
}
else
{
   //Error
}
</code>```

The iterator.MoveNext() doesn't modify your original nav object.

Title: Using xpath with c#, help

Body:
I'm trying to select the content of MINRANGE of the below XML. This is the code I'm using, the string min just gives me a long block of text not the node i wanted.

XPathDocument _BTCall = new XPathDocument(callUrl);
XPathNavigator nav = _BTCall.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//MAX/MINRANGE");
XPathNodeIterator iterator = nav.Select(exp);
iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
string min = nav.Value;
return int.Parse(min);

<ADSL_CHECKER>
  <ERRORID>0</ERRORID>
  <INPUT>01491410786</INPUT>
  <INPUTTYPE>TELNO</INPUTTYPE>
  <FIXEDRATE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </FIXEDRATE>
  <RATEADAPTIVE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </RATEADAPTIVE>
  <MAX>
    <RAG>G</RAG>
    <SPEED>4500</SPEED>
    <MINRANGE>3500</MINRANGE>
    <MAXRANGE>5500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </MAX>
  <WBC>
    <RAG>G</RAG>
    <SPEED>5500</SPEED>
    <MINRANGE>4500</MINRANGE>
    <MAXRANGE>6500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBC>
  <WBCFTTC>
    <RAG>G</RAG>
    <DOWNSPEED>32500</DOWNSPEED>
    <UPSPEED>7200</UPSPEED>
    <MINRANGE />
    <MAXRANGE />
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBCFTTC>
  <EXCHANGECODE>THHT</EXCHANGECODE>
  <EXCHANGENAME>HENLEY-ON-THAMES</EXCHANGENAME>
  <REASONCODE>L</REASONCODE>
  <VPCONTENTION>N</VPCONTENTION>
  <SPNAME />
  <CAD />
  <CPNAME>BE UN LIMITED</CPNAME>
  <CPCONTACTNO>02074795000</CPCONTACTNO>
  <POSTCODE>RG9 1LT</POSTCODE>
  <SUGGESTEDMSG>Your exchange is ADSL enabled, and our initial test on your line indicates that your line should be able to have an ADSL broadband service that provides a fixed line speed up to 2Mbps.

    Our test also indicates that your line currently supports an estimated ADSL Max broadband line speed of 4.5Mbps. Similar lines predicted with this speed have achieved ADSL Max line speeds in the range of 3.5 to 5.5Mbps.
    Our test also indicates that your line currently supports an estimated ADSL2+ broadband line speed of 5.5Mbps. Similar lines predicted with this speed have achieved ADSL2+ line speed in the range of 4.5 to 6.5Mbps.
    Our test also indicates that your line currently supports a fibre technology with an estimated WBC FTTC Broadband where consumers have received downstream line speed of 32.5Mbps and upstream line speed of 7.2Mbps.
    The actual stable line speed supportable will be determined during the first 10 days of use. This speed may change over time, to ensure line stability is maintained.
    If you decide to place an order, a further test will be performed to confirm if your line is suitable for the service you wish to purchase.
    Thank you for your interest.
    Please note that postcode and address check results are indicative only. Most accurate results can be obtained from a telephone number check.
  </SUGGESTEDMSG>
  <SUPPLEMENTARYMSG>Note: If you already have a Broadband service enabled on this line and you want to switch service providers, you will need to contact both your current provider and your new provider to get your service changed over new and existing service provider to have this service transferred.
  </SUPPLEMENTARYMSG>
</ADSL_CHECKER>

Text in XML was modified slightly for formatting purposes.  See previous version for exact.

Body:
You need to capture the result of iterator.MoveNext().

XPathNodeIterator iterator = nav.Select(exp);
if (iterator.MoveNext())
{
   XPathNavigator res = iterator.Current;
   string min = res.Value;
}
else
{
   //Error
}

The iterator.MoveNext() doesn't modify your original nav object.


问:
How to append & update JSON file
I have below json file format , depending on input args I need to append emp_email's if the key matches , if no match then append at end.

```<code>    {
  "key1": {
    "emp_email": [
      "xxxx@email.com",
      "yyyy@email.com"
    ]
  },
  "key2": {
    "emp_email": [
      "aaaaa@email.com",
      "bbbbb@email.com"
    ]
  }
}
</code>```

input_key = 'key2'

emp_email = 'cccc@email.com'

Above email 'cccc@email.com' needs to be updated for key key2 along with 2 existing email

input_key = 'key3'

emp_email = 'cccc@email.com'

This should append a new key value pair at end of JSON

```<code>    {
  "key1": {
    "emp_email": [
      "xxxx@email.com",
      "yyyy@email.com"
    ]
  },
  "key2": {
    "emp_email": [
      "aaaaa@email.com",
      "bbbbb@email.com"
    ]
  },
  "key3": {
    "emp_email": [
      "ccccc@email.com"
    ]
  }
}
</code>```

I started with below code

```<code>try:
    json_file_read = open(json_file, "r")
    json_data = json.load(json_file_read)
except ValueError as e:
    print "Invalid JSON"
except IOError as e:
    print "File Not Present"

key_list = []
for key, value in json_data.items():
    key_list.append(key)
existing_key = " ".join(key_list)
existing_key_list = existing_key.split()
print(existing_key_list)

email_list = emp_email.split(",")
print email_list

for f in input_key.split(","):
    if f in existing_key_list:
        print "key exists...!!!"
        existing_email_list = json_data[f]["emp_email"]
        # create new appended list (new + existing)
        new_email_list = email_list + list(set(existing_email_list) - set(email_list))
        # not sure how to append for the specific key

    else:
        print "new key"
        # append the new key & email block at end
</code>```

答:
There's no need to create a list of keys. You can just use if f in json_data: to tell if the key exists.

```<code>for i, key in enumerate(input_key.split(",")):
    if key in json_data:
        print "key exists!"
        json_data[key]['emp_email'].append(email_list[i])
    else:
        print "new key"
        json_data[key] = {'emp_email': [email_list[i]]}
</code>```

Title: How to append & update JSON file

Body:
I have below json file format , depending on input args I need to append emp_email's if the key matches , if no match then append at end.

    {
  "key1": {
    "emp_email": [
      "xxxx@email.com",
      "yyyy@email.com"
    ]
  },
  "key2": {
    "emp_email": [
      "aaaaa@email.com",
      "bbbbb@email.com"
    ]
  }
}

input_key = 'key2'

emp_email = 'cccc@email.com'

Above email 'cccc@email.com' needs to be updated for key key2 along with 2 existing email

input_key = 'key3'

emp_email = 'cccc@email.com'

This should append a new key value pair at end of JSON

    {
  "key1": {
    "emp_email": [
      "xxxx@email.com",
      "yyyy@email.com"
    ]
  },
  "key2": {
    "emp_email": [
      "aaaaa@email.com",
      "bbbbb@email.com"
    ]
  },
  "key3": {
    "emp_email": [
      "ccccc@email.com"
    ]
  }
}

I started with below code

try:
    json_file_read = open(json_file, "r")
    json_data = json.load(json_file_read)
except ValueError as e:
    print "Invalid JSON"
except IOError as e:
    print "File Not Present"

key_list = []
for key, value in json_data.items():
    key_list.append(key)
existing_key = " ".join(key_list)
existing_key_list = existing_key.split()
print(existing_key_list)

email_list = emp_email.split(",")
print email_list

for f in input_key.split(","):
    if f in existing_key_list:
        print "key exists...!!!"
        existing_email_list = json_data[f]["emp_email"]
        # create new appended list (new + existing)
        new_email_list = email_list + list(set(existing_email_list) - set(email_list))
        # not sure how to append for the specific key

    else:
        print "new key"
        # append the new key & email block at end

Body:
There's no need to create a list of keys. You can just use if f in json_data: to tell if the key exists.

for i, key in enumerate(input_key.split(",")):
    if key in json_data:
        print "key exists!"
        json_data[key]['emp_email'].append(email_list[i])
    else:
        print "new key"
        json_data[key] = {'emp_email': [email_list[i]]}


问:
How can I create a loop to click all buttons of a page using Selenium
I have 60 buttons on a page and I want to click all of them. Is it possible to create a loop to do so?

XPATH for the buttons:

/html/body/form/div[3]/div[4]/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/div/div/div/ct-polling-activity/div/div/div/div[2]/div[1]/table/tbody/tr[1]/td[6]/div/i

/html/body/form/div[3]/div[4]/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/div/div/div/ct-polling-activity/div/div/div/div[2]/div[1]/table/tbody/tr[2]/td[6]/div/i

The only different number for them is the last tr[ ], being a sequence until it reaches 60.

This is the function that I'm using to click the buttons.

```<code>def explicit_wait_xpath(my_selector):
    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.XPATH,
                                                my_selector)))
    element.click()
</code>```

答:
According to the question you asked, I think you can just create a loop, dynamically update the selector and pass it to function call.</p>

```<code>def explicit_wait_xpath(my_selector):
    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.XPATH,my_selector)))
    element.click()

for i in range(1,61):
   # use of f-string
   selector = f'"/html/body/form/div[3]/div[4]/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/div/div/div/ct-polling-activity/div/div/div/div[2]/div[1]/table/tbody/tr[{i}]/td[6]/div/i"'
   explicit_wait_xpath(selector)
</code>```

Body:
I have 60 buttons on a page and I want to click all of them. Is it possible to create a loop to do so?

XPATH for the buttons:

/html/body/form/div[3]/div[4]/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/div/div/div/ct-polling-activity/div/div/div/div[2]/div[1]/table/tbody/tr[1]/td[6]/div/i

/html/body/form/div[3]/div[4]/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/div/div/div/ct-polling-activity/div/div/div/div[2]/div[1]/table/tbody/tr[2]/td[6]/div/i

The only different number for them is the last tr[ ], being a sequence until it reaches 60.

This is the function that I'm using to click the buttons.

def explicit_wait_xpath(my_selector):
    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.XPATH,
                                                my_selector)))
    element.click()

Body:
According to the question you asked, I think you can just create a loop, dynamically update the selector and pass it to function call.

def explicit_wait_xpath(my_selector):
    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.XPATH,my_selector)))
    element.click()

for i in range(1,61):
   # use of f-string
   selector = f'"/html/body/form/div[3]/div[4]/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/div/div/div/ct-polling-activity/div/div/div/div[2]/div[1]/table/tbody/tr[{i}]/td[6]/div/i"'
   explicit_wait_xpath(selector)


问:
(itertools.combinations) Python Shell hangs in a bigger than specific amount size and throws memory error
I am trying to run a specific code to find the sum of all the possible combinations of the list that is coming from a .in file. The same code, when running with relatively small files, runs perfectly and with bigger files hangs and after a bit throws MEMORY ERROR

```<code>import itertools

file = open("c_medium.in","r")
if file.mode=='r':
    content = file.readlines()
    maxSlices,numberOfPizza = map(int,content[0].split())
    numberOfSlices = tuple(map(int,content[1].split()))
    print(maxSlices)
    print(numberOfSlices)
    sol = []
    sumOfSlices = []
    for x in range(1,len(numberOfSlices)+1):
        print(x)
        for y in itertools.combinations(numberOfSlices,x):
            if sum(y) <= maxSlices:
                sumOfSlices.append(sum(y))
    sumOfSlices.sort()
    print(sumOfSlices)
    checkSum = sumOfSlices[len(sumOfSlices)-1]
    print(checkSum)
    found = False
    if found == False:
        for x in range(1,len(numberOfSlices)+1):
            print(x)
            for y in itertools.combinations(numberOfSlices,x):
                if found == False:
                    if sum(y) == checkSum:
                        for z in y:
                            sol.append(numberOfSlices.index(z))
                        found = True
    solution = tuple(map(str,sol))
    print(solution)
</code>```

答:
The number of combinations of N elements grows very, very fast with N.

Regarding your code in particular, if (sum(y) <= maxSlices) is always true, then you'll generate a list with  2^(numberOfSlices) elements.  i.e., you'll overflow a 32-bit integer if numberOfSlices=32.

I'd recommend trying to solve your task without explicitly building a list.  If you describe what your code is doing, maybe someone can help.

Body:
I am trying to run a specific code to find the sum of all the possible combinations of the list that is coming from a .in file. The same code, when running with relatively small files, runs perfectly and with bigger files hangs and after a bit throws MEMORY ERROR

import itertools

file = open("c_medium.in","r")
if file.mode=='r':
    content = file.readlines()
    maxSlices,numberOfPizza = map(int,content[0].split())
    numberOfSlices = tuple(map(int,content[1].split()))
    print(maxSlices)
    print(numberOfSlices)
    sol = []
    sumOfSlices = []
    for x in range(1,len(numberOfSlices)+1):
        print(x)
        for y in itertools.combinations(numberOfSlices,x):
            if sum(y) <= maxSlices:
                sumOfSlices.append(sum(y))
    sumOfSlices.sort()
    print(sumOfSlices)
    checkSum = sumOfSlices[len(sumOfSlices)-1]
    print(checkSum)
    found = False
    if found == False:
        for x in range(1,len(numberOfSlices)+1):
            print(x)
            for y in itertools.combinations(numberOfSlices,x):
                if found == False:
                    if sum(y) == checkSum:
                        for z in y:
                            sol.append(numberOfSlices.index(z))
                        found = True
    solution = tuple(map(str,sol))
    print(solution)


问:
Nuxtjs application structure for mixed type of pages
In my application a bunch of pages can be generated statically. There are some pages which could run in browser (no SEO required). Some pages need to be having huge set of dynamic data which I hope could better be SSR. What would be the approach to maintain this kind of project? Do I need to maintain static files in separate project and other categories in separate project?</p>

答: Currently managing with 2 separate projects. One handles dynamic data part using SPA. Another project uses static generation. SSR was not an option.</p>


问:
Sum multiple fields with select new and where raises error 'Model' does not have definition of 'Sum'
First timer to C# and want to see if i can change a query. Basically, I want an aggregated values of the two currency columns in one go. There are Car dealer, with each dealer having a list of cars in their possession. So I want to get list of car dealers along with a total cost of all the cars under them. For now what I am doing is I loop over each dealer, get the cars then loop the cars over summing each cars price, which sounds inefficient to me.

```<code>public object DealerObj(Dealer d)
{
    var cars = d.DealerCars.Select(cc => new { cc.Cost }).ToList();

    var totalCost decimal = 0;
    foreach (var car in cars){
        totalCost += car.Cost;
    }

    return new {
        d.DealerName,
        totalCost = totalCost
    }
}
</code>```

While I am getting the correct results, the query appears slower. Is there a way to do a Sum() on the results and avoid the loop, something like below

```<code>   var cars = d.DealerCars.Select(cc => new { total = cc.Sum(s=>s.Cost) });
</code>```

答:
From the document

Computes the sum of a sequence of numeric values

So you can only Sum() for IEnumerable<Cost> like below.

```<code>var totalCost = d.DealerCars.Sum(p => p.Cost });

/* From my point of view, you should where the condition from your parameter
var totalCost = d.DealerCars.Where(p => p.DealerID == d.DealerID)
                            .Sum(p => p.Cost }); */
return new { d.DealerName, totalCost = totalCost }
</code>```

Body:
First timer to C# and want to see if i can change a query. Basically, I want an aggregated values of the two currency columns in one go. There are Car dealer, with each dealer having a list of cars in their possession. So I want to get list of car dealers along with a total cost of all the cars under them. For now what I am doing is I loop over each dealer, get the cars then loop the cars over summing each cars price, which sounds inefficient to me.

public object DealerObj(Dealer d)
{
    var cars = d.DealerCars.Select(cc => new { cc.Cost }).ToList();

    var totalCost decimal = 0;
    foreach (var car in cars){
        totalCost += car.Cost;
    }

    return new {
        d.DealerName,
        totalCost = totalCost
    }
}

While I am getting the correct results, the query appears slower. Is there a way to do a Sum() on the results and avoid the loop, something like below

   var cars = d.DealerCars.Select(cc => new { total = cc.Sum(s=>s.Cost) });

Body:
From the document

Computes the sum of a sequence of numeric values

So you can only Sum() for IEnumerable<Cost> like below.

var totalCost = d.DealerCars.Sum(p => p.Cost });

/* From my point of view, you should where the condition from your parameter
var totalCost = d.DealerCars.Where(p => p.DealerID == d.DealerID)
                            .Sum(p => p.Cost }); */
return new { d.DealerName, totalCost = totalCost }


问:
Lombok/Jackson - POJO for a json array
I have a json array that I need to receive(de-serialize) from a server and send (serialize) to another server:

Example:

```<code>[
  {
    "car-name": "string",
    "parts": [
      "engine",
      "wheels"
    ]
  }
]
</code>```

I started with writing the following POJO to represent this Json array:

```<code>import lombok.Builder;
import lombok.Singular;
import lombok.Value;

@Builder
@Value
public class Car {

    private String carName;
    @Singular("part")
    private List<String> parts;
}
</code>```

With this:

I am able to build the object using Lombok as:

Car myCar = Car.builder().carName("Tesla").part("engine").part("wheels").build();

Unmarshal using something like unmarshal().json(Jackson, Car.class).

While 1) and 2) work, they do NOT give me objects that actually represent the json example above.

They instead give this:

```<code>  {
    "car-name": "string",
    "parts": [
      "engine",
      "wheels"
    ]
  }
</code>```

I tried using a parent class as below:

```<code>import lombok.Builder;
import lombok.Singular;
import lombok.Value;

@Builder
@Value
public class Vehicle {

    private List<Car> vehicles;
}
</code>```

But this also gives me a wrong object (notice the "vehicles" key Vs what I have in my above Example):

```<code>  {
    "vehicles": {
        "car-name": "string",
        "parts": [
             "engine",
             "wheels"
             ]
        }
}
</code>```

How can I write a POJO that represents this JSON array, preferably using Lombok? Or Jackson?

答:
You don't need to wrap List<Car> in Vehicle class because Vehicle represents JsonObject and vehicles is a property in it. Just directly return or serialize the List<Car>

```<code>objectmapper.writeValueAsString(List<Car>);
</code>```

Title: Lombok/Jackson - POJO for a json array

Body:
I have a json array that I need to receive(de-serialize) from a server and send (serialize) to another server:

Example:

[
  {
    "car-name": "string",
    "parts": [
      "engine",
      "wheels"
    ]
  }
]

I started with writing the following POJO to represent this Json array:

import lombok.Builder;
import lombok.Singular;
import lombok.Value;

@Builder
@Value
public class Car {

    private String carName;
    @Singular("part")
    private List<String> parts;
}

With this:

I am able to build the object using Lombok as:

Car myCar = Car.builder().carName("Tesla").part("engine").part("wheels").build();

Unmarshal using something like unmarshal().json(Jackson, Car.class).

While 1) and 2) work, they do NOT give me objects that actually represent the json example above.

They instead give this:

  {
    "car-name": "string",
    "parts": [
      "engine",
      "wheels"
    ]
  }

I tried using a parent class as below:

import lombok.Builder;
import lombok.Singular;
import lombok.Value;

@Builder
@Value
public class Vehicle {

    private List<Car> vehicles;
}

But this also gives me a wrong object (notice the "vehicles" key Vs what I have in my above Example):

  {
    "vehicles": {
        "car-name": "string",
        "parts": [
             "engine",
             "wheels"
             ]
        }
}

How can I write a POJO that represents this JSON array, preferably using Lombok? Or Jackson?

Body:
You don't need to wrap List<Car> in Vehicle class because Vehicle represents JsonObject and vehicles is a property in it. Just directly return or serialize the List<Car>

objectmapper.writeValueAsString(List<Car>);