问:
Using MongoDB query to show all items in a Collection with a specific value (DiscordJS v13)
I'm trying to make my last command for my discord bot (Discord.js v13), a marketplace with a MongoDB Collection called "Perso".

The problem is that I really don't know how to make it work, even after reading MongoDB and mongoose documentation, also searching similar (not really) problems on Stack Overflow.

Here is the little piece of code I did to test a return of value :

```<code>    let persoOnSale = await Perso.count({ onSale: 1}); // There are 2 "Perso" with the "onSale" field equals to 1.
    let perso = Perso.find({ onSale: 1}, 'name value').sort({value: 1});

     for (let index = 0; index < persoOnSale; index++) {
         const element = perso[index];
         console.log(element); // element return "undefined", 2 times.

     }
</code>```

Here is the console.log return when it's console.log(perso) :

```<code>[
  {
    _id: new ObjectId("61fc60165a048fa5700de25d"),
    name: 'Perso Name',
    value: 160
  },
  {
    _id: new ObjectId("61fbe486ef3f2c2b31c57dc5"),
    name: 'Perso Name 2',
    value: 10000
  }
]

</code>```

I was trying to show all the "Perso" with (onSale: 1), showing their name and value, and sort them in order to show the "Perso" with the least value amount first.

First of all, I imagine I need to put an index on the "perso" array, but I clearly don't know how to do that.

I'd be really thankful for your help.

答:
I just found out.

I have to put an await before "Perso.find"

let perso = await Perso.find({ onSale: 1}, 'name value').sort({value: 1});

(Now, the "Persos" are found).

Then, I have to add that :

```<code>const element = perso[index].name;
const value = perso[index].value;
</code>```

Body:
I'm trying to make my last command for my discord bot (Discord.js v13), a marketplace with a MongoDB Collection called "Perso".

The problem is that I really don't know how to make it work, even after reading MongoDB and mongoose documentation, also searching similar (not really) problems on Stack Overflow.

Here is the little piece of code I did to test a return of value :

    let persoOnSale = await Perso.count({ onSale: 1}); // There are 2 "Perso" with the "onSale" field equals to 1.
    let perso = Perso.find({ onSale: 1}, 'name value').sort({value: 1});

     for (let index = 0; index < persoOnSale; index++) {
         const element = perso[index];
         console.log(element); // element return "undefined", 2 times.

     }

Here is the console.log return when it's console.log(perso) :

[
  {
    _id: new ObjectId("61fc60165a048fa5700de25d"),
    name: 'Perso Name',
    value: 160
  },
  {
    _id: new ObjectId("61fbe486ef3f2c2b31c57dc5"),
    name: 'Perso Name 2',
    value: 10000
  }
]

I was trying to show all the "Perso" with (onSale: 1), showing their name and value, and sort them in order to show the "Perso" with the least value amount first.

First of all, I imagine I need to put an index on the "perso" array, but I clearly don't know how to do that.

I'd be really thankful for your help.

Body:
I just found out.

I have to put an await before "Perso.find"

let perso = await Perso.find({ onSale: 1}, 'name value').sort({value: 1});

(Now, the "Persos" are found).

Then, I have to add that :

const element = perso[index].name;
const value = perso[index].value;


来源: stackexchange

问:
git difftool fails silently when file is not found
Take any git repo and run the following

```<code>git difftool -- asdfasdfasdsfawerf
</code>```

i.e. give it an invalid filename. It will return immediately showing no diff, but it also has 0 return code. Obviously it should give some sort of error because it's not that there's no diffs in my file, the file itself doesn't exist either in my working tree or in HEAD so I'm asking an invalid question.

In case you think this is a contrived example, this can be a real issue if the name of a file is mistyped. You end up thinking there's no diff in the file when actually it couldn't find the file.

Does anyone know of a way to force it to fail if the file is not found?

答: It seems this only happens when -- is used. Removing it solves the problem, although it still seems like a bug.

ContentLicense: CC BY-SA 4.0

Body:
Take any git repo and run the following

git difftool -- asdfasdfasdsfawerf

i.e. give it an invalid filename. It will return immediately showing no diff, but it also has 0 return code. Obviously it should give some sort of error because it's not that there's no diffs in my file, the file itself doesn't exist either in my working tree or in HEAD so I'm asking an invalid question.

In case you think this is a contrived example, this can be a real issue if the name of a file is mistyped. You end up thinking there's no diff in the file when actually it couldn't find the file.

Does anyone know of a way to force it to fail if the file is not found?


Title: How do I make sure my column descends by year instead of the day of the month?

Body:
Given I have the column x

head(daily_negative_PRscore$x)
"2018-01-02 10:29:00 CET" "2017-01-03 18:28:00 CET" "2017-01-03 19:29:00 CET" "2018-01-03 00:00:00 CET" "2017-01-04 10:47:00 CET" "2017-01-04 11:05:00 CET"

And the way I would it to descend ideally is in the following manner:

2017-01-03 18:28:00  2017-01-03 19:29:00 2017-01-04 00:00:00 ...

Body:
Another option is to use arrange:

library(tidyverse)

daily_negative_PRscore %>%
  arrange(desc(as.POSIXct(x)))

Or another base R option with as.Date:

daily_negative_PRscore[rev(order(as.Date(daily_negative_PRscore$x, format = "%Y-%m-%d %H:%M:%S"))),]

Output

                        x
1 2018-01-03 00:00:00 CET
2 2018-01-02 10:29:00 CET
3 2017-01-04 11:05:00 CET
4 2017-01-04 10:47:00 CET
5 2017-01-03 19:29:00 CET
6 2017-01-03 18:28:00 CET

Data

daily_negative_PRscore <- structure(list(x = c("2018-01-02 10:29:00 CET", "2017-01-03 18:28:00 CET",
                                               "2017-01-03 19:29:00 CET", "2018-01-03 00:00:00 CET", "2017-01-04 10:47:00 CET",
                                               "2017-01-04 11:05:00 CET")), class = "data.frame", row.names = c(NA,
                                                                                -6L))


问:
Writing a function that returns true if given string has exactly 6 characters
I am trying to write a function that returns true or false if a given string has exactly  6 consecutive characters with the same value. If the string has more or less than 6, it will return false:

I am not allowed to use lists, sets or import any packages. I am only restricted to while loops, for loops, and utilizing basic mathematical operations

Two example runs are shown below:

```<code>Enter a string: 367777776
True
</code>```
```<code>Enter a string: 3677777777776
False
</code>```

Note that although I entered numbers, it is actually a string within the function argument for example: consecutive('3777776')

I tried to convert the string into an ASCII table and then try and filter out the numbers there. However, I

```<code>def consecutive(x):
    storage= ' '
    acc=0
    count=0
    for s in x:
        storage+= str(ord(s)) + ' '
        acc+=ord(s)
        if acc == acc:
            count+=1
    for s in x-1:

    return count

</code>```

My intention is to compare the previous character's ASCII code  to the current character's ASCII code in the string. If the ASCII doesnt match, I will add an accumulator for it. The accumulator will list the number of duplicates. From there, I will implement an if-else statement to see if it is greater or less than 6 However, I have a hard time translating my thoughts into python code.

Can anyone assist me?

答:
You can try a two pointer approach, where the left pointer is fixed at the first instance of some digit and the right one is shifted as long as the digit is seen.

```<code>def consecutive(x):
    left = 0
    while left != len(x):
        right = left
        while right < len(x) and x[right] == x[left]:
            right += 1
        length = (right - 1) - left + 1 # from left to right - 1 inclusive, x[left] repeated
        if length == 6: # found desired length
            return True

        left = right

    return False # no segment found

tests = [
    '3677777777776',
    '367777776'
]

for test in tests:
    print(f"{test}: {consecutive(test)}")
</code>```

Output

```<code>3677777777776: False
367777776: True
</code>```

Body:
I am trying to write a function that returns true or false if a given string has exactly  6 consecutive characters with the same value. If the string has more or less than 6, it will return false:

I am not allowed to use lists, sets or import any packages. I am only restricted to while loops, for loops, and utilizing basic mathematical operations

Two example runs are shown below:

Enter a string: 367777776
True

Enter a string: 3677777777776
False

Note that although I entered numbers, it is actually a string within the function argument for example: consecutive('3777776')

I tried to convert the string into an ASCII table and then try and filter out the numbers there. However, I

def consecutive(x):
    storage= ' '
    acc=0
    count=0
    for s in x:
        storage+= str(ord(s)) + ' '
        acc+=ord(s)
        if acc == acc:
            count+=1
    for s in x-1:

    return count

My intention is to compare the previous character's ASCII code  to the current character's ASCII code in the string. If the ASCII doesnt match, I will add an accumulator for it. The accumulator will list the number of duplicates. From there, I will implement an if-else statement to see if it is greater or less than 6 However, I have a hard time translating my thoughts into python code.

Can anyone assist me?

Body:
You can try a two pointer approach, where the left pointer is fixed at the first instance of some digit and the right one is shifted as long as the digit is seen.

def consecutive(x):
    left = 0
    while left != len(x):
        right = left
        while right < len(x) and x[right] == x[left]:
            right += 1
        length = (right - 1) - left + 1 # from left to right - 1 inclusive, x[left] repeated
        if length == 6: # found desired length
            return True

        left = right

    return False # no segment found

tests = [
    '3677777777776',
    '367777776'
]

for test in tests:
    print(f"{test}: {consecutive(test)}")

Output

3677777777776: False
367777776: True


问:
Pytorch CNN script training, but not getting results
I’m just getting started with pytorch. I am trying to do a simple binary classification project with the cats and dogs dataset. After much fumbling around, I was able to get the model to train, but I’m not getting the expected results.

First, the loss starts out way too low. To me, that seems to indicate I’m not measuring loss correctly.

Second, the model just predicts everything as 0.

I’m sure there are many mistakes here, but I would appreciate it if someone could take a look and let me know what I’m doing wrong. Thank you!

```<code>import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.nn.functional as F
from torchvision.io import read_image
from torch.utils.data import Dataset, DataLoader
from torchvision.utils import make_grid
from torchvision.utils import save_image
from sklearn.model_selection import train_test_split
import os
import numpy as np
from sklearn import preprocessing
import glob
import cv2

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(device)

IMAGE_SIZE = 64
DATA_DIR = "C:\\Users\\user\\source\\repos\\pytorch-youtube\\data\\catsdogs\\PetImages\\"
LABELS = ('cat', 'dog')

# custom dataset class
# expects the root folder to have sub folders with class names
# and pictures of classes inside folder
class CustomImageDataset(Dataset):
    def __init__(self):
        self.imgs_path = DATA_DIR
        file_list = glob.glob(self.imgs_path + "*")
        self.data = []
        for class_path in file_list:
            class_name = class_path.split("\\")[-1]
            for img_path in glob.glob(class_path + "\\*.jpg"):
                self.data.append([img_path, class_name])
        self.class_map = {"Dog": 0, "Cat": 1}
        self.img_dim = (IMAGE_SIZE, IMAGE_SIZE)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        img_path, class_name = self.data[idx]
        # this is to handle corrupt images in the dataset
        # could probably be handled better
        try:
            img = cv2.imread(img_path)
            img = cv2.resize(img, self.img_dim)
        except:
            img_path, class_name = self.data[idx+1]
            img = cv2.imread(img_path)
            img = cv2.resize(img, self.img_dim)
        class_id = self.class_map[class_name]
        img_tensor = torch.from_numpy(img)
        img_tensor = img_tensor.permute(2, 0, 1) # not exactly sure what/why for this line
        class_id = torch.tensor([class_id])
        return img_tensor, class_id

# as is, we aren't using these
transform = transforms.Compose(
    [transforms.Resize((64, 64)),
    transforms.ConvertImageDtype(torch.float32),
    transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5)),

    ]
)

dataset = CustomImageDataset()
dataloader = DataLoader(dataset, batch_size=4, shuffle=True)

dataiter = iter(dataloader)
train_features, train_labels = dataiter.next()

class Net(nn.Module):
    def __init__(self):
        super().__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(2704, 128) # only way I got input size was by running code
        self.fc2 = nn.Linear(128, 64)
        self.fc3 = nn.Linear(64, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

net = Net()
# net.to(device)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001)

for epoch in range(2):
    running_loss = 0.0
    for i, data in enumerate(dataloader, 0):

        inputs, labels = data

        # this is the fix for "expected scalar type Byte but found Float"
        # this seems to completely destroy the features in the image to just white
        inputs = inputs.float()
        optimizer.zero_grad()

        outputs = net(inputs)

        loss = criterion(outputs, torch.max(labels,1)[1])
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.10f}')
            running_loss = 0.0

print("finished")

# save the model
PATH = './custom_trained_model_dogs_cats.pth'
torch.save(net.state_dict(), PATH)
</code>```

答:
It seems I was passing in the wrong thing to my loss function. I changed this line

```<code>loss = criterion(outputs, torch.max(labels,1)[1])
</code>```

to this

```<code>loss = criterion(outputs, torch.max(labels,1)[0])
</code>```

and everything seems to be working. I'm able to correctly classify the cats and dogs.

Body:
I’m just getting started with pytorch. I am trying to do a simple binary classification project with the cats and dogs dataset. After much fumbling around, I was able to get the model to train, but I’m not getting the expected results.

First, the loss starts out way too low. To me, that seems to indicate I’m not measuring loss correctly.

Second, the model just predicts everything as 0.

I’m sure there are many mistakes here, but I would appreciate it if someone could take a look and let me know what I’m doing wrong. Thank you!

import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.nn.functional as F
from torchvision.io import read_image
from torch.utils.data import Dataset, DataLoader
from torchvision.utils import make_grid
from torchvision.utils import save_image
from sklearn.model_selection import train_test_split
import os
import numpy as np
from sklearn import preprocessing
import glob
import cv2

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(device)

IMAGE_SIZE = 64
DATA_DIR = "C:\\Users\\user\\source\\repos\\pytorch-youtube\\data\\catsdogs\\PetImages\\"
LABELS = ('cat', 'dog')

# custom dataset class
# expects the root folder to have sub folders with class names
# and pictures of classes inside folder
class CustomImageDataset(Dataset):
    def __init__(self):
        self.imgs_path = DATA_DIR
        file_list = glob.glob(self.imgs_path + "*")
        self.data = []
        for class_path in file_list:
            class_name = class_path.split("\\")[-1]
            for img_path in glob.glob(class_path + "\\*.jpg"):
                self.data.append([img_path, class_name])
        self.class_map = {"Dog": 0, "Cat": 1}
        self.img_dim = (IMAGE_SIZE, IMAGE_SIZE)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        img_path, class_name = self.data[idx]
        # this is to handle corrupt images in the dataset
        # could probably be handled better
        try:
            img = cv2.imread(img_path)
            img = cv2.resize(img, self.img_dim)
        except:
            img_path, class_name = self.data[idx+1]
            img = cv2.imread(img_path)
            img = cv2.resize(img, self.img_dim)
        class_id = self.class_map[class_name]
        img_tensor = torch.from_numpy(img)
        img_tensor = img_tensor.permute(2, 0, 1) # not exactly sure what/why for this line
        class_id = torch.tensor([class_id])
        return img_tensor, class_id

# as is, we aren't using these
transform = transforms.Compose(
    [transforms.Resize((64, 64)),
    transforms.ConvertImageDtype(torch.float32),
    transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5)),

    ]
)

dataset = CustomImageDataset()
dataloader = DataLoader(dataset, batch_size=4, shuffle=True)

dataiter = iter(dataloader)
train_features, train_labels = dataiter.next()

class Net(nn.Module):
    def __init__(self):
        super().__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(2704, 128) # only way I got input size was by running code
        self.fc2 = nn.Linear(128, 64)
        self.fc3 = nn.Linear(64, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

net = Net()
# net.to(device)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001)

for epoch in range(2):
    running_loss = 0.0
    for i, data in enumerate(dataloader, 0):

        inputs, labels = data

        # this is the fix for "expected scalar type Byte but found Float"
        # this seems to completely destroy the features in the image to just white
        inputs = inputs.float()
        optimizer.zero_grad()

        outputs = net(inputs)

        loss = criterion(outputs, torch.max(labels,1)[1])
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.10f}')
            running_loss = 0.0

print("finished")

# save the model
PATH = './custom_trained_model_dogs_cats.pth'
torch.save(net.state_dict(), PATH)

Body:
It seems I was passing in the wrong thing to my loss function. I changed this line

loss = criterion(outputs, torch.max(labels,1)[1])

to this

loss = criterion(outputs, torch.max(labels,1)[0])

and everything seems to be working. I'm able to correctly classify the cats and dogs.


答:
That's a pretty good start!

A few comments:

Variables storage and acc play the same role, and are a little more complicated than they have to be. All you want to know when you arrive at character s is whether or not s is identical to the previous character. So, you only need to store the previously seen character.

Condition acc == acc is always going to be True. I think you meant acc == s?

When you encounter an identical character, you correctly increase the count with count += 1. However, when we change characters, you should reset the count.

With these comments in mind, I fixed your code, then blanked out a few parts for you to fill. I've also renamed storage and acc to previous_char which I think is more explicit.

def has_6_consecutive(x):
    previous_char = None
    count = 0
    for s in x:
        if s == previous_char:
            ???
        elif count == 6:
            ???
        else:
            ???
            previous_char = ???
    ???
```

Title: Writing a function that returns true if given string has exactly 6 characters


问:
Calling a function from outside class with user input without using global
I am trying to avoid using global, instead I created a class. I am having trouble calling the class, instead, I am getting the following error

```<code>TypeError: phone.__init__() missing 1 required positional argument: 'NUMBER_INPUT'
</code>```

Any ideas? Thanks in advance!

```<code>class phone:

        def __init__(self,NUMBER_INPUT):
            self.NUMBER_INPUT = NUMBER_INPUT

        def phone_number(self):
            """validate user input of phone number"""
            while True:
                self.NUMBER_INPUT = input("Please enter your phone number: ")
                if  re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
                    print("You phone number is: " + self.NUMBER_INPUT)
                    break
                print("Please enter a valid phone number ex. 123-456-5678")

    phone().phone_number()
</code>```

答:
You must provide a value for NUMBER_INPUT when calling phone() like phone("123").phone_number().

But it would be better if you will use dummy value for NUMBER_INPUT in constructor like:

```<code>class phone:

        def __init__(self):
            self.NUMBER_INPUT = ""

        def phone_number(self):
            """validate user input of phone number"""
            while True:
                self.NUMBER_INPUT = input("Please enter your phone number: ")
                if  re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
                    print("You phone number is: " + self.NUMBER_INPUT)
                    break
                print("Please enter a valid phone number ex. 123-456-5678")

phone().phone_number()
</code>```

Body:
I am trying to avoid using global, instead I created a class. I am having trouble calling the class, instead, I am getting the following error

TypeError: phone.__init__() missing 1 required positional argument: 'NUMBER_INPUT'

Any ideas? Thanks in advance!

class phone:

        def __init__(self,NUMBER_INPUT):
            self.NUMBER_INPUT = NUMBER_INPUT

        def phone_number(self):
            """validate user input of phone number"""
            while True:
                self.NUMBER_INPUT = input("Please enter your phone number: ")
                if  re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
                    print("You phone number is: " + self.NUMBER_INPUT)
                    break
                print("Please enter a valid phone number ex. 123-456-5678")

    phone().phone_number()

Body:
You must provide a value for NUMBER_INPUT when calling phone() like phone("123").phone_number().

But it would be better if you will use dummy value for NUMBER_INPUT in constructor like:

class phone:

        def __init__(self):
            self.NUMBER_INPUT = ""

        def phone_number(self):
            """validate user input of phone number"""
            while True:
                self.NUMBER_INPUT = input("Please enter your phone number: ")
                if  re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
                    print("You phone number is: " + self.NUMBER_INPUT)
                    break
                print("Please enter a valid phone number ex. 123-456-5678")

phone().phone_number()


问:
Is creating many schemas in H2 a good strategy for sharding and performance?
On a mailing list, someone exposed the following issue:

We have millions of users (1 to 5 MB of data per user)

A given user data does not access or modify other user data

How can we implement sharding using H2 while remaining performant?

Someone else answered the following:

You could create 1 schema per user

The benefit is that user data would be located in separate table instances

Hence, this would improve performance when updating those tables

My question is:

has anyone attempted this?

Is this really an interesting strategy to shard data and improve/keep performance?

答:
If you have millions of users, and 2 MB data per user on average, then you get about 2 TB. I think it's too much to store in one single database file. On the other hand, you don't want to use millions of database files either.

I would use multiple databases, each database with up to 1000 users (depending on the amount of data).

You can then either create multiple schemas (but please note that for H2, the schema metadata is kept in memory), or add a 'userId' column to each table.

ContentLicense: CC BY-SA 3.0


问:
I need to convert a python programme that merge the content of two files into one
```<code>def read_file(filename):

    with open("files/file1.txt", "r") as f1:
        content1 = f1.read()

    with open("files/file2.txt", "r") as f2:
        content2 = f2.read()

    return content1, content2

def merge_file_to_one(content1,content2):
    content1 += "\n"
    content1 += content2
    with open("files/file3.txt", "w") as f3:
        f3.write(content1)

merge_file_to_one(content1, content2)
</code>```

i have tried to adopt your code into mine using my file names but I still cant make sense out of it. In the first function, am I supposed to just read one file. What happens to the second file.
/when I finally called the function, I get an error that content 1 and content 2 wasn't defined.

答:
Taking your program and making it into functions you get:

```<code>#helper function to read file
def read_file(filename):
    with open(filename, "r") as f1:
        content1 = f1.read()
    return content1

# Python program to merge the content of two files into a third
def convert_files_to_one(filename_one_read, filename_two_read, write_to_file):
    content1 = f"{read_file(filename_one_read)}\n{read_file(filename_two_read)}"

    with open(write_to_file, "w") as f3:
        f3.write(content1)

convert_files_to_one("files/file1.txt", "files/file2.txt", "files/file3.txt")
</code>```

using the 'with' context manager is usually a better form than closing the files manually

Also when things are repeated it's best to put it into a function, so that you can reuse that logic easily elsewhere.

Body:
def read_file(filename):

    with open("files/file1.txt", "r") as f1:
        content1 = f1.read()

    with open("files/file2.txt", "r") as f2:
        content2 = f2.read()

    return content1, content2

def merge_file_to_one(content1,content2):
    content1 += "\n"
    content1 += content2
    with open("files/file3.txt", "w") as f3:
        f3.write(content1)

merge_file_to_one(content1, content2)

i have tried to adopt your code into mine using my file names but I still cant make sense out of it. In the first function, am I supposed to just read one file. What happens to the second file.
/when I finally called the function, I get an error that content 1 and content 2 wasn't defined.

Body:
Taking your program and making it into functions you get:

#helper function to read file
def read_file(filename):
    with open(filename, "r") as f1:
        content1 = f1.read()
    return content1

# Python program to merge the content of two files into a third
def convert_files_to_one(filename_one_read, filename_two_read, write_to_file):
    content1 = f"{read_file(filename_one_read)}\n{read_file(filename_two_read)}"

    with open(write_to_file, "w") as f3:
        f3.write(content1)

convert_files_to_one("files/file1.txt", "files/file2.txt", "files/file3.txt")

using the 'with' context manager is usually a better form than closing the files manually

Also when things are repeated it's best to put it into a function, so that you can reuse that logic easily elsewhere.


问:
In springboot error sayingThe declared package "com.example.demo" does not match the expected package ""
```<code>package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootEdurekaTrialApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootEdurekaTrialApplication.class, args);
    }

}

  [1]: https://i.stack.imgur.com/78XDP.png
</code>```

I have shared the screenshot of project package in above image. I have created the class under same package but I don't know why I am getting error. please guide.

答:
In my case, the directory structure is fine.  It could be that the source path of the main application is pointing to a different directory than the default path such as "src/main/java".  Since this file was automatically created by Spring Boot, there seemed to be no way to fix it.

The way I resolved this compiler error was to add a new class using a different name from scratch and then copy the original content into the new class before removing the old one.  You can then rename the class afterward.

Body:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootEdurekaTrialApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootEdurekaTrialApplication.class, args);
    }

}

  [1]: https://i.stack.imgur.com/78XDP.png

I have shared the screenshot of project package in above image. I have created the class under same package but I don't know why I am getting error. please guide.


问:
how can test my API in different PC which is in same wifi network using my IPv4 address?
how can I test my API in different PC which is in same WIFI network using my IPv4 address ?
like if i have if 192.168.2.222 then I got the error URL image plz tell me how can I solve.The API is working fine in local host. but in IPv4 I got this error so plz guide me. I have tried all the configuration from different sources but still getting this error.</p>

答:
Use ifconfig to find out your local network ip

In my case it is 192.168.1.131:

ifconfig
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=400<CHANNEL_IO>
inet 192.168.1.131 netmask 0xffffff00 broadcast 192.168.1.255
media: autoselect
status: active

Then you need to run the server with

php -S 0.0.0.0:5500 index.php or

php -S 192.168.1.131:5500 index.php

You can now open a browser on a device on your local network with

http://192.168.1.131:5500


问:
Remove Server : istio-envoy header in Istio 1.8.2
How can I remove the server header generated by Istio ?

In Istio 1.5.6 I had an Istio EnvoyFilter, but that doesn't seem to work anymore in Istio 1.8.2.

```<code>apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: dgp-headerstrip-server
  namespace: istio-system
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        filterChain:
          filter:
            name: "envoy.http_connection_manager"
    patch:
      operation: MERGE
      value:
        config:
          server_header_transformation: PASS_THROUGH
</code>```

答:
You can also set, add, remove a header directly from Istio, with a VirtualService object?

Example

```<code>apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: reviews-route
spec:
  hosts:
  - reviews.prod.svc.cluster.local
  http:
  - headers:
      request:
        set:
          test: "true"
    route:
    - destination:
        host: reviews.prod.svc.cluster.local
        subset: v2
      weight: 25
    - destination:
        host: reviews.prod.svc.cluster.local
        subset: v1
      headers:
        response:   # this is from the response, but you can put it in the request as well.
          remove:
          - foo
      weight: 75
</code>```

Header parameters.

Body:
How can I remove the server header generated by Istio ?

In Istio 1.5.6 I had an Istio EnvoyFilter, but that doesn't seem to work anymore in Istio 1.8.2.

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: dgp-headerstrip-server
  namespace: istio-system
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        filterChain:
          filter:
            name: "envoy.http_connection_manager"
    patch:
      operation: MERGE
      value:
        config:
          server_header_transformation: PASS_THROUGH

Body:
You can also set, add, remove a header directly from Istio, with a VirtualService object?

Example

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: reviews-route
spec:
  hosts:
  - reviews.prod.svc.cluster.local
  http:
  - headers:
      request:
        set:
          test: "true"
    route:
    - destination:
        host: reviews.prod.svc.cluster.local
        subset: v2
      weight: 25
    - destination:
        host: reviews.prod.svc.cluster.local
        subset: v1
      headers:
        response:   # this is from the response, but you can put it in the request as well.
          remove:
          - foo
      weight: 75

Header parameters.


问:
How to writing logs to STDERR base on log level using Serilog
I'm using Serilog for my .netcore application and write logs to console.
And all logs come to STDOUT streams, but the requirement is Error and Fatal level should come to STDERR streams. I already added "standardErrorFromLevel": "Error" to arg of Writeto Console setting in appsetting.json but not working and my STDERR still empty.
How do I redirect the logs for error and fatal level to STDERR? Please help!!!

答:
I tried to achieve the same thing as you and I got it to work with VS.Net 2020 and Serilog.

My appSettings.json looks like this:

```<code>{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "standardErrorFromLevel": "Error"
        }
      }
    ],
  }
}
</code>```

I tried this with setting command line arguments in my web projects properties, Debug, General, Launch Profiles to:
>c:\temp\stdout.log 2>c:\temp\stderr.log. And the logging gets nicely separated into these two files.

My .Net6 program.cs contains this for SeriLog:

```<code>builder.Host.UseSerilog((context, configuration) => configuration
    .Enrich.FromLogContext()
    .ReadFrom.Configuration(context.Configuration)
    })
);
</code>```

To make SeriLog the default ILogger<T> for dependency injection in controllers, I have added:

```<code>builder.Services.AddLogging(x =>
{
    x.ClearProviders();
    x.AddSerilog(dispose: true);
});
</code>```

Might it be you are using DI and not actually be using SeriLog at all?

If you want to try and set the propeties in code, just add

```<code>    .WriteTo.Async(x =>
    {
         x.Console(standardErrorFromLevel: LogEventLevel.Error);
    }
</code>```

inside UseSerilog().

I have to following SeriLog packages installed:

Serilog.AspNetCore 4.1.0

Serilog.Extensions.Logging 3.1.0

SeriLog.Settings.Configuration 3.3.0

SeriLog.Extensions.Logging.File 2.0.0

The latter should not be relevant there.

Body:
I tried to achieve the same thing as you and I got it to work with VS.Net 2020 and Serilog.

My appSettings.json looks like this:

{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "standardErrorFromLevel": "Error"
        }
      }
    ],
  }
}

I tried this with setting command line arguments in my web projects properties, Debug, General, Launch Profiles to:
>c:\temp\stdout.log 2>c:\temp\stderr.log. And the logging gets nicely separated into these two files.

My .Net6 program.cs contains this for SeriLog:

builder.Host.UseSerilog((context, configuration) => configuration
    .Enrich.FromLogContext()
    .ReadFrom.Configuration(context.Configuration)
    })
);

To make SeriLog the default ILogger<T> for dependency injection in controllers, I have added:

builder.Services.AddLogging(x =>
{
    x.ClearProviders();
    x.AddSerilog(dispose: true);
});

Might it be you are using DI and not actually be using SeriLog at all?

If you want to try and set the propeties in code, just add

    .WriteTo.Async(x =>
    {
         x.Console(standardErrorFromLevel: LogEventLevel.Error);
    }

inside UseSerilog().

I have to following SeriLog packages installed:

Serilog.AspNetCore 4.1.0

Serilog.Extensions.Logging 3.1.0

SeriLog.Settings.Configuration 3.3.0

SeriLog.Extensions.Logging.File 2.0.0

The latter should not be relevant there.


问:
How to read property of control defined inside style in silverlight.?
I am using NumericUpDown control in my silver-light application. Code is as follows

```<code> <StackPanel Style="{StaticResource StackPanelStyle_LableValue}">
                        <TextBlock Text="{Binding Path=ViewItem.Strength, Source={StaticResource LocalizedStrings }}" Style="{StaticResource TextBlockStyle}" />
                        <inputToolkit:NumericUpDown Style="{StaticResource NumericUpdownStyle_Strength}"
                                                    Value="{Binding RightSpecGlassStrength, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}"
                                                    TabIndex="5" />
                    </StackPanel>
</code>```

and Style that i bind to NumericUpDown control as follows

```<code> <Style x:Key="NumericUpdownStyle_Strength" TargetType="inputToolkit:NumericUpDown">
    <Setter Property="Width" Value="Auto"></Setter>
    <Setter Property="MinWidth" Value="50"></Setter>
    <Setter Property="Height" Value="20"></Setter>
    <Setter Property="Minimum" Value="-28"></Setter>
    <Setter Property="Maximum" Value="28"></Setter>
    <Setter Property="BorderThickness" Value="0"></Setter>
    <Setter Property="BorderBrush" Value="White"></Setter>
    <Setter Property="DecimalPlaces" Value="2"></Setter>
    <Setter Property="Increment" Value="0.25"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="inputToolkit:NumericUpDown">
                <Grid>
                    <VisualStateManager.VisualStateGroups>

                        <VisualStateGroup x:Name="CommonStates">
                            <VisualStateGroup.Transitions>
                                <VisualTransition GeneratedDuration="0"/>
                            </VisualStateGroup.Transitions>
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="(UIElement.Opacity)" To="1"/>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="FocusStates">
                            <VisualState x:Name="Focused">
                                <Storyboard>
                                    <DoubleAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity">
                                        <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                    </DoubleAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Unfocused"/>
                        </VisualStateGroup>

                        <VisualStateGroup x:Name="ValidationStates">
                            <VisualState x:Name="Valid"/>
                            <VisualState x:Name="InvalidUnfocused">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="InvalidFocused">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsOpen">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <sys:Boolean>True</sys:Boolean>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>

                    </VisualStateManager.VisualStateGroups>
                    <inputToolkit:ButtonSpinner x:Name="Spinner" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" MinWidth="35">
                        <StackPanel Background="White" Orientation="Horizontal" HorizontalAlignment="Right" Width="Auto">
                            <TextBox x:Name="Text"  Style="{StaticResource TextBoxStyle}" TabIndex="0"
                                 BorderThickness="0" FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" FontStretch="{TemplateBinding FontStretch}" FontStyle="{TemplateBinding FontStyle}" FontWeight="{TemplateBinding FontWeight}" Foreground="{TemplateBinding Foreground}" MinWidth="50" Width="Auto"  AcceptsReturn="False" Text="{TemplateBinding Value}" TextAlignment="Left" TextWrapping="NoWrap"/>
                        </StackPanel>
                    </inputToolkit:ButtonSpinner>
                    <Border x:Name="DisabledVisualElement" IsHitTestVisible="false" Opacity="0" Background="#A5FFFFFF" CornerRadius="2.5,2.5,2.5,2.5"/>
                    <Border x:Name="FocusVisualElement" IsHitTestVisible="False" Opacity="0" BorderBrush="#FF45D6FA" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1,1,1,1"/>
                    <Border x:Name="ValidationErrorElement" Visibility="Collapsed" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1">
                        <ToolTipService.ToolTip>
                            <ToolTip x:Name="validationTooltip" Height="Auto" Width="Auto" Template="{StaticResource ValidationToolTipTemplate}" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}">
                                <ToolTip.Triggers>
                                    <EventTrigger RoutedEvent="Canvas.Loaded">
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsHitTestVisible">
                                                    <DiscreteObjectKeyFrame KeyTime="0">
                                                        <DiscreteObjectKeyFrame.Value>
                                                            <sys:Boolean>true</sys:Boolean>
                                                        </DiscreteObjectKeyFrame.Value>
                                                    </DiscreteObjectKeyFrame>
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </EventTrigger>
                                </ToolTip.Triggers>
                            </ToolTip>
                        </ToolTipService.ToolTip>
                        <Grid Height="12" HorizontalAlignment="Right" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12" Background="Transparent">
                            <Path Fill="#FFDC000C" Margin="1,3,0,0" Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z"/>
                            <Path Fill="#ffffff" Margin="1,3,0,0" Data="M 0,0 L2,0 L 8,6 L8,8"/>
                        </Grid>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

I found bug while running appliction build using above code.

To solve that bug I want read value that entered TextBox defined inside <inputToolkit:ButtonSpinner > </inputToolkit:ButtonSpinner >  "Text" defined in the style of  App.xaml  for the NumericUpDown control.

How do i read value from textBox at run time on ValueChainging/ValueChanged/GotFocus/LostFocust or any other event of NumericUpDown control.

答:
Your inputToolkit:ButtonSpinner control has a name in the Template i.e. Spinner

So using that you can get the control as below (only after the Visual Tree is fully formed such as after Load event)...

```<code> var mySpinner = myNumericUpDownControl.Template.FindName("Spinner", myNumericUpDownControl)
</code>```

your myNumericUpDownControl can be directly named as myNumericUpDownControl in XAML or you can have an attached behavior to extract the spinner control out of it. Whatever decision you take, make sure you do that after VisualTree is fully formed otherwise FindName will fail.

Let me know if this helps.

Body:
I am using NumericUpDown control in my silver-light application. Code is as follows

 <StackPanel Style="{StaticResource StackPanelStyle_LableValue}">
                        <TextBlock Text="{Binding Path=ViewItem.Strength, Source={StaticResource LocalizedStrings }}" Style="{StaticResource TextBlockStyle}" />
                        <inputToolkit:NumericUpDown Style="{StaticResource NumericUpdownStyle_Strength}"
                                                    Value="{Binding RightSpecGlassStrength, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}"
                                                    TabIndex="5" />
                    </StackPanel>

and Style that i bind to NumericUpDown control as follows

I found bug while running appliction build using above code.

To solve that bug I want read value that entered TextBox defined inside <inputToolkit:ButtonSpinner > </inputToolkit:ButtonSpinner >  "Text" defined in the style of  App.xaml  for the NumericUpDown control.

How do i read value from textBox at run time on ValueChainging/ValueChanged/GotFocus/LostFocust or any other event of NumericUpDown control.

Body:
Your inputToolkit:ButtonSpinner control has a name in the Template i.e. Spinner

So using that you can get the control as below (only after the Visual Tree is fully formed such as after Load event)...

 var mySpinner = myNumericUpDownControl.Template.FindName("Spinner", myNumericUpDownControl)

your myNumericUpDownControl can be directly named as myNumericUpDownControl in XAML or you can have an attached behavior to extract the spinner control out of it. Whatever decision you take, make sure you do that after VisualTree is fully formed otherwise FindName will fail.

Let me know if this helps.


问:
Tkinter winfo on TabControl
I have Python Tkinter Tab with a label on the second tab. I want to find the label's y and height parameters. Here is what I have done:

```<code>#! python

from tkinter import *
from tkinter import ttk

main = Tk()
main.geometry('450x400')

tabControl = ttk.Notebook(main)
tab1 = Frame(tabControl)
tab2 = Frame(tabControl)

tabControl.add(tab1, text ='Tab Heading 1')
tabControl.add(tab2, text ='Tab Heading 2')

tabControl.pack(expand = 1, fill ="both")

Label(tab1,text="Label on Tab 1").place(x=20, y=40)

Label(tab2,text ="Label on Tab 2").pack(padx=20, pady=(0,30))
L = Label(tab2,text ="Another Tab2 Label")
L.pack()

#tab2.pack()
tab2.update()

print ( L.winfo_y(), L.winfo_height() )

main.mainloop()
</code>```

As the code is written, the print statement prints 0, 1; a clearly incorrect result.
If I uncomment tab2.pack(), the print statement gives 51, 21; presumably the correct values for y and height. However, it also disables tab2. The Label on Tab2 moves to where the Heading was and tab2 is inaccessible even using the Tab key. How can I get the label parameters and have a working tab?

答:
Ok I have found where is the problem.
The problem is'nt the tab2.pack().

In fact, the problem relies on the position of the "L" label when the tab2 is'nt selected. (do you follow me ?)
I'm not sure but I think the Label "L" is'nt visible, but it is actually on the screen when you have selected the tab1.

I have confirmed it by trying to print the position after one second after opening the window, and quickly go on the tab2 when opened. And it printed me "51 21".

But if I don't go on the tab2 after one second, it prints me "0 1".

So if you have understood what I have said, you can now try to fix your code ( I can't because I dont know what were your intentions were. Why did you want the position of the "L" label.)

Welcome

Title: Tkinter winfo on TabControl

Body:
I have Python Tkinter Tab with a label on the second tab. I want to find the label's y and height parameters. Here is what I have done:

#! python

from tkinter import *
from tkinter import ttk

main = Tk()
main.geometry('450x400')

tabControl = ttk.Notebook(main)
tab1 = Frame(tabControl)
tab2 = Frame(tabControl)

tabControl.add(tab1, text ='Tab Heading 1')
tabControl.add(tab2, text ='Tab Heading 2')

tabControl.pack(expand = 1, fill ="both")

Label(tab1,text="Label on Tab 1").place(x=20, y=40)

Label(tab2,text ="Label on Tab 2").pack(padx=20, pady=(0,30))
L = Label(tab2,text ="Another Tab2 Label")
L.pack()

#tab2.pack()
tab2.update()

print ( L.winfo_y(), L.winfo_height() )

main.mainloop()

As the code is written, the print statement prints 0, 1; a clearly incorrect result.
If I uncomment tab2.pack(), the print statement gives 51, 21; presumably the correct values for y and height. However, it also disables tab2. The Label on Tab2 moves to where the Heading was and tab2 is inaccessible even using the Tab key. How can I get the label parameters and have a working tab?


问:
How to avoid for loop in spark?
I've a use case as below in PySpark:

```<code>df.show()
emp_no dept_no emp_name emp_address location
 1.     10.     ABC.     AAA.         X
 2.     20.     DEF.     CCC.         Y
 3.     20.     GHI.     DDD.         Z
 4.     10.     JKL.     EEE.         Y
</code>```

And, I've below 2 lists:

```<code>dept_list = [10, 20]
location_list = ['Y', 'Z']
</code>```

now i'm iterating lists for data-frame and doing joining as below:

```<code>lst = []
for a, b in zip(dept_list, location_list):
  df1 = df.where(col('dept_no' == a))
  df2 = df.where(col('location' == b))
  join_conditions = [df1.dept_no==df2.dept_no, df1.emp_address==df2.emp_address]
  result_df = df1.join(df2, join_conditions, how="inner").select(df1.emp_id, df1.emp_name)
  lst.append(result_df)
</code>```

Finally doing union of all as below:

```<code>from functools import reduce
from pyspark.sql import DataFrame
final_df = reduce(DataFrame.union, lst)
</code>```

Now final result:

```<code>final_df.show()
emp_no emp_name
  4.   JKL
  3.   GHI
</code>```

How can I avoid this FOR loop ?

EDIT1:
if we have similar lists for same column [i.e., location] then how to use ?
For example:

```<code>location_list_1 = ['X', 'Y']
location_list_2 = ['Z', 'Z'] # value can be repeated here, but len(location_list_1)=len(location_list_2)

lst = []
for a, b in zip(location_list_1, location_list_2):
  df1 = df.where(col('location' == a))
  df2 = df.where(col('location' == b))
  join_conditions = [df1.dept_no==df2.dept_no, df1.emp_address==df2.emp_address]
  result_df = df1.join(df2, join_conditions, how="fullouter").select(nvl(df1.emp_id, df2.emp_id), nvl(df1.emp_name, df2.emp_name))
  lst.append(result_df)
</code>```

And output should be:

```<code>emp_no emp_name
  1.   ABC  # from 1st iteration in FOR loop [for location 'X' & 'Z']
  3.   GHI  # from 1st iteration in FOR loop [for location 'X' & 'Z']
  2.   DEF  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']
  4.   JKL  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']
  3.   GHI  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']

# Here, 3-GHI should come twice.
</code>```

Here similarly, how to avoid FOR loop ?

答:
If emp_address is not unique then perform a self-join on it (df.join(df, 'emp_address')) and then filter using the following condition: (dept_no, location) in zip(dept_list, location_list).

The easiest way to do this would be to create a tiny UDF:

```<code>def check(x, y):
  return (x,y) in zip(list1, list2)

f = udf(check, StringType(), IntegerType())
df.filter(f(col(x), col(y))
</code>```

Alternatively, you can concatenate the two columns as strings (using some separator) - then you can use isin:

```<code>my_list = [f'{x}:::{y}' for x, y in zip(list1, list2)]
df.filter(concatenate(col(x), lit(':::'), col(y)).isin(my_list))
</code>```

You may need to pass some parameters like r_suffix to the join since you have the same column names on both sides of the join.

If your joins are anything but inner, you need to join first before filtering. Otherwise, filter first so you have fewer rows to join.

Title: How to avoid for loop in spark?

Body:
I've a use case as below in PySpark:

df.show()
emp_no dept_no emp_name emp_address location
 1.     10.     ABC.     AAA.         X
 2.     20.     DEF.     CCC.         Y
 3.     20.     GHI.     DDD.         Z
 4.     10.     JKL.     EEE.         Y

And, I've below 2 lists:

dept_list = [10, 20]
location_list = ['Y', 'Z']

now i'm iterating lists for data-frame and doing joining as below:

lst = []
for a, b in zip(dept_list, location_list):
  df1 = df.where(col('dept_no' == a))
  df2 = df.where(col('location' == b))
  join_conditions = [df1.dept_no==df2.dept_no, df1.emp_address==df2.emp_address]
  result_df = df1.join(df2, join_conditions, how="inner").select(df1.emp_id, df1.emp_name)
  lst.append(result_df)

Finally doing union of all as below:

from functools import reduce
from pyspark.sql import DataFrame
final_df = reduce(DataFrame.union, lst)

Now final result:

final_df.show()
emp_no emp_name
  4.   JKL
  3.   GHI

How can I avoid this FOR loop ?

EDIT1:
if we have similar lists for same column [i.e., location] then how to use ?
For example:

location_list_1 = ['X', 'Y']
location_list_2 = ['Z', 'Z'] # value can be repeated here, but len(location_list_1)=len(location_list_2)

lst = []
for a, b in zip(location_list_1, location_list_2):
  df1 = df.where(col('location' == a))
  df2 = df.where(col('location' == b))
  join_conditions = [df1.dept_no==df2.dept_no, df1.emp_address==df2.emp_address]
  result_df = df1.join(df2, join_conditions, how="fullouter").select(nvl(df1.emp_id, df2.emp_id), nvl(df1.emp_name, df2.emp_name))
  lst.append(result_df)

And output should be:

emp_no emp_name
  1.   ABC  # from 1st iteration in FOR loop [for location 'X' & 'Z']
  3.   GHI  # from 1st iteration in FOR loop [for location 'X' & 'Z']
  2.   DEF  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']
  4.   JKL  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']
  3.   GHI  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']

# Here, 3-GHI should come twice.

Here similarly, how to avoid FOR loop ?

Body:
If emp_address is not unique then perform a self-join on it (df.join(df, 'emp_address')) and then filter using the following condition: (dept_no, location) in zip(dept_list, location_list).

The easiest way to do this would be to create a tiny UDF:

def check(x, y):
  return (x,y) in zip(list1, list2)

f = udf(check, StringType(), IntegerType())
df.filter(f(col(x), col(y))

Alternatively, you can concatenate the two columns as strings (using some separator) - then you can use isin:

my_list = [f'{x}:::{y}' for x, y in zip(list1, list2)]
df.filter(concatenate(col(x), lit(':::'), col(y)).isin(my_list))

You may need to pass some parameters like r_suffix to the join since you have the same column names on both sides of the join.

If your joins are anything but inner, you need to join first before filtering. Otherwise, filter first so you have fewer rows to join.


问:
How to go to another window on button click?
I have several windows in my .py file so that the user can switch to another window on button click. However, I don't want the window to open as a new one, a.k.a. pop up. Rather, I want the old window (tkWindow1) to simply be replaced by the new one (tkWindow2). How can I do something like that?

```<code>def download:
    function body

tkWindow1 = Tk()

button = Button(tkWindow1, command=someFunction)
</code>```

like this:

答:
The simplest solution is to create a function or class to define the contents of the window before and after the click, and then just delete the original contents and replace with the new.</p>
```<code>import tkinter as tk

class LandingPage(tk.Frame):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)

        button = tk.Button(self, text="Enter", command=begin_download)
        button.place(relx=.5, rely=.5, anchor="c")

class DownloadPage(tk.Frame):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)

        label = tk.Label(self, text="Your download has begun!")
        label.place(relx=.5, rely=.5, anchor="c")

def begin_download():
    for child in root.winfo_children():
        child.destroy()
    download_page = DownloadPage(root)
    download_page.pack(fill="both", expand=True)

def main():
    global root
    root = tk.Tk()
    root.geometry("400x400")
    root.configure()
    landing_page = LandingPage(root)
    landing_page.pack(fill="both", expand=True)
    root.mainloop()

main()
</code>```

Body:
I have several windows in my .py file so that the user can switch to another window on button click. However, I don't want the window to open as a new one, a.k.a. pop up. Rather, I want the old window (tkWindow1) to simply be replaced by the new one (tkWindow2). How can I do something like that?

def download:
    function body

tkWindow1 = Tk()

button = Button(tkWindow1, command=someFunction)

like this:

Body:
The simplest solution is to create a function or class to define the contents of the window before and after the click, and then just delete the original contents and replace with the new.

import tkinter as tk

class LandingPage(tk.Frame):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)

        button = tk.Button(self, text="Enter", command=begin_download)
        button.place(relx=.5, rely=.5, anchor="c")

class DownloadPage(tk.Frame):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)

        label = tk.Label(self, text="Your download has begun!")
        label.place(relx=.5, rely=.5, anchor="c")

def begin_download():
    for child in root.winfo_children():
        child.destroy()
    download_page = DownloadPage(root)
    download_page.pack(fill="both", expand=True)

def main():
    global root
    root = tk.Tk()
    root.geometry("400x400")
    root.configure()
    landing_page = LandingPage(root)
    landing_page.pack(fill="both", expand=True)
    root.mainloop()

main()


问:
Trying to loop over JSON keys
i have been wondering how to solve the following problem.

you have a JSON like this and you parse using serde.

```<code>{
    "student_name": "this guy",
    "subjects": [{"Chemistry": 0},
                {"Politics": 0},
                {"Biology": 0},
                {"Art": 0}],
}
</code>```

then use a struct to map the types

```<code>struct Environment {
    student_name: String,
    subjects: Vec<HashMap<String, i32>>,
}
</code>```

but when you try to loop over the keys from the
subjects Vector you get all kinds of nasty errors like this one

```<code>error[E0308]: mismatched types
  --> src/main.rs:15:9
   |
15 |     for (key, val) in json.subjects.iter() {
   |         ^^^^^^^^^^    -------------------- this expression has type std::option::Option<&HashMap<std::string::String, i32>>`
   |         |
   |         expected struct `HashMap`, found tuple
   |
note: expected struct `HashMap<std::string::String, i32>`
               found tuple `(_, _)`

</code>```

this is all the code, i would really be greatful of someone helping me out. i really lost all hope; thank you beforehand.

```<code>use serde_derive::Deserialize;
use serde_json::Result;
use std::{collections::HashMap, fs};

#[derive(Deserialize, Clone)]
struct Environment {
    student_name: String,
    subjects: Vec<HashMap<String, i32>>
}

fn data_parser() -> Result<()> {
    let data = fs::read_to_string("./src/data.json").unwrap();
    let json = serde_json::from_str::<Environment>(&data)?;
    for (key, val) in json.subjects.iter() {
        println!("{}", key);
        println!("----------------------");
    }
    Ok(())
}

fn main() {
    data_parser();
}

</code>```

答:
A subject is a <HashMap<String, i32>. Try iterating through every subject.

```<code>fn data_parser() -> Result<()> {
    let data = fs::read_to_string("./src/data.json").unwrap();
    let json = serde_json::from_str::<Environment>(&data)?;
    for subject in json.subjects.iter() {
        for (_key, value) in subject {
            println!("{}", value);
            println!("----------------------");
        }
    }
    Ok(())
}
</code>```

Or, better yet, you can "forget" about loops altogether:

```<code> json.subjects
        .iter()
        .flat_map(|s| s.iter())
        .for_each(|(key, value)| {
            println!("{key}: {value}");
            println!("----------------------");
        });
</code>```

Title: Trying to loop over JSON keys

Body:
i have been wondering how to solve the following problem.

you have a JSON like this and you parse using serde.

{
    "student_name": "this guy",
    "subjects": [{"Chemistry": 0},
                {"Politics": 0},
                {"Biology": 0},
                {"Art": 0}],
}

then use a struct to map the types

struct Environment {
    student_name: String,
    subjects: Vec<HashMap<String, i32>>,
}

but when you try to loop over the keys from the
subjects Vector you get all kinds of nasty errors like this one

error[E0308]: mismatched types
  --> src/main.rs:15:9
   |
15 |     for (key, val) in json.subjects.iter() {
   |         ^^^^^^^^^^    -------------------- this expression has type std::option::Option<&HashMap<std::string::String, i32>>`
   |         |
   |         expected struct `HashMap`, found tuple
   |
note: expected struct `HashMap<std::string::String, i32>`
               found tuple `(_, _)`

this is all the code, i would really be greatful of someone helping me out. i really lost all hope; thank you beforehand.

use serde_derive::Deserialize;
use serde_json::Result;
use std::{collections::HashMap, fs};

#[derive(Deserialize, Clone)]
struct Environment {
    student_name: String,
    subjects: Vec<HashMap<String, i32>>
}

fn data_parser() -> Result<()> {
    let data = fs::read_to_string("./src/data.json").unwrap();
    let json = serde_json::from_str::<Environment>(&data)?;
    for (key, val) in json.subjects.iter() {
        println!("{}", key);
        println!("----------------------");
    }
    Ok(())
}

fn main() {
    data_parser();
}

Body:
A subject is a <HashMap<String, i32>. Try iterating through every subject.

fn data_parser() -> Result<()> {
    let data = fs::read_to_string("./src/data.json").unwrap();
    let json = serde_json::from_str::<Environment>(&data)?;
    for subject in json.subjects.iter() {
        for (_key, value) in subject {
            println!("{}", value);
            println!("----------------------");
        }
    }
    Ok(())
}

Or, better yet, you can "forget" about loops altogether:

 json.subjects
        .iter()
        .flat_map(|s| s.iter())
        .for_each(|(key, value)| {
            println!("{key}: {value}");
            println!("----------------------");
        });


答:
You collection is of type Vec<HashMap<String, i32>>, so you are given references to HashMap<String, i32> when iterating, you can flat_map over those as iterators also to actually get what you need:

for (key, val) in json.subjects.iter().flat_map(|d| d.iter()) {
    println!("{}", key);
    println!("----------------------");
}
```

Playground

Title: Trying to loop over JSON keys

Body:
You collection is of type Vec<HashMap<String, i32>>, so you are given references to HashMap<String, i32> when iterating, you can flat_map over those as iterators also to actually get what you need:

for (key, val) in json.subjects.iter().flat_map(|d| d.iter()) {
    println!("{}", key);
    println!("----------------------");
}

Playground


问:
How to get the indexes of all minimum values in pandas dataframe?
I have a dataframe:

```<code>df = pd.DataFrame({'A': [0, 0, 1], 'B': [1, 0, 0]}, index=['x', 'y', 'z'])

   A  B
x  0  1
y  0  0
z  1  0
</code>```

For each row, I want the names of all the columns with the lowest value (edit: per row), something like:

```<code>x  A
y  A
y  B
z  B

# or

x  [A]
y  [A, B]
z  [B]
</code>```

I know idxmin() gives the first instance of the lowest value:

```<code>df.idxmin(axis=1)

x    A
y    A
z    B
</code>```

But what is an efficient way to get all of them?

This question gives all of the rows with the minimum value in a specific column, but that's not quite what I want.

Edit: Here's a better toy df to play with for getting the column names with the minimum value in each row:

```<code>df2 = pd.DataFrame({'A': [1, 0, 6], 'B': [3, 0, 2]}, index=['x', 'y', 'z'])

   A  B
x  1  3
y  0  0
z  6  2
</code>```

答:
This is a one-liner, similar to @mozway's second solution but uses a boolean mask similar to @wwnde's:

```<code>min_cols = df.eq(df.min(axis=1), axis=0).stack().groupby(level=0).apply(lambda x: x.index.get_level_values(1)[x].tolist())
</code>```

Output:

```<code>x       [A]
y    [A, B]
z       [B]
</code>```

Body:
I have a dataframe:

df = pd.DataFrame({'A': [0, 0, 1], 'B': [1, 0, 0]}, index=['x', 'y', 'z'])

   A  B
x  0  1
y  0  0
z  1  0

For each row, I want the names of all the columns with the lowest value (edit: per row), something like:

x  A
y  A
y  B
z  B

# or

x  [A]
y  [A, B]
z  [B]

I know idxmin() gives the first instance of the lowest value:

df.idxmin(axis=1)

x    A
y    A
z    B

But what is an efficient way to get all of them?

This question gives all of the rows with the minimum value in a specific column, but that's not quite what I want.

Edit: Here's a better toy df to play with for getting the column names with the minimum value in each row:

df2 = pd.DataFrame({'A': [1, 0, 6], 'B': [3, 0, 2]}, index=['x', 'y', 'z'])

   A  B
x  1  3
y  0  0
z  6  2

Body:
This is a one-liner, similar to @mozway's second solution but uses a boolean mask similar to @wwnde's:

min_cols = df.eq(df.min(axis=1), axis=0).stack().groupby(level=0).apply(lambda x: x.index.get_level_values(1)[x].tolist())

Output:

x       [A]
y    [A, B]
z       [B]


答:
Here is a potential approach:

```<code># ensure datetime type for meaningful comparisons
df['end'] = pd.to_datetime(df['end'])
df['start'] = pd.to_datetime(df['start'])

# sort by start time
df = df.sort_values(by='start')

# valid data have a start time greater than the previous end time
# or no previous time (NaT in the shift)
s = df.groupby('user')['end'].shift()
df[df['start'].gt(s)|s.isna()]
</code>```

Output:

```<code>  user               start                 end
3  Dan 2020-01-01 06:30:00 2020-01-01 10:00:00
1  Dan 2020-01-01 16:20:00 2020-01-02 01:00:00
4  Ron 2020-01-01 17:00:00 2020-01-01 21:00:00
</code>```

Title: Removing Rows With The Same Id Based On Overlapping Time

Body:
I have the following dataframe

df = pd.DataFrame({'user':['Dan','Dan','Dan','Dan','Ron'], 'start':['2020-01-01 17:00:00',
'2020-01-01 16:20:00','2020-01-01 17:00:00', '2020-01-01 06:30:00','2020-01-01 17:00:00'],
'end':['2020-01-01 21:00:00', '2020-01-02 01:00:00','2020-01-01 21:15:00',
'2020-01-01 10:00:00','2020-01-01 21:00:00']})

user
start
end

Dan
2020-01-01 17:00:00
2020-01-01 21:00:00

Dan
2020-01-01 16:20:00
2020-01-02 01:00:00

Dan
2020-01-01 17:00:00
2020-01-01 21:15:00

Dan
2020-01-01 06:30:00
2020-01-01 10:00:00

Ron
2020-01-01 17:00:00
2020-01-01 21:00:00

For the same user, I would like to leave just one of the records which have overlapping start-end time intervals (no matter which) for example:

user
start
end

Dan
2020-01-01 17:00:00
2020-01-01 21:00:00

Dan
2020-01-01 06:30:00
2020-01-01 10:00:00

Ron
2020-01-01 17:00:00
2020-01-01 21:00:00

My try, for a given user to run:

idx, single_user, single_start, single_end = df.to_records()[0]
a = df.loc[((df['user'] == single_user) & ((df['start'] < single_start) & (df['end']< single_end))
|((df['start']> single_start) &(df['end'] > single_end)))].index.tolist()
a.append(df.iloc[idx].name)

And obtain the result using:

test_df.iloc[a]

There must be a better way, is there a pandas method to tackle it?

Body:
Here is a potential approach:

# ensure datetime type for meaningful comparisons
df['end'] = pd.to_datetime(df['end'])
df['start'] = pd.to_datetime(df['start'])

# sort by start time
df = df.sort_values(by='start')

# valid data have a start time greater than the previous end time
# or no previous time (NaT in the shift)
s = df.groupby('user')['end'].shift()
df[df['start'].gt(s)|s.isna()]

Output:

  user               start                 end
3  Dan 2020-01-01 06:30:00 2020-01-01 10:00:00
1  Dan 2020-01-01 16:20:00 2020-01-02 01:00:00
4  Ron 2020-01-01 17:00:00 2020-01-01 21:00:00


问:
Multiple cursors appearing in each cell in Jupyter notebook
I'm getting a separate cursor for each cell. After execution of one cell, the cursor does not move to the other and when I click on the next cell the cursor appears in previous and present both.
CLICK TO SEE THE IMAGE</p>

答:
Was researching this problem and found an answer;
the answer happens to be from your post as well!

Solution 1: Change the default browser (link)

Solution 2: Reset the browser to factory settings (link)


问:
How to Reduce redundant code of If-Else Statements in Python
How to Reduce Code Duplication of If-Else Statements in Python from below function. Also, which specific exception can i raise here?</p>
```<code>def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
    try:
        table_id=f"{database}_stg.{table}"
        gcp_path = f"gs://{env}/{database}/{table}/"
        if dc != '-1':
            table_id = table_id + '_' + dc + '_stg'
            gcp_path = gcp_path + dc + "/dt=" + date_folder + "/*.parquet"
        else:
            table_id = table_id + '_stg'
            gcp_path = gcp_path + "dt=" + date_folder + "/*.parquet"

    except Exception as e:
        print(e)
        raise

    return table_id, gcp_path
</code>```

答:
```<code>
def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
    try:
        table_id=f"{database}_stg.{table}"
        gcp_path = f"gs://{env}/{database}/{table}/"
        table_id = table_id + '_' + dc + '_stg' if dc != '-1' else table_id + '_stg'
        gcp_path = gcp_path + dc + "/dt=" + date_folder + "/*.parquet" if dc != '-1' else gcp_path + "dt=" + date_folder + "/*.parquet"
    except Exception as e:
        print(e)
        raise

    return table_id, gcp_path

</code>```

or in one line

```<code>
def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
    try:
        table_id=f"{database}_stg.{table}"
        gcp_path = f"gs://{env}/{database}/{table}/"
        gcp_path,table_id = (gcp_path + dc + "/dt=" + date_folder + "/*.parquet" , table_id + '_' + dc + '_stg') if dc != '-1' else (gcp_path + "dt=" + date_folder + "/*.parquet",table_id + '_stg')
    except Exception as e:
        print(e)
        raise

    return table_id, gcp_path

</code>```

Body:
How to Reduce Code Duplication of If-Else Statements in Python from below function. Also, which specific exception can i raise here?

def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
    try:
        table_id=f"{database}_stg.{table}"
        gcp_path = f"gs://{env}/{database}/{table}/"
        if dc != '-1':
            table_id = table_id + '_' + dc + '_stg'
            gcp_path = gcp_path + dc + "/dt=" + date_folder + "/*.parquet"
        else:
            table_id = table_id + '_stg'
            gcp_path = gcp_path + "dt=" + date_folder + "/*.parquet"

    except Exception as e:
        print(e)
        raise

    return table_id, gcp_path

Body:
def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
    try:
        table_id=f"{database}_stg.{table}"
        gcp_path = f"gs://{env}/{database}/{table}/"
        table_id = table_id + '_' + dc + '_stg' if dc != '-1' else table_id + '_stg'
        gcp_path = gcp_path + dc + "/dt=" + date_folder + "/*.parquet" if dc != '-1' else gcp_path + "dt=" + date_folder + "/*.parquet"
    except Exception as e:
        print(e)
        raise

    return table_id, gcp_path

or in one line

def get_table_id_and_gcp_path(source, database, table, dc, env, date_folder):
    try:
        table_id=f"{database}_stg.{table}"
        gcp_path = f"gs://{env}/{database}/{table}/"
        gcp_path,table_id = (gcp_path + dc + "/dt=" + date_folder + "/*.parquet" , table_id + '_' + dc + '_stg') if dc != '-1' else (gcp_path + "dt=" + date_folder + "/*.parquet",table_id + '_stg')
    except Exception as e:
        print(e)
        raise

    return table_id, gcp_path


问:
2D summary plot with counts as labels
I have measurements of a quantity (value) at specific points (lon and lat), like the example data below:

```<code>library(ggplot2)
set.seed(1)
dat <- data.frame(lon = runif(1000, 1, 15),
                  lat = runif(1000, 40, 60),
                  value = rnorm(1000))
</code>```

I want to make a 2D summary (e.g. mean) of the measured values with color in space and on top of that I want to show the counts as labels.

I can plot the labels and to the summary plot

```<code>## Left plot
ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex")
## Right plot
ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_binhex(aes(label = ..count..), bins = 5, geom = "text")
</code>```

But when I combine both I loose the summary:

```<code>ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count..), bins = 5, geom = "text")
</code>```

I can achieve the opposite, counts as color and summary as labels:

```<code>ggplot(dat, aes(lon, lat, z = value)) +
  geom_hex(bins = 5) +
  stat_summary_hex(aes(label=..value..), bins = 5,
                   fun = function(x) round(mean(x), 3),
                   geom = "text")
</code>```

答:
While writing the question, which took some hours of testing, I found a solution: adding a fill=NULL, or fill=mean(value) in the text one gives me what I want. Below the code and their resulting plots; the only difference is the label of the legend.

But it feels very hacky, so I would appreciate a better solution.

```<code>ggplot(dat) +
  aes(x = lon, y = lat, z = value)  +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count.., fill = NULL), bins = 5, geom = "text") +
  theme_bw()

ggplot(dat) +
  aes(x = lon, y = lat, z = value)  +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count.., fill = mean(value)), bins = 5, geom = "text") +
  theme_bw()
</code>```

Title: 2D summary plot with counts as labels

Body:
I have measurements of a quantity (value) at specific points (lon and lat), like the example data below:

library(ggplot2)
set.seed(1)
dat <- data.frame(lon = runif(1000, 1, 15),
                  lat = runif(1000, 40, 60),
                  value = rnorm(1000))

I want to make a 2D summary (e.g. mean) of the measured values with color in space and on top of that I want to show the counts as labels.

I can plot the labels and to the summary plot

## Left plot
ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex")
## Right plot
ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_binhex(aes(label = ..count..), bins = 5, geom = "text")

But when I combine both I loose the summary:

ggplot(dat) +
  aes(x = lon, y = lat, z = value) +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count..), bins = 5, geom = "text")

I can achieve the opposite, counts as color and summary as labels:

ggplot(dat, aes(lon, lat, z = value)) +
  geom_hex(bins = 5) +
  stat_summary_hex(aes(label=..value..), bins = 5,
                   fun = function(x) round(mean(x), 3),
                   geom = "text")

Body:
While writing the question, which took some hours of testing, I found a solution: adding a fill=NULL, or fill=mean(value) in the text one gives me what I want. Below the code and their resulting plots; the only difference is the label of the legend.

But it feels very hacky, so I would appreciate a better solution.

ggplot(dat) +
  aes(x = lon, y = lat, z = value)  +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count.., fill = NULL), bins = 5, geom = "text") +
  theme_bw()

ggplot(dat) +
  aes(x = lon, y = lat, z = value)  +
  stat_summary_hex(bins = 5, fun = "mean", geom = "hex") +
  stat_binhex(aes(label = ..count.., fill = mean(value)), bins = 5, geom = "text") +
  theme_bw()


问:
Extending a class that has injected services without duplicating injectors in child class?
Ok, so I'm getting deep into TypeScript inheritance (specifically in Angular 11), and I've set up a BasePageComponent to provide all the necessary functions and services that exist across pages.
The issue I've run into, is that now my base is getting bloated, because there are services that are used only on one or two pages, but in order to extend the base, we have included those in the base.

export class BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    public exampleOneOffService: ExampleOneOffService
  ) {}
}
```
<p>I realize that it would be more performant to repeat all the injected services, and then pass them all up to <code>BasePageComponent</code> as so:</p>
<pre class="lang-js prettyprint-override"><code>export class ChildPageComponent extends BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    private exampleOneOffService: ExampleOneOffService
  ) {
    super(uiPopupService, loaderService, questionService, aBunchOfOthers);
  }
}
</code>```

I will do the above, if there's no other way, but I have as hinted at in the sample code, I have a bunch of other micro services that are included in the base (like 15-20), so I want to be able to do something like this, where I just declare the one additional service, and still inherit all the others from the parent class, but I am not seeing a way to do this.

export class ChildPageComponent extends BasePageComponent {

  constructor(private otherExampleService: OtherExampleService){
    super()
  };
}
```

Does this pattern exist and I'm just not googling the right keyword?

答:
This is not how the DI works.

The DI will provide to you the parameters of your constructor. It has no knowlegde of the parent class.

The parent classes will get nothing from the DI if it's called from a subclass. In this case, the parameters are passed via super()

Body:
Ok, so I'm getting deep into TypeScript inheritance (specifically in Angular 11), and I've set up a BasePageComponent to provide all the necessary functions and services that exist across pages.
The issue I've run into, is that now my base is getting bloated, because there are services that are used only on one or two pages, but in order to extend the base, we have included those in the base.

export class BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    public exampleOneOffService: ExampleOneOffService
  ) {}
}

I realize that it would be more performant to repeat all the injected services, and then pass them all up to BasePageComponent as so:

export class ChildPageComponent extends BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    private exampleOneOffService: ExampleOneOffService
  ) {
    super(uiPopupService, loaderService, questionService, aBunchOfOthers);
  }
}

I will do the above, if there's no other way, but I have as hinted at in the sample code, I have a bunch of other micro services that are included in the base (like 15-20), so I want to be able to do something like this, where I just declare the one additional service, and still inherit all the others from the parent class, but I am not seeing a way to do this.

export class ChildPageComponent extends BasePageComponent {

  constructor(private otherExampleService: OtherExampleService){
    super()
  };
}

Does this pattern exist and I'm just not googling the right keyword?


问:
iOS. Capturing photos with volume buttons
Hello there is a bunch of related questions but I would say none of them gives clear answer how to capture photos with volume buttons.

Currently I add observer to AVAudioSession instance but it doesn't work on max and min volume values and seems showing volume status shadow popup over camera.

```<code>private func setupButtonsListener(){
    do {
        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setActive(true)

        audioSession.addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.new, context: nil)
    } catch {
        print("Error")
    }

}
</code>```

Then I handle event in function:

```<code>override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "outputVolume" {
        capturePhoto() // Same function which I use for capturing photo for screen button.
    } else {
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
    }
}
</code>```

Could you recommend me any solution which will:
1. Work even when max/min volume values reached.
2. Won't show volume value popup over screen.

EDIT:

based on @jayesh-kanzariya answer I add how to use JPSVolumeButtonHandler in Swift:

Add pod 'JPSVolumeButtonHandler' to your pod file.

In project's root execute pod install

Configure bridging file for you project and add there: #import <JPSVolumeButtonHandler/JPSVolumeButtonHandler.h>

In you ViewController add following code:

```<code>import JPSVolumeButtonHandler

class YourViewController {
    var volumeHandler: JPSVolumeButtonHandler?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.volumeHandler = JPSVolumeButtonHandler(up: {self.capturePhoto()}, downBlock: {self.capturePhoto()})

        ...
    }
}
</code>```

Done!

答:
A modified version from @user2377805 for use in SwiftUI</p>
```<code>import JPSVolumeButtonHandler

struct ContentView: View {
    @State private var volumeHandler: JPSVolumeButtonHandler?

    var body: some View {
        YourView()
        .onAppear {
            volumeHandler = JPSVolumeButtonHandler(up: {self.capturePhoto()}, downBlock: {self.capturePhoto()})

            volumeHandler?.start(true)
        }
    }
}
</code>```

Body:
Hello there is a bunch of related questions but I would say none of them gives clear answer how to capture photos with volume buttons.

Currently I add observer to AVAudioSession instance but it doesn't work on max and min volume values and seems showing volume status shadow popup over camera.

private func setupButtonsListener(){
    do {
        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setActive(true)

        audioSession.addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.new, context: nil)
    } catch {
        print("Error")
    }

}

Then I handle event in function:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "outputVolume" {
        capturePhoto() // Same function which I use for capturing photo for screen button.
    } else {
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
    }
}

Could you recommend me any solution which will:
1. Work even when max/min volume values reached.
2. Won't show volume value popup over screen.

EDIT:

based on @jayesh-kanzariya answer I add how to use JPSVolumeButtonHandler in Swift:

Add pod 'JPSVolumeButtonHandler' to your pod file.

In project's root execute pod install

Configure bridging file for you project and add there: #import <JPSVolumeButtonHandler/JPSVolumeButtonHandler.h>

In you ViewController add following code:

import JPSVolumeButtonHandler

class YourViewController {
    var volumeHandler: JPSVolumeButtonHandler?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.volumeHandler = JPSVolumeButtonHandler(up: {self.capturePhoto()}, downBlock: {self.capturePhoto()})

        ...
    }
}

Done!

Body:
A modified version from @user2377805 for use in SwiftUI

import JPSVolumeButtonHandler

struct ContentView: View {
    @State private var volumeHandler: JPSVolumeButtonHandler?

    var body: some View {
        YourView()
        .onAppear {
            volumeHandler = JPSVolumeButtonHandler(up: {self.capturePhoto()}, downBlock: {self.capturePhoto()})

            volumeHandler?.start(true)
        }
    }
}


问:
File upload makes Node JS unresponsive with Multer
I am using Multer Node JS package to upload files to my app sever , the code is basically typical upload file code

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})```

But each time a file is being uploaded the Node server becomes unresponsive and frontend from other request doesnt receive any response from other APIs until the file is uploaded.

Whats the best way to tackle this ?

答:
In your sample code, you must just send a response to the client by res.json() or res.end() :

```<code>const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

const app = express();

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any

  res.status(204).end();
});

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any

  res.status(204).end();
});
</code>```

Body:
I am using Multer Node JS package to upload files to my app sever , the code is basically typical upload file code

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

But each time a file is being uploaded the Node server becomes unresponsive and frontend from other request doesnt receive any response from other APIs until the file is uploaded.

Whats the best way to tackle this ?

Body:
In your sample code, you must just send a response to the client by res.json() or res.end() :

const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

const app = express();

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any

  res.status(204).end();
});

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any

  res.status(204).end();
});


问:
Service worker: What to return if no network, and cache miss for a static resource (caching strategy)
I have various caching strategies, .e.g.

A GET for a page: Try network, then cache, else a default page.

However if it is a static resource like a .css or .js file. What should one return if it fails to get a response from the network? If it is not obtained within 4s I know the system is down, and a long timedout out fetch is not ideal.

At the moment I return a 404, but semantically this is not quite right, its not that the resource was not found, it was that the request never got to the server. But it seems like the most applicable 4XX series (client failure) code to me.

    get404Response(statusText = "") {
        const init = { status: 404, statusText: statusText };
        return new Response("", init);
    }
```

Alternatively I don't want to raise a fetch error, because in the chrome dev tools, under application for the service worker, it tracks how many errors your SW has raised, and I am trying to keep track of legitamate errors.

答:
This is a bit of a judgment call, and I don't think you're going to get a definitive answer.

My first preference would be to use Response.error(), though you mentioned that you're wary of logging noise in DevTools. Synthetically creating a Response.error() comes closest to matching the behavior you'd see if you let the request time out on its own.

If you would prefer to return a "valid" (non-error) response but aren't happy with using a 404 status code, then using a 503 might be an alternative? I'm not sure that you're going to see any functional difference worth worrying about, though.

Body:
I have various caching strategies, .e.g.

A GET for a page: Try network, then cache, else a default page.

However if it is a static resource like a .css or .js file. What should one return if it fails to get a response from the network? If it is not obtained within 4s I know the system is down, and a long timedout out fetch is not ideal.

At the moment I return a 404, but semantically this is not quite right, its not that the resource was not found, it was that the request never got to the server. But it seems like the most applicable 4XX series (client failure) code to me.

    get404Response(statusText = "") {
        const init = { status: 404, statusText: statusText };
        return new Response("", init);
    }

Alternatively I don't want to raise a fetch error, because in the chrome dev tools, under application for the service worker, it tracks how many errors your SW has raised, and I am trying to keep track of legitamate errors.