问:
"categorie.forEach is not a function"
I'm trying to display this.cat in a dropdown but I get this error :

categorie.forEach is not a function

This is my code :

```<code>
  getCategories(){
    this.policeService.getCategoriesList().subscribe(
      data => {
      this.categories=data;
      console.log(this.categories);
      },
     error =>
      console.log(error));
  }

changeCategories() {
    this.sourceCategories.length = 0;
    this.categories.forEach((categorie) => {
        categorie.forEach((categorie) => this.brancheid = categorie.branche.id);

        if(this.policeform.get("branche").value.id == this.brancheid) {
            this.sourceCategories.push(categorie);
            this.cat = JSON.parse(JSON.stringify(this.sourceCategories));
        }
    })
}
</code>```

答:
Your categories array seems like array in the form of object.

Try Array Prototype forEach method..  it will work .

```<code>Array.prototype.forEach.call(this.categories, categorie=> {
  console.log(categorie)
});
</code>```

Title: "categorie.forEach is not a function"

Body:
I'm trying to display this.cat in a dropdown but I get this error :

categorie.forEach is not a function

This is my code :

  getCategories(){
    this.policeService.getCategoriesList().subscribe(
      data => {
      this.categories=data;
      console.log(this.categories);
      },
     error =>
      console.log(error));
  }

changeCategories() {
    this.sourceCategories.length = 0;
    this.categories.forEach((categorie) => {
        categorie.forEach((categorie) => this.brancheid = categorie.branche.id);

        if(this.policeform.get("branche").value.id == this.brancheid) {
            this.sourceCategories.push(categorie);
            this.cat = JSON.parse(JSON.stringify(this.sourceCategories));
        }
    })
}

Body:
Your categories array seems like array in the form of object.

Try Array Prototype forEach method..  it will work .

Array.prototype.forEach.call(this.categories, categorie=> {
  console.log(categorie)
});


来源: stackexchange

答:
No need of for each in categorie. </p>

```<code>changeCategories(){
    this.sourceCategories.length=0;
    this.categories.forEach((categorie)=>{
      this.brancheid=categorie.branche.id;
      if(this.policeform.get("branche").value.id==this.brancheid){
        this.sourceCategories.push(categorie);
        this.cat=JSON.parse(JSON.stringify(this.sourceCategories));
      }
   })
   }
</code>```

ContentLicense: CC BY-SA 4.0

Title: "categorie.forEach is not a function"

Body:
No need of for each in categorie.

changeCategories(){
    this.sourceCategories.length=0;
    this.categories.forEach((categorie)=>{
      this.brancheid=categorie.branche.id;
      if(this.policeform.get("branche").value.id==this.brancheid){
        this.sourceCategories.push(categorie);
        this.cat=JSON.parse(JSON.stringify(this.sourceCategories));
      }
   })
   }


问:
Merge values in map kotlin
I need merge maps mapA andmapB with pairs of "name" - "phone number" into the final map, sticking together the values for duplicate keys, separated by commas. Duplicate values should be added only once.
I need the most idiomatic and correct in terms of language approach.

For example:

```<code>val mapA = mapOf("Emergency" to "112", "Fire department" to "101", "Police" to "102")
val mapB = mapOf("Emergency" to "911", "Police" to "102")
</code>```

The final result should look like this:

```<code>{"Emergency" to "112, 911", "Fire department" to "101", "Police" to "102"}
</code>```

This is my function:

```<code>fun mergePhoneBooks(mapA: Map<String, String>, mapB: Map<String, String>): Map<String, String> {
    val unionList: MutableMap <String, String> = mapA.toMutableMap()
    unionList.forEach { (key, value) -> TODO() } // here's I can't come on with a beatiful solution

    return unionList
}
</code>```

答:
A more generic approach (as this post comes up when searching for kotlin and merging maps):

```<code>fun <K, V1, V2, R> Map<K, V1>.mergeReduce(other: Map<K, V2>, reduce: (key: K, value1: V1?, value2: V2?) -> R): Map<K, R> =
    (this.keys + other.keys).associateWith { reduce(it, this[it], other[it]) }
</code>```

It allows for Maps with different types of values to be merged, increased freedom with a custom reducer and increased readability.

Your problem can than be solved as:

```<code>mapA.mergeReduce(mapB) { _, value1, value2 -> listOfNotNull(value1, value2).joinToString(", ") }
</code>```

Title: Merge values in map kotlin

Body:
I need merge maps mapA andmapB with pairs of "name" - "phone number" into the final map, sticking together the values for duplicate keys, separated by commas. Duplicate values should be added only once.
I need the most idiomatic and correct in terms of language approach.

For example:

val mapA = mapOf("Emergency" to "112", "Fire department" to "101", "Police" to "102")
val mapB = mapOf("Emergency" to "911", "Police" to "102")

The final result should look like this:

{"Emergency" to "112, 911", "Fire department" to "101", "Police" to "102"}

This is my function:

fun mergePhoneBooks(mapA: Map<String, String>, mapB: Map<String, String>): Map<String, String> {
    val unionList: MutableMap <String, String> = mapA.toMutableMap()
    unionList.forEach { (key, value) -> TODO() } // here's I can't come on with a beatiful solution

    return unionList
}

Body:
A more generic approach (as this post comes up when searching for kotlin and merging maps):

fun <K, V1, V2, R> Map<K, V1>.mergeReduce(other: Map<K, V2>, reduce: (key: K, value1: V1?, value2: V2?) -> R): Map<K, R> =
    (this.keys + other.keys).associateWith { reduce(it, this[it], other[it]) }

It allows for Maps with different types of values to be merged, increased freedom with a custom reducer and increased readability.

Your problem can than be solved as:

mapA.mergeReduce(mapB) { _, value1, value2 -> listOfNotNull(value1, value2).joinToString(", ") }


问:
Removing a .docx file starting with ~$ via the terminal
After playing around in the terminal I found that my desktop directory had a file named "~$Löp.docx" that wasn't visible outside the terminal. The file seems to be some kind of crash log for a (now deleted) word file called "Löp". I would like to remove the file and have thus far failed to enter a rm command that works.

When trying to echo the filename as

```<code>    echo "~$Löp.docx"
</code>```

I get the output

```<code>    ~?p.docx
</code>```

How can I retain the correct name for a rm statement?

答:
Just Quote it, here's an example:</p>

```<code>rm '~$some file name.docx'
</code>```

Body:
After playing around in the terminal I found that my desktop directory had a file named "~$Löp.docx" that wasn't visible outside the terminal. The file seems to be some kind of crash log for a (now deleted) word file called "Löp". I would like to remove the file and have thus far failed to enter a rm command that works.

When trying to echo the filename as

    echo "~$Löp.docx"

I get the output

    ~?p.docx

How can I retain the correct name for a rm statement?

Body:
Just Quote it, here's an example:

rm '~$some file name.docx'


问:
How do i detect which specific button in my controller is being released in pygame
i am trying to detect which button is being pressed from my controller and when it is released.
This is how far i have managed to get.

import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                if j.get_button(1):
                    print("x")
                elif j.get_button(2):
                    print("a")
            elif event.type == pygame.JOYBUTTONUP:
                print("button released")

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()
```

i am new to programming and i dont entirely understand this piece of code.
this detects if x or a is being pressed and if any button is being released. I want it to detect if x or a is being pressed and when they are released.
Thanks for reading!

答:
pygame.event.get() returns a list of events(events are a type of structure/object of pygame generated when the user does something moves mouse / presses buttons e.t.c.).then for each of those events you check if the they are the event you want(pygame.JOYBUTTONDOWN or event.type,pygame.JOYBUTTONUP).
you can only check if a button is pressed and then see which button is pressed.

                if event.type == pygame.JOYBUTTONDOWN:
                    if j.get_button(1):
                        print("x")
                    elif j.get_button(2):
                        print("a")
```

<p>to see when buttons get released best way i can think off is having a list of Button Status .When the status for a button changes you do something .</p>

```ButtonStatus[2];
ButtonStatus[0]=get_button(1);#a
ButtonStatus[1]=get_button(2);#x
if event.type == pygame.JOYBUTTONUP:
           if ButtonStatus[0]!=get_button(1)
                #status changed do yr code for button release a
                pass;
           if ButtonStatus[1]!=get_button(2)
                #status changed do yr code for button release b
                pass;
```

above code is a sample not actually compiled . general idea is to check when a button is released,check which button changes status and execute code accordingly.

Body:
i am trying to detect which button is being pressed from my controller and when it is released.
This is how far i have managed to get.

import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                if j.get_button(1):
                    print("x")
                elif j.get_button(2):
                    print("a")
            elif event.type == pygame.JOYBUTTONUP:
                print("button released")

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()

i am new to programming and i dont entirely understand this piece of code.
this detects if x or a is being pressed and if any button is being released. I want it to detect if x or a is being pressed and when they are released.
Thanks for reading!

Body:
pygame.event.get() returns a list of events(events are a type of structure/object of pygame generated when the user does something moves mouse / presses buttons e.t.c.).then for each of those events you check if the they are the event you want(pygame.JOYBUTTONDOWN or event.type,pygame.JOYBUTTONUP).
you can only check if a button is pressed and then see which button is pressed.

                if event.type == pygame.JOYBUTTONDOWN:
                    if j.get_button(1):
                        print("x")
                    elif j.get_button(2):
                        print("a")

to see when buttons get released best way i can think off is having a list of Button Status .When the status for a button changes you do something .

ButtonStatus[2];
ButtonStatus[0]=get_button(1);#a
ButtonStatus[1]=get_button(2);#x
if event.type == pygame.JOYBUTTONUP:
           if ButtonStatus[0]!=get_button(1)
                #status changed do yr code for button release a
                pass;
           if ButtonStatus[1]!=get_button(2)
                #status changed do yr code for button release b
                pass;

above code is a sample not actually compiled . general idea is to check when a button is released,check which button changes status and execute code accordingly.


问:
What is difference between empty_clob and createtemporary in Oracle?
Can anyone please tell what is the basic difference between empty_clob and createtemporary.

Here is my code.

```<code>/*empty_clob vs createtemporary()*/
DECLARE
    elob   CLOB;
    tlob   CLOB;
BEGIN
    IF elob IS NULL THEN
        dbms_output.put_line('elob is null');
    ELSE
        dbms_output.put_line('elob has a locator');
    END IF;

    IF tlob IS NULL THEN
        dbms_output.put_line('tlob is null');
    ELSE
        dbms_output.put_line('tlob has a locator');
    END IF;

    elob := empty_clob;
    dbms_lob.createtemporary(tlob, false);

    IF elob IS NULL THEN
        dbms_output.put_line('elob is null');
    ELSE
        dbms_output.put_line('elob has a locator');
    END IF;

    IF tlob IS NULL THEN
        dbms_output.put_line('tlob is null');
    ELSE
        dbms_output.put_line('tlob has a locator');
    END IF;

    dbms_lob.freetemporary(elob); -- exception
    dbms_lob.freetemporary(tlob);
END;
</code>```

and why I can not pass an empty object locator which is returned by empty_clob to any dbms_lob function/procedure.

答:
A temporary lob is a full blown LOB, the only difference to a normal, filled LOB is that it is not associated with a table and that it lives in a temporary tablespace. See here for details. The purpose is to manipulate your LOB in the temp space until you are ready to store it in a normal table row.

However, empty_clob initialized a LOB locator and creates a proper LOB of length 0. I copied Julian Dykes' example from his excellent presentation LOB Internals:

So you cannot call dbms_lob.freetemporary on an empty_clob, because it's not in the temp tablespace.

EDIT:

Once the empty_clob is stored in a table, you can inspect it's LOBID:

```<code>CREATE TABLE t (c CLOB, e CLOB DEFAULT EMPTY_CLOB()) LOB (e) STORE AS SECUREFILE;
INSERT INTO t (c) VALUES (null);

SELECT DBMS_LOBUTIL.getinode(e).lobid   AS lobid,
       DBMS_LOBUTIL.getinode(e).length  AS length,
       DBMS_LOBUTIL.getinode(e).extents AS extents
  FROM t;

LOBID                  LENGTH   EXTENTS
0000000100000007E5E1   0        0
</code>```

According to Julian, the LOBID is generated from a sequence, which means it is quite likely unique across the database.

Body:
Can anyone please tell what is the basic difference between empty_clob and createtemporary.

Here is my code.

/*empty_clob vs createtemporary()*/
DECLARE
    elob   CLOB;
    tlob   CLOB;
BEGIN
    IF elob IS NULL THEN
        dbms_output.put_line('elob is null');
    ELSE
        dbms_output.put_line('elob has a locator');
    END IF;

    IF tlob IS NULL THEN
        dbms_output.put_line('tlob is null');
    ELSE
        dbms_output.put_line('tlob has a locator');
    END IF;

    elob := empty_clob;
    dbms_lob.createtemporary(tlob, false);

    IF elob IS NULL THEN
        dbms_output.put_line('elob is null');
    ELSE
        dbms_output.put_line('elob has a locator');
    END IF;

    IF tlob IS NULL THEN
        dbms_output.put_line('tlob is null');
    ELSE
        dbms_output.put_line('tlob has a locator');
    END IF;

    dbms_lob.freetemporary(elob); -- exception
    dbms_lob.freetemporary(tlob);
END;

and why I can not pass an empty object locator which is returned by empty_clob to any dbms_lob function/procedure.

Body:
A temporary lob is a full blown LOB, the only difference to a normal, filled LOB is that it is not associated with a table and that it lives in a temporary tablespace. See here for details. The purpose is to manipulate your LOB in the temp space until you are ready to store it in a normal table row.

However, empty_clob initialized a LOB locator and creates a proper LOB of length 0. I copied Julian Dykes' example from his excellent presentation LOB Internals:

So you cannot call dbms_lob.freetemporary on an empty_clob, because it's not in the temp tablespace.

EDIT:

Once the empty_clob is stored in a table, you can inspect it's LOBID:

CREATE TABLE t (c CLOB, e CLOB DEFAULT EMPTY_CLOB()) LOB (e) STORE AS SECUREFILE;
INSERT INTO t (c) VALUES (null);

SELECT DBMS_LOBUTIL.getinode(e).lobid   AS lobid,
       DBMS_LOBUTIL.getinode(e).length  AS length,
       DBMS_LOBUTIL.getinode(e).extents AS extents
  FROM t;

LOBID                  LENGTH   EXTENTS
0000000100000007E5E1   0        0

According to Julian, the LOBID is generated from a sequence, which means it is quite likely unique across the database.


问:
A Function chooses the maximum value among values in two or more labels
this is the dummy data

```<code>df=structure(list(group1 = c("0.1531181", "0.1537821", "0.284066",
"0.7549542", "0.2495559"), group2 = c("0.3116818", "0.5837542",
"0.430886", "0.7856033", "0.6351635"), group3 = c(7.80191002743109e-17,
2.22008198884117e-49, 4.64379480824993e-13, 0.0476184338005978,
2.2062018808144e-39)), row.names = c("C4orf39", "FAM89A", "FMNL1",
"CYB5R2", "CHST2"), class = "data.frame")
</code>```

As you can see, the 'df' has three columns: group1, group2 and group3. Each of rows is gene name.

Now I want to build a function in R so that it will automatically detemine which value in either of the columns is maximum, and assign the group number to a new column 'GeneCluster'. The final result looks like:

------------------group1----------group2-----------GeneCluster

Gene1-----------(0.8)---------------(0.7)---------------------1

Gene2----------(-0.4)---------------(0.25)-------------------2

Of course the number of columns (groups) can be 2 or more.

Any helps would be appreciated!

答:
Here you go, had to mess a little with the example to test

```<code>library(tidyverse)
df = structure(list(`group1` = c("0.1531181", "1",
                                 "0.284066", "0.7549542", "0.2495559"), `group2` = c("0.3116818",
                                                                                "0.5837542", "0.430886", "0.7856033", "0.6351635")), row.names = c("C4orf39",
                                                                                "FAM89A", "FMNL1", "CYB5R2", "CHST2"), class = "data.frame")

df %>%
  mutate(GeneCluster = if_else(group1 > group2,1,2))
</code>```

Here is my second attempt should be general enough

```<code>set.seed(42)
df %>%
  mutate_all(as.numeric) %>%
  mutate(group3 = group2 * rnorm(5) + .5,
         row = row_number()) %>%
  pivot_longer(-row) %>%
  group_by(row) %>%
  mutate(max_value = max(value),
         group_number = str_extract(name,"[:digit:]") %>% as.numeric(),
         group_max_value = if_else(value == max_value ,group_number,NA_real_)) %>%
  fill(group_max_value,.direction = c("updown")) %>%
  select(-group_number,-max_value) %>%
  pivot_wider(names_from = name,values_from = value)
</code>```

Here is a new solution using the new version of dplyr

```<code>df %>%
  mutate(across(everything(),as.numeric)) %>%
  rowwise() %>%
  mutate(result = c_across(contains("group")) %>% which.max())
</code>```

Body:
this is the dummy data

df=structure(list(group1 = c("0.1531181", "0.1537821", "0.284066",
"0.7549542", "0.2495559"), group2 = c("0.3116818", "0.5837542",
"0.430886", "0.7856033", "0.6351635"), group3 = c(7.80191002743109e-17,
2.22008198884117e-49, 4.64379480824993e-13, 0.0476184338005978,
2.2062018808144e-39)), row.names = c("C4orf39", "FAM89A", "FMNL1",
"CYB5R2", "CHST2"), class = "data.frame")

As you can see, the 'df' has three columns: group1, group2 and group3. Each of rows is gene name.

Now I want to build a function in R so that it will automatically detemine which value in either of the columns is maximum, and assign the group number to a new column 'GeneCluster'. The final result looks like:

------------------group1----------group2-----------GeneCluster

Gene1-----------(0.8)---------------(0.7)---------------------1

Gene2----------(-0.4)---------------(0.25)-------------------2

Of course the number of columns (groups) can be 2 or more.

Any helps would be appreciated!

Body:
Here you go, had to mess a little with the example to test

library(tidyverse)
df = structure(list(`group1` = c("0.1531181", "1",
                                 "0.284066", "0.7549542", "0.2495559"), `group2` = c("0.3116818",
                                                                                "0.5837542", "0.430886", "0.7856033", "0.6351635")), row.names = c("C4orf39",
                                                                                "FAM89A", "FMNL1", "CYB5R2", "CHST2"), class = "data.frame")

df %>%
  mutate(GeneCluster = if_else(group1 > group2,1,2))

Here is my second attempt should be general enough

set.seed(42)
df %>%
  mutate_all(as.numeric) %>%
  mutate(group3 = group2 * rnorm(5) + .5,
         row = row_number()) %>%
  pivot_longer(-row) %>%
  group_by(row) %>%
  mutate(max_value = max(value),
         group_number = str_extract(name,"[:digit:]") %>% as.numeric(),
         group_max_value = if_else(value == max_value ,group_number,NA_real_)) %>%
  fill(group_max_value,.direction = c("updown")) %>%
  select(-group_number,-max_value) %>%
  pivot_wider(names_from = name,values_from = value)

Here is a new solution using the new version of dplyr

df %>%
  mutate(across(everything(),as.numeric)) %>%
  rowwise() %>%
  mutate(result = c_across(contains("group")) %>% which.max())


问:
Android emulator(Android Studio) Home button not working and giving logcat - I/WindowManager: Not starting activity because user setup is in progress
Started emulator from Android Studio and it's Home button not working.
When I press Home button, in logcat I can see

```<code>I/WindowManager: Not starting activity because user setup is in progress: Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 (has extras) }
</code>```

And same happens(same logcat) when keyboard shortcut(keyboard Home button) is used.

I restarted emulator and my machine several times, but no help.

The thing I want to achieve is killing my app by Home button Long Press

Emulator details:

```<code>Name: 2_7_QVGA_slider_API_23_L
CPU/ABI: ARM (armeabi-v7a)
Path: C:\Users\sh56000\.android\avd\2_7_QVGA_slider_API_23_L.avd

Target: Android 6.0 (API level 23)
Skin: 240x320
SD Card: 100M
Snapshot: no
hw.dPad: no
runtime.network.speed: full
hw.accelerometer: yes
hw.device.name: 2.7in QVGA slider
vm.heapSize: 16
skin.dynamic: yes
hw.device.manufacturer: Generic
hw.gps: yes
hw.audioInput: yes
hw.keyboard.lid: yes
hw.cpu.model: cortex-a8
tag.id: default
hw.camera.back: none
hw.mainKeys: yes
AvdId: 2_7_QVGA_slider_API_23_L
hw.camera.front: none
hw.lcd.density: 120
runtime.scalefactor: auto
avd.ini.displayname: 2.7 QVGA slider API 23 L
snapshot.present: no
hw.device.hash2: MD5:89d*************55e42054c413
hw.ramSize: 512
hw.trackBall: no
hw.battery: yes
hw.sdCard: yes
tag.display: Default
runtime.network.latency: none
hw.keyboard: yes
hw.sensors.proximity: yes
disk.dataPartition.size: 200M
hw.sensors.orientation: yes
avd.ini.encoding: UTF-8
hw.gpu.enabled: yes
</code>```

答: It might be a different situation but here is what helped. Wnen on Android Q, home button would not work, but when I dragged the ask google desktop widget up (don't ask me why I did that), this revealed the apps drawer. When here, home button does work by showing desktop. </p>

ContentLicense: CC BY-SA 3.0

Body:
Started emulator from Android Studio and it's Home button not working.
When I press Home button, in logcat I can see

I/WindowManager: Not starting activity because user setup is in progress: Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 (has extras) }

And same happens(same logcat) when keyboard shortcut(keyboard Home button) is used.

I restarted emulator and my machine several times, but no help.

The thing I want to achieve is killing my app by Home button Long Press

Emulator details:

Name: 2_7_QVGA_slider_API_23_L
CPU/ABI: ARM (armeabi-v7a)
Path: C:\Users\sh56000\.android\avd\2_7_QVGA_slider_API_23_L.avd

Target: Android 6.0 (API level 23)
Skin: 240x320
SD Card: 100M
Snapshot: no
hw.dPad: no
runtime.network.speed: full
hw.accelerometer: yes
hw.device.name: 2.7in QVGA slider
vm.heapSize: 16
skin.dynamic: yes
hw.device.manufacturer: Generic
hw.gps: yes
hw.audioInput: yes
hw.keyboard.lid: yes
hw.cpu.model: cortex-a8
tag.id: default
hw.camera.back: none
hw.mainKeys: yes
AvdId: 2_7_QVGA_slider_API_23_L
hw.camera.front: none
hw.lcd.density: 120
runtime.scalefactor: auto
avd.ini.displayname: 2.7 QVGA slider API 23 L
snapshot.present: no
hw.device.hash2: MD5:89d*************55e42054c413
hw.ramSize: 512
hw.trackBall: no
hw.battery: yes
hw.sdCard: yes
tag.display: Default
runtime.network.latency: none
hw.keyboard: yes
hw.sensors.proximity: yes
disk.dataPartition.size: 200M
hw.sensors.orientation: yes
avd.ini.encoding: UTF-8
hw.gpu.enabled: yes


问:
Need Help With Memory Leaks
I've just run Intrument's Memory Leaks Tool for my app and am getting the following errors:

Here is the method it is referring to:

Specficlaly at this line: NSSet *filteredExercisesFromSession = [session.exercises filteredSetUsingPredicate:[NSPredicate predicateWithFormat: @"name == %@", selectedExerciseName]]

```<code>- (void)createSession
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *dateComponentsForToday = [calendar components:unitFlags fromDate:self.picker.date];
    [dateComponentsForToday setHour:0];
    [dateComponentsForToday setMinute:0];
    [dateComponentsForToday setSecond:0];
    NSDate *targetDateBegins = [calendar dateFromComponents:dateComponentsForToday];
    NSDate *targetDateEnds = [targetDateBegins dateByAddingTimeInterval:(60 * 60 * 24 - 1)];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat: @"(timeStamp >= %@ && timeStamp <= %@)", targetDateBegins, targetDateEnds]];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];

    NSError *error = nil;
    NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    NSLog(@"Fetch error: %@", error);

    if ([results count])
    {
        session = (Session *)[results objectAtIndex:0];
        NSLog(@"Already have session for date: %@", session.timeStamp);
    }
    else
    {
        session = (Session *)[NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:managedObjectContext];
        session.timeStamp = self.picker.date;
        NSLog(@"New session for date: %@", session.timeStamp);
    }

    NSSet *filteredExercisesFromSession = [session.exercises filteredSetUsingPredicate:[NSPredicate predicateWithFormat: @"name == %@", selectedExerciseName]];
    if ([filteredExercisesFromSession count] > 0)
    {
        self.exercise = [filteredExercisesFromSession anyObject];
    }
    else
    {
        NSLog(@"exercise does not already exist");
        self.exercise = (Exercise *)[NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:managedObjectContext];
        self.exercise.name = selectedExerciseName;
        [session addExercisesObject:exercise];
        NSLog(@"exercise name: %@", exercise.name);
        NSLog(@"exercises in session:  %@",session.exercises);
    }

    if (![managedObjectContext save:&error])
    {
        // Handle the error.
    }
    NSLog(@"Save error: %@", error);

    [fetchRequest release];
    self.fetchedResultsController = nil;
    [setsTableView reloadData];
}
</code>```

答: Your code has self.exercise = which takes ownership so make sure in the dealloc you release the member variable that backs the exercise property.

Title: Need Help With Memory Leaks

Body:
I've just run Intrument's Memory Leaks Tool for my app and am getting the following errors:

Here is the method it is referring to:

Specficlaly at this line: NSSet *filteredExercisesFromSession = [session.exercises filteredSetUsingPredicate:[NSPredicate predicateWithFormat: @"name == %@", selectedExerciseName]]

- (void)createSession
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *dateComponentsForToday = [calendar components:unitFlags fromDate:self.picker.date];
    [dateComponentsForToday setHour:0];
    [dateComponentsForToday setMinute:0];
    [dateComponentsForToday setSecond:0];
    NSDate *targetDateBegins = [calendar dateFromComponents:dateComponentsForToday];
    NSDate *targetDateEnds = [targetDateBegins dateByAddingTimeInterval:(60 * 60 * 24 - 1)];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat: @"(timeStamp >= %@ && timeStamp <= %@)", targetDateBegins, targetDateEnds]];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];

    NSError *error = nil;
    NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    NSLog(@"Fetch error: %@", error);

    if ([results count])
    {
        session = (Session *)[results objectAtIndex:0];
        NSLog(@"Already have session for date: %@", session.timeStamp);
    }
    else
    {
        session = (Session *)[NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:managedObjectContext];
        session.timeStamp = self.picker.date;
        NSLog(@"New session for date: %@", session.timeStamp);
    }

    NSSet *filteredExercisesFromSession = [session.exercises filteredSetUsingPredicate:[NSPredicate predicateWithFormat: @"name == %@", selectedExerciseName]];
    if ([filteredExercisesFromSession count] > 0)
    {
        self.exercise = [filteredExercisesFromSession anyObject];
    }
    else
    {
        NSLog(@"exercise does not already exist");
        self.exercise = (Exercise *)[NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:managedObjectContext];
        self.exercise.name = selectedExerciseName;
        [session addExercisesObject:exercise];
        NSLog(@"exercise name: %@", exercise.name);
        NSLog(@"exercises in session:  %@",session.exercises);
    }

    if (![managedObjectContext save:&error])
    {
        // Handle the error.
    }
    NSLog(@"Save error: %@", error);

    [fetchRequest release];
    self.fetchedResultsController = nil;
    [setsTableView reloadData];
}


问:
AMSv3 Multiple track files as inputs to an Asset
Goal: Use a single streaming locator to several tracks of mp3s where the client can get one token with the streaming locator's claim and play each track during its lifetime.

I modified my output asset job process to use the List<string> files, but the job fails saying the input asset does not have a primary file.

Is my approach wrong, or is there a way to say track1.mp3 is the primary?

I am trying to configure a situation like this:

1 stream locator (1 claim required for access)

several tracks in that locator (1.mp3, 2.mp3, ... 50.mp3)

customer buys 1 sku, gets that stream locator's claim

This would be my expected approach.  However, my fallback (and fear) is that AMS wants me to have a 1:1 with 1.mp3:streamlocator.contentkey.id and maintain that list in a backend, then use this sequence flow:

Client requests token from a lookup endpoint

Endpoint compares their ownership vs the requested 1.mp3

If they have access to the sku 1.mp3 belongs to in the backend, issue signed token with the the content key id associated from 1.mp3:streamlocator.contentkey.id

If they dont have access, 401 the token request back the client app to handle

答:
Let's take a step back and modify the scenario a bit: suppose it is a (single bitrate or multi-bitrate) video with 3 audio streams. And you want a 1:1 mapping for streaming_locator : content_key_id : media_asset. With a token containing the right claims you can get the decryption key/license and play any of the 3 audio streams (with video) with a video player. This scenario is supported by AMS and I don't see any problem with this.

However, your scenario is MP3 (without video). My concern is whether there is a binding between MP3 and AES-128 encryption or any DRM, and using such binding in AMS dynamic packaging. Without such encryption, how do you enforce the protection or what is the purpose of token?


问:
how to stop flickering C# winforms
I have a program that is essentially like a paint application. However, my program has some flickering issues. I have the following line in my code (which should get rid of flickering - but doesn't):

```<code>this.SetStyle(ControlStyles.AllPaintingInWmPaint
| ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
</code>```

my code(minus the super and sub classes for the shapes is as follows:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Paint
{
    public partial class Paint : Form
    {
        private Point startPoint;
        private Point endPoint;
        private Rectangle rect = new Rectangle();
        private Int32 brushThickness = 0;
        private Boolean drawSPaint = false;
        private List<Shapes> listOfShapes = new List<Shapes>();
        private Color currentColor;
        private Color currentBoarderColor;
        private Boolean IsShapeRectangle = false;
        private Boolean IsShapeCircle = false;
        private Boolean IsShapeLine = false;

        public SPaint()
        {

            InitializeComponent();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);

            currentColor = Color.Red;
            currentBoarderColor = Color.DodgerBlue;
            IsShapeRectangle = true;
        }

        private void panelArea_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = panelArea.CreateGraphics();

            if (drawSPaint == true)
            {

                Pen p = new Pen(Color.Blue);
                p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

                if (IsShapeRectangle == true)
                {
                    g.DrawRectangle(p, rect);
                }
                else if (IsShapeCircle == true)
                {
                    g.DrawEllipse(p, rect);
                }
                else if (IsShapeLine == true)
                {
                    g.DrawLine(p, startPoint, endPoint);
                }
            }
            foreach (Shapes shape in listOfShapes)
            {

                shape.Draw(g);

            }
        }

        private void panelArea_MouseDown(object sender, MouseEventArgs e)
        {

            startPoint.X = e.X;
            startPoint.Y = e.Y;

            drawSPaint = true;
        }

        private void panelArea_MouseMove(object sender, MouseEventArgs e)
        {

            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {

                if (e.X > startPoint.X)
                {
                    rect.X = startPoint.X;
                    rect.Width = e.X - startPoint.X;
                }
                else
                {
                    rect.X = e.X;
                    rect.Width = startPoint.X - e.X;
                }
                if (e.Y > startPoint.Y)
                {
                    rect.Y = startPoint.Y;
                    rect.Height = e.Y - startPoint.Y;
                }
                else
                {
                    rect.Y = e.Y;
                    rect.Height = startPoint.Y - e.Y;
                }

                panelArea.Invalidate();

            }

        }

        private void panelArea_MouseUp(object sender, MouseEventArgs e)
        {

            endPoint.X = e.X;
            endPoint.Y = e.Y;

            drawSPaint = false;

            if (rect.Width > 0 && rect.Height > 0)
            {
                if (IsShapeRectangle == true)
                {
                    listOfShapes.Add(new TheRectangles(rect, currentColor, currentBoarderColor, brushThickness));
                }
                else if (IsShapeCircle == true)
                {
                    listOfShapes.Add(new TheCircles(rect, currentColor, currentBoarderColor, brushThickness));
                }
                else if (IsShapeLine == true)
                {
                    listOfShapes.Add(new TheLines(startPoint, endPoint, currentColor, currentBoarderColor, brushThickness));
                }

                panelArea.Invalidate();
            }
        }

        private void rectangleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsShapeRectangle = true;
            IsShapeCircle = false;
            IsShapeLine = false;
        }

        private void ellipseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsShapeRectangle = false;
            IsShapeCircle = true;
            IsShapeLine = false;
        }

        private void lineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsShapeCircle = false;
            IsShapeRectangle = false;
            IsShapeLine = true;
        }

        private void ThicknessLevel0_Click(object sender, EventArgs e)
        {
            brushThickness = 0;
        }

        private void ThicknessLevel2_Click(object sender, EventArgs e)
        {
            brushThickness = 2;
        }

        private void ThicknessLevel4_Click(object sender, EventArgs e)
        {
            brushThickness = 4;
        }

        private void ThicknessLevel6_Click(object sender, EventArgs e)
        {
            brushThickness = 6;
        }

        private void ThicknessLevel8_Click(object sender, EventArgs e)
        {
            brushThickness = 8;
        }

        private void ThicknessLevel10_Click(object sender, EventArgs e)
        {
            brushThickness = 10;
        }

        private void ThicknessLevel12_Click(object sender, EventArgs e)
        {
            brushThickness = 12;
        }

        private void ThicknessLevel14_Click(object sender, EventArgs e)
        {
            brushThickness = 14;
        }

        private void FillColour_Click(object sender, EventArgs e)
        {

            ColorDialog fillColourDialog = new ColorDialog();
            fillColourDialog.ShowDialog();
            currentColor = fillColourDialog.Color;
            panelArea.Invalidate();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            ColorDialog fillColourDialog = new ColorDialog();
            fillColourDialog.ShowDialog();
            currentBoarderColor = fillColourDialog.Color;
            panelArea.Invalidate();
        }

    }
}
</code>```

How do i stop the flickering?

*UPDATE:*This code actually works great when i'm drawing directly on the form. However, when i try to draw on the panel, flickering becomes an issue

答:
Drawing onto a Label instead of a Panel, solved the problem for me.

No need to use DoubleBuffering or anything either.

You can remove the text from the label, set AutoSize to false, then Dock it or set the Size and use it as for the Panel.

Best wishes,

Title: how to stop flickering C# winforms

Body:
I have a program that is essentially like a paint application. However, my program has some flickering issues. I have the following line in my code (which should get rid of flickering - but doesn't):

this.SetStyle(ControlStyles.AllPaintingInWmPaint
| ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);

my code(minus the super and sub classes for the shapes is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Paint
{
    public partial class Paint : Form
    {
        private Point startPoint;
        private Point endPoint;
        private Rectangle rect = new Rectangle();
        private Int32 brushThickness = 0;
        private Boolean drawSPaint = false;
        private List<Shapes> listOfShapes = new List<Shapes>();
        private Color currentColor;
        private Color currentBoarderColor;
        private Boolean IsShapeRectangle = false;
        private Boolean IsShapeCircle = false;
        private Boolean IsShapeLine = false;

        public SPaint()
        {

            InitializeComponent();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);

            currentColor = Color.Red;
            currentBoarderColor = Color.DodgerBlue;
            IsShapeRectangle = true;
        }

        private void panelArea_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = panelArea.CreateGraphics();

            if (drawSPaint == true)
            {

                Pen p = new Pen(Color.Blue);
                p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

                if (IsShapeRectangle == true)
                {
                    g.DrawRectangle(p, rect);
                }
                else if (IsShapeCircle == true)
                {
                    g.DrawEllipse(p, rect);
                }
                else if (IsShapeLine == true)
                {
                    g.DrawLine(p, startPoint, endPoint);
                }
            }
            foreach (Shapes shape in listOfShapes)
            {

                shape.Draw(g);

            }
        }

        private void panelArea_MouseDown(object sender, MouseEventArgs e)
        {

            startPoint.X = e.X;
            startPoint.Y = e.Y;

            drawSPaint = true;
        }

        private void panelArea_MouseMove(object sender, MouseEventArgs e)
        {

            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {

                if (e.X > startPoint.X)
                {
                    rect.X = startPoint.X;
                    rect.Width = e.X - startPoint.X;
                }
                else
                {
                    rect.X = e.X;
                    rect.Width = startPoint.X - e.X;
                }
                if (e.Y > startPoint.Y)
                {
                    rect.Y = startPoint.Y;
                    rect.Height = e.Y - startPoint.Y;
                }
                else
                {
                    rect.Y = e.Y;
                    rect.Height = startPoint.Y - e.Y;
                }

                panelArea.Invalidate();

            }

        }

        private void panelArea_MouseUp(object sender, MouseEventArgs e)
        {

            endPoint.X = e.X;
            endPoint.Y = e.Y;

            drawSPaint = false;

            if (rect.Width > 0 && rect.Height > 0)
            {
                if (IsShapeRectangle == true)
                {
                    listOfShapes.Add(new TheRectangles(rect, currentColor, currentBoarderColor, brushThickness));
                }
                else if (IsShapeCircle == true)
                {
                    listOfShapes.Add(new TheCircles(rect, currentColor, currentBoarderColor, brushThickness));
                }
                else if (IsShapeLine == true)
                {
                    listOfShapes.Add(new TheLines(startPoint, endPoint, currentColor, currentBoarderColor, brushThickness));
                }

                panelArea.Invalidate();
            }
        }

        private void rectangleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsShapeRectangle = true;
            IsShapeCircle = false;
            IsShapeLine = false;
        }

        private void ellipseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsShapeRectangle = false;
            IsShapeCircle = true;
            IsShapeLine = false;
        }

        private void lineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsShapeCircle = false;
            IsShapeRectangle = false;
            IsShapeLine = true;
        }

        private void ThicknessLevel0_Click(object sender, EventArgs e)
        {
            brushThickness = 0;
        }

        private void ThicknessLevel2_Click(object sender, EventArgs e)
        {
            brushThickness = 2;
        }

        private void ThicknessLevel4_Click(object sender, EventArgs e)
        {
            brushThickness = 4;
        }

        private void ThicknessLevel6_Click(object sender, EventArgs e)
        {
            brushThickness = 6;
        }

        private void ThicknessLevel8_Click(object sender, EventArgs e)
        {
            brushThickness = 8;
        }

        private void ThicknessLevel10_Click(object sender, EventArgs e)
        {
            brushThickness = 10;
        }

        private void ThicknessLevel12_Click(object sender, EventArgs e)
        {
            brushThickness = 12;
        }

        private void ThicknessLevel14_Click(object sender, EventArgs e)
        {
            brushThickness = 14;
        }

        private void FillColour_Click(object sender, EventArgs e)
        {

            ColorDialog fillColourDialog = new ColorDialog();
            fillColourDialog.ShowDialog();
            currentColor = fillColourDialog.Color;
            panelArea.Invalidate();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            ColorDialog fillColourDialog = new ColorDialog();
            fillColourDialog.ShowDialog();
            currentBoarderColor = fillColourDialog.Color;
            panelArea.Invalidate();
        }

    }
}

How do i stop the flickering?

*UPDATE:*This code actually works great when i'm drawing directly on the form. However, when i try to draw on the panel, flickering becomes an issue


问:
Difference between malloc(sizeof(ptr)) and malloc(sizeof(ptr*))?
I want to know what is the difference between these two lines :

```<code> queue* f=(queue*)malloc(sizeof(queue));
</code>```

```<code> queue* f=(queue*)malloc(sizeof(queue*));
</code>```

Here's the definition of queue:

```<code>typedef struct queue
{
    int arr[N];
    int tail;
}queue;
</code>```

Thanks in advance!

答:
The difference is that the second line is wrong; it allocates enough space to store a pointer to a queue, not a queue itself, but it's assigned to a type that assumes it points to enough space for a whole queue.

Neither one requires a cast, so the correct form is:

```<code>queue *f = malloc(sizeof(queue));
</code>```

To be even safer, don't refer to the type itself, refer to the variable you're assigning to, to avoid repeating the type (potentially causing maintenance problems if the type is changed); this also means sizeof doesn't need parentheses:

```<code>queue *f = malloc(sizeof *f);
</code>```

Body:
I want to know what is the difference between these two lines :

 queue* f=(queue*)malloc(sizeof(queue));

 queue* f=(queue*)malloc(sizeof(queue*));

Here's the definition of queue:

typedef struct queue
{
    int arr[N];
    int tail;
}queue;

Thanks in advance!

Body:
The difference is that the second line is wrong; it allocates enough space to store a pointer to a queue, not a queue itself, but it's assigned to a type that assumes it points to enough space for a whole queue.

Neither one requires a cast, so the correct form is:

queue *f = malloc(sizeof(queue));

To be even safer, don't refer to the type itself, refer to the variable you're assigning to, to avoid repeating the type (potentially causing maintenance problems if the type is changed); this also means sizeof doesn't need parentheses:

queue *f = malloc(sizeof *f);


问:
Using JavaScript , how do I keep user input on page after it has reloaded?
I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

        <TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>

        <button  onclick="display()">post</button>

```

With JavaScript, is there anyway to make input stay once the page reloads?

答:
I think you can use preventDefault like this:

```<code>function display(event){
event.preventDefault()

var post = document.getElementById("userInput").value;
document.getElementById("printhere").innerHTML = post;
}
</code>```

Body:
I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

        <TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>

        <button  onclick="display()">post</button>

With JavaScript, is there anyway to make input stay once the page reloads?

Body:
I think you can use preventDefault like this:

function display(event){
event.preventDefault()

var post = document.getElementById("userInput").value;
document.getElementById("printhere").innerHTML = post;
}


问:
Using Mutate and/or Apply Function on horse racing ratings dataframe to find average of two values
I am still new to the group and R.
I am working on a horse racing database.
The dataframe below displays the performance ratings achieved by seven different race
horse (rows 1 to 7). The performance ratings for each horse (column) are labelled DaH1 to DaH3,
where DaH1 is the most recent performance rating and DaH3 is the 3rd from recent performance
rating.  The dataset also has some NA values.  These are races that took place under different
conditions to todays race so are not considered as valid performances for consideration.

```<code>> racehorse_data
  DaH1 DaH2 DaH3
1    0  124  121
2  124  117  119
3  121  125  123
4  123  120  119
5    0  125   NA
6   NA    0    0
7  110   NA  123

</code>```

I have generated some basic stats on the dataset such as mean and max (see code below).
I would now like to generate some calculations on the ratings of each racehorse using custom functions.
I am reading about the apply functions and mutate but am struggling to create code that
will enable me to find what I describe as the average of the best two performances over the last
three races (for each horse, row)
So for example, for horse 3, the average of the best two performances is 124, using (123+125)/2.
Where there is only 2 values for consideration due to NA values I would just evaluate the ratings two
ratings that I have.
My idea was to sort or order the rating values in each row by highest first and then take the
average of the highest 2.  I'm trying this with Apply and Mutate but not quite getting there.
The code is below.  I'd be grateful for any help the group can prove.
Thanks

```<code>racehorse_data$Mean <- apply(racehorse_data,1,mean,na.rm=T)
racehorse_data$Max <- apply(racehorse_data,1,max,na.rm=T)

</code>```

Gives:

```<code>
  DaH1 DaH2 DaH3      Mean Max
1    0  124  121  81.66667 124
2  124  117  119 120.00000 124
3  121  125  123 123.00000 125
4  123  120  119 120.66667 123
5    0  125   NA  62.50000 125
6   NA    0    0   0.00000   0
7  110   NA  123 116.50000 123

</code>```

Thanks
Graham

答:
One thing that's making your problem harder than it needs to be is the format of your data.  It's not tidy because the names of your columns contain information about the data.  For example, the 3 in DaH3 indiocates that the information in this column relates the last-but-third race that this particular horse took part in.  Even the row number has implied meaning - all the columns in this row relate to one horse.

If, for example, your dataset had columns, say, Horse, RaceIndex and Rating, where Rating is 1 for the most recent race, 2 for the one before that and so on, then your problem is simple: filter to include only rows with Rating %in c(1, 2) then take the average of Rating grouped by Horse.

The distinction may seem trivial for a simple case like this, but if you routinely make your data tidy, you will find that your analysis becomes simpler, even for more complex problems.  I promise.

So, how to answer your question in a tidy context?

```<code>library(tidyverse)

originalData <- tibble(
                  DaH1=c(0, 124, 121, 123, 0, NA, 110),
                  DaH2=c(124, 117, 125, 120, 125, 0, NA),
                  DaH3=c(121, 119, 123, 119, NA, 0, 123)
                )

# Tidy the data
tidyData <- originalData %>%
              pivot_longer(
                values_to="Rating",
                cols=c(DaH1, DaH2, DaH3),
                names_prefix="DaH",
                names_to="RaceIdx"
              ) %>%
              mutate(
                RaceIdx=as.numeric(RaceIdx),
                Horse=rep(1:7, each=3)
              )
# Check it looks right
tidyData %>% head()
# Answer the question
tidyData %>%
  filter(RaceIdx < 3) %>%
  group_by(Horse) %>%
  summarise(Rating=mean(Rating, rm.na=TRUE))
</code>```

Giving

```<code># A tibble: 7 x 2
  Horse Rating
  <int>  <dbl>
1     1   62
2     2  120.
3     3  123
4     4  122.
5     5   62.5
6     6   NA
7     7   NA
</code>```

** Edit **

Or, to answer the question you actually asked (sorry!)

```<code>tidyData %>%
  group_by(Horse) %>%
  arrange(desc(Rating)) %>%
  mutate(Rank=row_number()) %>%
  filter(Rank < 3) %>%
  summarise(Rating=mean(Rating))
</code>```

Giving

```<code># A tibble: 7 x 2
  Horse Rating
  <int>  <dbl>
1     1  122.
2     2  122.
3     3  124
4     4  122.
5     5   62.5
6     6    0
7     7  116.
</code>```

Body:
I am still new to the group and R.
I am working on a horse racing database.
The dataframe below displays the performance ratings achieved by seven different race
horse (rows 1 to 7). The performance ratings for each horse (column) are labelled DaH1 to DaH3,
where DaH1 is the most recent performance rating and DaH3 is the 3rd from recent performance
rating.  The dataset also has some NA values.  These are races that took place under different
conditions to todays race so are not considered as valid performances for consideration.

> racehorse_data
  DaH1 DaH2 DaH3
1    0  124  121
2  124  117  119
3  121  125  123
4  123  120  119
5    0  125   NA
6   NA    0    0
7  110   NA  123

I have generated some basic stats on the dataset such as mean and max (see code below).
I would now like to generate some calculations on the ratings of each racehorse using custom functions.
I am reading about the apply functions and mutate but am struggling to create code that
will enable me to find what I describe as the average of the best two performances over the last
three races (for each horse, row)
So for example, for horse 3, the average of the best two performances is 124, using (123+125)/2.
Where there is only 2 values for consideration due to NA values I would just evaluate the ratings two
ratings that I have.
My idea was to sort or order the rating values in each row by highest first and then take the
average of the highest 2.  I'm trying this with Apply and Mutate but not quite getting there.
The code is below.  I'd be grateful for any help the group can prove.
Thanks

racehorse_data$Mean <- apply(racehorse_data,1,mean,na.rm=T)
racehorse_data$Max <- apply(racehorse_data,1,max,na.rm=T)

Gives:

  DaH1 DaH2 DaH3      Mean Max
1    0  124  121  81.66667 124
2  124  117  119 120.00000 124
3  121  125  123 123.00000 125
4  123  120  119 120.66667 123
5    0  125   NA  62.50000 125
6   NA    0    0   0.00000   0
7  110   NA  123 116.50000 123

Thanks
Graham

Body:
One thing that's making your problem harder than it needs to be is the format of your data.  It's not tidy because the names of your columns contain information about the data.  For example, the 3 in DaH3 indiocates that the information in this column relates the last-but-third race that this particular horse took part in.  Even the row number has implied meaning - all the columns in this row relate to one horse.

If, for example, your dataset had columns, say, Horse, RaceIndex and Rating, where Rating is 1 for the most recent race, 2 for the one before that and so on, then your problem is simple: filter to include only rows with Rating %in c(1, 2) then take the average of Rating grouped by Horse.

The distinction may seem trivial for a simple case like this, but if you routinely make your data tidy, you will find that your analysis becomes simpler, even for more complex problems.  I promise.

So, how to answer your question in a tidy context?

library(tidyverse)

originalData <- tibble(
                  DaH1=c(0, 124, 121, 123, 0, NA, 110),
                  DaH2=c(124, 117, 125, 120, 125, 0, NA),
                  DaH3=c(121, 119, 123, 119, NA, 0, 123)
                )

# Tidy the data
tidyData <- originalData %>%
              pivot_longer(
                values_to="Rating",
                cols=c(DaH1, DaH2, DaH3),
                names_prefix="DaH",
                names_to="RaceIdx"
              ) %>%
              mutate(
                RaceIdx=as.numeric(RaceIdx),
                Horse=rep(1:7, each=3)
              )
# Check it looks right
tidyData %>% head()
# Answer the question
tidyData %>%
  filter(RaceIdx < 3) %>%
  group_by(Horse) %>%
  summarise(Rating=mean(Rating, rm.na=TRUE))

Giving

# A tibble: 7 x 2
  Horse Rating
  <int>  <dbl>
1     1   62
2     2  120.
3     3  123
4     4  122.
5     5   62.5
6     6   NA
7     7   NA

** Edit **

Or, to answer the question you actually asked (sorry!)

tidyData %>%
  group_by(Horse) %>%
  arrange(desc(Rating)) %>%
  mutate(Rank=row_number()) %>%
  filter(Rank < 3) %>%
  summarise(Rating=mean(Rating))

Giving

# A tibble: 7 x 2
  Horse Rating
  <int>  <dbl>
1     1  122.
2     2  122.
3     3  124
4     4  122.
5     5   62.5
6     6    0
7     7  116.


问:
List all the directors who directed a 'Comedy' movie in a leap year
Here i am trying to all director name who directed comedy movie in leap year. I am getting wrong result and that may be because the way i am implementing leap year code is not right. Please help.</p>

```<code>SELECT m.Title,p.Name,m.year
FROM Movie m JOIN
     M_director d
     ON m.MID = d.MID JOIN
     Person p
     ON d.PID = p.PID JOIN
     M_Genre mg
     ON m.MID = mg.MID JOIN
     Genre g
     ON g.GID = mg.GID
WHERE g.Name LIKE '%Comedy%' AND m.year%4 = 0 AND m.year % 100 <> 0 OR  m.year % 400 = 0
</code>```

答:
AND has higher precedence over OR, so when you write:

```<code>WHERE g.Name LIKE '%Comedy%'
AND m.year%4 = 0
AND m.year % 100 <> 0
OR  m.year % 400 = 0
</code>```

This means: name has to contain Comedy AND the year must be divisible by 4 AND the year must not be a multiple of 100. Either that OR the year is divisible by 400 (without any other constraints, so regardless of the name). Use parentheses to explicitly specify precedence:

```<code>WHERE g.Name LIKE '%Comedy%'
AND ( m.year%4 = 0
AND m.year % 100 <> 0
OR  m.year % 400 = 0 )
</code>```

Body:
Here i am trying to all director name who directed comedy movie in leap year. I am getting wrong result and that may be because the way i am implementing leap year code is not right. Please help.

SELECT m.Title,p.Name,m.year
FROM Movie m JOIN
     M_director d
     ON m.MID = d.MID JOIN
     Person p
     ON d.PID = p.PID JOIN
     M_Genre mg
     ON m.MID = mg.MID JOIN
     Genre g
     ON g.GID = mg.GID
WHERE g.Name LIKE '%Comedy%' AND m.year%4 = 0 AND m.year % 100 <> 0 OR  m.year % 400 = 0

Body:
AND has higher precedence over OR, so when you write:

WHERE g.Name LIKE '%Comedy%'
AND m.year%4 = 0
AND m.year % 100 <> 0
OR  m.year % 400 = 0

This means: name has to contain Comedy AND the year must be divisible by 4 AND the year must not be a multiple of 100. Either that OR the year is divisible by 400 (without any other constraints, so regardless of the name). Use parentheses to explicitly specify precedence:

WHERE g.Name LIKE '%Comedy%'
AND ( m.year%4 = 0
AND m.year % 100 <> 0
OR  m.year % 400 = 0 )


问:
Route to home page with page refresh
I am using react,redux and next.js .

I have a USER component loaded with user data.In this component,I have logout button along with user data. Here, userdata route and home route are on same location.

When i click on logout, I am re-setting the store state and replacing the route with Router.replace('/').

After logout, its resetting the store state. But, page is not refreshed because userdata route and home route ('/') are on same location. How to refresh the page ? Any possible option without using Router.reload() ?

答:
Try using

window.location.reload()

It will help you to reload whole page by initializing the states.
Hope, it'll help you.

Title: Route to home page with page refresh


问:
Looping through Numpy Array elements
Is there a more readable way to code a loop in Python that goes through each element of a Numpy array? I have come up with the following code, but it seems cumbersome & not very readable:

```<code>import numpy as np
arr01 = np.random.randint(1,10,(3,3))
for i in range(0,(np.shape(arr01[0])[0]+1)):
    for j in range(0,(np.shape(arr01[1])[0]+1)):
        print (arr01[i,j])
</code>```

I could make it more explicit such as:

```<code>import numpy as np
arr01 = np.random.randint(1,10,(3,3))
rows = np.shape(arr01[0])[0]
cols = np.shape(arr01[1])[0]
for i in range(0, (rows + 1)):
    for j in range(0, (cols + 1)):
        print (arr01[i,j])
</code>```

However, that still seems a bit more cumbersome, compared to other languages, i.e. an equivalent code in VBA could read (supposing the array had already been populated):

```<code>dim i, j as integer
for i = lbound(arr01,1) to ubound(arr01,1)
   for j = lbound(arr01,2) to ubound(arr01,2)
       msgBox arr01(i, j)
   next j
next i
</code>```

答:
Seems like you've skipped over some intro Python chapters.  With a list there are several simple ways of iterating:

```<code>In [1]: alist = ['a','b','c']
In [2]: for i in alist: print(i)        # on the list itself
a
b
c
In [3]: len(alist)
Out[3]: 3
In [4]: for i in range(len(alist)): print(i,alist[i])  # index is ok
0 a
1 b
2 c
In [5]: for i,v in enumerate(alist): print(i,v)   # but enumerate is simpler
0 a
1 b
2 c
</code>```

Note the indexes.  range(3) is sufficient.  alist[3] produces an error.

```<code>In [6]: arr = np.arange(6).reshape(2,3)
In [7]: arr
Out[7]:
array([[0, 1, 2],
       [3, 4, 5]])
In [8]: for row in arr:
   ...:     for col in row:
   ...:         print(row,col)
   ...:
[0 1 2] 0
[0 1 2] 1
[0 1 2] 2
[3 4 5] 3
[3 4 5] 4
[3 4 5] 5
</code>```

The shape is a tuple.  The row count is then arr.shape[0], and columns arr.shape[1].  Or you can 'unpack' both at once:

```<code>In [9]: arr.shape
Out[9]: (2, 3)
In [10]: n,m = arr.shape
In [11]: [arr[i,j] for i in range(n) for j in range(m)]
Out[11]: [0, 1, 2, 3, 4, 5]
</code>```

But we can get the same flat list of values with ravel and optional conversion to list:

```<code>In [12]: arr.ravel()
Out[12]: array([0, 1, 2, 3, 4, 5])
In [13]: arr.ravel().tolist()
Out[13]: [0, 1, 2, 3, 4, 5]
</code>```

But usually with numpy arrays, you shouldn't be iterating at all.  Learn enough of the numpy basics so you can work with the whole array, not elements.

nditer can be used, as the other answer shows, to iterate through an array in a flat manner, but there are a number of details about it that could easily confuse a beginner.  There are a couple of intro pages to nditer, but they should be read in full.  Usually I discourage its use.

```<code>In [14]: for i in np.nditer(arr):
    ...:     print(i, type(i), i.shape)
    ...:
0 <class 'numpy.ndarray'> ()        # this element is a 0d array, not a scalar integer
1 <class 'numpy.ndarray'> ()
2 <class 'numpy.ndarray'> ()
...
</code>```

Iterating with ndenumerate or on the tolist produce different types of elements.  The type may matter if you try to do more than display the value, so be careful.

```<code>In [15]: list(np.ndenumerate(arr))
Out[15]: [((0, 0), 0), ((0, 1), 1), ((0, 2), 2), ((1, 0), 3), ((1, 1), 4), ((1, 2), 5)]
In [16]: for ij, v in np.ndenumerate(arr):
    ...:     print(ij, v, type(v))
    ...:
(0, 0) 0 <class 'numpy.int64'>
(0, 1) 1 <class 'numpy.int64'>
...
In [17]: for i, v in enumerate(arr.ravel().tolist()):
    ...:     print(i, v, type(v))
    ...:
0 0 <class 'int'>
1 1 <class 'int'>
...
</code>```

Title: Looping through Numpy Array elements

Body:
Is there a more readable way to code a loop in Python that goes through each element of a Numpy array? I have come up with the following code, but it seems cumbersome & not very readable:

import numpy as np
arr01 = np.random.randint(1,10,(3,3))
for i in range(0,(np.shape(arr01[0])[0]+1)):
    for j in range(0,(np.shape(arr01[1])[0]+1)):
        print (arr01[i,j])

I could make it more explicit such as:

import numpy as np
arr01 = np.random.randint(1,10,(3,3))
rows = np.shape(arr01[0])[0]
cols = np.shape(arr01[1])[0]
for i in range(0, (rows + 1)):
    for j in range(0, (cols + 1)):
        print (arr01[i,j])

However, that still seems a bit more cumbersome, compared to other languages, i.e. an equivalent code in VBA could read (supposing the array had already been populated):

dim i, j as integer
for i = lbound(arr01,1) to ubound(arr01,1)
   for j = lbound(arr01,2) to ubound(arr01,2)
       msgBox arr01(i, j)
   next j
next i

Body:
Seems like you've skipped over some intro Python chapters.  With a list there are several simple ways of iterating:

In [1]: alist = ['a','b','c']
In [2]: for i in alist: print(i)        # on the list itself
a
b
c
In [3]: len(alist)
Out[3]: 3
In [4]: for i in range(len(alist)): print(i,alist[i])  # index is ok
0 a
1 b
2 c
In [5]: for i,v in enumerate(alist): print(i,v)   # but enumerate is simpler
0 a
1 b
2 c

Note the indexes.  range(3) is sufficient.  alist[3] produces an error.

In [6]: arr = np.arange(6).reshape(2,3)
In [7]: arr
Out[7]:
array([[0, 1, 2],
       [3, 4, 5]])
In [8]: for row in arr:
   ...:     for col in row:
   ...:         print(row,col)
   ...:
[0 1 2] 0
[0 1 2] 1
[0 1 2] 2
[3 4 5] 3
[3 4 5] 4
[3 4 5] 5

The shape is a tuple.  The row count is then arr.shape[0], and columns arr.shape[1].  Or you can 'unpack' both at once:

In [9]: arr.shape
Out[9]: (2, 3)
In [10]: n,m = arr.shape
In [11]: [arr[i,j] for i in range(n) for j in range(m)]
Out[11]: [0, 1, 2, 3, 4, 5]

But we can get the same flat list of values with ravel and optional conversion to list:

In [12]: arr.ravel()
Out[12]: array([0, 1, 2, 3, 4, 5])
In [13]: arr.ravel().tolist()
Out[13]: [0, 1, 2, 3, 4, 5]

But usually with numpy arrays, you shouldn't be iterating at all.  Learn enough of the numpy basics so you can work with the whole array, not elements.

nditer can be used, as the other answer shows, to iterate through an array in a flat manner, but there are a number of details about it that could easily confuse a beginner.  There are a couple of intro pages to nditer, but they should be read in full.  Usually I discourage its use.

In [14]: for i in np.nditer(arr):
    ...:     print(i, type(i), i.shape)
    ...:
0 <class 'numpy.ndarray'> ()        # this element is a 0d array, not a scalar integer
1 <class 'numpy.ndarray'> ()
2 <class 'numpy.ndarray'> ()
...

Iterating with ndenumerate or on the tolist produce different types of elements.  The type may matter if you try to do more than display the value, so be careful.

In [15]: list(np.ndenumerate(arr))
Out[15]: [((0, 0), 0), ((0, 1), 1), ((0, 2), 2), ((1, 0), 3), ((1, 1), 4), ((1, 2), 5)]
In [16]: for ij, v in np.ndenumerate(arr):
    ...:     print(ij, v, type(v))
    ...:
(0, 0) 0 <class 'numpy.int64'>
(0, 1) 1 <class 'numpy.int64'>
...
In [17]: for i, v in enumerate(arr.ravel().tolist()):
    ...:     print(i, v, type(v))
    ...:
0 0 <class 'int'>
1 1 <class 'int'>
...


问:
Generating a new dataframe from existing columns
I am trying to create a new column D from existing A, B, C column.

first value in Col D is A1

second value in Col D is B2

third value in Col D is C3

fourth value in Col D is A4

fifth value in Col D is B5

sixth value in Col D is C6

following this pattern, the rest of the values in Col D is iteration of this pattern. Please reference the graph.

Any code ideas?

Click the link to see the picture

Body:
Here's a solution (in a couple of steps for better clarity):

df = pd.DataFrame({"a": range(0, 10), "b": range(10, 20), "c": range(20, 30)})

df["inx"] = range(len(df))
df["d"] = np.where(df.inx % 3 == 0, df["a"],
         np.where(df.inx % 3 == 1, df["b"], df["c"]))
df = df.drop("inx", axis="columns")

Result:

   a   b   c   d
0  0  10  20   0
1  1  11  21  11
2  2  12  22  22
3  3  13  23   3
4  4  14  24  14
5  5  15  25  25
6  6  16  26   6
7  7  17  27  17
8  8  18  28  28
9  9  19  29   9


问:
How do you split a string after a symbol in python?
```<code>import sympy
equation = input('Enter an equation: ')
a = equation.split(('=') or ('<') or ('>') or ('<=') or ('>=') or ('==') or ('!='))[0:2]
b = sympify(a[0])
c = sympify(a[1])
d = simplify(b - c)
print('This is the equation simplified: ' + str(d))
</code>```

I want to split the equation in two parts when one of the symbols (=,<,>,>=,<=,==,!=) appear, but in this code it only works when the '=' sign is the symbol.

答:
I think your code should be like that:</p>

```<code>import re        #<--- add this
import sympy

equation = input('Enter an equation: ')
a = re.split(r'[=|<|>|<=|>=|==]', equation)[0:2]   #<--- only change this

b = sympify(a[0])
c = sympify(a[1])
d = simplify(b - c)
print('This is the equation simplified: ' + str(d))
</code>```

Body:
import sympy
equation = input('Enter an equation: ')
a = equation.split(('=') or ('<') or ('>') or ('<=') or ('>=') or ('==') or ('!='))[0:2]
b = sympify(a[0])
c = sympify(a[1])
d = simplify(b - c)
print('This is the equation simplified: ' + str(d))

I want to split the equation in two parts when one of the symbols (=,<,>,>=,<=,==,!=) appear, but in this code it only works when the '=' sign is the symbol.

Body:
I think your code should be like that:

import re        #<--- add this
import sympy

equation = input('Enter an equation: ')
a = re.split(r'[=|<|>|<=|>=|==]', equation)[0:2]   #<--- only change this

b = sympify(a[0])
c = sympify(a[1])
d = simplify(b - c)
print('This is the equation simplified: ' + str(d))


问:
Preloading game assets (images) for latter / instant use
I am working on a game ui that requires high amount of images that also total to relatively big size (~30mb). I've been caching them to the disc via service workers, but some of them are ~3mb in size and even when they come from disc there is noticeable delay before they appear (a flick of sorts).

After some research on other games it seems that common practice is to preload these into memory and break it down logically i.e only preload assets required for specific level.

How would one preload images into memory with javascript and keep track of what is still being loaded or has been evicted from memory? Note that elements that display these images can appear on page dynamically i.e. not be there initially.

答:
I think you could use createObjectURL to preload it. Also having the images somewhere in the DOM would prevent the browser to start garbage collecting the asset.

Different strategy would obviously be to

cut your assets up in to multiple assets

to use the webp image format

to further compress/downsize them (ie. only load highres if the device has a highDPI display)


问:
Rails 6 gemfile.lock removed, generate it again
I remove te gemfile.lock because is corrupted, but now i can use bundle

```<code>The deployment setting requires a Gemfile.lock. Please make sure you have checked your Gemfile.lock into version control
before deploying.
</code>```

how i re gen the gemfile.lock?

答: Yes, run bundle install again, it will create a new Gemfile.lock

Body:
I remove te gemfile.lock because is corrupted, but now i can use bundle

The deployment setting requires a Gemfile.lock. Please make sure you have checked your Gemfile.lock into version control
before deploying.

how i re gen the gemfile.lock?


问:
Can't connect to MySQL server on 'db' Heroku
I an using Docker Compose with my app and database. My app connects to my database using the hostname db as shown in my docker-compose.yml:

```<code>db:
    image: mysql
    # container_name: mysql_db
    environment:
      - MYSQL_USER=test
      - MYSQL_ROOT_PASSWORD=test
      - MYSQL_PASSWORD=test
      - MYSQL_DATABASE=test
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - ./db:/docker-entrypoint-initdb.d
    restart: always
    ports:
      - 3306:3306`
</code>```

But when I open my app on Heroku I get a connection error:

```<code> sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name or service not known)")
</code>```

I supposed  that this error appear because Heroku has dynamic hosts.
How can I set my database container up on Heroku?

答:
How can I set my database container up on Heroku?

Don't.

One database container and one code container might make sense in development, but in production these things shouldn't be coupled. Use a hosted database provider instead; there are several options, including MySQL services, most of which have a free starter tier.

This matches Heroku's recommendation:

Use Heroku add-ons in production

For local development: use official Docker images, such as Postgres and Redis.

For staging and production: use Heroku add-ons, such as Heroku Postgres and Heroku Redis.

Using official Docker images locally and Heroku add-ons in production provides you with the best of both worlds:

Parity: You get parity by using the same services on your local machine as you do in production

Reduced ops burden: By using add-ons, Heroku – or the add-on provider – takes the ops burden of replication, availability, and backup.

Body:
I an using Docker Compose with my app and database. My app connects to my database using the hostname db as shown in my docker-compose.yml:

db:
    image: mysql
    # container_name: mysql_db
    environment:
      - MYSQL_USER=test
      - MYSQL_ROOT_PASSWORD=test
      - MYSQL_PASSWORD=test
      - MYSQL_DATABASE=test
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - ./db:/docker-entrypoint-initdb.d
    restart: always
    ports:
      - 3306:3306`

But when I open my app on Heroku I get a connection error:

 sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name or service not known)")

I supposed  that this error appear because Heroku has dynamic hosts.
How can I set my database container up on Heroku?


问:
SQL CASE switch for parameter
I have a parameter that can be 1 of 3 possible values 0, 2 or NULL (these are values for an enum 0 is Pending, 1 is UnderReview and 2 is Closed). If it is NULL it should retrieve all regardless of the Status but If it is 2 it should retrieve all the closed ones however if the value is 0 it should retrieve the ones that are pending or under review. This last one means that I want to retrieve records that have a status of either 0 or 1. I have the following code so far and tried with a CASE switch but it doesn't work.

```<code>SELECT * FROM PurchaseOrder
    WHERE (CreationDate >= @StartDate AND CreationDate <= @EndDate)
    AND (@POStatus IS NULL OR [Status] = @POStatus)
    AND (@POStatus IS NULL OR [Status] = CASE @POStatus WHEN 0 THEN 1 END)
    AND (@PurchaseOrderIdSearch IS NULL OR PurchaseOrderId LIKE @PurchaseOrderIdSearch)
    AND EmployeeId = @EmployeeId
    ORDER BY CreationDate DESC, PurchaseOrderId DESC
</code>```

I solved it adding an if statement, I was looking for a simpler way to do it to avoid repetition, this is how it looks like now:

```<code>IF @POStatus = 0
    BEGIN
        SELECT * FROM PurchaseOrder
        WHERE (CreationDate >= @StartDate AND CreationDate <= @EndDate)
        AND (([Status] = @POStatus)
        OR ([Status] = 1))
        AND (@PurchaseOrderIdSearch IS NULL OR PurchaseOrderId LIKE @PurchaseOrderIdSearch)
        AND EmployeeId = @EmployeeId
        ORDER BY CreationDate DESC, PurchaseOrderId DESC
    END
    ELSE
    BEGIN
        SELECT * FROM PurchaseOrder
        WHERE (CreationDate >= @StartDate AND CreationDate <= @EndDate)
        AND (@POStatus IS NULL OR [Status] = @POStatus)
        AND (@PurchaseOrderIdSearch IS NULL OR PurchaseOrderId LIKE @PurchaseOrderIdSearch)
        AND EmployeeId = @EmployeeId
        ORDER BY CreationDate DESC, PurchaseOrderId DESC
    END
</code>```

答:
I suppose you're looking for something like

```<code>DECLARE @MyParam INT; --Try to set 0, 1 or 2

SELECT *
FROM
(
  VALUES
  (0),
  (1),
  (2)
) T(Value)
WHERE (Value = @MyParam) OR (@MyParam IS NULL);
</code>```

Here is a db<>fiddle to see how it's working.

Update:

It seems like you're looking for

```<code>DECLARE @MyParam INT; --Try to set 0, 1 or 2

SELECT *
FROM
(
  VALUES
  (0),
  (1),
  (2)
) T(Value)
WHERE
(
  CASE WHEN @MyParam = 0 OR @MyParam = 1 THEN 1 ELSE 0 END = 1
  AND Value IN(0, 1)
)
OR
(Value = @MyParam AND @MyParam = 2)
OR
@MyParam IS NULL;
</code>```

Here is a db<>fiddle

Title: SQL CASE switch for parameter

Body:
I have a parameter that can be 1 of 3 possible values 0, 2 or NULL (these are values for an enum 0 is Pending, 1 is UnderReview and 2 is Closed). If it is NULL it should retrieve all regardless of the Status but If it is 2 it should retrieve all the closed ones however if the value is 0 it should retrieve the ones that are pending or under review. This last one means that I want to retrieve records that have a status of either 0 or 1. I have the following code so far and tried with a CASE switch but it doesn't work.

SELECT * FROM PurchaseOrder
    WHERE (CreationDate >= @StartDate AND CreationDate <= @EndDate)
    AND (@POStatus IS NULL OR [Status] = @POStatus)
    AND (@POStatus IS NULL OR [Status] = CASE @POStatus WHEN 0 THEN 1 END)
    AND (@PurchaseOrderIdSearch IS NULL OR PurchaseOrderId LIKE @PurchaseOrderIdSearch)
    AND EmployeeId = @EmployeeId
    ORDER BY CreationDate DESC, PurchaseOrderId DESC

I solved it adding an if statement, I was looking for a simpler way to do it to avoid repetition, this is how it looks like now:

IF @POStatus = 0
    BEGIN
        SELECT * FROM PurchaseOrder
        WHERE (CreationDate >= @StartDate AND CreationDate <= @EndDate)
        AND (([Status] = @POStatus)
        OR ([Status] = 1))
        AND (@PurchaseOrderIdSearch IS NULL OR PurchaseOrderId LIKE @PurchaseOrderIdSearch)
        AND EmployeeId = @EmployeeId
        ORDER BY CreationDate DESC, PurchaseOrderId DESC
    END
    ELSE
    BEGIN
        SELECT * FROM PurchaseOrder
        WHERE (CreationDate >= @StartDate AND CreationDate <= @EndDate)
        AND (@POStatus IS NULL OR [Status] = @POStatus)
        AND (@PurchaseOrderIdSearch IS NULL OR PurchaseOrderId LIKE @PurchaseOrderIdSearch)
        AND EmployeeId = @EmployeeId
        ORDER BY CreationDate DESC, PurchaseOrderId DESC
    END

Body:
I suppose you're looking for something like

DECLARE @MyParam INT; --Try to set 0, 1 or 2

SELECT *
FROM
(
  VALUES
  (0),
  (1),
  (2)
) T(Value)
WHERE (Value = @MyParam) OR (@MyParam IS NULL);

Here is a db<>fiddle to see how it's working.

Update:

It seems like you're looking for

DECLARE @MyParam INT; --Try to set 0, 1 or 2

SELECT *
FROM
(
  VALUES
  (0),
  (1),
  (2)
) T(Value)
WHERE
(
  CASE WHEN @MyParam = 0 OR @MyParam = 1 THEN 1 ELSE 0 END = 1
  AND Value IN(0, 1)
)
OR
(Value = @MyParam AND @MyParam = 2)
OR
@MyParam IS NULL;

Here is a db<>fiddle


问:
Is there any big problem using mybatis code in vertx.executeBlocking code?
I want to use MyBatis to read and write database in Eclipse Vert.x. Vert.x officially recommends using executeBlocking to handle blocking code.

Is there any big problem using MyBatis code in vertx.executeBlocking code? What needs attention？

In Vert.x, using vert.executeBlocking or Worker verticles to run a program that blocks jdbc code, the performance and concurrency will not be as good as that of a traditional blocking program?

答:
Clarification: Vert.x states that if you absolutely must use blocking code, you could wrap it into "executeBlocking". This is definitely not a recommendation or a good practice to do so.

First, executeBlocking will run on a default worker thread pool, which is quite small for long running tasks - 20 threads, by default.
Second, if you invoke this from your EventLoop verticles (such as a Router, for example) your concurrency will be even worse due to thread affinity. Basically, this will result in having a blocking thread pool of size equal to number of your CPU cores.

If your application doesn't need to scale and doesn't need throughput - that may be fine. But then maybe Vert.x is not the best choice anyway.

Much more scalable way would be to run your DB code in a set of worker verticles, communicating with your handler using EventBus.


问:
print the current time for every 30 minutes in a file
I have tried this code to print the current time for every 30 minutes in a file and also if day changes print the next day time in the newfile and second day file name is incremental of first day file name.
But mistake of this code is it's not printing next days 30minutes increment time in new file created for that day.

```<code>set i 1
set c [open "$i.txt" w+]
set a [clock seconds]
set b [expr {$a+1800}]
set d [expr {$a+86400}]
while {$a > 0} {
    incr a
    if {$a == $b} {
        if { $a == $d} {
            incr i
            set e [open "$i.txt" w+]
            puts $e "The time is: [clock format $a -format %H:%M:%S]"
            set d [expr {$a+86400}]
        }
        puts $c "The time is: [clock format $a -format %H:%M:%S]"
        set b [expr {$a+1800}]
    }
}
</code>```

答:
I haven't tested the code, but I'm guessing it's because you are still using puts $c ... even after creating the new file, and by the way, you should close the previous file if you are done with it. Only addressing the issue you mentioned, it should be more like:

```<code>set i 1
set c [open "$i.txt" w+]
set a [clock seconds]
set b [expr {$a+1800}]
set d [expr {$a+86400}]
while {$a > 0} {
    incr a
    if {$a == $b} {
        if { $a == $d} {
            close $c     ;# close the previous file
            incr i
            set c [open "$i.txt" w+] ;# open it in the same channel
            set d [expr {$a+86400}]
        }
        puts $c "The time is: [clock format $a -format %H:%M:%S]"
        set b [expr {$a+1800}]
    }
}
</code>```

Body:
I have tried this code to print the current time for every 30 minutes in a file and also if day changes print the next day time in the newfile and second day file name is incremental of first day file name.
But mistake of this code is it's not printing next days 30minutes increment time in new file created for that day.

set i 1
set c [open "$i.txt" w+]
set a [clock seconds]
set b [expr {$a+1800}]
set d [expr {$a+86400}]
while {$a > 0} {
    incr a
    if {$a == $b} {
        if { $a == $d} {
            incr i
            set e [open "$i.txt" w+]
            puts $e "The time is: [clock format $a -format %H:%M:%S]"
            set d [expr {$a+86400}]
        }
        puts $c "The time is: [clock format $a -format %H:%M:%S]"
        set b [expr {$a+1800}]
    }
}

Body:
I haven't tested the code, but I'm guessing it's because you are still using puts $c ... even after creating the new file, and by the way, you should close the previous file if you are done with it. Only addressing the issue you mentioned, it should be more like:

set i 1
set c [open "$i.txt" w+]
set a [clock seconds]
set b [expr {$a+1800}]
set d [expr {$a+86400}]
while {$a > 0} {
    incr a
    if {$a == $b} {
        if { $a == $d} {
            close $c     ;# close the previous file
            incr i
            set c [open "$i.txt" w+] ;# open it in the same channel
            set d [expr {$a+86400}]
        }
        puts $c "The time is: [clock format $a -format %H:%M:%S]"
        set b [expr {$a+1800}]
    }
}


问:
Javascript fetch doesn't return despite correct URL
I've used JQuery in the past to do AJAX requests. I am trying to now use fetch and I am struggling.

My code is very simple, and it calls a C# backend. The back end break point is hit, so I don't believe there is any issue with the URL

```<code>this.get = function (url) {
    return getData(url);
};

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });

    return await response.json(); // BREAK POINT NEVER HIT
}
</code>```

In the browsers dev tools, I put a break point at the line const response = await fetch(url, { and another on the return await response.json;

The first break is hit. The second never hits. I don't see any error message or exception.

How do I find out what is going on?

Looking at the response, it shows it's pending a promise

EDIT

It seems as if my program is not waiting with await... My understanding is the code should not progress until it has received (waited) for a response. What is happening is, as soon as it hits the await, it seems to exit the function. The breakpoint on return await response.json() does eventually get hit, but await is acting like a new thread.

答:
Usually when there is no response (either 200 as positive or any error status code like 404, 500), this means that there was no response at all. Happens sometimes because request goes in an infinite loop of redirects or really long loop of redirects.

I suggest trying request without redirect set to "follow", like this

```<code>async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        referrerPolicy: 'no-referrer'
    });

    return response.json(); // BREAK POINT NEVER HIT
}
</code>```

Body:
I've used JQuery in the past to do AJAX requests. I am trying to now use fetch and I am struggling.

My code is very simple, and it calls a C# backend. The back end break point is hit, so I don't believe there is any issue with the URL

this.get = function (url) {
    return getData(url);
};

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });

    return await response.json(); // BREAK POINT NEVER HIT
}

In the browsers dev tools, I put a break point at the line const response = await fetch(url, { and another on the return await response.json;

The first break is hit. The second never hits. I don't see any error message or exception.

How do I find out what is going on?

Looking at the response, it shows it's pending a promise

EDIT

It seems as if my program is not waiting with await... My understanding is the code should not progress until it has received (waited) for a response. What is happening is, as soon as it hits the await, it seems to exit the function. The breakpoint on return await response.json() does eventually get hit, but await is acting like a new thread.

Body:
Usually when there is no response (either 200 as positive or any error status code like 404, 500), this means that there was no response at all. Happens sometimes because request goes in an infinite loop of redirects or really long loop of redirects.

I suggest trying request without redirect set to "follow", like this

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        referrerPolicy: 'no-referrer'
    });

    return response.json(); // BREAK POINT NEVER HIT
}


问:
Cannot compare types 'ndarray(dtype=int64)' and 'str'
Example of data that I want to replace

Data has the following attributes

Buying v-high,high,med,low

Maint v-high,high,med,low

Doors 2,3,4,5-more

persons 2,4-more

lug_boot small,med,big

safety low,med.high

here is what I did

```<code>enter code here
#Buying price generalization
df["Buying_Price"]=df["Buying_Price"].replace({"vhigh":4})
df["Buying_Price"]=df["Buying_Price"].replace({"high":3})
df["Buying_Price"]=df["Buying_Price"].replace({"med":2})
df["Buying_Price"]=df["Buying_Price"].replace({"low":1})

#Maintanace generalization
df["Maintanance_price"]=df["Maintanance_price"].replace({"vhigh":4})
df["Maintanance_price"]=df["Maintanance_price"].replace({"high":3})
df["Maintanance_price"]=df["Maintanance_price"].replace({"med":2})
df["Maintanance_price"]=df["Maintanance_price"].replace({"low":1})

#lug_boot generalization
df["Lug_boot"]=df["Lug_boot"].replace({"small":1})
df["Lug_boot"]=df["Lug_boot"].replace({"med":2})
df["Lug_boot"]=df["Lug_boot"].replace({"big":3})

#Safety Generalization
df["Safety"]=df["Safety"].replace({"low":1})
df["Safety"]=df["Safety"].replace({"med":2})
df["Safety"]=df["Safety"].replace({"big":3})

print(df.head())
</code>```

while printing it showed:

```<code>Cannot compare types 'ndarray(dtype=int64)' and 'str'
</code>```

答:
I was facing the same issue and what worked for me was converting the datatype of the feature to an object type.

```<code>   train['Some_feature']=train.Some_feature.astype(object)
</code>```

Hope it helps.

Body:
Example of data that I want to replace

Data has the following attributes

Buying v-high,high,med,low

Maint v-high,high,med,low

Doors 2,3,4,5-more

persons 2,4-more

lug_boot small,med,big

safety low,med.high

here is what I did

enter code here
#Buying price generalization
df["Buying_Price"]=df["Buying_Price"].replace({"vhigh":4})
df["Buying_Price"]=df["Buying_Price"].replace({"high":3})
df["Buying_Price"]=df["Buying_Price"].replace({"med":2})
df["Buying_Price"]=df["Buying_Price"].replace({"low":1})

#Maintanace generalization
df["Maintanance_price"]=df["Maintanance_price"].replace({"vhigh":4})
df["Maintanance_price"]=df["Maintanance_price"].replace({"high":3})
df["Maintanance_price"]=df["Maintanance_price"].replace({"med":2})
df["Maintanance_price"]=df["Maintanance_price"].replace({"low":1})

#lug_boot generalization
df["Lug_boot"]=df["Lug_boot"].replace({"small":1})
df["Lug_boot"]=df["Lug_boot"].replace({"med":2})
df["Lug_boot"]=df["Lug_boot"].replace({"big":3})

#Safety Generalization
df["Safety"]=df["Safety"].replace({"low":1})
df["Safety"]=df["Safety"].replace({"med":2})
df["Safety"]=df["Safety"].replace({"big":3})

print(df.head())

while printing it showed:

Cannot compare types 'ndarray(dtype=int64)' and 'str'

Body:
I was facing the same issue and what worked for me was converting the datatype of the feature to an object type.

   train['Some_feature']=train.Some_feature.astype(object)

Hope it helps.


问:
how to adjust function location in a LLVM Module
I know how to parse a module from a LLVM bitcode image and how to iterate over the function definitions.

Now, I want to do a reordering to the functions to improve the locality between some functions that is measured to have closer relations with each other.

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/CFG.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/raw_ostream.h>
using namespace llvm;
constexpr const char TEST_FILE[] = "some-file";
std::vector<std::string> symbol_order {};
int some_function() {
    auto context = LLVMContext{};
    SMDiagnostic err;
    auto module = parseIRFile(TEST_FILE, err, context);

    // get all functions and adjust order according to symbol order
    // wrtie back to a valid module bitcode file

}

```

<p>It turns out to be hard because I may need to close the function and insert them by order, which is beyond my current knowledge.</p>

<p>Before I really turn myself into this question, I have some more concerns:</p>

<ol>
<li><p>will the order of the definitions in IR file effectively affect the final ELF output?</p></li>
<li><p>I am currently writing an executable directly operate on the IR files; will it be more proper to write a module pass?</p></li>
</ol>

update

<p>I see a possible way to sort the function is:</p>

<pre class="lang-cpp prettyprint-override"><code>#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/CFG.h>
#include <llvm/Bitcode/BitcodeWriter.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/raw_ostream.h>
#include <absl/container/flat_hash_map.h>
using namespace llvm;
constexpr const char TEST_FILE[] = "file.bc";
absl::flat_hash_map<std::string, size_t> order;
struct Compare {
    bool operator()(const Function& a, const Function& b) {
        return order[a.getName().data()] < order[b.getName().data()];
    }
};
int main() {
    auto context = LLVMContext{};
    SMDiagnostic err;
    auto module = parseIRFile(TEST_FILE, err, context);
    auto& list  = module->getFunctionList();
    list.sort(Compare());
    WriteBitcodeToFile(*module, llvm::outs());
    // get all functions and adjust order according to symbol order
    // wrtie back to a valid module bitcode file
}
</code>```

will it break some dependency relations?

答: The order of the functions in IR in general does not define the order of functions in the final binary. Even more, the linker is free to reorder functions as necessary. And typically it's the linker job to improve the locality of the functions. LLD has some code for this already.</p>

Body:
I know how to parse a module from a LLVM bitcode image and how to iterate over the function definitions.

Now, I want to do a reordering to the functions to improve the locality between some functions that is measured to have closer relations with each other.

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/CFG.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/raw_ostream.h>
using namespace llvm;
constexpr const char TEST_FILE[] = "some-file";
std::vector<std::string> symbol_order {};
int some_function() {
    auto context = LLVMContext{};
    SMDiagnostic err;
    auto module = parseIRFile(TEST_FILE, err, context);

    // get all functions and adjust order according to symbol order
    // wrtie back to a valid module bitcode file

}

It turns out to be hard because I may need to close the function and insert them by order, which is beyond my current knowledge.

Before I really turn myself into this question, I have some more concerns:

will the order of the definitions in IR file effectively affect the final ELF output?

I am currently writing an executable directly operate on the IR files; will it be more proper to write a module pass?

update

I see a possible way to sort the function is:

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/CFG.h>
#include <llvm/Bitcode/BitcodeWriter.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/raw_ostream.h>
#include <absl/container/flat_hash_map.h>
using namespace llvm;
constexpr const char TEST_FILE[] = "file.bc";
absl::flat_hash_map<std::string, size_t> order;
struct Compare {
    bool operator()(const Function& a, const Function& b) {
        return order[a.getName().data()] < order[b.getName().data()];
    }
};
int main() {
    auto context = LLVMContext{};
    SMDiagnostic err;
    auto module = parseIRFile(TEST_FILE, err, context);
    auto& list  = module->getFunctionList();
    list.sort(Compare());
    WriteBitcodeToFile(*module, llvm::outs());
    // get all functions and adjust order according to symbol order
    // wrtie back to a valid module bitcode file
}

will it break some dependency relations?