问:
Java switch statement is directly going to default
I am inheriting a Result class from java class in Result class. In the constructor I am using a Switch but if user enter 1 or another value it not executing and directly going to default.

What is the problem? Any one can explain it to me and also want to utilize FileHandling in  this code as well but how do it not getting the idea?

```<code>public class Vehicle {
    final public void choose() {
        System.out.println("Thanks!for choosing us");
    }

    public void select() {
        System.out.println("select");
    }
}

class Car extends Vehicle {

    int Brand;
    int price;
    int noofpeople;

    public void select() {
        Scanner s = new Scanner(System.in);
        System.out.println("hello we will help you to choose"
                + "best car for you but for this you have answer some questions.");
        System.out.println("Which Brand you want to choose?");
        System.out.println("press 1 for Toyota");
        System.out.println("Press 2 for Honda");
        System.out.println("Press 3 for BMW");
        Brand = s.nextInt();
        System.out.println();
        System.out.println("Please enter your price less than or equal to 20lack");
        price = s.nextInt();
        System.out.println("please enter your family members");
        noofpeople = s.nextInt();
    }
}

class Toyota extends Car {
    Toyota() {
       System.out.println("You selected toyota");
        if (price == 1000000 && noofpeople == 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("passo");
            System.out.println("mooco");
        } else if (price == 200000 && noofpeople == 5) {
            System.out.println("Corolla Grande");
        } else if (price <= 2000000 && noofpeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Corolla gli");
        } else if (price > 2000000 && noofpeople > 5) {
            System.out.println("No car for found");
        }
    }
}

class Honda extends Car {
    Honda() {
        System.out.println("You selected Honda");
        if (price < 1000000 && noofpeople >= 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("honda fit");
            System.out.println("honda pure");
        } else if (price == 2000000 && noofpeople >= 5) {
            System.out.println("honda vezel");
        } else if ((price < 2000000 && price > 1000000) && noofpeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Honda civic");
        } else if (price >= 200000 && noofpeople >= 5) {
            System.out.println("No car for found");

        } else if (noofpeople < 4) {
            System.out.println("No car for found");
        }
    }
}

class BMW extends Car {

    BMW() {
        System.out.println("You selected BMW");
        if (price < 1000000 && noofpeople >= 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("honda fit");
            System.out.println("honda pure");
        } else if (price == 2000000 && noofpeople >= 5) {
            System.out.println("honda vezel");
        } else if ((price < 2000000 && price > 1000000) && noofpeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Honda civic");
        } else if (price >= 200000 && noofpeople >= 5) {
            System.out.println("No car for found");
        } else if (noofpeople < 4) {
            System.out.println("No car for found");
        }
    }
}

class Result extends Car {
    Result() {
        Car c = new Car();
        c.choose();
        c.select();
        switch (Brand) {
            case 1:
                Toyota a = new Toyota();
                break;
            case 2:
                Honda h = new Honda();
                break;
            default:
                BMW n = new BMW();
                break;
        }
    }
}

</code>```

答:
There are few wrong concepts in your code. Here are some of them:

Your class Result should not extends Car. It is not a car.

Your class Result mixes properties of the Car with the logic to choose the car

Leave the properties of the Car inside the car class itself.

The switch is part of your input, don't let it inside your model.

Use camel standard for coding, more details here

I don't see why you use Car and Vehicle together.

For Price, int is not the best option in a production code environment. One suggestion, as you are learning, is using BigDecimal.

What I would do:

Remove the class Result

Let the values inside the Car object

The selection is part of you flow not your model

Here your code modified:

```<code>import java.util.Scanner;

class Scratch {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("hello we will help you to choose"
                + "best car for you but for this you have answer some questions.");
        System.out.println("Which Brand you want to choose?");
        System.out.println("press 1 for Toyota");
        System.out.println("Press 2 for Honda");
        System.out.println("Press 3 for BMW");
        int brand = s.nextInt();

        System.out.println("\nPlease enter your price less than or equal to 20lack");
        int price = s.nextInt();

        System.out.println("please enter your family members");
        int numberOfPeople = s.nextInt();

        switch (brand) {
            case 1:
                Car toyota = new Toyota(price, numberOfPeople);
                toyota.select();
                break;
            case 2:
                Car honda = new Honda(price, numberOfPeople);
                honda.select();
                break;
            default:
                Car bmw = new BMW(price, numberOfPeople);
                bmw.select();
                break;
        }

    }
}

abstract class Car {
    int price;
    int numberOfPeople;

    public Car(int price, int numberOfPeople) {
        this.price = price;
        this.numberOfPeople = numberOfPeople;
    }

    public abstract void select();

}

class Toyota extends Car {
    public Toyota(int price, int numberOfPeople) {
        super(price, numberOfPeople);
    }

    @Override
    public void select() {
        System.out.println("You selected toyota");
        if (price == 1000000 && numberOfPeople == 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("passo");
            System.out.println("mooco");
        } else if (price == 200000 && numberOfPeople == 5) {
            System.out.println("Corolla Grande");
        } else if (price <= 2000000 && numberOfPeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Corolla gli");
        } else if (price > 2000000 && numberOfPeople > 5) {
            System.out.println("No car for found");
        }
    }
}

class Honda extends Car {
    public Honda(int price, int numberOfPeople) {
        super(price, numberOfPeople);
    }

    @Override
    public void select() {
        System.out.println("You selected Honda");
        if (price < 1000000 && numberOfPeople >= 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("honda fit");
            System.out.println("honda pure");
        } else if (price == 2000000 && numberOfPeople >= 5) {
            System.out.println("honda vezel");
        } else if ((price < 2000000 && price > 1000000) && numberOfPeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Honda civic");
        } else if (price >= 200000 && numberOfPeople >= 5) {
            System.out.println("No car for found");

        } else if (numberOfPeople < 4) {
            System.out.println("No car for found");
        }
    }
}

class BMW extends Car {
    public BMW(int price, int numberOfPeople) {
        super(price, numberOfPeople);
    }

    public void select() {
        System.out.println("You selected BMW");
        if (price < 1000000 && numberOfPeople >= 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("honda fit");
            System.out.println("honda pure");
        } else if (price == 2000000 && numberOfPeople >= 5) {
            System.out.println("honda vezel");
        } else if ((price < 2000000 && price > 1000000) && numberOfPeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Honda civic");
        } else if (price >= 200000 && numberOfPeople >= 5) {
            System.out.println("No car for found");
        } else if (numberOfPeople < 4) {
            System.out.println("No car for found");
        }
    }
}
</code>```

Body:
I am inheriting a Result class from java class in Result class. In the constructor I am using a Switch but if user enter 1 or another value it not executing and directly going to default.

What is the problem? Any one can explain it to me and also want to utilize FileHandling in  this code as well but how do it not getting the idea?

public class Vehicle {
    final public void choose() {
        System.out.println("Thanks!for choosing us");
    }

    public void select() {
        System.out.println("select");
    }
}

class Car extends Vehicle {

    int Brand;
    int price;
    int noofpeople;

    public void select() {
        Scanner s = new Scanner(System.in);
        System.out.println("hello we will help you to choose"
                + "best car for you but for this you have answer some questions.");
        System.out.println("Which Brand you want to choose?");
        System.out.println("press 1 for Toyota");
        System.out.println("Press 2 for Honda");
        System.out.println("Press 3 for BMW");
        Brand = s.nextInt();
        System.out.println();
        System.out.println("Please enter your price less than or equal to 20lack");
        price = s.nextInt();
        System.out.println("please enter your family members");
        noofpeople = s.nextInt();
    }
}

class Toyota extends Car {
    Toyota() {
       System.out.println("You selected toyota");
        if (price == 1000000 && noofpeople == 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("passo");
            System.out.println("mooco");
        } else if (price == 200000 && noofpeople == 5) {
            System.out.println("Corolla Grande");
        } else if (price <= 2000000 && noofpeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Corolla gli");
        } else if (price > 2000000 && noofpeople > 5) {
            System.out.println("No car for found");
        }
    }
}

class Honda extends Car {
    Honda() {
        System.out.println("You selected Honda");
        if (price < 1000000 && noofpeople >= 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("honda fit");
            System.out.println("honda pure");
        } else if (price == 2000000 && noofpeople >= 5) {
            System.out.println("honda vezel");
        } else if ((price < 2000000 && price > 1000000) && noofpeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Honda civic");
        } else if (price >= 200000 && noofpeople >= 5) {
            System.out.println("No car for found");

        } else if (noofpeople < 4) {
            System.out.println("No car for found");
        }
    }
}

class BMW extends Car {

    BMW() {
        System.out.println("You selected BMW");
        if (price < 1000000 && noofpeople >= 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("honda fit");
            System.out.println("honda pure");
        } else if (price == 2000000 && noofpeople >= 5) {
            System.out.println("honda vezel");
        } else if ((price < 2000000 && price > 1000000) && noofpeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Honda civic");
        } else if (price >= 200000 && noofpeople >= 5) {
            System.out.println("No car for found");
        } else if (noofpeople < 4) {
            System.out.println("No car for found");
        }
    }
}

class Result extends Car {
    Result() {
        Car c = new Car();
        c.choose();
        c.select();
        switch (Brand) {
            case 1:
                Toyota a = new Toyota();
                break;
            case 2:
                Honda h = new Honda();
                break;
            default:
                BMW n = new BMW();
                break;
        }
    }
}

Body:
There are few wrong concepts in your code. Here are some of them:

Your class Result should not extends Car. It is not a car.

Your class Result mixes properties of the Car with the logic to choose the car

Leave the properties of the Car inside the car class itself.

The switch is part of your input, don't let it inside your model.

Use camel standard for coding, more details here

I don't see why you use Car and Vehicle together.

For Price, int is not the best option in a production code environment. One suggestion, as you are learning, is using BigDecimal.

What I would do:

Remove the class Result

Let the values inside the Car object

The selection is part of you flow not your model

Here your code modified:

import java.util.Scanner;

class Scratch {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("hello we will help you to choose"
                + "best car for you but for this you have answer some questions.");
        System.out.println("Which Brand you want to choose?");
        System.out.println("press 1 for Toyota");
        System.out.println("Press 2 for Honda");
        System.out.println("Press 3 for BMW");
        int brand = s.nextInt();

        System.out.println("\nPlease enter your price less than or equal to 20lack");
        int price = s.nextInt();

        System.out.println("please enter your family members");
        int numberOfPeople = s.nextInt();

        switch (brand) {
            case 1:
                Car toyota = new Toyota(price, numberOfPeople);
                toyota.select();
                break;
            case 2:
                Car honda = new Honda(price, numberOfPeople);
                honda.select();
                break;
            default:
                Car bmw = new BMW(price, numberOfPeople);
                bmw.select();
                break;
        }

    }
}

abstract class Car {
    int price;
    int numberOfPeople;

    public Car(int price, int numberOfPeople) {
        this.price = price;
        this.numberOfPeople = numberOfPeople;
    }

    public abstract void select();

}

class Toyota extends Car {
    public Toyota(int price, int numberOfPeople) {
        super(price, numberOfPeople);
    }

    @Override
    public void select() {
        System.out.println("You selected toyota");
        if (price == 1000000 && numberOfPeople == 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("passo");
            System.out.println("mooco");
        } else if (price == 200000 && numberOfPeople == 5) {
            System.out.println("Corolla Grande");
        } else if (price <= 2000000 && numberOfPeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Corolla gli");
        } else if (price > 2000000 && numberOfPeople > 5) {
            System.out.println("No car for found");
        }
    }
}

class Honda extends Car {
    public Honda(int price, int numberOfPeople) {
        super(price, numberOfPeople);
    }

    @Override
    public void select() {
        System.out.println("You selected Honda");
        if (price < 1000000 && numberOfPeople >= 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("honda fit");
            System.out.println("honda pure");
        } else if (price == 2000000 && numberOfPeople >= 5) {
            System.out.println("honda vezel");
        } else if ((price < 2000000 && price > 1000000) && numberOfPeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Honda civic");
        } else if (price >= 200000 && numberOfPeople >= 5) {
            System.out.println("No car for found");

        } else if (numberOfPeople < 4) {
            System.out.println("No car for found");
        }
    }
}

class BMW extends Car {
    public BMW(int price, int numberOfPeople) {
        super(price, numberOfPeople);
    }

    public void select() {
        System.out.println("You selected BMW");
        if (price < 1000000 && numberOfPeople >= 4) {
            System.out.println("The Best Cars for you are:");
            System.out.println("honda fit");
            System.out.println("honda pure");
        } else if (price == 2000000 && numberOfPeople >= 5) {
            System.out.println("honda vezel");
        } else if ((price < 2000000 && price > 1000000) && numberOfPeople == 5) {
            System.out.println("The Best Cars for you are:");
            System.out.println("Honda civic");
        } else if (price >= 200000 && numberOfPeople >= 5) {
            System.out.println("No car for found");
        } else if (numberOfPeople < 4) {
            System.out.println("No car for found");
        }
    }
}


来源: stackexchange

问:
Importing 'react-native-vector-icon' results 'Unable to resolve module '@expo/vector-icons' error
```<code>error: bundling failed: Error: Unable to resolve module `@expo/vector-icons/Ionicons` from `E:\React Projects\Tourism\src\screens\TouristInformation\TouristInformation.js`: Module `@expo/vector-icons/Ionicons` does not exist in the Haste module map

This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
  1. Clear watchman watches: `watchman watch-del-all`.
  2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
  3. Reset Metro Bundler cache: `rm -rf /tmp/metro-bundler-cache-*` or `npm start -- --reset-cache`.
  4. Remove haste cache: `rm -rf /tmp/haste-map-react-native-packager-*`.
    at ModuleResolver.resolveDependency (E:\React Projects\Tourism\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:139:15)
    at ResolutionRequest.resolveDependency (E:\React Projects\Tourism\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:49:18)
    at DependencyGraph.resolveDependency (E:\React Projects\Tourism\node_modules\metro\src\node-haste\DependencyGraph.js:218:16)
    at Object.resolve (E:\React Projects\Tourism\node_modules\metro\src\lib\transformHelpers.js:141:30)
    at dependencies.map.result (E:\React Projects\Tourism\node_modules\metro\src\DeltaBundler\traverseDependencies.js:373:31)
    at Array.map (<anonymous>)
    at resolveDependencies (E:\React Projects\Tourism\node_modules\metro\src\DeltaBundler\traverseDependencies.js:369:18)
    at E:\React Projects\Tourism\node_modules\metro\src\DeltaBundler\traverseDependencies.js:188:33
    at Generator.next (<anonymous>)
    at step (E:\React Projects\Tourism\node_modules\metro\src\DeltaBundler\traverseDependencies.js:298:30)
 BUNDLE  [android, dev] ..\..\../index.js ▓▓▓▓▓▓▓░░░░░░░░░ 48.8% (311/450), failed.

::ffff:127.0.0.1 - - [17/Jan/2019:21:01:47 +0000] "GET /index.delta?platform=android&dev=true&minify=false HTTP/1.1" 500 - "-" "okhttp/3.11.0"
</code>```

I ejected the project running 'expo eject'.
Then I added 'react-native-vector-icon' to use font icons provided by that package. But, whenever I import that library to any of my js file. Though I'm importing 'react-native-vector-icon',it shows the above error.

TouristInformation.js

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  Image,
  View,
} from 'react-native';
import residentBackgroundImage from '../../assets/residentBackground.jpg';
import Icon from 'react-native-vector-icons/Ionicons';
export default class TouristInformation extends Component {
  render() {
    return(
      <View>
        <Image
          source = {residentBackgroundImage}
          style = {styles.image} />
        <Text> Yomuna </Text>
      <Icon name="ios-person" size={30} color="#4F8EF7" />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  image:{

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

答:
Run the below commands.</p>

```<code>npm i react-native-vector-icons
npx react-native link react-native-vector-icons

</code>```

ContentLicense: CC BY-SA 4.0

Body:
error: bundling failed: Error: Unable to resolve module `@expo/vector-icons/Ionicons` from `E:\React Projects\Tourism\src\screens\TouristInformation\TouristInformation.js`: Module `@expo/vector-icons/Ionicons` does not exist in the Haste module map

This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
  1. Clear watchman watches: `watchman watch-del-all`.
  2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
  3. Reset Metro Bundler cache: `rm -rf /tmp/metro-bundler-cache-*` or `npm start -- --reset-cache`.
  4. Remove haste cache: `rm -rf /tmp/haste-map-react-native-packager-*`.
    at ModuleResolver.resolveDependency (E:\React Projects\Tourism\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:139:15)
    at ResolutionRequest.resolveDependency (E:\React Projects\Tourism\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:49:18)
    at DependencyGraph.resolveDependency (E:\React Projects\Tourism\node_modules\metro\src\node-haste\DependencyGraph.js:218:16)
    at Object.resolve (E:\React Projects\Tourism\node_modules\metro\src\lib\transformHelpers.js:141:30)
    at dependencies.map.result (E:\React Projects\Tourism\node_modules\metro\src\DeltaBundler\traverseDependencies.js:373:31)
    at Array.map (<anonymous>)
    at resolveDependencies (E:\React Projects\Tourism\node_modules\metro\src\DeltaBundler\traverseDependencies.js:369:18)
    at E:\React Projects\Tourism\node_modules\metro\src\DeltaBundler\traverseDependencies.js:188:33
    at Generator.next (<anonymous>)
    at step (E:\React Projects\Tourism\node_modules\metro\src\DeltaBundler\traverseDependencies.js:298:30)
 BUNDLE  [android, dev] ..\..\../index.js ▓▓▓▓▓▓▓░░░░░░░░░ 48.8% (311/450), failed.

::ffff:127.0.0.1 - - [17/Jan/2019:21:01:47 +0000] "GET /index.delta?platform=android&dev=true&minify=false HTTP/1.1" 500 - "-" "okhttp/3.11.0"

I ejected the project running 'expo eject'.
Then I added 'react-native-vector-icon' to use font icons provided by that package. But, whenever I import that library to any of my js file. Though I'm importing 'react-native-vector-icon',it shows the above error.

TouristInformation.js

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  Image,
  View,
} from 'react-native';
import residentBackgroundImage from '../../assets/residentBackground.jpg';
import Icon from 'react-native-vector-icons/Ionicons';
export default class TouristInformation extends Component {
  render() {
    return(
      <View>
        <Image
          source = {residentBackgroundImage}
          style = {styles.image} />
        <Text> Yomuna </Text>
      <Icon name="ios-person" size={30} color="#4F8EF7" />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  image:{

  },
});

Body:
Run the below commands.

npm i react-native-vector-icons
npx react-native link react-native-vector-icons


问:
Powershell Find and Replace in XML with duplicate lines
Goal:

I want a Powershell script to find and replace text in a singel XML file. But i only want to change one of the parameters in the XML. (see XML below)

Somthing like:

```<code>(Get-Content C:\test\config.xml).Replace("<Comport>1", "<Comport>2") | Set-Content C:\test\config.xml
</code>```

After a day of googling and reading on Stackoverflow i still cant figur it out.

Problem:

The xml file do contain a lot of the same words and sentences.

The XML file will not always contain the same amount of data or lines.

I cant figure out how to target the right line that contains "comport".

excerpt from XML:

```<code><Config>
  <utiliti1>
    <Enabled>1</Enabled>
    <Comport>0</Comport>
    <Baudrate>9600</Baudrate>
    <Stopbit>1</Stopbit>
    <Parity>NONE</Parity>
    <Databits>8</Databits>
    <IpPort>0</IpPort>
    <IpAdresse>0</IpAdresse>
  </utiliti1>
  <utiliti2>
    <Enabled>1</Enabled>
    <Comport>0</Comport>
    <Baudrate>9600</Baudrate>
    <Stopbit>1</Stopbit>
    <Parity>NONE</Parity>
    <Databits>8</Databits>
    <IpPort>0</IpPort>
    <IpAdresse>0</IpAdresse>
  </utiliti2>
  <utiliti3>
    <Enabled>1</Enabled>
    <Comport>0</Comport>
    <Baudrate>9600</Baudrate>
    <Stopbit>1</Stopbit>
    <Parity>NONE</Parity>
    <Databits>8</Databits>
    <IpPort>0</IpPort>
    <IpAdresse>0</IpAdresse>
  </utiliti3>
</code>```

答:
If you do not know which utiliti* node to select but know the unique comport value, you can do the following:

```<code># Find and replace Comport 20 with 37
$x = [xml](Get-Content C:\test\config.xml)
$x.SelectSingleNode('//Config/*[Comport="20"]').Comport = '37'
$x.Save('C:\test\config.xml')
</code>```

XPATH //Config/*[Comport="20"] selects the Config element with a child element that contains a child element called Comport with a string value of 20.

If you want to replace an unknown number of duplicate Comport values with new values, you can do the following:

```<code>$x = [xml](Get-Content C:\test\config.xml)
$usedComports = @{} # Tracks already seen comports
$newComport = 0 # Current available comport
$comportNodes = $x.SelectNodes('//Config/*[Comport]')
$comports = $comportNodes.Comport
($comportNodes | Group Comport | Where Count -gt 1).Group | Foreach-Object {
    if ($_.Comport -in $usedComports.Keys) {
        # Increase $newComport until it is unique among your xml comport values
        do {$newComport++} until ($newComport -notin $comports+$usedComports.Keys)
        $_.Comport = "$newComport" # Using quotes to make it a string
    }
    # Adds current comport to tracker table
    if ($_.Comport -notin $usedComports.Keys) {
        $usedComports.Add($_.Comport,0)
    }
}
$x.Save('C:\test\config.xml')
</code>```

Body:
Goal:

I want a Powershell script to find and replace text in a singel XML file. But i only want to change one of the parameters in the XML. (see XML below)

Somthing like:

(Get-Content C:\test\config.xml).Replace("<Comport>1", "<Comport>2") | Set-Content C:\test\config.xml

After a day of googling and reading on Stackoverflow i still cant figur it out.

Problem:

The xml file do contain a lot of the same words and sentences.

The XML file will not always contain the same amount of data or lines.

I cant figure out how to target the right line that contains "comport".

excerpt from XML:

<Config>
  <utiliti1>
    <Enabled>1</Enabled>
    <Comport>0</Comport>
    <Baudrate>9600</Baudrate>
    <Stopbit>1</Stopbit>
    <Parity>NONE</Parity>
    <Databits>8</Databits>
    <IpPort>0</IpPort>
    <IpAdresse>0</IpAdresse>
  </utiliti1>
  <utiliti2>
    <Enabled>1</Enabled>
    <Comport>0</Comport>
    <Baudrate>9600</Baudrate>
    <Stopbit>1</Stopbit>
    <Parity>NONE</Parity>
    <Databits>8</Databits>
    <IpPort>0</IpPort>
    <IpAdresse>0</IpAdresse>
  </utiliti2>
  <utiliti3>
    <Enabled>1</Enabled>
    <Comport>0</Comport>
    <Baudrate>9600</Baudrate>
    <Stopbit>1</Stopbit>
    <Parity>NONE</Parity>
    <Databits>8</Databits>
    <IpPort>0</IpPort>
    <IpAdresse>0</IpAdresse>
  </utiliti3>

Body:
If you do not know which utiliti* node to select but know the unique comport value, you can do the following:

# Find and replace Comport 20 with 37
$x = [xml](Get-Content C:\test\config.xml)
$x.SelectSingleNode('//Config/*[Comport="20"]').Comport = '37'
$x.Save('C:\test\config.xml')

XPATH //Config/*[Comport="20"] selects the Config element with a child element that contains a child element called Comport with a string value of 20.

If you want to replace an unknown number of duplicate Comport values with new values, you can do the following:

$x = [xml](Get-Content C:\test\config.xml)
$usedComports = @{} # Tracks already seen comports
$newComport = 0 # Current available comport
$comportNodes = $x.SelectNodes('//Config/*[Comport]')
$comports = $comportNodes.Comport
($comportNodes | Group Comport | Where Count -gt 1).Group | Foreach-Object {
    if ($_.Comport -in $usedComports.Keys) {
        # Increase $newComport until it is unique among your xml comport values
        do {$newComport++} until ($newComport -notin $comports+$usedComports.Keys)
        $_.Comport = "$newComport" # Using quotes to make it a string
    }
    # Adds current comport to tracker table
    if ($_.Comport -notin $usedComports.Keys) {
        $usedComports.Add($_.Comport,0)
    }
}
$x.Save('C:\test\config.xml')


问:
How to reset the indices of remaining dataframe values after removing duplicate rows?
I have a dataframe and have removed duplicate rows using .drop_duplicates() method. But the initial index of the rows and still the same.

```<code>data = data.drop_duplicates(keep=False, inplace=True)
</code>```

```<code>    id  Name    Designation     DOB
2   7934    'MILLER'    'CLERK' 7782.0  '23-JAN-82' 1300        10
8   7521    'WARD'  'SALESMAN'  7698.0  '22-FEB-81' 1250    500.0   30
9   7902    'FORD'  'ANALYST'   7566.0  '3-DEC-81'  3000        20
10  7876    'ADAMS' 'CLERK' 7788.0  '12-JAN-83' 1100        20
11  7566    'JONES' 'MANAGER'   7839.0  '2-APR-81'  2975        20
12  7698    'BLAKE' 'MANAGER'   7839.0  '1-MAY-81'  2850        30
17  7839    'KING-WEB'  'PRESIDENT'     '17-NOV-81' 15000       10
</code>```

I want to re-index all the rows like this:

```<code>    id  Name    Designation     DOB
1   7934    'MILLER'    'CLERK' 7782.0  '23-JAN-82' 1300        10
2   7521    'WARD'  'SALESMAN'  7698.0  '22-FEB-81' 1250    500.0   30
3   7902    'FORD'  'ANALYST'   7566.0  '3-DEC-81'  3000        20
4   7876    'ADAMS' 'CLERK' 7788.0  '12-JAN-83' 1100        20
5   7566    'JONES' 'MANAGER'   7839.0  '2-APR-81'  2975        20
6   7698    'BLAKE' 'MANAGER'   7839.0  '1-MAY-81'  2850        30
7   7839    'KING-WEB'  'PRESIDENT'     '17-NOV-81' 15000       10
</code>```

答:
```<code>data = data.reset_index(drop=True)
</code>```

Body:
I have a dataframe and have removed duplicate rows using .drop_duplicates() method. But the initial index of the rows and still the same.

data = data.drop_duplicates(keep=False, inplace=True)

    id  Name    Designation     DOB
2   7934    'MILLER'    'CLERK' 7782.0  '23-JAN-82' 1300        10
8   7521    'WARD'  'SALESMAN'  7698.0  '22-FEB-81' 1250    500.0   30
9   7902    'FORD'  'ANALYST'   7566.0  '3-DEC-81'  3000        20
10  7876    'ADAMS' 'CLERK' 7788.0  '12-JAN-83' 1100        20
11  7566    'JONES' 'MANAGER'   7839.0  '2-APR-81'  2975        20
12  7698    'BLAKE' 'MANAGER'   7839.0  '1-MAY-81'  2850        30
17  7839    'KING-WEB'  'PRESIDENT'     '17-NOV-81' 15000       10

I want to re-index all the rows like this:

    id  Name    Designation     DOB
1   7934    'MILLER'    'CLERK' 7782.0  '23-JAN-82' 1300        10
2   7521    'WARD'  'SALESMAN'  7698.0  '22-FEB-81' 1250    500.0   30
3   7902    'FORD'  'ANALYST'   7566.0  '3-DEC-81'  3000        20
4   7876    'ADAMS' 'CLERK' 7788.0  '12-JAN-83' 1100        20
5   7566    'JONES' 'MANAGER'   7839.0  '2-APR-81'  2975        20
6   7698    'BLAKE' 'MANAGER'   7839.0  '1-MAY-81'  2850        30
7   7839    'KING-WEB'  'PRESIDENT'     '17-NOV-81' 15000       10

Body: data = data.reset_index(drop=True)


问:
Return a function with arbitrary properties in typescript
I have a hook useEvent which takes a function and needs to return an event. However, I'm having trouble to match the return type of the hook.

```<code>const useEvent = (event: (events: Events) => Function) => {
  const { events }: { events: Events } = useContext(Context);
  return useMemo(() => {
      return event(events);
    }
  }, [event, events]);
};
</code>```

And this is how I get the events in the components:

```<code>const trackClick = useEvent(events => events.trackClickedApp);
...
trackClick(name, page, location, variable);
</code>```

I wanted it to be more specific than Function. I created interfaces for all the events which can take input

```<code>interface trackClickSortBy {
  (sort: string): void;
}
interface trackClickedApp {
  (
    name: string,
    page: string,
    location: string | null,
    variable: string | null,
  ): void;
}
...
</code>```

Then I added all these interfaces to a type Event.

```<code>type Event = trackClickSortBy | trackClickedApp | ...;
</code>```

And finally add the new type to the return of the hook

```<code>const useEvent = (event: (events: Events) => Event) => {
</code>```

I expected this to work, but it doesn't. In three cases I get Expected 7 arguments, but got 2
Any other way that I can solve this?
Please let me know if there's any info I should provide

答:
I ended up using Generics.

This is how it looks in the end:

```<code>const useEvent = <T>(event: (events: Events) => T)
</code>```

Body:
I have a hook useEvent which takes a function and needs to return an event. However, I'm having trouble to match the return type of the hook.

const useEvent = (event: (events: Events) => Function) => {
  const { events }: { events: Events } = useContext(Context);
  return useMemo(() => {
      return event(events);
    }
  }, [event, events]);
};

And this is how I get the events in the components:

const trackClick = useEvent(events => events.trackClickedApp);
...
trackClick(name, page, location, variable);

I wanted it to be more specific than Function. I created interfaces for all the events which can take input

interface trackClickSortBy {
  (sort: string): void;
}
interface trackClickedApp {
  (
    name: string,
    page: string,
    location: string | null,
    variable: string | null,
  ): void;
}
...

Then I added all these interfaces to a type Event.

type Event = trackClickSortBy | trackClickedApp | ...;

And finally add the new type to the return of the hook

const useEvent = (event: (events: Events) => Event) => {

I expected this to work, but it doesn't. In three cases I get Expected 7 arguments, but got 2
Any other way that I can solve this?
Please let me know if there's any info I should provide

Body:
I ended up using Generics.

This is how it looks in the end:

const useEvent = <T>(event: (events: Events) => T)


问:
How to mock the npm module that exports the default and the object
I have created a library that exports the default object that includes a few utility functions. Along with default, I have also exported a couple of enums. Here is how my exports look like in the root file of the library

```<code>exports.default = new _oAuth2.default();
var OAUTH_LOG_LEVELS = exports.LOG_LEVELS = {DEBUG: 10, WARN: 20};
var OAUTH_VERSIONS = exports.VERSIONS = {V1: '1.0', v2: '2.0'}
</code>```

In my react app I am importing and using the values this like

```<code>import lib1, {VERSIONS, LOG_LEVELS} from 'mylib';

lib1.init({
  verion: VERSIONS.V1,
})
</code>```

Everything is working fine in the app. Now, I want to add a unit test in the app using Jest, I tried to mock the library. Here is my mock

```<code>jest.mock('myLib', () => ({
  init: jest.fn(),
}));
</code>```

Now, my question is, how to mock the library to include the enums along with defaults? I tried multiple ways but did not succeed. Without that, I cannot use the enums exposed by the library. When I try to use that, the unit test is throwing an error that VERSIONS is not defined.

答:
After digging more into Jest documentation, I found a way to explicitly mock the library as an esModule. I updated my mock to

```<code>jest.mock('myLib', () => ({
  __esModule: true,
  default: {
    init: jest.fn(),
  },
  VERSIONS: {V1: '1.0'},
}));
</code>```

This fixed my problem.

Body:
I have created a library that exports the default object that includes a few utility functions. Along with default, I have also exported a couple of enums. Here is how my exports look like in the root file of the library

exports.default = new _oAuth2.default();
var OAUTH_LOG_LEVELS = exports.LOG_LEVELS = {DEBUG: 10, WARN: 20};
var OAUTH_VERSIONS = exports.VERSIONS = {V1: '1.0', v2: '2.0'}

In my react app I am importing and using the values this like

import lib1, {VERSIONS, LOG_LEVELS} from 'mylib';

lib1.init({
  verion: VERSIONS.V1,
})

Everything is working fine in the app. Now, I want to add a unit test in the app using Jest, I tried to mock the library. Here is my mock

jest.mock('myLib', () => ({
  init: jest.fn(),
}));

Now, my question is, how to mock the library to include the enums along with defaults? I tried multiple ways but did not succeed. Without that, I cannot use the enums exposed by the library. When I try to use that, the unit test is throwing an error that VERSIONS is not defined.

Body:
After digging more into Jest documentation, I found a way to explicitly mock the library as an esModule. I updated my mock to

jest.mock('myLib', () => ({
  __esModule: true,
  default: {
    init: jest.fn(),
  },
  VERSIONS: {V1: '1.0'},
}));

This fixed my problem.


问:
saving and naming files in R automatically based on input filename
I have generated several Utilisation Distributions (UD) with AdehabitatHR and stored them as Geotiffs. I am now using the same UDs with the Lattice package to generate some maps and saving them to a high-res tiff image with LZW compression. Problem is that I have literally hundreds of maps to make, save and name. Is there a way automatically do this once i have loaded all the necessary files from a directory? Each one of my UDs has the following structure of the filename "UD_resolution_species_area_year_season. tif" and in the final name I give to my map I would like to keep the same structure (or entire filename) but add the prefix "blablabla_" e.g. "blablabla_UD_resolution_species_area_year_season.tiff". The image also include a main name, a capital letter, which should also change.

At the moment I am using the following:

```<code>rlist = list.files(getwd(), pattern = "tif$", full.names = FALSE)
for (i in rlist) {
  assign(unlist(strsplit(i, "[.]"))[1], raster(i))
}

 shplist = list.files(getwd(), pattern = "shp$", full.names = FALSE)
for (i in shplist) {
  assign(unlist(strsplit(i, "[.]"))[1], readOGR(i))
}

UD <- 'UD_resolution_species_area_year_season'
    ext <- extent(UD) + 0.3 # set the extent for the plot

    aa <-
      quantile(UD,
               probs = c(0.25, 0.75),
               type = 8,
               names = TRUE)
    my.at <- c(aa[1], aa[2])
    my.at <- round(my.at, 3)

    maxval <- maxValue(UD)

tiff(
  "C:/myworkingdirectory/maps/blablabla_UD_resolution_species_area_year_season.tiff",
  res = 600,
  compression = "lzw",
  width = 15,
  height = 15,
  units = "cm"
)

levelplot(
  UD,
  xlab = "",
  ylab = "",
  xlim = c(ext[1], ext[2]),
  ylim = c(ext[3], ext[4]),
  margin = FALSE,
  contour = FALSE,
  col.regions = viridis(1000),
  colorkey = list(at = seq(0, maxval)),
  main = "A",
  maxpixels = 2e5
) + latticeExtra::layer(sp.polygons(Land, fill = "grey50", col = NA)) + contourplot(
  `UD`,
  at = my.at[1],
  labels = FALSE,
  margin = FALSE,
  lty = 2,
  col = "orange",
  pretty = TRUE
) + contourplot(
  UD,
  at = my.at[2],
  labels = FALSE,
  margin = FALSE,
  lty = 2,
  col = "red",
  pretty = TRUE,
)

dev.off()
</code>```

答:
It is a common beginners mistake to use assign. Do not use it, it creates the type of trouble you are now facing. In stead, you can make lists and/or use a loop.

Also what you are asking is basic R stuff, but you are complicating the question with adding lots of irrelevant detail about setting the extent, and levelplot. It is better to learn about doing these basic things by removing the clutter and focus on a simple case first. That is also how you should write questions for this forum.

In essence you have a bunch of files you want to process. Below I show how you can loop over a vector of the names and then loop and do what you need to do in that loop.

```<code>library(raster)
rastfiles <- list.files(pattern = "tif$", full.names=TRUE)
outputfiles <- file.path("output/path", paste0("prefix_", basename(rastfiles)))
for (i in 1:length(rastfiles))
   r <- raster(rastfiles[i])
   png(outputfiles[i])
   plot(r)
   dev.off()
 }
</code>```

You can also first read all the files into a list

```<code>rastfiles <- list.files(pattern = "tif$", full.names=TRUE)
rlist <- lapply(rastfiles, raster)
names(rlist) <- gsub(".tif$", "", basename(rastfiles))

rastfiles <- list.files(pattern = "shp$", full.names=TRUE)
slist <- lapply(shpfiles, readOGR)
names(slist) <- gsub(".shp$", "", basename(shpfiles))
</code>```

And perhaps create a vector of output filenames

```<code>outputtif <- file.path("output/dir", basename(rastfiles))
</code>```

And then loop over the items in the list, or the output filenames

Body:
I have generated several Utilisation Distributions (UD) with AdehabitatHR and stored them as Geotiffs. I am now using the same UDs with the Lattice package to generate some maps and saving them to a high-res tiff image with LZW compression. Problem is that I have literally hundreds of maps to make, save and name. Is there a way automatically do this once i have loaded all the necessary files from a directory? Each one of my UDs has the following structure of the filename "UD_resolution_species_area_year_season. tif" and in the final name I give to my map I would like to keep the same structure (or entire filename) but add the prefix "blablabla_" e.g. "blablabla_UD_resolution_species_area_year_season.tiff". The image also include a main name, a capital letter, which should also change.

At the moment I am using the following:

rlist = list.files(getwd(), pattern = "tif$", full.names = FALSE)
for (i in rlist) {
  assign(unlist(strsplit(i, "[.]"))[1], raster(i))
}

 shplist = list.files(getwd(), pattern = "shp$", full.names = FALSE)
for (i in shplist) {
  assign(unlist(strsplit(i, "[.]"))[1], readOGR(i))
}

UD <- 'UD_resolution_species_area_year_season'
    ext <- extent(UD) + 0.3 # set the extent for the plot

    aa <-
      quantile(UD,
               probs = c(0.25, 0.75),
               type = 8,
               names = TRUE)
    my.at <- c(aa[1], aa[2])
    my.at <- round(my.at, 3)

    maxval <- maxValue(UD)

tiff(
  "C:/myworkingdirectory/maps/blablabla_UD_resolution_species_area_year_season.tiff",
  res = 600,
  compression = "lzw",
  width = 15,
  height = 15,
  units = "cm"
)

levelplot(
  UD,
  xlab = "",
  ylab = "",
  xlim = c(ext[1], ext[2]),
  ylim = c(ext[3], ext[4]),
  margin = FALSE,
  contour = FALSE,
  col.regions = viridis(1000),
  colorkey = list(at = seq(0, maxval)),
  main = "A",
  maxpixels = 2e5
) + latticeExtra::layer(sp.polygons(Land, fill = "grey50", col = NA)) + contourplot(
  `UD`,
  at = my.at[1],
  labels = FALSE,
  margin = FALSE,
  lty = 2,
  col = "orange",
  pretty = TRUE
) + contourplot(
  UD,
  at = my.at[2],
  labels = FALSE,
  margin = FALSE,
  lty = 2,
  col = "red",
  pretty = TRUE,
)

dev.off()

Body:
It is a common beginners mistake to use assign. Do not use it, it creates the type of trouble you are now facing. In stead, you can make lists and/or use a loop.

Also what you are asking is basic R stuff, but you are complicating the question with adding lots of irrelevant detail about setting the extent, and levelplot. It is better to learn about doing these basic things by removing the clutter and focus on a simple case first. That is also how you should write questions for this forum.

In essence you have a bunch of files you want to process. Below I show how you can loop over a vector of the names and then loop and do what you need to do in that loop.

library(raster)
rastfiles <- list.files(pattern = "tif$", full.names=TRUE)
outputfiles <- file.path("output/path", paste0("prefix_", basename(rastfiles)))
for (i in 1:length(rastfiles))
   r <- raster(rastfiles[i])
   png(outputfiles[i])
   plot(r)
   dev.off()
 }

You can also first read all the files into a list

rastfiles <- list.files(pattern = "tif$", full.names=TRUE)
rlist <- lapply(rastfiles, raster)
names(rlist) <- gsub(".tif$", "", basename(rastfiles))

rastfiles <- list.files(pattern = "shp$", full.names=TRUE)
slist <- lapply(shpfiles, readOGR)
names(slist) <- gsub(".shp$", "", basename(shpfiles))

And perhaps create a vector of output filenames

outputtif <- file.path("output/dir", basename(rastfiles))

And then loop over the items in the list, or the output filenames


答:
This is basically a lag() and lead():

```<code>select d.time as startime, lead(d.time, 1, max_time) over (order by time) as endtime,
       (value is not null) as has_value
from (select d.*,
             lag(value) over (order by time) as prev_value,
             max(time) over () as max_time
      from data d
     ) d
where (prev_value is null and value is not null) or
      (prev_value is not null and value is null)
</code>```

Here is a db<>fiddle.

The above works because the first row has a non-NULL value.  If the first row had a NULL value, then you can use:

```<code>select d.time as startime, lead(d.time, 1, max_time) over (order by time) as endtime,
       (value is not null) as has_value
from (select d.*,
             lag(value) over (order by time) as prev_value,
             max(time) over () as max_time,
             row_number() over (order by time) as seqnum
      from data d
     ) d
where seqnum = 1 or
      (prev_value is null and value is not null) or
      (prev_value is not null and value is null)
</code>```

Or more concisely as:

```<code>select d.time as startime, lead(d.time, 1, max_time) over (order by time) as endtime,
       has_value
from (select d.*, v.has_value,
             lag(v.has_value) over (order by d.time) as prev_has_value,
             max(d.time) over () as max_time
      from data d cross join lateral
           (values (d.value is not null)) v(has_value)
     ) d
where prev_has_value is null or
      (not prev_has_value and has_value) or
      (prev_has_value and not has_value);
</code>```

Title: How to construct an interval table in PostgreSQL?

Body:
I have a table data with two fields time and value.

Table Data
| time                 | value            |
|----------------------|------------------|
|"2020-05-31 17:16:48" | 132.868607594937 |
|"2020-05-31 17:31:12" | 74.1302380952381 |
|"2020-05-31 17:45:36" | 27.9773333333333 |
|"2020-05-31 18:00:00" | NULL             |
|"2020-05-31 18:14:24" | NULL             |
|"2020-05-31 18:28:48" | NULL             |
|"2020-06-01 05:16:48" | NULL             |
|"2020-06-01 05:31:12" | NULL             |
|"2020-06-01 05:45:36" | 10.3688461538462 |
|"2020-06-01 06:00:00" | 0.5295           |
|"2020-06-01 06:14:24" | 0.516052631578947|

As you can see there are rows in the table with and without values. I'd love to build a table that would list intervals when there were and were not values coming. It would look like this:

Table: Results
| startTime            | endTime               | hasValues |
|----------------------|-----------------------|-----------|
|"2020-05-31 17:16:48" | "2020-05-31 18:00:00" | true      |
|"2020-05-31 18:00:00" | "2020-06-01 05:45:36" | false     |
|"2020-06-01 05:45:36" | "2020-06-01 06:14:24" | true      |

How can I do it? I'm using Postgres 12.

Body:
This is basically a lag() and lead():

select d.time as startime, lead(d.time, 1, max_time) over (order by time) as endtime,
       (value is not null) as has_value
from (select d.*,
             lag(value) over (order by time) as prev_value,
             max(time) over () as max_time
      from data d
     ) d
where (prev_value is null and value is not null) or
      (prev_value is not null and value is null)

Here is a db<>fiddle.

The above works because the first row has a non-NULL value.  If the first row had a NULL value, then you can use:

select d.time as startime, lead(d.time, 1, max_time) over (order by time) as endtime,
       (value is not null) as has_value
from (select d.*,
             lag(value) over (order by time) as prev_value,
             max(time) over () as max_time,
             row_number() over (order by time) as seqnum
      from data d
     ) d
where seqnum = 1 or
      (prev_value is null and value is not null) or
      (prev_value is not null and value is null)

Or more concisely as:

select d.time as startime, lead(d.time, 1, max_time) over (order by time) as endtime,
       has_value
from (select d.*, v.has_value,
             lag(v.has_value) over (order by d.time) as prev_has_value,
             max(d.time) over () as max_time
      from data d cross join lateral
           (values (d.value is not null)) v(has_value)
     ) d
where prev_has_value is null or
      (not prev_has_value and has_value) or
      (prev_has_value and not has_value);


问:
How to avoid having too many nested function when using promises
So I'm working on a Discord bot using Discord.js. Here's the code I want to simplify:

message.channel.send('**Card 1:** (type `next` to reveal the second card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
  message.channel.awaitMessages(filter, {
      max: 1,
      time: 30000,
      errors: ['time']
    })
    .then(collected => {
      message.channel.send('**Card 2:** (type `next` to reveal the third card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
        message.channel.awaitMessages(filter, {
            max: 1,
            time: 30000,
            errors: ['time']
          })
          .then(collected => {
            message.channel.send('**Card 3:** (type `next` to reveal the fourth card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
              message.channel.awaitMessages(filter, {
                  max: 1,
                  time: 30000,
                  errors: ['time']
                })
                .then(collected => {
                  message.channel.send('**Card 4:** (type `next` to reveal the last card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
                    message.channel.awaitMessages(filter, {
                        max: 1,
                        time: 30000,
                        errors: ['time']
                      })
                      .then(collected => {
                        message.channel.send('**Card 5:** \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]);
                      })
                  })
                })
            })
          })
      })
    })
    .catch(collected => {
      message.channel.send('Pack forfeited.');
    });
});
```

<p>The code above works, but it's too messy. Is there a way to simplify this?</p>

<p>EDIT: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>async function revealCard(i) {
  message.channel.send(`**Card ${i + 1}:** (type \`next\` to reveal card ${i + 2}) \n` + specs[Math.floor(Math.random() * specs.length)][pictureKey]);
  let collected = await message.channel.awaitMessages(filter, {
    max: 1,
    time: 30000,
    errors: ['time']
  });
}

for (i = 0; i > 5; i++) {
  revealCard(i);

  if (collected === null) {
    break;
  }
}</code>```

This is my current code. Pretty sure I must have done something wrong because when I attempt running this command, nothing happens. No errors. Just nothingness. Am I doing this correctly?

Thanks in advance.

答:
Other's have mentioned using await, but another solution is just to return the promise instead.

For example:

client.channels.fetch("id")
 .then(channel => channel.messages.fetch("id"))
 .then(message => message.delete())
 .then(() => console.log("done"));
```

Like Federico Grandi suggested I think you should relearn the basics instead of just using a library like discord.js,
99% of the errors you will come across is just because you don't know js, like most of the posts on here.

Body:
So I'm working on a Discord bot using Discord.js. Here's the code I want to simplify:

message.channel.send('**Card 1:** (type `next` to reveal the second card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
  message.channel.awaitMessages(filter, {
      max: 1,
      time: 30000,
      errors: ['time']
    })
    .then(collected => {
      message.channel.send('**Card 2:** (type `next` to reveal the third card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
        message.channel.awaitMessages(filter, {
            max: 1,
            time: 30000,
            errors: ['time']
          })
          .then(collected => {
            message.channel.send('**Card 3:** (type `next` to reveal the fourth card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
              message.channel.awaitMessages(filter, {
                  max: 1,
                  time: 30000,
                  errors: ['time']
                })
                .then(collected => {
                  message.channel.send('**Card 4:** (type `next` to reveal the last card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
                    message.channel.awaitMessages(filter, {
                        max: 1,
                        time: 30000,
                        errors: ['time']
                      })
                      .then(collected => {
                        message.channel.send('**Card 5:** \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]);
                      })
                  })
                })
            })
          })
      })
    })
    .catch(collected => {
      message.channel.send('Pack forfeited.');
    });
});

The code above works, but it's too messy. Is there a way to simplify this?

EDIT:

async function revealCard(i) {
  message.channel.send(`**Card ${i + 1}:** (type \`next\` to reveal card ${i + 2}) \n` + specs[Math.floor(Math.random() * specs.length)][pictureKey]);
  let collected = await message.channel.awaitMessages(filter, {
    max: 1,
    time: 30000,
    errors: ['time']
  });
}

for (i = 0; i > 5; i++) {
  revealCard(i);

  if (collected === null) {
    break;
  }
}

This is my current code. Pretty sure I must have done something wrong because when I attempt running this command, nothing happens. No errors. Just nothingness. Am I doing this correctly?

Thanks in advance.

Body:
Other's have mentioned using await, but another solution is just to return the promise instead.

For example:

client.channels.fetch("id")
 .then(channel => channel.messages.fetch("id"))
 .then(message => message.delete())
 .then(() => console.log("done"));

Like Federico Grandi suggested I think you should relearn the basics instead of just using a library like discord.js,
99% of the errors you will come across is just because you don't know js, like most of the posts on here.


问:
ModuleNotFoundError with pytest
I want my tests folder separate to my application code. My project structure is like so

```<code>myproject/
  myproject/
    myproject.py
    moduleone.py
  tests/
    myproject_test.py
</code>```

myproject.py

```<code>from moduleone import ModuleOne

class MyProject(object)
....
</code>```

myproject_test.py

```<code>from myproject.myproject import MyProject
import pytest

...
</code>```

I use myproject.myproject since I use the command

```<code>python -m pytest
</code>```

from the project root directory ./myproject/

However, then the imports within those modules fail with

E   ModuleNotFoundError: No module named 'moduleone'

I am running Python 3.7 and have read that since 3.3, empty __init__ files are no longer needed which means my project becomes an implicit namespace package

However, I have tried adding an __init__.py file in myproject/myproject/ and also tried adding a conftest.py file in myproject/ but  neither works

I have read answers that say to mess with the paths and then upvoted comments in other questions saying not to.

What is the correct way and what am I missing?

EDIT;

Possibly related, I used a requirements.txt to install pytest using pip. Could this be related? And if so, what is the correct way to install pytest in this case?

EDIT 2:

One of the paths in sys.path is /usr/src/app/ which is a docker volume lined to /my/local/path/myproject/.

Should the volume be /my/local/path/myproject/myproject/ instead?

答:
Kept everything same and just added a blank test file at the root folder .. Solved

Here are the findings, this problem really bugged me for a while.
My folder structure was

```<code>mathapp/
    - server.py
    - configuration.py
    - __init__.py
    - static/
       - home.html
tests/
    - functional
       - test_errors.py
    - unit
       - test_add.py
</code>```

and pytest would complain with the ModuleNotFoundError.

I introduced a mock test file at the same level as mathsapp and tests directory. The file contained nothing. Now pytest does not complain.

Result without the file

```<code>$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error

=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
    from mathapp.service import sum
E   ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================
</code>```

Results with the file

```<code>$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items

tests\functional\test_func.py .                                          [ 50%]
tests\unit\test_unit.py .                                                [100%]

============================== 2 passed in 0.11s ==============================
</code>```

Title: ModuleNotFoundError with pytest

Body:
I want my tests folder separate to my application code. My project structure is like so

myproject/
  myproject/
    myproject.py
    moduleone.py
  tests/
    myproject_test.py

myproject.py

from moduleone import ModuleOne

class MyProject(object)
....

myproject_test.py

from myproject.myproject import MyProject
import pytest

...

I use myproject.myproject since I use the command

python -m pytest

from the project root directory ./myproject/

However, then the imports within those modules fail with

E   ModuleNotFoundError: No module named 'moduleone'

I am running Python 3.7 and have read that since 3.3, empty __init__ files are no longer needed which means my project becomes an implicit namespace package

However, I have tried adding an __init__.py file in myproject/myproject/ and also tried adding a conftest.py file in myproject/ but  neither works

I have read answers that say to mess with the paths and then upvoted comments in other questions saying not to.

What is the correct way and what am I missing?

EDIT;

Possibly related, I used a requirements.txt to install pytest using pip. Could this be related? And if so, what is the correct way to install pytest in this case?

EDIT 2:

One of the paths in sys.path is /usr/src/app/ which is a docker volume lined to /my/local/path/myproject/.

Should the volume be /my/local/path/myproject/myproject/ instead?

Body:
Kept everything same and just added a blank test file at the root folder .. Solved

Here are the findings, this problem really bugged me for a while.
My folder structure was

mathapp/
    - server.py
    - configuration.py
    - __init__.py
    - static/
       - home.html
tests/
    - functional
       - test_errors.py
    - unit
       - test_add.py

and pytest would complain with the ModuleNotFoundError.

I introduced a mock test file at the same level as mathsapp and tests directory. The file contained nothing. Now pytest does not complain.

Result without the file

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error

=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
    from mathapp.service import sum
E   ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================

Results with the file

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items

tests\functional\test_func.py .                                          [ 50%]
tests\unit\test_unit.py .                                                [100%]

============================== 2 passed in 0.11s ==============================


问:
How do I find highest value using pointer?
I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.

```<code>#include <iostream>
#include <string>
using namespace std;
int main() {
  int a[10], i, index;
  int *p, *max;
  for (i = 0; i < 10; i++) cin >> a[i];
  max = 0;
  p = &a[10];
  for (index = 0; index < 10; index++) {
    if ((p[index]) > *max) {
      *max = (p[index]);
    }
  }
  cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
  return 0;
}
</code>```

答:
I'd remove p and use a range-based for-loop where possible and iterators when it'll improve performance.

Comments in the code:

```<code>#include <iostream>
#include <iterator>

// using namespace std; // don't do this

int main() {
    using std::cin, std::cout;

    int a[10];

    // use a range-based for-loop:
    for(int& aref : a) { // aref is a reference to the current element in a

        // check that extraction from std::cin actually works
        if(!(cin >> aref)) {
            std::cerr << "error reading int\n";
            return 1;
        }
    }

    // initialize max to point at the first element
    auto max = std::begin(a);

    // Start at the second element since max is already set to point at the first element.
    // Don't use magic numbers. Define a constant or use std::size(<array>)
    // ...or use iterators like in this example:
    for(auto curr = std::next(std::begin(a)); curr != std::end(a); ++curr) {
        if(*curr > *max) {
            max = curr;
        }
    }

    // you can use std::distance ot calculate the index for max:
    cout << "Highest value=" << *max << '\n'
         << "is at index=" << std::distance(std::begin(a), max) << '\n';
}
</code>```

Body:
I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.

#include <iostream>
#include <string>
using namespace std;
int main() {
  int a[10], i, index;
  int *p, *max;
  for (i = 0; i < 10; i++) cin >> a[i];
  max = 0;
  p = &a[10];
  for (index = 0; index < 10; index++) {
    if ((p[index]) > *max) {
      *max = (p[index]);
    }
  }
  cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
  return 0;
}

Body:
I'd remove p and use a range-based for-loop where possible and iterators when it'll improve performance.

Comments in the code:

#include <iostream>
#include <iterator>

// using namespace std; // don't do this

int main() {
    using std::cin, std::cout;

    int a[10];

    // use a range-based for-loop:
    for(int& aref : a) { // aref is a reference to the current element in a

        // check that extraction from std::cin actually works
        if(!(cin >> aref)) {
            std::cerr << "error reading int\n";
            return 1;
        }
    }

    // initialize max to point at the first element
    auto max = std::begin(a);

    // Start at the second element since max is already set to point at the first element.
    // Don't use magic numbers. Define a constant or use std::size(<array>)
    // ...or use iterators like in this example:
    for(auto curr = std::next(std::begin(a)); curr != std::end(a); ++curr) {
        if(*curr > *max) {
            max = curr;
        }
    }

    // you can use std::distance ot calculate the index for max:
    cout << "Highest value=" << *max << '\n'
         << "is at index=" << std::distance(std::begin(a), max) << '\n';
}


问:
How do you write an SSL redirect in NodeJS running on AWS EC2 without using port 80 (http) or port 43 (https)?
I have two node servers on a single host. One HTTP server with the responsibility of redirecting to HTTPS, and one HTTPS server responsible for serving my application:

```<code>const express = require('express');
const https = require('https');
const http = require('http')
const fs = require('fs');
const app = express();

const httpsOptions = {
  key: fs.readFileSync('./local-ssl/key.pem'),
  cert: fs.readFileSync('./local-ssl/cert.pem'),
  passphrase: '*****'
}

//other stuff

http.createServer(function (req, res) {
  res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
  res.end();
}).listen(80);

https.createServer(httpsOptions, app).listen(443)
</code>```

This works great locally.

The issue is, when I deploy this code and run these servers on AWS EC2 you cannot start servers on ports 80 and 443. I am trying to figure out how I can get around this issue. If I run them on different ports, the servers will not respond, and worse, redirect incorrectly.

Example:
If I serve HTTP on 8081 and HTTPS on 8443, when a redirect occurs, the code redirects to

https://my-fun-url.com:8081

which of course does not work because I am not responding to HTTPS on port 8081.

Now, I've explored the option of port forwarding, but how would this work? If I forward ports 80 and 443 to internal ports (let's say) 3000 and 4000 the same redirection problem will occur.

I have scoured the internet for so long and to me this is a simple requirement for any web-app. I would very much appreciate some detailed guidance on my strategy.

答:
If you want to keep ports 8081 and 8443, then you simply replace 8081 with 8443 in the host header:

httpsHost = req.headers.host.replace('8081', '8443');
res.writeHead(301, {
  "Location": "https://" + httpsHost + req.url
});
```

Now, I've explored the option of port forwarding, but how would this work? If I forward ports 80 and 443 to internal ports (let's say) 3000 and 4000 the same redirection problem will occur.

Not exactly. When someone navigates to http://my-fun-url.com (80) the request is forwarded to 3000. Your http server will respond with a redirect to https://my-fun-url.com (443) which will be forwarded to 4000, and the https server will take it from there.

The difference between the two methods is that with ports 80 and 443 being the default, they are implied and therefore can be left out from the host part of the URL. Which makes the redirect easier as there's no port in the host to replace in the first place, just the protocol part (HTTP/HTTPS).

Body:
I have two node servers on a single host. One HTTP server with the responsibility of redirecting to HTTPS, and one HTTPS server responsible for serving my application:

const express = require('express');
const https = require('https');
const http = require('http')
const fs = require('fs');
const app = express();

const httpsOptions = {
  key: fs.readFileSync('./local-ssl/key.pem'),
  cert: fs.readFileSync('./local-ssl/cert.pem'),
  passphrase: '*****'
}

//other stuff

http.createServer(function (req, res) {
  res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
  res.end();
}).listen(80);

https.createServer(httpsOptions, app).listen(443)

This works great locally.

The issue is, when I deploy this code and run these servers on AWS EC2 you cannot start servers on ports 80 and 443. I am trying to figure out how I can get around this issue. If I run them on different ports, the servers will not respond, and worse, redirect incorrectly.

Example:
If I serve HTTP on 8081 and HTTPS on 8443, when a redirect occurs, the code redirects to

https://my-fun-url.com:8081

which of course does not work because I am not responding to HTTPS on port 8081.

Now, I've explored the option of port forwarding, but how would this work? If I forward ports 80 and 443 to internal ports (let's say) 3000 and 4000 the same redirection problem will occur.

I have scoured the internet for so long and to me this is a simple requirement for any web-app. I would very much appreciate some detailed guidance on my strategy.

Body:
If you want to keep ports 8081 and 8443, then you simply replace 8081 with 8443 in the host header:

httpsHost = req.headers.host.replace('8081', '8443');
res.writeHead(301, {
  "Location": "https://" + httpsHost + req.url
});

Now, I've explored the option of port forwarding, but how would this work? If I forward ports 80 and 443 to internal ports (let's say) 3000 and 4000 the same redirection problem will occur.

Not exactly. When someone navigates to http://my-fun-url.com (80) the request is forwarded to 3000. Your http server will respond with a redirect to https://my-fun-url.com (443) which will be forwarded to 4000, and the https server will take it from there.

The difference between the two methods is that with ports 80 and 443 being the default, they are implied and therefore can be left out from the host part of the URL. Which makes the redirect easier as there's no port in the host to replace in the first place, just the protocol part (HTTP/HTTPS).


问:
cmath header confusion
What is the namespace for math functions? Global or std?

Consider cos function. It has 3 overloads. But there is also legacy cos from math.h. C doesn't know anything about function overloading. Therefore cos(x) can't be resolved to cos(float). The solution is to call the single precision version explicitly cosf(x). Did I miss anything?

答:
You get the same functions by including <math.c> and <cmath> in C++, the only differences is the namespace. I.E. including <math.h> also gives you the overload.

In theory, in C++03, using <math.h> gives you the symbols defined in the global namespace and also in the std namespace while using <cmath> gives you the symbols defined in the std namespace and not in the global namespace.

The practice is different and C++ 0X aligned the theory with the practice. <math.h> gives you the symbols defined in the global namespace and perhaps also in the std namespace while using <cmath> gives you the symbols defined in the std namespace and perhaps also in the global namespace.

Title: cmath header confusion

ContentLicense: CC BY-SA 3.0


问:
Startup Script in Metadata Not Running (Python, Google Compute Engine, Cloud Storage Trigger)
I have an app running on Google App Engine, and an AI running on Google Compute Engine. I'm triggering the VM instance to start on a change in a Google Cloud Storage bucket, and have a start-up script that I attempt to store in the metadata of the GCE instance. My cloud functions looks like this:

```<code>import os
from googleapiclient.discovery import build

def start(event, context):
    file = event
    print(file["id"])

    string = file["id"]

    new_string = string.split('/')
    user_id = new_string[1]
    payment_id = new_string[2]
    name = new_string[3]

    print(name)

    if name == "uploadcomplete.txt":
        startup_script = """ #! /bin/bash
                sudo su username
                cd directory/directory
                python analysis.py -- gs://location/{userId}/{paymentId}
                """.format(userId=user_id, paymentId=payment_id)
        # initialize compute api
        service = build('compute', 'v1', cache_discovery=False)
        print('VM Instance starting')
        project = 'zephyrd'
        zone = 'us-east1-c'
        instance = 'zephyr-a'

        # get metadata fingerprint in order to set new metadata
        metadata = service.instances().get(project=project, zone=zone, instance=instance)
        metares = metadata.execute()
        fingerprint = metares["metadata"]["fingerprint"]

        # set new metadata
        bodydata = {"fingerprint": fingerprint,
                    "items": [{"key": "startup-script", "value": startup_script}]}
        meta = service.instances().setMetadata(project=project, zone=zone, instance=instance,
                                               body=bodydata).execute()
        print(meta)

        # confirm new metdata
        instanceget = service.instances().get(project=project, zone=zone, instance=instance).execute()
        print("'New Metadata:", instanceget['metadata'])
        print(instanceget)

        # start VM
        request = service.instances().start(project=project, zone=zone, instance=instance)
        response = request.execute()
        print('VM Instance started')
        print(response)
</code>```

The VM starts, but the startup script does not run. The script has been simplified for the purposes of the question, but this is just a basic command I'm trying to run. I would add the script directly to the metadata in the console, but I use values from the cloud function trigger to run commands in the VM. What am I missing?

I've attempted to set the metadata in two ways:

```<code>"items": [{"key": "startup-script", "value": startup_script}]
</code>```

as well as:

```<code>"items": [{"startup-script" : startup_script}]
</code>```

Neither work. The commands run beautifully if I manually type them in the shell.

答:
Look into your logs to determine why its not executing.

https://cloud.google.com/compute/docs/startupscript#viewing_startup_script_logs

Probably you the issue is that you are trying to execute a python script instead of a bash script.

Your startup script should be something like:

```<code>#! /bin/bash

# ...
python3 paht/to/python_script.py
</code>```

Body:
I have an app running on Google App Engine, and an AI running on Google Compute Engine. I'm triggering the VM instance to start on a change in a Google Cloud Storage bucket, and have a start-up script that I attempt to store in the metadata of the GCE instance. My cloud functions looks like this:

import os
from googleapiclient.discovery import build

def start(event, context):
    file = event
    print(file["id"])

    string = file["id"]

    new_string = string.split('/')
    user_id = new_string[1]
    payment_id = new_string[2]
    name = new_string[3]

    print(name)

    if name == "uploadcomplete.txt":
        startup_script = """ #! /bin/bash
                sudo su username
                cd directory/directory
                python analysis.py -- gs://location/{userId}/{paymentId}
                """.format(userId=user_id, paymentId=payment_id)
        # initialize compute api
        service = build('compute', 'v1', cache_discovery=False)
        print('VM Instance starting')
        project = 'zephyrd'
        zone = 'us-east1-c'
        instance = 'zephyr-a'

        # get metadata fingerprint in order to set new metadata
        metadata = service.instances().get(project=project, zone=zone, instance=instance)
        metares = metadata.execute()
        fingerprint = metares["metadata"]["fingerprint"]

        # set new metadata
        bodydata = {"fingerprint": fingerprint,
                    "items": [{"key": "startup-script", "value": startup_script}]}
        meta = service.instances().setMetadata(project=project, zone=zone, instance=instance,
                                               body=bodydata).execute()
        print(meta)

        # confirm new metdata
        instanceget = service.instances().get(project=project, zone=zone, instance=instance).execute()
        print("'New Metadata:", instanceget['metadata'])
        print(instanceget)

        # start VM
        request = service.instances().start(project=project, zone=zone, instance=instance)
        response = request.execute()
        print('VM Instance started')
        print(response)

The VM starts, but the startup script does not run. The script has been simplified for the purposes of the question, but this is just a basic command I'm trying to run. I would add the script directly to the metadata in the console, but I use values from the cloud function trigger to run commands in the VM. What am I missing?

I've attempted to set the metadata in two ways:

"items": [{"key": "startup-script", "value": startup_script}]

as well as:

"items": [{"startup-script" : startup_script}]

Neither work. The commands run beautifully if I manually type them in the shell.

Body:
Look into your logs to determine why its not executing.

https://cloud.google.com/compute/docs/startupscript#viewing_startup_script_logs

Probably you the issue is that you are trying to execute a python script instead of a bash script.

Your startup script should be something like:

#! /bin/bash

# ...
python3 paht/to/python_script.py


问:
c++ get unique values in set and map containers
How can I get unique values in container?
I see there is unique() for vector and list, but I can't find anything similar for set and map.

UPD: I use this to generate values in container.

```<code>#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <map>

using namespace std;
template <class T>
void rvec(T& t, int l) {
    for (int i = 0; i < l; i++)t.push_back(rand() % 10);
}
template <class T>
void rlist(T &t, int l){
  for(int i=0;i<l;i++)t.push_back(rand()%10);
}
template <class T>
void rmset(T &t, int l){
  for(int i=0;i<l;i++)t.insert(rand()%10);
}
template <class T>
void rmap(T &t, int l){
  for(int i=0;i<l;i++)t[i]=rand()%10;
}
template <class T>
void show(T& t) {
    for (auto element : t)cout << element << " ";
    cout << endl;
}
template <class T>
void showmap(T &t){
  for(auto element:t)cout<<element.second<<" ";
  cout<<endl;
}

int main() {
    vector<int> v;
    list<int> l;
    multiset<int> s;
    map<int,int> m;

    int num = 30;
    int rtd = rand() % 10;

    rvec(v, num);
    rlist(l, num);
    rmset(s, num);
    rmap(m, num);

    show(v);
    show(l);
    show(s);
    showmap(m);
    cout << endl;

    auto last = unique(v.begin(), v.end());
    v.resize(distance(v.begin(), last));
    l.unique();
    //something for list
    //something for map

    show(v);
    show(l);
    show(s);
    showmap(m);
    return 0;
}
</code>```

after launching I got

0 0 1 1 1 1 1 2 2 2 3 3 3 3 4 5 5 5 5 5 5 6 7 7 8 8 8 8 9 9 for set and

2 9 2 0 7 2 6 0 8 5 5 1 9 0 3 1 9 3 0 5 3 0 9 3 1 7 2 2 0 7 for map

答:
c++ get unique values in set

All values in set are unique, at least in respect to the comparison function.

If you need uniqueness in respect to another comparison function f2, then copy the elements from the input set into another set that uses f2. Alternatively, copy the elements into a vector (any sequential container would be OK, but arrays are simple and typically fast), then sort and use std::unique.

Solutions described in previous paragraph work for map and multiset as well: Copy the elements into a set and you're all done. Or copy them into a vector, and then apply the algorithms.

Body:
How can I get unique values in container?
I see there is unique() for vector and list, but I can't find anything similar for set and map.

UPD: I use this to generate values in container.

#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <map>

using namespace std;
template <class T>
void rvec(T& t, int l) {
    for (int i = 0; i < l; i++)t.push_back(rand() % 10);
}
template <class T>
void rlist(T &t, int l){
  for(int i=0;i<l;i++)t.push_back(rand()%10);
}
template <class T>
void rmset(T &t, int l){
  for(int i=0;i<l;i++)t.insert(rand()%10);
}
template <class T>
void rmap(T &t, int l){
  for(int i=0;i<l;i++)t[i]=rand()%10;
}
template <class T>
void show(T& t) {
    for (auto element : t)cout << element << " ";
    cout << endl;
}
template <class T>
void showmap(T &t){
  for(auto element:t)cout<<element.second<<" ";
  cout<<endl;
}

int main() {
    vector<int> v;
    list<int> l;
    multiset<int> s;
    map<int,int> m;

    int num = 30;
    int rtd = rand() % 10;

    rvec(v, num);
    rlist(l, num);
    rmset(s, num);
    rmap(m, num);

    show(v);
    show(l);
    show(s);
    showmap(m);
    cout << endl;

    auto last = unique(v.begin(), v.end());
    v.resize(distance(v.begin(), last));
    l.unique();
    //something for list
    //something for map

    show(v);
    show(l);
    show(s);
    showmap(m);
    return 0;
}

after launching I got

0 0 1 1 1 1 1 2 2 2 3 3 3 3 4 5 5 5 5 5 5 6 7 7 8 8 8 8 9 9 for set and

2 9 2 0 7 2 6 0 8 5 5 1 9 0 3 1 9 3 0 5 3 0 9 3 1 7 2 2 0 7 for map


问:
Gracefully Close application With Yes Response
We have application and when we close it, it ask to change the status to offline. When we hit Yes, application get closed and its status changed. I tried to close the application with powershell using below code.

Get-Process 'Application' |? { $_.CloseMainWindow() | Out-Null }

But it prompt for status change diaolog box to hit yes to close. I want to pass this yes to close directly without any prompt for response.

Please help.

答:
Maybe using "Kill" method (see MS docs) or combining both, would help?

Or you could try "[System.Windows.Forms.SendKeys]::SendWait("%F4")" (see MS docs


问:
Does a handle passed to unmanaged code need to be pinned?
I have an unmanaged function that I need to call which takes in as an argument a wait handle.  The unmanaged code signals this wait handle when appropriate to notify my code of some condition.  My question is, do I need to pin this wait handle in some way to prevent GC from moving the wait handle?

The (pseudo) code looks like:

```<code>using (var resetEvent = new AutoResetEvent(false))
{
    var iBuffer = Convert.ToUInt32(resetEvent.SafeWaitHandle.DangerousGetHandle().ToInt32());
    // Pass iBuffer to unmanaged API function.  The unmanaged API passes in the wait handle as a ref uint.

    var handles = new[] {resetEvent, _cancellationTokenSource.Token.WaitHandle};
    while(WaitHandle.WaitAny(handles) == 0)
    {
       // do stuff in response to resetEvent being signaled.
    }
}
</code>```

I'm not passing the AutoResetEvent object (or even the 'SafeWaitHandle' from it) directly, but actually the DangerousGetHandle() returned.  I'm unclear if the 'Dangerous' handle returned really represents an unmanaged resource already and hence would not require any pinning?

答:
As far as I can tell, No.

Pinning is needed to prevent managed memory from being moved. A handle on the other hand represents some operating system resource, and therefore does not need to be pinned.

You may still need to be carefull the handle is not saved by the unmanaged code, and ensure the handle is not release/invalidate/close/dispose while it is used by the unmanaged code.

Body:
I have an unmanaged function that I need to call which takes in as an argument a wait handle.  The unmanaged code signals this wait handle when appropriate to notify my code of some condition.  My question is, do I need to pin this wait handle in some way to prevent GC from moving the wait handle?

The (pseudo) code looks like:

using (var resetEvent = new AutoResetEvent(false))
{
    var iBuffer = Convert.ToUInt32(resetEvent.SafeWaitHandle.DangerousGetHandle().ToInt32());
    // Pass iBuffer to unmanaged API function.  The unmanaged API passes in the wait handle as a ref uint.

    var handles = new[] {resetEvent, _cancellationTokenSource.Token.WaitHandle};
    while(WaitHandle.WaitAny(handles) == 0)
    {
       // do stuff in response to resetEvent being signaled.
    }
}

I'm not passing the AutoResetEvent object (or even the 'SafeWaitHandle' from it) directly, but actually the DangerousGetHandle() returned.  I'm unclear if the 'Dangerous' handle returned really represents an unmanaged resource already and hence would not require any pinning?


问:
CNN model predict the same value in most part of cases
I'm trying to train a CNN model for image classification.

There are nine classes and every class have 1000 images.

Here's my code

```<code>model = Sequential()

model.add(Conv2D(32, kernel_size=(5,5), activation='relu',kernel_initializer='random_uniform', input_shape=(128,646,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(16, kernel_size=(5,5), activation='relu', input_shape=(64,321,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())

model.add(Flatten())
model.add(Dense(16, activation = 'relu',kernel_initializer='normal'))
model.add(Dropout(0.5))
model.add(Dense(9, activation = 'softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
</code>```

I have tried this on MNIST dataset and it's works will

but on my dataset it always predict the same value.

(True Label above and predict label value bottom)

```<code>[[0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0.]]
[[0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]
 [0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]
 [0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]
 [0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]
 [0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]]
</code>```

Accuracy curves
Loss curves

I have tried to change the initializer, optimizer, loss function, more epoch, ... still nothing change.

But when I

1.set the both Conv2D kernel number to 1

2.set the 1st Conv2D activate function to tanh

the model start predict different value for the input but performance not will.

I'm mainly confuse about

1.Setting the kernel number to 1 seems uncommon,but in my experience it avoid predicting the same value.

2.The value of the input image are all greater than zero,but setting the activate function to tanh can also change the result to different predicted classes?

Besides, the image size is 128*646
Every image value is in the range of 0~80

```<code>array([[[33.74863434],
        [27.84932709],
        [22.6257019 ],
        ...,
        [21.47132492],
        [19.61938477],
        [14.22393227]],

       [[16.31633759],
        [29.69265747],
        [25.40621376],
        ...,
        [28.50727081],
        [11.46302605],
        [ 4.04836655]],

       [[ 9.1305275 ],
        [10.00378227],
        [28.46733665],
        ...,
        [23.54629517],
        [20.91897202],
        [ 1.38314819]],

       ...,

       [[63.33175659],
        [66.34197998],
        [68.40023804],
        ...,
        [73.8707428 ],
        [68.64536285],
        [67.72910309]],

       [[67.61167908],
        [67.59188843],
        [66.96526337],
        ...,
        [70.63095856],
        [74.70448303],
        [72.90202332]],

       [[71.49047852],
        [74.54782104],
        [69.39613342],
        ...,
        [80.        ],
        [80.        ],
        [80.        ]]])

</code>```

Update

My dataset is from Free Music Archive

Including track audio data (.mp3) and track metadata(genre,artist,...)

I chose the small version (8000 tracks) and converted into spectrogram by libROSA package.

Just like this link Using CNNs and RNNs for Music Genre Recognition

But I'd like to try CNN model only first.

The spectrogram converted by libROSA package have the size of 128*646.

The row data is like this

```<code>array([[-65.06227 , -47.759537, -44.17627 , ..., -39.40817 , -41.736862,
        -25.19515 ],
       [-65.40295 , -52.76098 , -49.17935 , ..., -16.40555 , -16.314035,
        -17.56438 ],
       [-69.481834, -56.676388, -50.506615, ..., -16.358843, -16.072405,
        -18.807785],
       ...,
       [-79.42308 , -59.743004, -36.382896, ..., -46.371193, -42.364635,
        -50.037727],
       [-80.      , -63.419754, -41.73323 , ..., -50.383797, -46.90663 ,
        -55.136078],
       [-80.      , -73.820724, -52.94601 , ..., -63.188026, -56.469948,
        -60.473305]], dtype=float32)
</code>```

I divided the value by 80 and calculated the absolute value for those spectrogram as CNN model input

答:
Mentioning the Solution here (Answer Section) even though it is present in the Comments Section, for the benefit of the Community. Adding more suggestions as well.

Increasing the Number of Kernels or Filters to more than 50, like 64 has resulted in improved Accuracy. This is because more number of Kernels/Filters improves the Representational Power of the Model, especially, when the Data is not very simple to learn.

In order to improve the Accuracy, the Model can be changed from

```<code>model = Sequential()

model.add(Conv2D(32, kernel_size=(5,5), activation='relu',kernel_initializer='random_uniform', input_shape=(128,646,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(16, kernel_size=(5,5), activation='relu', input_shape=(64,321,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())

model.add(Flatten())
model.add(Dense(16, activation = 'relu',kernel_initializer='normal'))
model.add(Dropout(0.5))
model.add(Dense(9, activation = 'softmax'))
</code>```

to

```<code>model = Sequential()

model.add(Conv2D(64, kernel_size=(5,5),
activation='relu',kernel_initializer='random_uniform',
input_shape=(128,646,1))) # Increased the Number of Kernels in this Conv2D
Layer
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(64, kernel_size=(5,5), activation='relu',
input_shape=(64,321,1))) # Increased the Number of Kernels in this Conv2D
Layer
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())

model.add(Flatten())
model.add(Dense(256, activation = 'relu',
kernel_initializer='normal')) #Increased the Number of Neurons in this Dense
Layer
model.add(Dropout(0.5))
model.add(Dense(9, activation = 'softmax'))
</code>```

Also, the Input Data is in the Range 0 to 80. Normalizing it to values between 0 and 1 will result in more better accuracy.

General Pre-Processing steps are shown below:

```<code>from tensorflow.keras.preprocessing import image

Test_Dir = 'Dogs_Vs_Cats_Small/test/cats'
Image_File = os.path.join(Test_Dir, 'cat.1545.jpg')

Image = image.load_img(Image_File, target_size = (128,646))

Image_Tensor = image.img_to_array(Image)

Image_Tensor = tf.expand_dims(Image_Tensor, axis = 0)

Image_Tensor = Image_Tensor/255.0
</code>```

Hope this helps. Happy Learning!

Body:
I'm trying to train a CNN model for image classification.

There are nine classes and every class have 1000 images.

Here's my code

model = Sequential()

model.add(Conv2D(32, kernel_size=(5,5), activation='relu',kernel_initializer='random_uniform', input_shape=(128,646,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(16, kernel_size=(5,5), activation='relu', input_shape=(64,321,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())

model.add(Flatten())
model.add(Dense(16, activation = 'relu',kernel_initializer='normal'))
model.add(Dropout(0.5))
model.add(Dense(9, activation = 'softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

I have tried this on MNIST dataset and it's works will

but on my dataset it always predict the same value.

(True Label above and predict label value bottom)

[[0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0.]]
[[0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]
 [0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]
 [0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]
 [0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]
 [0.11161657 0.11246169 0.11564494 0.11465651 0.11153363 0.10664304
  0.11097018 0.11052497 0.10594855]]

Accuracy curves
Loss curves

I have tried to change the initializer, optimizer, loss function, more epoch, ... still nothing change.

But when I

1.set the both Conv2D kernel number to 1

2.set the 1st Conv2D activate function to tanh

the model start predict different value for the input but performance not will.

I'm mainly confuse about

1.Setting the kernel number to 1 seems uncommon,but in my experience it avoid predicting the same value.

2.The value of the input image are all greater than zero,but setting the activate function to tanh can also change the result to different predicted classes?

Besides, the image size is 128*646
Every image value is in the range of 0~80

array([[[33.74863434],
        [27.84932709],
        [22.6257019 ],
        ...,
        [21.47132492],
        [19.61938477],
        [14.22393227]],

       [[16.31633759],
        [29.69265747],
        [25.40621376],
        ...,
        [28.50727081],
        [11.46302605],
        [ 4.04836655]],

       [[ 9.1305275 ],
        [10.00378227],
        [28.46733665],
        ...,
        [23.54629517],
        [20.91897202],
        [ 1.38314819]],

       ...,

       [[63.33175659],
        [66.34197998],
        [68.40023804],
        ...,
        [73.8707428 ],
        [68.64536285],
        [67.72910309]],

       [[67.61167908],
        [67.59188843],
        [66.96526337],
        ...,
        [70.63095856],
        [74.70448303],
        [72.90202332]],

       [[71.49047852],
        [74.54782104],
        [69.39613342],
        ...,
        [80.        ],
        [80.        ],
        [80.        ]]])

Update

My dataset is from Free Music Archive

Including track audio data (.mp3) and track metadata(genre,artist,...)

I chose the small version (8000 tracks) and converted into spectrogram by libROSA package.

Just like this link Using CNNs and RNNs for Music Genre Recognition

But I'd like to try CNN model only first.

The spectrogram converted by libROSA package have the size of 128*646.

The row data is like this

array([[-65.06227 , -47.759537, -44.17627 , ..., -39.40817 , -41.736862,
        -25.19515 ],
       [-65.40295 , -52.76098 , -49.17935 , ..., -16.40555 , -16.314035,
        -17.56438 ],
       [-69.481834, -56.676388, -50.506615, ..., -16.358843, -16.072405,
        -18.807785],
       ...,
       [-79.42308 , -59.743004, -36.382896, ..., -46.371193, -42.364635,
        -50.037727],
       [-80.      , -63.419754, -41.73323 , ..., -50.383797, -46.90663 ,
        -55.136078],
       [-80.      , -73.820724, -52.94601 , ..., -63.188026, -56.469948,
        -60.473305]], dtype=float32)

I divided the value by 80 and calculated the absolute value for those spectrogram as CNN model input

Body:
Mentioning the Solution here (Answer Section) even though it is present in the Comments Section, for the benefit of the Community. Adding more suggestions as well.

Increasing the Number of Kernels or Filters to more than 50, like 64 has resulted in improved Accuracy. This is because more number of Kernels/Filters improves the Representational Power of the Model, especially, when the Data is not very simple to learn.

In order to improve the Accuracy, the Model can be changed from

model = Sequential()

model.add(Conv2D(32, kernel_size=(5,5), activation='relu',kernel_initializer='random_uniform', input_shape=(128,646,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(16, kernel_size=(5,5), activation='relu', input_shape=(64,321,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())

model.add(Flatten())
model.add(Dense(16, activation = 'relu',kernel_initializer='normal'))
model.add(Dropout(0.5))
model.add(Dense(9, activation = 'softmax'))

to

model = Sequential()

model.add(Conv2D(64, kernel_size=(5,5),
activation='relu',kernel_initializer='random_uniform',
input_shape=(128,646,1))) # Increased the Number of Kernels in this Conv2D
Layer
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(64, kernel_size=(5,5), activation='relu',
input_shape=(64,321,1))) # Increased the Number of Kernels in this Conv2D
Layer
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())

model.add(Flatten())
model.add(Dense(256, activation = 'relu',
kernel_initializer='normal')) #Increased the Number of Neurons in this Dense
Layer
model.add(Dropout(0.5))
model.add(Dense(9, activation = 'softmax'))

Also, the Input Data is in the Range 0 to 80. Normalizing it to values between 0 and 1 will result in more better accuracy.

General Pre-Processing steps are shown below:

from tensorflow.keras.preprocessing import image

Test_Dir = 'Dogs_Vs_Cats_Small/test/cats'
Image_File = os.path.join(Test_Dir, 'cat.1545.jpg')

Image = image.load_img(Image_File, target_size = (128,646))

Image_Tensor = image.img_to_array(Image)

Image_Tensor = tf.expand_dims(Image_Tensor, axis = 0)

Image_Tensor = Image_Tensor/255.0

Hope this helps. Happy Learning!