问:
How do inspect.exe or VisualUIAVerifyNative.exe send clicks internally?
I am trying to write a test for a windows form app to automate certain UI actions. I learned I can send clicks to elements(windows) that I have handle of. In my app, certain buttons don’t seem to have a handle ID (Spy++ doesn’t find them) But both inspect.exe and VisualUIAVerifyNative.exe can send clicks when selecting elements in their respective tree views. How do I do the same with windows api?</p>

答:
Both these apps use UI Automation which is a standard Windows API.

For example, let's say you have a window (a Winform for example) that has a button, then you can click on it using the Invoke Pattern with a code like this, in any other application (like a Console app):

```<code>static void Main(string[] args)
{
    // get the app process
    var process = Process.GetProcessesByName("WindowsFormsApp1")[0];

    // get the element corresponding to the main handle (=> the form)
    var element = AutomationElement.FromHandle(process.MainWindowHandle); // needs a reference to UIAutomationClient

    // find the first button in that element
    var button = element.FindFirst(TreeScope.Subtree,
        new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));  // needs a reference to UIAutomationTypes

    // get the pattern and invoke (=> click)
    button.TryGetCurrentPattern(InvokePattern.Pattern, out var p);
    var pattern = (InvokePattern)p;
    pattern.Invoke();
}
</code>```

If you own the form, you can even set the AccessibleName button property to something, for example "MyButton", and get it directly by this name, like this:

```<code>var button = element.FindFirst(TreeScope.Subtree,
    new PropertyCondition(AutomationElement.NameProperty, "MyButton"));
</code>```

Body:
Both these apps use UI Automation which is a standard Windows API.

For example, let's say you have a window (a Winform for example) that has a button, then you can click on it using the Invoke Pattern with a code like this, in any other application (like a Console app):

static void Main(string[] args)
{
    // get the app process
    var process = Process.GetProcessesByName("WindowsFormsApp1")[0];

    // get the element corresponding to the main handle (=> the form)
    var element = AutomationElement.FromHandle(process.MainWindowHandle); // needs a reference to UIAutomationClient

    // find the first button in that element
    var button = element.FindFirst(TreeScope.Subtree,
        new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));  // needs a reference to UIAutomationTypes

    // get the pattern and invoke (=> click)
    button.TryGetCurrentPattern(InvokePattern.Pattern, out var p);
    var pattern = (InvokePattern)p;
    pattern.Invoke();
}

If you own the form, you can even set the AccessibleName button property to something, for example "MyButton", and get it directly by this name, like this:

var button = element.FindFirst(TreeScope.Subtree,
    new PropertyCondition(AutomationElement.NameProperty, "MyButton"));


来源: stackexchange

问:
Expo Permissions returns status of 'undetermined' in Production
In my react native app which I ave published on the Google Play Store, I require Camera Roll permissions. This works during testing, but not in the published version of the app.

```<code>  getPermissionAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (status !== "granted") {
      alert("Sorry, we need camera roll permissions to make this work!");
    }
    await this.setState({ permission: status === "granted" });
  };

  _pickMedia = async () => {
    if (this.state.permission != true) {
      await this.getPermissionAsync();
    }
    if (this.state.permission == true) {
        // get image
    }
  };
</code>```

In testing this works as expected, asking permission to access the camera roll every time the user tries to upload a picture till its given. However in production, the user is prompted once for permission to use the camera roll and whether or not they allow it, the alert box comes up and the user is unable to pick an image. If they try to add media again, they aren't prompted for permissions and it just alerts again.

As per the expo docs I have added READ_EXTERNAL_STORAGE to my permissions in app.json:

```<code>    "android": {
      "permissions": ["READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"],
    }
</code>```

Could someone tell me why this doesn't work in production?

答:
it is not working in production becasue you did not add CAMERA permission.so, add CAMERA permission

```<code>"android": {
      "permissions": ["CAMERA","READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"],
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my react native app which I ave published on the Google Play Store, I require Camera Roll permissions. This works during testing, but not in the published version of the app.

  getPermissionAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (status !== "granted") {
      alert("Sorry, we need camera roll permissions to make this work!");
    }
    await this.setState({ permission: status === "granted" });
  };

  _pickMedia = async () => {
    if (this.state.permission != true) {
      await this.getPermissionAsync();
    }
    if (this.state.permission == true) {
        // get image
    }
  };

In testing this works as expected, asking permission to access the camera roll every time the user tries to upload a picture till its given. However in production, the user is prompted once for permission to use the camera roll and whether or not they allow it, the alert box comes up and the user is unable to pick an image. If they try to add media again, they aren't prompted for permissions and it just alerts again.

As per the expo docs I have added READ_EXTERNAL_STORAGE to my permissions in app.json:

    "android": {
      "permissions": ["READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"],
    }

Could someone tell me why this doesn't work in production?

Body:
it is not working in production becasue you did not add CAMERA permission.so, add CAMERA permission

"android": {
      "permissions": ["CAMERA","READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"],
 }


问:
make site available only from given ip
Is it possible to set my entaire web application available only from given ip address ? Can I use global.asax or something to place the code only in one place and be able to remove this freely ?

Thanks for any hints

答:
```<code>  protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string ip = Request.Params["REMOTE_ADDR"].ToString();
        if (ip == "your-ip")
        {
            // no action
        }
        else
        {
            Response.Redirect("url");
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: make site available only from given ip


问:
How can find out a custom date ( with calendar format ) based on an input in Python?
My problem sounds like this:
For N people , input their names and birthday dates. Based on this information, using substitute, create a custom message like:
"Hey ... ! There are ... more days until your birthday, when you will turn ... years old. A trip awaits you in the following days: ... - ... ( the period has to start 3 days before the birthday, and end 3 days after.)

For example:
n = 1
Steve Potter
02.07.2000

output:
Hey Steve Potter ! There are 31 more days until your birthday, when you will turn 20 years old, A trip awaits you in the following days: 29.06.2020 - 05.07.2020

So far, I can't figure out more than that:

```<code>import string
import time

invitation = string.Template("Hey $name , There are $nrdays days until your birthday, when you will turn $years old. A trip awaits you in the following days: $start - $end")

n = int(input("Number of people:"))

for i in range(0, n):
    i_name = input("Name of the guest?")
    i_data = input("Birthday?")
    data = time.localtime()
    i_bdday = int(i_data[0] + i_data[1] )
    i_bdmonth = int(i_data[3] + i_data[4] )
    i_bdyear = int(i_data[6] + i_data[7] + i_data[8] + i_data[9] )
    i_years = data[0] - i_bdyear
    print ( invitation.substitute(name = i_name , years = i_years) )
</code>```

How can I figure out how more days are there until a given date and also the interval I need?
Thank you

答:
See this:

```<code>https://docs.python.org/3/library/datetime.html?highlight=datetime#module-datetime
</code>```

Maybe you can find your own solution after reading it.

Body:
My problem sounds like this:
For N people , input their names and birthday dates. Based on this information, using substitute, create a custom message like:
"Hey ... ! There are ... more days until your birthday, when you will turn ... years old. A trip awaits you in the following days: ... - ... ( the period has to start 3 days before the birthday, and end 3 days after.)

For example:
n = 1
Steve Potter
02.07.2000

output:
Hey Steve Potter ! There are 31 more days until your birthday, when you will turn 20 years old, A trip awaits you in the following days: 29.06.2020 - 05.07.2020

So far, I can't figure out more than that:

import string
import time

invitation = string.Template("Hey $name , There are $nrdays days until your birthday, when you will turn $years old. A trip awaits you in the following days: $start - $end")

n = int(input("Number of people:"))

for i in range(0, n):
    i_name = input("Name of the guest?")
    i_data = input("Birthday?")
    data = time.localtime()
    i_bdday = int(i_data[0] + i_data[1] )
    i_bdmonth = int(i_data[3] + i_data[4] )
    i_bdyear = int(i_data[6] + i_data[7] + i_data[8] + i_data[9] )
    i_years = data[0] - i_bdyear
    print ( invitation.substitute(name = i_name , years = i_years) )

How can I figure out how more days are there until a given date and also the interval I need?
Thank you

Body:
See this:

https://docs.python.org/3/library/datetime.html?highlight=datetime#module-datetime

Maybe you can find your own solution after reading it.


问:
High Loss Validation
I use the following model to predict the competition: "intel-mobileodt-cervical-cancer-screening".
The labels are divided into 3 categories(1 ,2 ,3).

When I want to do a prediction workout I get the next output

Model:

```<code>resnet50 = pretrainedmodels.__dict__["resnet50"](num_classes=1000, pretrained='imagenet')
resnet50.last_linear=torch.nn.Linear(in_features=2048,out_features=3, bias=True)
#optim
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model=model.to(device)
loss_cross=torch.nn.CrossEntropyLoss().cuda()
</code>```

optim Adam

DataLoader:

```<code>class Kaggle_Cancer(Dataset):
  def __init__(self, root_path, transform=None,preprocessing=None,resize=216):
    self.path = root_path
    self.transform=transform
    self.preprocessing=preprocessing
    self.resize=resize

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

  def __getitem__(self, idx):
    p=self.path[idx]
    image1=cv2.imread(p)
    label=p.split("/")[-2].split("_")[-1]
    image1=cv2.cvtColor(image1,cv2.COLOR_BGR2RGB)
    if self.transform:
      image1=self.transform(image=image1)['image']
    image1=transforms.ToPILImage()(image1)
    image1=transforms.ToTensor()(image1)
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
    image1=normalize(image1)
    return image1,int(label)
</code>```

Train :

```<code>def train(epoch_number,model,optim,loss):
  model.train()
  all_loss=0
  correct=0
  tqdm_loader=tqdm(training_set)
  for  index,(img,target) in enumerate(tqdm_loader):
    img=img.float().cuda()
    target=target.long().cuda()

    optim.zero_grad()
    out=model(img)
    print(out," target ",target)
    loss1=loss(out,target)
    print(loss1)
    loss1.backward()
    optim.step()
    all_loss+=loss1.item()
    avg_loss=all_loss/(index+1)
    pred=out.argmax(dim=1,keepdim=True)
    correct+=pred.eq(target.view_as(pred)).sum().item()/len(target)

    avg_acc=correct/(index+1)
    tqdm_loader.set_description("Epoch {} train loss={:4}  acc={:4} ".format(epoch_number,round(avg_loss,4),round(avg_acc,4)))

  return avg_loss,avg_acc
</code>```

output:

print(out," target ",target)

```<code>,
        [ 6.1667e-02, -3.9864e-01, -4.1212e-01],
        [-2.3100e-01, -3.7821e-01, -2.8159e-01],
        [-2.9442e-01, -5.0409e-01, -3.1046e-01],
        [ 1.4866e-01, -2.8496e-01, -1.7643e-01],
        [-2.4554e-01, -2.5063e-01, -6.7061e-01],
        [-7.1597e-02, -3.5376e-01, -5.7830e-01],
        [-2.1527e-01, -4.0284e-01, -4.5993e-01],
        [ 1.2050e-02, -5.5684e-01, -1.6044e-01],
        [-3.7750e-02, -5.3680e-01, -4.3820e-01],
        [-1.1966e-01, -2.5146e-01, -4.9405e-01],
        [-2.3308e-01, -6.3452e-01, -3.9821e-01],
        [-3.6530e-01, -1.5242e-01, -2.6457e-01],
        [-1.8864e-01, -6.0979e-01, -5.5342e-01],
        [-2.4755e-01, -4.7011e-01, -2.6204e-01],
        [-3.1907e-01, -4.2680e-01, -3.4576e-01],
        [-2.1872e-01, -5.3857e-01, -2.9729e-01],
        [-7.1475e-02, -4.0458e-01, -3.2042e-01],
        [-2.8925e-01, -4.3376e-02, -4.9899e-01],
        [-4.8227e-02, -1.8701e-01, -2.2106e-01],
        [ 1.7829e-02, -6.5816e-01, -4.0141e-01],
        [-2.7450e-01, -3.9498e-01, -2.3189e-01],
        [-1.8847e-01, -6.8187e-01, -2.0631e-01],
        [-3.5251e-01, -5.3258e-01, -6.3298e-01],
        [-6.5548e-02, -2.5093e-01, -5.4346e-01],
        [ 2.3848e-01, -3.6152e-01, -1.6380e-01],
        [-2.1488e-01, -6.4888e-01, -7.7022e-01],.....

target  tensor([2, 2, 2, 1, 1, 2, 2, 2, 2, 1, 3, 2, 3, 2, 2, 2, 2, 3, 2, 1, 3, 3, 2, 2,
        3, 2, 3, 2, 3, 1, 3, 3, 1, 2, 3, 2, 1, 1, 3, 1, 1, 2, 3, 2, 2, 2, 2, 2,.....
</code>```

print(loss1)

```<code> 1, 2, 3, 3, 1, 3, 1, 3, 3, 2, 3, 3, 2, 3, 2, 3], device='cuda:0'
tensor(1.0870, device='cuda:0', grad_fn=<NllLossBackward>
</code>```

number epoch =10/20/30:

same result:

val loss=1.2  acc=0.4 train loss=0.6  acc=0.65

What i do wrong?

答:
When the validation loss is larger than the training loss, It is usually a sign of overfitting. There area few things you can do:

Add Dropout of Batch Normalisation:

This makes the model more robust.

Make the model deeper:

Add more layers to the model for a better comprehension of the patterns.

Use better optimizers:

Adaptive optimizers such as Adam, Adagrad and RMSprop are usually effective.

Title: High Loss Validation

Body:
I use the following model to predict the competition: "intel-mobileodt-cervical-cancer-screening".
The labels are divided into 3 categories(1 ,2 ,3).

When I want to do a prediction workout I get the next output

Model:

resnet50 = pretrainedmodels.__dict__["resnet50"](num_classes=1000, pretrained='imagenet')
resnet50.last_linear=torch.nn.Linear(in_features=2048,out_features=3, bias=True)
#optim
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model=model.to(device)
loss_cross=torch.nn.CrossEntropyLoss().cuda()

optim Adam

DataLoader:

class Kaggle_Cancer(Dataset):
  def __init__(self, root_path, transform=None,preprocessing=None,resize=216):
    self.path = root_path
    self.transform=transform
    self.preprocessing=preprocessing
    self.resize=resize

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

  def __getitem__(self, idx):
    p=self.path[idx]
    image1=cv2.imread(p)
    label=p.split("/")[-2].split("_")[-1]
    image1=cv2.cvtColor(image1,cv2.COLOR_BGR2RGB)
    if self.transform:
      image1=self.transform(image=image1)['image']
    image1=transforms.ToPILImage()(image1)
    image1=transforms.ToTensor()(image1)
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
    image1=normalize(image1)
    return image1,int(label)

Train :

def train(epoch_number,model,optim,loss):
  model.train()
  all_loss=0
  correct=0
  tqdm_loader=tqdm(training_set)
  for  index,(img,target) in enumerate(tqdm_loader):
    img=img.float().cuda()
    target=target.long().cuda()

    optim.zero_grad()
    out=model(img)
    print(out," target ",target)
    loss1=loss(out,target)
    print(loss1)
    loss1.backward()
    optim.step()
    all_loss+=loss1.item()
    avg_loss=all_loss/(index+1)
    pred=out.argmax(dim=1,keepdim=True)
    correct+=pred.eq(target.view_as(pred)).sum().item()/len(target)

    avg_acc=correct/(index+1)
    tqdm_loader.set_description("Epoch {} train loss={:4}  acc={:4} ".format(epoch_number,round(avg_loss,4),round(avg_acc,4)))

  return avg_loss,avg_acc

output:

print(out," target ",target)

,
        [ 6.1667e-02, -3.9864e-01, -4.1212e-01],
        [-2.3100e-01, -3.7821e-01, -2.8159e-01],
        [-2.9442e-01, -5.0409e-01, -3.1046e-01],
        [ 1.4866e-01, -2.8496e-01, -1.7643e-01],
        [-2.4554e-01, -2.5063e-01, -6.7061e-01],
        [-7.1597e-02, -3.5376e-01, -5.7830e-01],
        [-2.1527e-01, -4.0284e-01, -4.5993e-01],
        [ 1.2050e-02, -5.5684e-01, -1.6044e-01],
        [-3.7750e-02, -5.3680e-01, -4.3820e-01],
        [-1.1966e-01, -2.5146e-01, -4.9405e-01],
        [-2.3308e-01, -6.3452e-01, -3.9821e-01],
        [-3.6530e-01, -1.5242e-01, -2.6457e-01],
        [-1.8864e-01, -6.0979e-01, -5.5342e-01],
        [-2.4755e-01, -4.7011e-01, -2.6204e-01],
        [-3.1907e-01, -4.2680e-01, -3.4576e-01],
        [-2.1872e-01, -5.3857e-01, -2.9729e-01],
        [-7.1475e-02, -4.0458e-01, -3.2042e-01],
        [-2.8925e-01, -4.3376e-02, -4.9899e-01],
        [-4.8227e-02, -1.8701e-01, -2.2106e-01],
        [ 1.7829e-02, -6.5816e-01, -4.0141e-01],
        [-2.7450e-01, -3.9498e-01, -2.3189e-01],
        [-1.8847e-01, -6.8187e-01, -2.0631e-01],
        [-3.5251e-01, -5.3258e-01, -6.3298e-01],
        [-6.5548e-02, -2.5093e-01, -5.4346e-01],
        [ 2.3848e-01, -3.6152e-01, -1.6380e-01],
        [-2.1488e-01, -6.4888e-01, -7.7022e-01],.....

target  tensor([2, 2, 2, 1, 1, 2, 2, 2, 2, 1, 3, 2, 3, 2, 2, 2, 2, 3, 2, 1, 3, 3, 2, 2,
        3, 2, 3, 2, 3, 1, 3, 3, 1, 2, 3, 2, 1, 1, 3, 1, 1, 2, 3, 2, 2, 2, 2, 2,.....

print(loss1)

 1, 2, 3, 3, 1, 3, 1, 3, 3, 2, 3, 3, 2, 3, 2, 3], device='cuda:0'
tensor(1.0870, device='cuda:0', grad_fn=<NllLossBackward>

number epoch =10/20/30:

same result:

val loss=1.2  acc=0.4 train loss=0.6  acc=0.65

What i do wrong?


问:
Determine if a number contains a digit in Tcl
I am trying to write a function that takes in a list, and for each number in the list I would like it to check if there is the digit 5 in it. If the digit 5 is in the number it would print true and move on to the next number in the list until the end

Example is the list [155 12 14 6 254 15]

155 prints true as there is a 5 in it

12 prints false as there is no 5 in it

etc..

This is what I have done so far

```<code>proc containsDigit {l} {
    foreach nxt $l {

    while {$nxt!= 0} {
    set int [expr {fmod($nxt, 10)}]

    if {$int == 5 } {
        puts "true"
            }else{
                set $nxt [expr {$nxt/10}]
            }
        puts false

    }

    }
}

set a [list 155 12 14 6 254 15]
containsDigit $a
</code>```

Thanks for your help!

答:
Instead of using fmod(), the integer modulo operator should be used:

set int [expr {$nxt % 10}]

You need to break out of the loop when the 'true' condition is found.  If there
is a 5 present, you don't want to look further.

The syntax here is wrong:

```<code> set $nxt [expr {$nxt/10}]
</code>```

This will, for example, set the variable 12 to 1.
You want:

```<code> set nxt [expr {$nxt/10}]
</code>```

Body:
I am trying to write a function that takes in a list, and for each number in the list I would like it to check if there is the digit 5 in it. If the digit 5 is in the number it would print true and move on to the next number in the list until the end

Example is the list [155 12 14 6 254 15]

155 prints true as there is a 5 in it

12 prints false as there is no 5 in it

etc..

This is what I have done so far

proc containsDigit {l} {
    foreach nxt $l {

    while {$nxt!= 0} {
    set int [expr {fmod($nxt, 10)}]

    if {$int == 5 } {
        puts "true"
            }else{
                set $nxt [expr {$nxt/10}]
            }
        puts false

    }

    }
}

set a [list 155 12 14 6 254 15]
containsDigit $a

Thanks for your help!

Body:
Instead of using fmod(), the integer modulo operator should be used:

set int [expr {$nxt % 10}]

You need to break out of the loop when the 'true' condition is found.  If there
is a 5 present, you don't want to look further.

The syntax here is wrong:

 set $nxt [expr {$nxt/10}]

This will, for example, set the variable 12 to 1.
You want:

 set nxt [expr {$nxt/10}]


答:
The easiest way is to treat the number as a string and use string first or string match. I prefer string match.

```<code>proc containsDigit {l} {
    foreach nxt $l {
        if {[string match *5* $nxt]} {
            puts "true"
        } else {
            puts "false"
        }
    }
}
</code>```

If the numbers are possibly hexadecimal but you want to only ever search the decimal form, condition the string to search by using format %d:

```<code>proc containsDigit {l} {
    foreach nxt $l {
        if {[string match *5* [format "%d" $nxt]]} {
            puts "true"
        } else {
            puts "false"
        }
    }
}
</code>```

Title: Determine if a number contains a digit in Tcl

Body:
The easiest way is to treat the number as a string and use string first or string match. I prefer string match.

proc containsDigit {l} {
    foreach nxt $l {
        if {[string match *5* $nxt]} {
            puts "true"
        } else {
            puts "false"
        }
    }
}

If the numbers are possibly hexadecimal but you want to only ever search the decimal form, condition the string to search by using format %d:

proc containsDigit {l} {
    foreach nxt $l {
        if {[string match *5* [format "%d" $nxt]]} {
            puts "true"
        } else {
            puts "false"
        }
    }
}


问:
How can I solve the output error in flipping a coin?
I am writing code about the probability of flipping a coin as follows, but I keep getting errors.

```<code>import random

tries = 0
number = random.randint(0, 1)
def coin_probability(hehe):
    for a in range(1, 101):
        heads = 0; tails = 0
        tries += 1
        if tries <= 10:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
        else:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 :  %s' %(n, coin_probability(n))) `
</code>```

I want the probability to come out one by one from 1 to 10, and display 10 units from 11 to 100. For example:

```<code>1 번째까지~: (probability)%
2 번째까지~: (probability)%
3 번째까지~: (probability)%
...
10 번째까지~: (probability)%
20 번째까지~: (probability)%
...
</code>```

it should be printed like this.
(※I set heads to 0 and tails to 1.)

答:
You could handle the print() after another if with

```<code>...
else:
    if tries % 10 == 0:
        print("something", cp, tries)
</code>```

also you give n to your function as "hehe" but never use it? Other than that you could be a little more specific what kind of error occurs.

Body:
I am writing code about the probability of flipping a coin as follows, but I keep getting errors.

import random

tries = 0
number = random.randint(0, 1)
def coin_probability(hehe):
    for a in range(1, 101):
        heads = 0; tails = 0
        tries += 1
        if tries <= 10:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
        else:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 :  %s' %(n, coin_probability(n))) `

I want the probability to come out one by one from 1 to 10, and display 10 units from 11 to 100. For example:

1 번째까지~: (probability)%
2 번째까지~: (probability)%
3 번째까지~: (probability)%
...
10 번째까지~: (probability)%
20 번째까지~: (probability)%
...

it should be printed like this.
(※I set heads to 0 and tails to 1.)

Body:
You could handle the print() after another if with

...
else:
    if tries % 10 == 0:
        print("something", cp, tries)

also you give n to your function as "hehe" but never use it? Other than that you could be a little more specific what kind of error occurs.


问:
Compare two strings of ints in java
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10? </p>

```<code>String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
</code>```

答: You split the strings on whitespace (using either String.split or StringTokenizer) and then convert each of the tokens into a number. Place all the numbers in string one into a HashSet. Do the same for string two. Now all you have to do is to check whether each entry in the first HashSet also occurs in the second one.

Title: Compare two strings of ints in java

Body:
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?

String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";


问:
How create one query?
One author has many books. There are many authors with books in the database.
It is required to get the latest books of authors. In one query.</p>

```<code>class Autor(models.Model):
    name = models.Charfield()

class Book(models.Model):
    name = models.Charfield()
    author = models.ForegnKey("Autors", models.CASCADE)
    created_at = models.DatetimeField(auto_now_add=True)

# its a many queries
last_books = []
for author in Autor.objects.all():
    last_book = Book.object.filter(autor=autor).latest("created_at")
    last_books.append(last_book)
# need one query
</code>```

答:
This will get the answer in one query. Group the books by author and get the latest created_date of each group. Filter the records matching the created date in latest_dates

```<code>qs = Book.objects.all()
latest_dates = qs.values('author').annotate(latest_created_at=Max('created_at'))
qs = qs.filter(created_at__in=latest_dates.values('latest_created_at')).order_by('-created_at')
</code>```

Title: How create one query?

Body:
One author has many books. There are many authors with books in the database.
It is required to get the latest books of authors. In one query.

class Autor(models.Model):
    name = models.Charfield()

class Book(models.Model):
    name = models.Charfield()
    author = models.ForegnKey("Autors", models.CASCADE)
    created_at = models.DatetimeField(auto_now_add=True)

# its a many queries
last_books = []
for author in Autor.objects.all():
    last_book = Book.object.filter(autor=autor).latest("created_at")
    last_books.append(last_book)
# need one query

Body:
This will get the answer in one query. Group the books by author and get the latest created_date of each group. Filter the records matching the created date in latest_dates

qs = Book.objects.all()
latest_dates = qs.values('author').annotate(latest_created_at=Max('created_at'))
qs = qs.filter(created_at__in=latest_dates.values('latest_created_at')).order_by('-created_at')


问:
Add values from a list to each unique ID code [SQL]
I have a list of product names (Book, Car, Table). My table currently looks like this:

What i would like my table to show is all 3 products for each JobID e.g.:

So essentially for each distinct JobID, there should be 3 products.

How can I do this in SQL? This is a sample dataset, i'm actually working with a much larger and complex dataset but I would like to understand how to do this with a simple dataset and adapt it to my larger dataset.

答:
You have to use cross join,</p>

```<code>select * from table t1
cross join table t2;
</code>```

Body:
You have to use cross join,

select * from table t1
cross join table t2;


问:
Can't read and write a TIFF image file using Java ImageIO standard library
I don't know what to do with TIFF images, but I can't read or write any of them using straight Java standard ImageIO library. Any thoughts?

Thanks.

答:
Java supports TIFF format only from Java 9 release. If you are trying to use ImageIO for TIFF into older Java version it will give you exception.

If you want to use TIFF in earlier version as well, you Twelve Monkey plugin along with Java just by adding dependency of Twelve Monkey.

Maven Dependency for Twelve Monkey:

```<code><dependency>
   <groupId>com.twelvemonkeys.imageio</groupId>
   <artifactId>imageio-tiff</artifactId>
   <version>3.5</version>
</dependency>*
</code>```

I'm also giving example to merge the multiple images into Single TIFF with pages using Twelve Monkey,

```<code>BufferedImage b1 = null;
BufferedImage b2 = null;

TIFFImageReaderSpi SPI = new TIFFImageReaderSpi();

ImageReader imageReader1 = SPI.createReaderInstance();
ImageInputStream iis1 = ImageIO.createImageInputStream(new File("1.tif"));
imageReader1.setInput(iis1);
b1 = imageReader1.read(0);

ImageReader imageReader2 = SPI.createReaderInstance();
ImageInputStream iis2 = ImageIO.createImageInputStream(new File("2.tif"));
imageReader2.setInput(iis2);
b2 = imageReader2.read(0);

ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();

writer.setOutput(ImageIO.createImageOutputStream(new File("3.tif")));

ImageWriteParam writeParam = writer.getDefaultWriteParam();
//writeParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
//writeParam.setCompressionType("Deflate");

writer.prepareWriteSequence(null);

IIOImage i1 = new IIOImage(b1, null, null);
IIOImage i2 = new IIOImage(b2, null, null);

writer.writeToSequence(i1, writeParam);
writer.writeToSequence(i2, writeParam);

writer.endWriteSequence();
writer.dispose();
</code>```

The above code will work with Java8 and written to open two TIFF image and merge into single.

Also, you may use compression as needed. Just use comment lines to add compression.

ContentLicense: CC BY-SA 2.5

Body:
Java supports TIFF format only from Java 9 release. If you are trying to use ImageIO for TIFF into older Java version it will give you exception.

If you want to use TIFF in earlier version as well, you Twelve Monkey plugin along with Java just by adding dependency of Twelve Monkey.

Maven Dependency for Twelve Monkey:

<dependency>
   <groupId>com.twelvemonkeys.imageio</groupId>
   <artifactId>imageio-tiff</artifactId>
   <version>3.5</version>
</dependency>*

I'm also giving example to merge the multiple images into Single TIFF with pages using Twelve Monkey,

BufferedImage b1 = null;
BufferedImage b2 = null;

TIFFImageReaderSpi SPI = new TIFFImageReaderSpi();

ImageReader imageReader1 = SPI.createReaderInstance();
ImageInputStream iis1 = ImageIO.createImageInputStream(new File("1.tif"));
imageReader1.setInput(iis1);
b1 = imageReader1.read(0);

ImageReader imageReader2 = SPI.createReaderInstance();
ImageInputStream iis2 = ImageIO.createImageInputStream(new File("2.tif"));
imageReader2.setInput(iis2);
b2 = imageReader2.read(0);

ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();

writer.setOutput(ImageIO.createImageOutputStream(new File("3.tif")));

ImageWriteParam writeParam = writer.getDefaultWriteParam();
//writeParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
//writeParam.setCompressionType("Deflate");

writer.prepareWriteSequence(null);

IIOImage i1 = new IIOImage(b1, null, null);
IIOImage i2 = new IIOImage(b2, null, null);

writer.writeToSequence(i1, writeParam);
writer.writeToSequence(i2, writeParam);

writer.endWriteSequence();
writer.dispose();

The above code will work with Java8 and written to open two TIFF image and merge into single.

Also, you may use compression as needed. Just use comment lines to add compression.


问:
How to select the state from within Redux-Saga
I have a react app where I'm creating an unit and it requires authorization.

```<code>function* createUnitWorker(action) {
  const { payload: {unitDetails, history} } = action;
  try {
    const unit = yield axios({
      method: 'post',
      url: `https://myBackend/units/`,
      headers: {'Authorization': 'Bearer'+token},
      data: {
         ...unitDetails
      }
    });
    yield put(call(createUnitSuccess, unit));
    yield history.push(`/unit/${unit.code}`)
  } catch (error) {
    yield put(createUnitFailure(error));
    yield put(history.push('/error'))
  }
}
export function* createUnitWatcher() {
  yield takeLatest(unitActionTypes.CREATE_UNIT_START, createUnitWorker);
}
</code>```

Should I send the token from the component as part of the payload or should I select the token from the user state I have stored in the saga?. Because it seems to me that it is complicated to select the token mapStateToProps and then send it with the action when I could just select the token from within the saga

答:
I would recommend to use axios interceptors so you don't have to manually add the token to each request you send.

```<code>const axiosInstance = axios.create({
  baseURL: 'https://baseUrl.com',
  headers: { "Content-Type": "application/json" }
});

axiosInstance.interceptors.request.use(function (config) {
    config.headers.Authorization = 'Bearer'+token;
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });
</code>```

This means you can just use the axiosInstance in each saga, without worrying about the token. Something like this:

```<code>axiosInstance.post('/units', payload);
</code>```

Body:
I have a react app where I'm creating an unit and it requires authorization.

function* createUnitWorker(action) {
  const { payload: {unitDetails, history} } = action;
  try {
    const unit = yield axios({
      method: 'post',
      url: `https://myBackend/units/`,
      headers: {'Authorization': 'Bearer'+token},
      data: {
         ...unitDetails
      }
    });
    yield put(call(createUnitSuccess, unit));
    yield history.push(`/unit/${unit.code}`)
  } catch (error) {
    yield put(createUnitFailure(error));
    yield put(history.push('/error'))
  }
}
export function* createUnitWatcher() {
  yield takeLatest(unitActionTypes.CREATE_UNIT_START, createUnitWorker);
}

Should I send the token from the component as part of the payload or should I select the token from the user state I have stored in the saga?. Because it seems to me that it is complicated to select the token mapStateToProps and then send it with the action when I could just select the token from within the saga

Body:
I would recommend to use axios interceptors so you don't have to manually add the token to each request you send.

const axiosInstance = axios.create({
  baseURL: 'https://baseUrl.com',
  headers: { "Content-Type": "application/json" }
});

axiosInstance.interceptors.request.use(function (config) {
    config.headers.Authorization = 'Bearer'+token;
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

This means you can just use the axiosInstance in each saga, without worrying about the token. Something like this:

axiosInstance.post('/units', payload);


问:
Iterate through an array of characters in C
Recently I saw this while loop condition in C in the example below but I have no idea what the while condition really means and how the compiler knows when it is done. Could someone explain it to me?

This is what I believe it means: while loop iterates through the char array until the ending of the array since there is nothing else then the while loop ends, or am I wrong? I tried to use the same while loop but in another language such as Go, however, the compiler threw an error saying that I cannot use a non-bool.

```<code>// C program to demonstrate
// example of tolower() function.

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

int main()
{
    int j = 0;
    char str[] = "GEEKSFORGEEKS\n";

    // Character to be converted to lowercase
    char ch = 'G';

    // convert ch to lowercase using toLower()
    char ch;

    while (str[j]) { // <- this part, how is this a condition?
        ch = str[j];

        // convert ch to lowercase using toLower()
        putchar(tolower(ch));

        j++;
    }

    return 0;
}
</code>```

答:
Although, you got your answer. Still, I wanna add some more details or an explanatory answer here.

In C, a conditional statement will have either the value 1 or 0. In the end, they all are evaluated to Boolean values true or false or 1 or 0.

So first, try to understand or dry run that while(str[j]). Guess what will be the value of str[j] when j = 0. It'll be the first character "G". Similarly in the next iteration, you'll get the next character until NULL character or String Termination character. Now, anything in between those parentheses in while(str[j]) will be considered as a conditional statement and they all are evaluated to 1 or 0. Now here's the thing that anyhow if that conditional statement isn't being evaluated specifically to 0, then It'll be supposed to have the value of 1.
So, here str[j] when j = 0 will be evaluated as 1, then next character and so on. Now, when we find \0 which is an escape character equivalent to 0. So, at \0 while loop will terminate as the condition will be false.

Can, you tell me what will be the output of this program?

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

int main()
{
    if(printf("Hello TraineeGuy\n"))
        printf("TRUE");
    else
        printf("FALSE");
    return 0;
}
</code>```

Body:
Recently I saw this while loop condition in C in the example below but I have no idea what the while condition really means and how the compiler knows when it is done. Could someone explain it to me?

This is what I believe it means: while loop iterates through the char array until the ending of the array since there is nothing else then the while loop ends, or am I wrong? I tried to use the same while loop but in another language such as Go, however, the compiler threw an error saying that I cannot use a non-bool.

// C program to demonstrate
// example of tolower() function.

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

int main()
{
    int j = 0;
    char str[] = "GEEKSFORGEEKS\n";

    // Character to be converted to lowercase
    char ch = 'G';

    // convert ch to lowercase using toLower()
    char ch;

    while (str[j]) { // <- this part, how is this a condition?
        ch = str[j];

        // convert ch to lowercase using toLower()
        putchar(tolower(ch));

        j++;
    }

    return 0;
}

Body:
Although, you got your answer. Still, I wanna add some more details or an explanatory answer here.

In C, a conditional statement will have either the value 1 or 0. In the end, they all are evaluated to Boolean values true or false or 1 or 0.

So first, try to understand or dry run that while(str[j]). Guess what will be the value of str[j] when j = 0. It'll be the first character "G". Similarly in the next iteration, you'll get the next character until NULL character or String Termination character. Now, anything in between those parentheses in while(str[j]) will be considered as a conditional statement and they all are evaluated to 1 or 0. Now here's the thing that anyhow if that conditional statement isn't being evaluated specifically to 0, then It'll be supposed to have the value of 1.
So, here str[j] when j = 0 will be evaluated as 1, then next character and so on. Now, when we find \0 which is an escape character equivalent to 0. So, at \0 while loop will terminate as the condition will be false.

Can, you tell me what will be the output of this program?

#include<stdio.h>

int main()
{
    if(printf("Hello TraineeGuy\n"))
        printf("TRUE");
    else
        printf("FALSE");
    return 0;
}


问:
Flask SQL Alchemy querying a table with a != column condition

Edit - This is what the working solution looked like for me

thanks to the answer below by @abhishek Jebaraj I was able to adapt the code as follows by changing the not_in_lists function.

```<code>def not_in_lists(self):
        query = List.query.filter(
            List.id.notin_(
                db.session.query(items_lists.c.list_id).filter(
                    items_lists.c.item_id == self.id)))
        list = []
        for i in query:
            list.append(i)

        return list
</code>```

Original Post

My questions seems to be related to: Flask SQLAlchemy querying a column with "not equals", but can't seem to figure it out with the information there. Perhaps someone can help.

I have a many to many table and am trying to run 2 queries that separate one of the tables into two lists - those that have an item and those that don't.

I have a table called items and a table called lists with a many to many relationship. The functions shown below are part lf the item model class. When an item id is passed into the function it checks the association table for all records and then filters for its own value. I wrote a test function that creates 4 lists and adds 1 item to two of them.

The test then calls both of these functions. The first function correctly returns the 2 lists that it was added to. The second test incorrectly returns all 4 lists. The only difference between the two functions is == vs !=. Meaning my non equality condition isnt firing.

Using Flask with Flask-SQLAlchemy

The first query checking for equality works as expected, but the not equal query doesn't work at all.

I've tried the SQLAlchemy docs, tried using !=, not_, is not but not having any luck.

Googling doesn't yield any helpful results either.

In SQLITE3 this works and this is exactly what I'm trying to accomplish with flask-SQLAlchemy:

```<code>select * from List
left join items_lists
on items_lists.list_id = List.id
WHERE items_lists.item_id is not item.id;
</code>```

Here's my code and thanks in advance for the guidance.

```<code>def in_list(self):
        return List.query.join(
            items_lists, (items_lists.c.list_id == list.id)
            ).filter(
               items_lists.c.item_id == self.id
               )

def not_in_list(self):
        return List.query.join(
            items_lists, (items_lists.c.list_id == list.id)
            ).filter(
                items_lists.c.item_id != self.id
                )
</code>```

I'm testing with Python's unittest - here's the code that checks for the conditions. The test fails at self.assertEqual(nm1, [l2, l4]) instead of seeing [l2, l4] as the result, I'm getting [l1,l2,l3,l4] - per the test condition, item1 - i1 is in the lists - [l1, l3] so the second query condition isn't working.

```<code>def test_show_members(self):
        i1 = Item(text = "this is an item")
        i2 = Item(text = "This is a second item")
        i3 = Item(text = "This is a third item")
        i4 = Item(text = "This is a fourth item")

        l1 = List(title = "Canaries")
        l2 = List(title = "Bluejays")
        l3 = List(title = "Crows")
        l4 = List(title = "Ravens")

        db.session.add_all([i1,i2,i3,i4,l1, l2,l3,l4])
        db.session.commit()

        #i1 in 2 lists - Canaries + Crows
        i1.AddToList(l1)
        i1.AddToList(l3)

        #i2 in 1 list - Bluejays
        i2.AddToList(l2)

        #i3 in all lists - Canaries, Bluejays, Crows, Ravens
        i3.AddToList(l1)
        i3.AddToList(l2)
        i3.AddToList(l3)
        i3.AddToList(l4)
        #i4 not in any lists

        db.session.commit()

        m1 = i1.in_lists().all()
        m2 = i2.in_lists().all()
        m3 = i3.in_lists().all()
        m4 = i4.in_lists().all()

        nm1 = i1.not_in_lists().all()
        nm2 = i2.not_in_lists().all()
        nm3 = i3.not_in_lists().all()
        nm4 = i4.not_in_lists().all()

        self.assertEqual(m1, [l1, l3])
        self.assertEqual(nm1, [l2, l4])

        self.assertEqual(m2, [l2])
        self.assertEqual(nm2, [l1, l3, l4])

        self.assertEqual(m3, [l1, l2, l3, l4])
        self.assertEqual(nm3, [])

        self.assertEqual(m4, [])
        self.assertEqual(nm4, [l1, l2, l3, l4])

</code>```

additional things that aren't working:

```<code>.filter(
   items_lists.c.list_id == not_(self.id)
)

.filter(
   items_lists.c.list_id == ~self.id
)
</code>```

This returns an empty list instead of having the two lists where item is not a member.

答:
Replace the not_in_list function with the below one.

```<code>def not_in_list(self):
        return List.query.filter(List.id.notin_(session.query(item_lists.c.list_id).filter(item_lists.c.item_id == self.id)))
</code>```

Its not working because when you say in your query != self.id , it means equal to everything else, including item 3 i3. But i3 is linked to all the lists. Therefore it returns all the lists to you.

Body:
Edit - This is what the working solution looked like for me

thanks to the answer below by @abhishek Jebaraj I was able to adapt the code as follows by changing the not_in_lists function.

def not_in_lists(self):
        query = List.query.filter(
            List.id.notin_(
                db.session.query(items_lists.c.list_id).filter(
                    items_lists.c.item_id == self.id)))
        list = []
        for i in query:
            list.append(i)

        return list

Original Post

My questions seems to be related to: Flask SQLAlchemy querying a column with "not equals", but can't seem to figure it out with the information there. Perhaps someone can help.

I have a many to many table and am trying to run 2 queries that separate one of the tables into two lists - those that have an item and those that don't.

I have a table called items and a table called lists with a many to many relationship. The functions shown below are part lf the item model class. When an item id is passed into the function it checks the association table for all records and then filters for its own value. I wrote a test function that creates 4 lists and adds 1 item to two of them.

The test then calls both of these functions. The first function correctly returns the 2 lists that it was added to. The second test incorrectly returns all 4 lists. The only difference between the two functions is == vs !=. Meaning my non equality condition isnt firing.

Using Flask with Flask-SQLAlchemy

The first query checking for equality works as expected, but the not equal query doesn't work at all.

I've tried the SQLAlchemy docs, tried using !=, not_, is not but not having any luck.

Googling doesn't yield any helpful results either.

In SQLITE3 this works and this is exactly what I'm trying to accomplish with flask-SQLAlchemy:

select * from List
left join items_lists
on items_lists.list_id = List.id
WHERE items_lists.item_id is not item.id;

Here's my code and thanks in advance for the guidance.

def in_list(self):
        return List.query.join(
            items_lists, (items_lists.c.list_id == list.id)
            ).filter(
               items_lists.c.item_id == self.id
               )

def not_in_list(self):
        return List.query.join(
            items_lists, (items_lists.c.list_id == list.id)
            ).filter(
                items_lists.c.item_id != self.id
                )

I'm testing with Python's unittest - here's the code that checks for the conditions. The test fails at self.assertEqual(nm1, [l2, l4]) instead of seeing [l2, l4] as the result, I'm getting [l1,l2,l3,l4] - per the test condition, item1 - i1 is in the lists - [l1, l3] so the second query condition isn't working.

def test_show_members(self):
        i1 = Item(text = "this is an item")
        i2 = Item(text = "This is a second item")
        i3 = Item(text = "This is a third item")
        i4 = Item(text = "This is a fourth item")

        l1 = List(title = "Canaries")
        l2 = List(title = "Bluejays")
        l3 = List(title = "Crows")
        l4 = List(title = "Ravens")

        db.session.add_all([i1,i2,i3,i4,l1, l2,l3,l4])
        db.session.commit()

        #i1 in 2 lists - Canaries + Crows
        i1.AddToList(l1)
        i1.AddToList(l3)

        #i2 in 1 list - Bluejays
        i2.AddToList(l2)

        #i3 in all lists - Canaries, Bluejays, Crows, Ravens
        i3.AddToList(l1)
        i3.AddToList(l2)
        i3.AddToList(l3)
        i3.AddToList(l4)
        #i4 not in any lists

        db.session.commit()

        m1 = i1.in_lists().all()
        m2 = i2.in_lists().all()
        m3 = i3.in_lists().all()
        m4 = i4.in_lists().all()

        nm1 = i1.not_in_lists().all()
        nm2 = i2.not_in_lists().all()
        nm3 = i3.not_in_lists().all()
        nm4 = i4.not_in_lists().all()

        self.assertEqual(m1, [l1, l3])
        self.assertEqual(nm1, [l2, l4])

        self.assertEqual(m2, [l2])
        self.assertEqual(nm2, [l1, l3, l4])

        self.assertEqual(m3, [l1, l2, l3, l4])
        self.assertEqual(nm3, [])

        self.assertEqual(m4, [])
        self.assertEqual(nm4, [l1, l2, l3, l4])

additional things that aren't working:

.filter(
   items_lists.c.list_id == not_(self.id)
)

.filter(
   items_lists.c.list_id == ~self.id
)

This returns an empty list instead of having the two lists where item is not a member.

Body:
Replace the not_in_list function with the below one.

def not_in_list(self):
        return List.query.filter(List.id.notin_(session.query(item_lists.c.list_id).filter(item_lists.c.item_id == self.id)))

Its not working because when you say in your query != self.id , it means equal to everything else, including item 3 i3. But i3 is linked to all the lists. Therefore it returns all the lists to you.


问:
Check data update in redux store
I have two audio players (mini and main) and when I dispatch pause or play in the mini player I must call the function in the main player. For this, I need to check if the isplaying parameter changes.

Does anyone have any idea on how can I achieve this?

In the mini player code:

store.dispatch({type: "PAUSE"})
```

<p>Then in the main player I call the pause function :</p>

<pre class="lang-js prettyprint-override"><code>const pause = () => {
audio.stop()
}
pause()
</code>```

How do I check if this parameter is changing?

答:
you must decorate the target component with the reducer variable:

example:

```<code>import React from 'react';
import { connect } from 'react-redux';

const Player = ({ status }) => (
   <div>
     {statys === 'PAUSE' ? 'paused' : 'playing'}
   </div>
)

const mapStateToProps = (state) => {
  const { status } = state.PlayerReducer;
  return { status };
};

export default connect(mapStateToProps, null)(Player);
</code>```

PlayerReducer:::

```<code>
export const Types = {
  PAUSE: 'player/PAUSE',
};

const initialState = {
  status: 'PLAYING',
};

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case Types.PAUSE:
      return { ...state, status: 'PAUSE' };
    default:
      return state;
  }
}

// Action Creators
export function pause() {
  return dispatch => {
    dispatch({
       type: Types.PAUSE
    });
  };
}
</code>```

Title: Check data update in redux store

Body:
I have two audio players (mini and main) and when I dispatch pause or play in the mini player I must call the function in the main player. For this, I need to check if the isplaying parameter changes.

Does anyone have any idea on how can I achieve this?

In the mini player code:

store.dispatch({type: "PAUSE"})

Then in the main player I call the pause function :

const pause = () => {
audio.stop()
}
pause()

How do I check if this parameter is changing?

Body:
you must decorate the target component with the reducer variable:

example:

import React from 'react';
import { connect } from 'react-redux';

const Player = ({ status }) => (
   <div>
     {statys === 'PAUSE' ? 'paused' : 'playing'}
   </div>
)

const mapStateToProps = (state) => {
  const { status } = state.PlayerReducer;
  return { status };
};

export default connect(mapStateToProps, null)(Player);

PlayerReducer:::

export const Types = {
  PAUSE: 'player/PAUSE',
};

const initialState = {
  status: 'PLAYING',
};

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case Types.PAUSE:
      return { ...state, status: 'PAUSE' };
    default:
      return state;
  }
}

// Action Creators
export function pause() {
  return dispatch => {
    dispatch({
       type: Types.PAUSE
    });
  };
}


问:
Whats the point of DOCTYPE?
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks </p>

<p>UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01? </p>

答: It's all about the standards and yes, browsers handles code differently. That means, that all browsers should display the page equally. If no standard is specified, browser will interpret the page as it wants.

Title: Whats the point of DOCTYPE?

Body:
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks

UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01?


问:
MSBUILD command not able to create artifacts
Tring to build asp.net web application using MSbuild. Build getting successful but in build_output folder only DLLs are present. When i do publish from visual studio I get a different output which i can deploy to IIS. But MSBUILD gives different output. I want same output as publish from visual studio.

The command I am using:

msbuild ASPWebApp.sln /t:Build /p:DeployOnBuild=true  /p:Configuration=Release /p:outdir=.\build_output

答:
Web application builds use a different target.  Try the "/t:WebPublish" target.</p>

```<code>/t:WebPublish /p:WebPublishMethod=FileSystem /p:PublishUrl="c:\build\output"
</code>```

Body:
Web application builds use a different target.  Try the "/t:WebPublish" target.

/t:WebPublish /p:WebPublishMethod=FileSystem /p:PublishUrl="c:\build\output"


问:
how do I get these results to add up to satisfy the conditions for the ifelse functions using data table method
```<code>        string <- c("AUSTRALIAN DOLLAR","BRAZILIAN REAL","CANADIAN DOLLAR","CHINESE YUAN","COLOMBIAN
        PESO","DANISH KRONER",
        "EURO, HONG KONG DOLLAR", "HUNGARIAN FORINT", "INDIAN RUPEE", "INDONESIAN RUPIAH",
        "JAPANESE YEN", "KOREA (SOUTH) WON", "MALAYSIAN RINGGIT", "MEXICAN PESO",
        "NEW ZEALAND DOLLAR", "NORWEIGIAN KRONER", "PERUCVIA SOL",
        "POLISH ZLOTY", "Russian Rouble (new)",
        "SINGAPORE DOLLAR", "STH AFRICAN RAND",
        "SWEIDSH KRONER", "SWISS FRANC", "TAIWANESE DOLAR",
        "THAILAND BAHTS", "TURKISH LIRA", "UK STERLING", "US DOLLAR")

          cashstring <- c("AUD","BRL","CAD","CHF","CNY","COP","DKK","EUR","GBP","HKD",
            "HUF","IDR","INR","JPY","KRW","MXN", "MYR","NOK","NZD",
            "PEN","PLN","RUB","SEK","SGD","THB","TRY","TWD",
            "USD","ZAR")

         lg$type <- ifelse(lg$cashtype == cashstring & lg$instrument_name == string, "Cash", "Not Cash")
</code>```

and i keep getting this error back:

```<code>                Warning messages:
                1: In lg$cashtype == cashstring :
                 longer object length is not a multiple of shorter object length
                2: In lg$instrument_name == string :
                 longer object length is not a multiple of shorter object length
</code>```

How could i fix this simple problem. the columns corresponds to the relevant currency so it shouldn't be a problem.

Thanks

答:
There are a couple of things going on here, but more information on what you're looking to do would be helpful.

The warning messages are telling you that the length of lg$cashtype is not a multiple of the length of cashstring, and similarly for instrument_name and string. It's doing this because it's comparing each entry of lg$cashtype to each of cashstring, in order, and then restarting once it reaches the end of the shorter object (and same for instrument_name and string. One weird thing is that the length of cashstring and string as you've posted them are not the same (I believe you're missing the cashstring entry for "ZAR") -- it's likely that this is part of your problem.

But even if you make that change, what your code will be doing is checking to see if the first row of lg (assuming it's a data frame) corresponds to "AUSTRALIAN DOLLAR" and "AUD", the second to "BRAZILIAN REAL" and "BRL", and so on. Unless your data frame is ordered in this very way (in which case you probably wouldn't be running this code), this probably isn't what you want. I imagine you want to do something like:

```<code>lg$type <- ifelse(lg$cashtype %in% cashstring & lg$instrument_name %in% string,
                  "Cash", "Not Cash")
</code>```

This will, for every row, tells you whether the corresponding cashtype is a value existing in cashstring, and the same for instrument_name and string.

If you provide more details about what you're trying to do, I'd be happy to refine my response.

Body:
        string <- c("AUSTRALIAN DOLLAR","BRAZILIAN REAL","CANADIAN DOLLAR","CHINESE YUAN","COLOMBIAN
        PESO","DANISH KRONER",
        "EURO, HONG KONG DOLLAR", "HUNGARIAN FORINT", "INDIAN RUPEE", "INDONESIAN RUPIAH",
        "JAPANESE YEN", "KOREA (SOUTH) WON", "MALAYSIAN RINGGIT", "MEXICAN PESO",
        "NEW ZEALAND DOLLAR", "NORWEIGIAN KRONER", "PERUCVIA SOL",
        "POLISH ZLOTY", "Russian Rouble (new)",
        "SINGAPORE DOLLAR", "STH AFRICAN RAND",
        "SWEIDSH KRONER", "SWISS FRANC", "TAIWANESE DOLAR",
        "THAILAND BAHTS", "TURKISH LIRA", "UK STERLING", "US DOLLAR")

          cashstring <- c("AUD","BRL","CAD","CHF","CNY","COP","DKK","EUR","GBP","HKD",
            "HUF","IDR","INR","JPY","KRW","MXN", "MYR","NOK","NZD",
            "PEN","PLN","RUB","SEK","SGD","THB","TRY","TWD",
            "USD","ZAR")

         lg$type <- ifelse(lg$cashtype == cashstring & lg$instrument_name == string, "Cash", "Not Cash")

and i keep getting this error back:

                Warning messages:
                1: In lg$cashtype == cashstring :
                 longer object length is not a multiple of shorter object length
                2: In lg$instrument_name == string :
                 longer object length is not a multiple of shorter object length

How could i fix this simple problem. the columns corresponds to the relevant currency so it shouldn't be a problem.

Thanks

Body:
There are a couple of things going on here, but more information on what you're looking to do would be helpful.

The warning messages are telling you that the length of lg$cashtype is not a multiple of the length of cashstring, and similarly for instrument_name and string. It's doing this because it's comparing each entry of lg$cashtype to each of cashstring, in order, and then restarting once it reaches the end of the shorter object (and same for instrument_name and string. One weird thing is that the length of cashstring and string as you've posted them are not the same (I believe you're missing the cashstring entry for "ZAR") -- it's likely that this is part of your problem.

But even if you make that change, what your code will be doing is checking to see if the first row of lg (assuming it's a data frame) corresponds to "AUSTRALIAN DOLLAR" and "AUD", the second to "BRAZILIAN REAL" and "BRL", and so on. Unless your data frame is ordered in this very way (in which case you probably wouldn't be running this code), this probably isn't what you want. I imagine you want to do something like:

lg$type <- ifelse(lg$cashtype %in% cashstring & lg$instrument_name %in% string,
                  "Cash", "Not Cash")

This will, for every row, tells you whether the corresponding cashtype is a value existing in cashstring, and the same for instrument_name and string.

If you provide more details about what you're trying to do, I'd be happy to refine my response.


问:
using recursion and default value to draw a pattern based on input
I have this code:

```<code>def pattern1(n, b=n):
  if n == 1:
    return 'A|'*b
  else:
    return 'A|'*b + '\n' + pattern1(n-1, b)

print(pattern1(5))
</code>```

so when i called the pattern1 method with 1 argument, the default second argument should have the same value, so this is not working, is there any code equivalent?

答:
You can't refer to other parameters in the function definition, but you can easily do this in the code as follows:

```<code>def pattern1(n, b):
  if not b:
    b = n
  if n == 1:
    return 'A|'*b
  else:
    return 'A|'*b + '\n' + pattern1(n-1, b)

print(pattern1(5))
</code>```

However it looks like in your code b is always n before you subtract 1, so just copy n before you modify it and don't pass a second parameter around:

```<code>def pattern1(n):
  if n == 1:
    return 'A|'*n
  else:
    n_copy = n
    return 'A|'*n + '\n' + pattern1(n-1, n_copy)

print(pattern1(5))
</code>```

Body:
I have this code:

def pattern1(n, b=n):
  if n == 1:
    return 'A|'*b
  else:
    return 'A|'*b + '\n' + pattern1(n-1, b)

print(pattern1(5))

so when i called the pattern1 method with 1 argument, the default second argument should have the same value, so this is not working, is there any code equivalent?

Body:
You can't refer to other parameters in the function definition, but you can easily do this in the code as follows:

def pattern1(n, b):
  if not b:
    b = n
  if n == 1:
    return 'A|'*b
  else:
    return 'A|'*b + '\n' + pattern1(n-1, b)

print(pattern1(5))

However it looks like in your code b is always n before you subtract 1, so just copy n before you modify it and don't pass a second parameter around:

def pattern1(n):
  if n == 1:
    return 'A|'*n
  else:
    n_copy = n
    return 'A|'*n + '\n' + pattern1(n-1, n_copy)

print(pattern1(5))


问:
Loop over NxN grid cells based of proximity to a certain cell
I have a N by N grid. I have a certain grid cell labeled with 0:

I intend to loop over grid cells, starting with 0 cell, in this order:

Start with cell labeled 0

Next cells are labeled 1

Next cells are labeled 2

...

Until the grid boundary is reached

How can I compose the loop?

I tried to follow this post. But I cannot adapt it to suit my situation.

答:
The property all cells labeled one is that the maximum distance in both axes is equal one, the same goes on for every cell that is if the 0 cell is on the cell (x0, y0) label of cell (x, y) will be equal to max(|x - x0|, |y - y0|)

Thus, to iterate over all labels, we can use something like this:

```<code>for (l = 0 -> min(x0, y0, N - x0, N - y0) + 1:
  for (x = x0 - l -> x0 + l)
     #checking cell (x, y0 - l)
  for (y = y0 - l -> y0 + l)
     #checking cell (x0 + l, y)
  for (x = x0 + l - 1 -> x0 + l)
     #checking cell (x, y0 + l)
  for (y = y0 - l -> y0 + l)
     #checking cell (x0 - l, y)
  #checking cell (x0 - l, y0 + l)
</code>```

you can merge loops iterating over x and y if you don't care that you iterate over adjacent cells.

ps: loop ranges are assumed to be closed on start and open in end. i.e. (x = a -> b) means range  (a, a+1, ..., b-1)

Body:
The property all cells labeled one is that the maximum distance in both axes is equal one, the same goes on for every cell that is if the 0 cell is on the cell (x0, y0) label of cell (x, y) will be equal to max(|x - x0|, |y - y0|)

Thus, to iterate over all labels, we can use something like this:

for (l = 0 -> min(x0, y0, N - x0, N - y0) + 1:
  for (x = x0 - l -> x0 + l)
     #checking cell (x, y0 - l)
  for (y = y0 - l -> y0 + l)
     #checking cell (x0 + l, y)
  for (x = x0 + l - 1 -> x0 + l)
     #checking cell (x, y0 + l)
  for (y = y0 - l -> y0 + l)
     #checking cell (x0 - l, y)
  #checking cell (x0 - l, y0 + l)

you can merge loops iterating over x and y if you don't care that you iterate over adjacent cells.

ps: loop ranges are assumed to be closed on start and open in end. i.e. (x = a -> b) means range  (a, a+1, ..., b-1)


问:
WeldContainer and SeContainer
What is the difference between using:

WeldContainer se = new Weld().initialize();

or

SeContainer se = SeContainerInitializer.newInstance().initialize();

I just want to use @Injection and @Produce annotations, but I have not found the difference between these two ways of initializing an object instance.

答:
Using SeContainerInitializer it will load an instance by ServiceLoader.load(...) and initialize it.

public static SeContainerInitializer newInstance() {
    return findSeContainerInitializer();
}

private static SeContainerInitializer findSeContainerInitializer() {

    SeContainerInitializer result;
    Iterator<SeContainerInitializer> iterator = ServiceLoader.load(SeContainerInitializer.class, SeContainerInitializer.class.getClassLoader()).iterator();

    if (!iterator.hasNext()) {
        throw new IllegalStateException("No valid CDI implementation found");
    }
    try {
        result = iterator.next();
    } catch (ServiceConfigurationError e) {
        throw new IllegalStateException("Error while instantiating SeContainerInitializer", e);
    }
    if (iterator.hasNext())
        throw new IllegalStateException("Two or more CDI implementations found, only one is supported");
    return result;
}

```

Weld is one implementation of SeContainerInitializer so if it exists on the classpath SeContainerInitializer.newInstance() method will create a new Weld instance and call initialize() method on this object.

Some hints which is a good choice

SeContainerInitializer.newInstance() is a factory method. If you want to create a vendor-independent application it would be good. But Weld is the reference implementation of CDI specification. Honestly I don't think choosing another implementation is necessary.

new Weld().initialize() will create a WeldContainer (which is an implementation of SeContainer). Using this method you will get a vendor-lock but you can use a lot of useful extra features (e.g. add alternatives or interceptors programmatically).
My opinion is: In this case vendor-lock doesn't matter anithing.

Conclusion

If you're planning to change CDI implementation anything else than Weld use independent SeContainerInitializer.newInstance() otherwise just create a Weld instance.
If I were you I would use new Weld() way.

Title: WeldContainer and SeContainer

Body:
Using SeContainerInitializer it will load an instance by ServiceLoader.load(...) and initialize it.

public static SeContainerInitializer newInstance() {
    return findSeContainerInitializer();
}

private static SeContainerInitializer findSeContainerInitializer() {

    SeContainerInitializer result;
    Iterator<SeContainerInitializer> iterator = ServiceLoader.load(SeContainerInitializer.class, SeContainerInitializer.class.getClassLoader()).iterator();

    if (!iterator.hasNext()) {
        throw new IllegalStateException("No valid CDI implementation found");
    }
    try {
        result = iterator.next();
    } catch (ServiceConfigurationError e) {
        throw new IllegalStateException("Error while instantiating SeContainerInitializer", e);
    }
    if (iterator.hasNext())
        throw new IllegalStateException("Two or more CDI implementations found, only one is supported");
    return result;
}

Weld is one implementation of SeContainerInitializer so if it exists on the classpath SeContainerInitializer.newInstance() method will create a new Weld instance and call initialize() method on this object.

Some hints which is a good choice

SeContainerInitializer.newInstance() is a factory method. If you want to create a vendor-independent application it would be good. But Weld is the reference implementation of CDI specification. Honestly I don't think choosing another implementation is necessary.

new Weld().initialize() will create a WeldContainer (which is an implementation of SeContainer). Using this method you will get a vendor-lock but you can use a lot of useful extra features (e.g. add alternatives or interceptors programmatically).
My opinion is: In this case vendor-lock doesn't matter anithing.

Conclusion

If you're planning to change CDI implementation anything else than Weld use independent SeContainerInitializer.newInstance() otherwise just create a Weld instance.
If I were you I would use new Weld() way.


问:
this.$scope is null in $postLink() of controller
```<code>class pageController {

    constructor($scope, MyEditableGrid) {
        this.$scope = $scope;
        this.MyEditableGrid = MyEditableGrid;
        this.myEditableGrid = {
            appScope: this.$scope,
            .....
        }
    }
    $postLink() {
        this.$scope.$on('message', function (event, data) {
            console.log(this.MyEditableGrid); ==> null?
            console.log(this.$scope);  ==> null?
            console.log(this.myEditableGrid); ==> null
        }
    }
}
</code>```

The message was broadcast from service.js:

$rootScope.$broadcast('message',data);

the error message in browser inspector for console.log(this.MyEditableGrid):

TypeError: Cannot read property 'MyEditableGrid' of null

The error message in browser inspector for console.log(this.$scope):

TypeError: Cannot read property '$scope' of null

答:
In your constructor you made EditableGrid a property of your class, not the $scope.

You can with access it with this.EditableGrid, or add it to the $scope in the constructor.

--UPDATE AFTER QUESTION CODE HAS BEEN UPDATED--

You are losing the scope of this by using function(..) rather than the fat arrow function which preserves the scope of this.

Try this:

```<code>this.$scope.$on('message', (event, data) => {
  // this still points to the class instance
}):
</code>```

Body:
class pageController {

    constructor($scope, MyEditableGrid) {
        this.$scope = $scope;
        this.MyEditableGrid = MyEditableGrid;
        this.myEditableGrid = {
            appScope: this.$scope,
            .....
        }
    }
    $postLink() {
        this.$scope.$on('message', function (event, data) {
            console.log(this.MyEditableGrid); ==> null?
            console.log(this.$scope);  ==> null?
            console.log(this.myEditableGrid); ==> null
        }
    }
}

The message was broadcast from service.js:

$rootScope.$broadcast('message',data);

the error message in browser inspector for console.log(this.MyEditableGrid):

TypeError: Cannot read property 'MyEditableGrid' of null

The error message in browser inspector for console.log(this.$scope):

TypeError: Cannot read property '$scope' of null

Body:
In your constructor you made EditableGrid a property of your class, not the $scope.

You can with access it with this.EditableGrid, or add it to the $scope in the constructor.

--UPDATE AFTER QUESTION CODE HAS BEEN UPDATED--

You are losing the scope of this by using function(..) rather than the fat arrow function which preserves the scope of this.

Try this:

this.$scope.$on('message', (event, data) => {
  // this still points to the class instance
}):


问:
How can I put text over image card header bootstrap 4
I try to put Title over the image, I want My card-title over my image not sure do I need CSS?

here is my HTML

```<code><div class="card card-blog">
        <div class="card">
            <a href="#pablo">
                <img class="img" src="assets/img/backgound.jpg">
            </a>
        </div>
        <div class="card-body text-center">
            <h4 class="card-title">
                TEXT OVER IMAGE
            </h4>
            <div class="card-description">
                <div class="table-responsive">

                </div>
            </div>
            <div class="card-footer">
                <a href="#pablo" class="btn btn-danger btn-round">View Article</a>
            </div>
        </div>
    </div>
</div>
</code>```

Output : Can I move card-title over image ?

答:
I know this is old, but for those that are using Bootstrap 4, there is a native way to do this using the card-img-overlay class.

```<code><div class="card bg-dark text-white">
  <img class="card-img" src="..." alt="Card image">
  <div class="card-img-overlay">
    <h5 class="card-title">Card title</h5>
    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
    <p class="card-text">Last updated 3 mins ago</p>
  </div>
</div>
</code>```

https://getbootstrap.com/docs/4.0/components/card/#image-overlays

Body:
I try to put Title over the image, I want My card-title over my image not sure do I need CSS?

here is my HTML

                TEXT OVER IMAGE

                View Article

Output : Can I move card-title over image ?

Body:
I know this is old, but for those that are using Bootstrap 4, there is a native way to do this using the card-img-overlay class.

<div class="card bg-dark text-white">
  <img class="card-img" src="..." alt="Card image">
  <div class="card-img-overlay">
    <h5 class="card-title">Card title</h5>
    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
    <p class="card-text">Last updated 3 mins ago</p>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/card/#image-overlays


问:
How to alert input value from JSON (javascript)
I have a problem trying to alert input values from json object. I get 'undefined' when i execute this code. Can someone please give me some ideas, I think I tried everything.
btw. I have to use JSON because it is my school project.
Thank you! xx</p>

```<code><script>
let arr = [];

function adduser(){
    let user = {
        name: document.getElementById("first_name").value,
        lname: document.getElementById("last_name").value,
        text: document.getElementById("txtara").value,
        email: document.getElementById("emails").value
    }

    arr.push(user);
    let json_str = JSON.stringify(arr);
    alert(json_str.name);
}
</script>
</code>```

答:
You can't access json the same way you access an object.
JSON is a string, you can still find user and it's name by searching through a string, but since it's your school project I honestly doubt that is the point of the lesson.

You probably have to to JSON.parse(arr)[0].name where 0 is first index of your array, since you push the user to it.


问:
Is it possible to access parent class's members from a nested class in an aggregation
My Question is, say i declare a class within a class, as a sort of an aggregation:

```<code>class A:

    self.foo = 20
    self.bar = 30

    def someFunc(self):

        class B:
            # some code here

        BObject = B()
</code>```

is it possible to access the foo/bar variables from within class B ? If yes, then how ?

I have run into this problem while using wxpython, and needing to write a class within the main frame class to handle a particular custom dialog.

Thanks in Advance :)

答:
I suggest the following correction:

```<code>>>> class A:
...      foo=20
...      bar=30
...      def build_child(self):
...              class B:
...                      def __init__(self, parent):
...                              self.parent = parent
...              return B(self)
...
>>> a = A()
>>> b = a.build_child()
>>> b
<__main__.B object at 0x89952ac>
>>> b.parent
<__main__.A object at 0x89956ec>
</code>```

This way, if you change class A, you don't have to update class B.

Body:
My Question is, say i declare a class within a class, as a sort of an aggregation:

class A:

    self.foo = 20
    self.bar = 30

    def someFunc(self):

        class B:
            # some code here

        BObject = B()

is it possible to access the foo/bar variables from within class B ? If yes, then how ?

I have run into this problem while using wxpython, and needing to write a class within the main frame class to handle a particular custom dialog.

Thanks in Advance :)

Body:
I suggest the following correction:

>>> class A:
...      foo=20
...      bar=30
...      def build_child(self):
...              class B:
...                      def __init__(self, parent):
...                              self.parent = parent
...              return B(self)
...
>>> a = A()
>>> b = a.build_child()
>>> b
<__main__.B object at 0x89952ac>
>>> b.parent
<__main__.A object at 0x89956ec>

This way, if you change class A, you don't have to update class B.


问:
Play audio file from a commands in Discord.js
I want to play an audio file in my folder from a command on Discord bot, in Discord.js. How should i do? Thanks
This is my code:

const Discord = require('discord.js');
const client =  new Discord.Client();
var ChannelId = "ID_CHANNEL";
var token = "TOKEN";

client.on("message", (message) => {

  if(message.content == "!audio"){
    /*HERE*/
  }

});```

答:
You'll need to find a voice channel first, for example the one the user typing the command is in (if any) like this :

```<code>const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send("No voice channel.");
</code>```

Then join the channel and then play your file :

```<code>voiceChannel.join()
   .then(connection => {
      connection.play('/path/to/yourFile.mp3');
   });
</code>```

You can check what else you can do by reading the docs.

Body:
You'll need to find a voice channel first, for example the one the user typing the command is in (if any) like this :

const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send("No voice channel.");

Then join the channel and then play your file :

voiceChannel.join()
   .then(connection => {
      connection.play('/path/to/yourFile.mp3');
   });

You can check what else you can do by reading the docs.


问:
HashMap in Java
I had an interview today, and I got the following Java code:

```<code>public class Question_6 {
    public static void main(String[] args){
        Map<Integer,String> map1 = new HashMap<Integer,String>();
        map1.put(new Integer(1),"001a");
        map1.put(new Integer(1),"001b");
        map1.put(new Integer(2),"002");

        System.out.println(map1.size());

        Map<MyInt,String> map2 = new HashMap<MyInt,String>();
        map2.put(new MyInt(1),"001a");
        map2.put(new MyInt(1),"001b");
        map2.put(new MyInt(2),"002");

        System.out.println(map2.size());

    }

}
public class MyInt {
    int i;
    public MyInt(int i) {
       this.i = i;
    }

}
</code>```

The questions were:

What will be printed to the console?

Suggest a solution to the problem.

I know now that the answer to the first question is :

```<code>2

3
</code>```

But I don't know why? What is the problem with MyInt?

答:
The Integer class overrides the equals() method to do value-based comparison.No need to manually include equals() or hashcode() methods. My solution is as follows

```<code>import java.util.HashMap;
import java.util.Map;

    public class HashMapEqualsHashcode {

        public static void main(String[] args) {

            MyInt obj = new MyInt(50);

            Map<Integer, String> map1 = new HashMap<Integer, String>();

              map1.put(new Integer(1),"001a");
              map1.put(new Integer(1),"001b");
              map1.put(new Integer(2),"002");

            System.out.println("map1 size "+map1.size());

            Map<MyInt,String> map2 = new HashMap<MyInt,String>();
            map2.put(new MyInt(1),"001a");
            map2.put(new MyInt(1),"001b");
            map2.put(new MyInt(2),"002");

            System.out.println("map2 size "+map2.size());
        }
    }

     class MyInt {
        int i;
        public MyInt(int i) {
           this.i = i;
        }

    }
</code>```

Screenshot for the solution

https://i.stack.imgur.com/yVkgL.png

Title: HashMap in Java

Body:
I had an interview today, and I got the following Java code:

public class Question_6 {
    public static void main(String[] args){
        Map<Integer,String> map1 = new HashMap<Integer,String>();
        map1.put(new Integer(1),"001a");
        map1.put(new Integer(1),"001b");
        map1.put(new Integer(2),"002");

        System.out.println(map1.size());

        Map<MyInt,String> map2 = new HashMap<MyInt,String>();
        map2.put(new MyInt(1),"001a");
        map2.put(new MyInt(1),"001b");
        map2.put(new MyInt(2),"002");

        System.out.println(map2.size());

    }

}
public class MyInt {
    int i;
    public MyInt(int i) {
       this.i = i;
    }

}

The questions were:

What will be printed to the console?

Suggest a solution to the problem.

I know now that the answer to the first question is :

2

3

But I don't know why? What is the problem with MyInt?

Body:
The Integer class overrides the equals() method to do value-based comparison.No need to manually include equals() or hashcode() methods. My solution is as follows

import java.util.HashMap;
import java.util.Map;

    public class HashMapEqualsHashcode {

        public static void main(String[] args) {

            MyInt obj = new MyInt(50);

            Map<Integer, String> map1 = new HashMap<Integer, String>();

              map1.put(new Integer(1),"001a");
              map1.put(new Integer(1),"001b");
              map1.put(new Integer(2),"002");

            System.out.println("map1 size "+map1.size());

            Map<MyInt,String> map2 = new HashMap<MyInt,String>();
            map2.put(new MyInt(1),"001a");
            map2.put(new MyInt(1),"001b");
            map2.put(new MyInt(2),"002");

            System.out.println("map2 size "+map2.size());
        }
    }

     class MyInt {
        int i;
        public MyInt(int i) {
           this.i = i;
        }

    }

Screenshot for the solution

https://i.stack.imgur.com/yVkgL.png


问:
W3C Validator returns an error in index.html, at app-root
I try to validate my html page but when i retrieve the following error:

```<code>Error: Element app-root not allowed as child of element body in this context.
(Suppressing further errors from this subtree.)

From line 4347, column 7; to line 4347, column 16

r">↩      <app-root>

Content model for element div:
Flow content.
Neither tag is omissible.
</code>```

This is the html of my index.html:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Example</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
  </head>
  <body>
      <app-root></app-root>
  </body>
</html>
</code>```

How I can, if it is possible, bypass the test?

答:
As Angular has a way to create custom elements to reuse the components, app-root tag is a custom element for Angular to render the App Component which is the root component of the project.

You can find this selector when going to src\app\app.component.ts file and check the selector property inside @Component.
app-root can be changed to any name you want by changing the selector property and the tag name.

The HTML validator will search for any unfamiliar tags and complain about it, even though it is a custom element that is used inside Angular.

Body:
I try to validate my html page but when i retrieve the following error:

Error: Element app-root not allowed as child of element body in this context.
(Suppressing further errors from this subtree.)

From line 4347, column 7; to line 4347, column 16

r">↩      <app-root>

Content model for element div:
Flow content.
Neither tag is omissible.

This is the html of my index.html:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Example</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />

      <app-root></app-root>

How I can, if it is possible, bypass the test?


问:
Django error, CSRF Failed: CSRF token missing or incorrect
I have Backend = Django+Django Rest+Djoser(Token based user auth app)
Fontend = React JS + Axios.

In Local Host/Development I could do user login and authentication using token. It did'nt give error in Postman too.

In production mode It gives error as CSRF failed.

Why is so ?

I think CSRF token only needed in session authentication.

I tried removing session auth but resulted in server crash

```<code>REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',

    ),
   ....
}
</code>```

middlewares

```<code>MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
</code>```

installed apps

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'shop',
    'corsheaders',
    'frontend',
    'djoser',
    'rest_framework.authtoken',
    'users'
]

</code>```

答:
Add following lines in settings.py:

```<code>REST_FRAMEWORK = {
  'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.BasicAuthentication',
   )
}
</code>```

Or if you have already added these lines in your settings.py file, then find and remove following line from settings.py:

```<code>rest_framework.authentication.SessionAuthentication
</code>```

Source: https://khalsalabs.com/disable-csrf-verification-for-django

Body:
I have Backend = Django+Django Rest+Djoser(Token based user auth app)
Fontend = React JS + Axios.

In Local Host/Development I could do user login and authentication using token. It did'nt give error in Postman too.

In production mode It gives error as CSRF failed.

Why is so ?

I think CSRF token only needed in session authentication.

I tried removing session auth but resulted in server crash

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',

    ),
   ....
}

middlewares

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

installed apps

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'shop',
    'corsheaders',
    'frontend',
    'djoser',
    'rest_framework.authtoken',
    'users'
]

Body:
Add following lines in settings.py:

REST_FRAMEWORK = {
  'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.BasicAuthentication',
   )
}

Or if you have already added these lines in your settings.py file, then find and remove following line from settings.py:

rest_framework.authentication.SessionAuthentication

Source: https://khalsalabs.com/disable-csrf-verification-for-django


问:
How does this pointer-based strcat work in C?
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

```<code>char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}
</code>```

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

答:
const char *src

src shouldn't be modified by the function, hence use const correctness to mark it as read-only.

char *rdest = dest;

Save the original position until later, since there's a requirement that strcat should return a pointer to the first element of the merged string (return rdest;).

while (*dest)

     dest++;

The while loop is implicitly looking for the null terminator. Meaning: find the end of the first string, so that after this loop, dest points at the null terminator of that string.

while (*dest++ = *src++)

This is a common, although admittedly confusing idiom in C. (It actually implements strcpy in this line.) Operator precedence says postfix ++ takes precedence over prefix * over assignment =.

So first each pointer is evaluated and ++ is applied to the pointers, not the pointed-at data. But since it is postfix, the actual increment of the pointer address does not happen until the end of the expression.

* takes the contents of each pointer before this increment, and then = copies the content from *src to *dest. Again, this happens before the addresses are incremented.

Finally, there is an implicit check against null termination, since the result of the = operand can actually be checked - it is equivalent to its left operand, in this case *dest. And note that the null terminator gets copied, too.

You could rewrite this while loop in a less confusing way:

```<code>*dst = *src;
while(*src != '\0')
{
  dst++;
  src++;
  *dst = *src;
}
</code>```

Body:
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

Body:
const char *src

src shouldn't be modified by the function, hence use const correctness to mark it as read-only.

char *rdest = dest;

Save the original position until later, since there's a requirement that strcat should return a pointer to the first element of the merged string (return rdest;).

while (*dest)

     dest++;

The while loop is implicitly looking for the null terminator. Meaning: find the end of the first string, so that after this loop, dest points at the null terminator of that string.

while (*dest++ = *src++)

This is a common, although admittedly confusing idiom in C. (It actually implements strcpy in this line.) Operator precedence says postfix ++ takes precedence over prefix * over assignment =.

So first each pointer is evaluated and ++ is applied to the pointers, not the pointed-at data. But since it is postfix, the actual increment of the pointer address does not happen until the end of the expression.

* takes the contents of each pointer before this increment, and then = copies the content from *src to *dest. Again, this happens before the addresses are incremented.

Finally, there is an implicit check against null termination, since the result of the = operand can actually be checked - it is equivalent to its left operand, in this case *dest. And note that the null terminator gets copied, too.

You could rewrite this while loop in a less confusing way:

*dst = *src;
while(*src != '\0')
{
  dst++;
  src++;
  *dst = *src;
}


问:
Can Haskell programs be represented as Lisp S-expressions?
This would be useful for genetic programming, which usually use a Lisp subset as representation for programs.

I've found something called Liskell (Lisp syntax, Haskell inside) on the web, but the links are broken and I can't find the paper on it...

答: In most genetic programming software, programs are represented as abstract syntax trees (AST) which are evaluated directly in that form. The Lisp S-expression syntax is only apparent when the programs are output as source code. Have you considered just modifying the output module in your chosen software to produce Haskell source code from the ASTs instead?</p>


问:
Angular load time is too long (too slow) on Safari (both Mac and iOS), much longer than Chrome (PC and Android)
Angular app loading is too slow on Safari, it takes much more time than it's on Chrome.
Both on PC and mobile device.
A same app,
Chrome:  9.47s
Safari: 27.78s

And on the Safari, there has some time no any action.
How to increase its load performance on Safari?
Appreciate any advice!

--Anndy

答:
Your network speed is throttled in safari for some reason. Because each bundle is taking atleast 4 times the time to download that in chrome. It's not angular's performance issue. It might be some configuration in your safari.

One of the references i could find is :- Safari Web Inspector network throttling


问:
How can I solve the output error in flipping a coin?
I am writing code about the probability of flipping a coin as follows, but I keep getting errors.

```<code>import random

tries = 0
number = random.randint(0, 1)
def coin_probability(hehe):
    for a in range(1, 101):
        heads = 0; tails = 0
        tries += 1
        if tries <= 10:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
        else:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 :  %s' %(n, coin_probability(n))) `
</code>```

I want the probability to come out one by one from 1 to 10, and display 10 units from 11 to 100. For example:

```<code>1 번째까지~: (probability)%
2 번째까지~: (probability)%
3 번째까지~: (probability)%
...
10 번째까지~: (probability)%
20 번째까지~: (probability)%
...
</code>```

it should be printed like this.
(※I set heads to 0 and tails to 1.)

答:
I hope that's what you want:

import random

def coin_probability(attempts):
    heads = 0
    for try_number in range(1, attempts + 1):
        number = random.randint(0, 1)

        if number == 0:
            heads += 1

        cp = (heads/try_number) * 100

        if try_number <= 10 or (try_number % 10) == 0:
            print(f"{try_number} 번째까지 던지기에서 앞면이 나온 확률: {round(cp,5)}")

def main():
    attempts = int(input("동전 던지기 시도 횟수를 입력: "))
    print('*' * 47)
    coin_probability(attempts)

if __name__ == "__main__":
    main()
```

Body:
I am writing code about the probability of flipping a coin as follows, but I keep getting errors.

import random

tries = 0
number = random.randint(0, 1)
def coin_probability(hehe):
    for a in range(1, 101):
        heads = 0; tails = 0
        tries += 1
        if tries <= 10:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
        else:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 :  %s' %(n, coin_probability(n))) `

I want the probability to come out one by one from 1 to 10, and display 10 units from 11 to 100. For example:

1 번째까지~: (probability)%
2 번째까지~: (probability)%
3 번째까지~: (probability)%
...
10 번째까지~: (probability)%
20 번째까지~: (probability)%
...

it should be printed like this.
(※I set heads to 0 and tails to 1.)