问:
Is it possible to declare reference variables in for or while loop?
I wrote a short code that declares 6 reference variables from a class named 'ChosenCompanies' to practice classes and constructors in Java.

It is the following:

```<code>public static void main(String[] args) {

    String[] FinalCompaniesName = new String[6];

    ChosenCompanies com1 = new ChosenCompanies();
    ChosenCompanies com2 = new ChosenCompanies();
    ChosenCompanies com3 = new ChosenCompanies();
    ChosenCompanies com4 = new ChosenCompanies();
    ChosenCompanies com5 = new ChosenCompanies();
    ChosenCompanies com6 = new ChosenCompanies();

    Scanner scanner = new Scanner(System.in);
    int choice;
    int count = 1;
    while(count <= 2) {
        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
        break;
        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
            }
            break;
        }
        count++;
    }
        System.out.println("You have chosen: "
 + FinalCompaniesName[0] + ", " + FinalCompaniesName[1]);

}
</code>```

As you can see from the above code, these two parts are almost the same except for the names of reference variables(com1, com2, com3, com4...):

part 1:

        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
         break;
```

<p>part 2:</p>

```        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
                }
            break;
        }
```

I am wondering if I can minimize the amount of the code above by using a for or while loop, since the name of the reference variables are increased by 1, like integer 'i' in a common for statement.

In short, is it possible to declare reference variables by using loop?

答:
Your example is confusing so I don't know what exactly are you trying to accomplish, but here is an example of how to prompt the user to select a new name for each company from a list of existing company names:

```<code>    public class Company {

    /**
     * Array of available company names used to construct
     * initial companies. These names are also used as possible
     * choices when changing company names through {@link #changeCompanyNames()}
     */
    private static final String[] COMPANY_NAMES = new String[]
            { "Alphabet", "Microsoft", "IBM", "Amazon", "Oracle", "Apple" };

    /**
     * <p>
     * Array of Company objects initialized with a fixed number of
     * new companies equal to the number of String entries in {@link #COMPANY_NAMES}.
     * </p><p>
     * Each company entry will inheriting a name from the mentioned array
     * in the initialization process done in {@link #initializeCompanies()}
     * </p>
     */
    public static final Company[] COMPANIES = initializeCompanies();

    private String name;

    /**
     * Internal constructor with private access to
     * prevent class construction outside this class
     */
    private Company(String name) {
        this.name = name;
    }

    /**
     * Should only be used internally on class loading to
     * construct an array of companies from a list of company names.
     */
    private static Company[] initializeCompanies() {

        Company[] companies = new Company[COMPANY_NAMES.length];
        for (int i = 0; i < COMPANY_NAMES.length; i++) {
            companies[i] = new Company(COMPANY_NAMES[i]);
        }
        return companies;
    }

    /**
     * Change any or all company names by prompting the user to choose
     * a new name for each company from the list of available companies.
     */
    public static void changeCompanyNames() {

        java.util.Scanner scanner = new java.util.Scanner(System.in);
        /*
         * Create a new array of company names that is identical to the existing
         * array of company names. We will change names here on user input and
         * then update each new company name to values from this array.
         */
        final String[] finalCompanyNames = COMPANY_NAMES.clone();
        /*
         * Iterate through an array of companies with a for-loop
         * accessing and processing each company entry
         */
        for (int i1 = 0; i1 < COMPANIES.length; i1++)
        {
            /* Prompt the user to choose a new company name for the
             * company at index i1 from COMPANIES array.
             */
            System.out.printf("Choose a new company name for %s company:%n", COMPANIES[i1].name);
            /*
             * Again iterate through all companies and print their names to
             * console offering the user a list of possible names to choose from
             */
            for (int i2 = 0; i2 < COMPANIES.length; i2++) {
                System.out.printf("%d. %s%n", i2 + 1, COMPANIES[i2].name);
            }
            /*
             * Get user input and validate it, then either update the array of
             * final names with the new entry or print an error and move the index
             * to the previous position if the input was an invalid number
             */
            int input = scanner.nextInt();
            if (input > 0 && input <= COMPANIES.length) {
                finalCompanyNames[i1] = COMPANY_NAMES[input - 1];
                System.out.println("You have choosen company name " + finalCompanyNames[i1]);
            }
            else {
                System.out.printf("Error: input is not in range (1-%d)%n", COMPANIES.length);
                /*
                 * It's imperative that we move the index to the previous
                 * position so we can iterate over this company entry again
                 */
                i1 -= 1;
            }
        }
        // Print simple line separator
        System.out.println("");

        /* Print each choosen name that is different then the original
         * company name and update the appropriate company name field value
         */
        for (int i = 0; i < finalCompanyNames.length; i++)
        {
            if (!finalCompanyNames[i].equals(COMPANY_NAMES[i])) {
                System.out.printf("Company %s has changed name to %s%n", COMPANY_NAMES[i], finalCompanyNames[i]);
                COMPANIES[i].name = finalCompanyNames[i];
            }
        }
    }
}
</code>```

Example console output after the user is done choosing:

```<code>Company Alphabet has changed name to IBM
Company Microsoft has changed name to Amazon
Company IBM has changed name to Alphabet
Company Amazon has changed name to Oracle
Company Oracle has changed name to Microsoft
Company Apple has changed name to Amazon
</code>```

Here we are able to set any number of companies and let the user choose any of the offered names for them. The code might look a tad bit daunting for a beginner but this is actually the simplest way of doing this without involving any of the more complex Java concepts into play.

Feel free to ask any questions regarding this implementation. I will be quite happy to help out.

EDIT: Updated the code to include detailed comments and a more comprehensive structure that is easier to understand and fixed an indexing issue.

Body:
I wrote a short code that declares 6 reference variables from a class named 'ChosenCompanies' to practice classes and constructors in Java.

It is the following:

public static void main(String[] args) {

    String[] FinalCompaniesName = new String[6];

    ChosenCompanies com1 = new ChosenCompanies();
    ChosenCompanies com2 = new ChosenCompanies();
    ChosenCompanies com3 = new ChosenCompanies();
    ChosenCompanies com4 = new ChosenCompanies();
    ChosenCompanies com5 = new ChosenCompanies();
    ChosenCompanies com6 = new ChosenCompanies();

    Scanner scanner = new Scanner(System.in);
    int choice;
    int count = 1;
    while(count <= 2) {
        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
        break;
        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
            }
            break;
        }
        count++;
    }
        System.out.println("You have chosen: "
 + FinalCompaniesName[0] + ", " + FinalCompaniesName[1]);

}

As you can see from the above code, these two parts are almost the same except for the names of reference variables(com1, com2, com3, com4...):

part 1:

        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
         break;

part 2:

        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
                }
            break;
        }

I am wondering if I can minimize the amount of the code above by using a for or while loop, since the name of the reference variables are increased by 1, like integer 'i' in a common for statement.

In short, is it possible to declare reference variables by using loop?

Body:
Your example is confusing so I don't know what exactly are you trying to accomplish, but here is an example of how to prompt the user to select a new name for each company from a list of existing company names:

    public class Company {

    /**
     * Array of available company names used to construct
     * initial companies. These names are also used as possible
     * choices when changing company names through {@link #changeCompanyNames()}
     */
    private static final String[] COMPANY_NAMES = new String[]
            { "Alphabet", "Microsoft", "IBM", "Amazon", "Oracle", "Apple" };

    /**
     * <p>
     * Array of Company objects initialized with a fixed number of
     * new companies equal to the number of String entries in {@link #COMPANY_NAMES}.
     * </p><p>
     * Each company entry will inheriting a name from the mentioned array
     * in the initialization process done in {@link #initializeCompanies()}
     * </p>
     */
    public static final Company[] COMPANIES = initializeCompanies();

    private String name;

    /**
     * Internal constructor with private access to
     * prevent class construction outside this class
     */
    private Company(String name) {
        this.name = name;
    }

    /**
     * Should only be used internally on class loading to
     * construct an array of companies from a list of company names.
     */
    private static Company[] initializeCompanies() {

        Company[] companies = new Company[COMPANY_NAMES.length];
        for (int i = 0; i < COMPANY_NAMES.length; i++) {
            companies[i] = new Company(COMPANY_NAMES[i]);
        }
        return companies;
    }

    /**
     * Change any or all company names by prompting the user to choose
     * a new name for each company from the list of available companies.
     */
    public static void changeCompanyNames() {

        java.util.Scanner scanner = new java.util.Scanner(System.in);
        /*
         * Create a new array of company names that is identical to the existing
         * array of company names. We will change names here on user input and
         * then update each new company name to values from this array.
         */
        final String[] finalCompanyNames = COMPANY_NAMES.clone();
        /*
         * Iterate through an array of companies with a for-loop
         * accessing and processing each company entry
         */
        for (int i1 = 0; i1 < COMPANIES.length; i1++)
        {
            /* Prompt the user to choose a new company name for the
             * company at index i1 from COMPANIES array.
             */
            System.out.printf("Choose a new company name for %s company:%n", COMPANIES[i1].name);
            /*
             * Again iterate through all companies and print their names to
             * console offering the user a list of possible names to choose from
             */
            for (int i2 = 0; i2 < COMPANIES.length; i2++) {
                System.out.printf("%d. %s%n", i2 + 1, COMPANIES[i2].name);
            }
            /*
             * Get user input and validate it, then either update the array of
             * final names with the new entry or print an error and move the index
             * to the previous position if the input was an invalid number
             */
            int input = scanner.nextInt();
            if (input > 0 && input <= COMPANIES.length) {
                finalCompanyNames[i1] = COMPANY_NAMES[input - 1];
                System.out.println("You have choosen company name " + finalCompanyNames[i1]);
            }
            else {
                System.out.printf("Error: input is not in range (1-%d)%n", COMPANIES.length);
                /*
                 * It's imperative that we move the index to the previous
                 * position so we can iterate over this company entry again
                 */
                i1 -= 1;
            }
        }
        // Print simple line separator
        System.out.println("");

        /* Print each choosen name that is different then the original
         * company name and update the appropriate company name field value
         */
        for (int i = 0; i < finalCompanyNames.length; i++)
        {
            if (!finalCompanyNames[i].equals(COMPANY_NAMES[i])) {
                System.out.printf("Company %s has changed name to %s%n", COMPANY_NAMES[i], finalCompanyNames[i]);
                COMPANIES[i].name = finalCompanyNames[i];
            }
        }
    }
}

Example console output after the user is done choosing:

Company Alphabet has changed name to IBM
Company Microsoft has changed name to Amazon
Company IBM has changed name to Alphabet
Company Amazon has changed name to Oracle
Company Oracle has changed name to Microsoft
Company Apple has changed name to Amazon

Here we are able to set any number of companies and let the user choose any of the offered names for them. The code might look a tad bit daunting for a beginner but this is actually the simplest way of doing this without involving any of the more complex Java concepts into play.

Feel free to ask any questions regarding this implementation. I will be quite happy to help out.

EDIT: Updated the code to include detailed comments and a more comprehensive structure that is easier to understand and fixed an indexing issue.


来源: stackexchange

问:
Issue Placing User Generated Data into path for JSON Data in Node.JS
I'm trying to get a changeable file link to work. It should be able to take in two variables and place them into a link to fetch some sentence out of a JSON file.

I've tried converting them to a string, which didn't work. When I hard coded the path, it worked, but I want it to be changeable on the fly.

```<code>//json parsing code
const url = 'storyline.json';
const fs = require('fs');
let rawdata = fs.readFileSync(url);
let storylineJSON = JSON.parse(rawdata);
//Json code (saved as storyline.json in different file in the same folder).
{
    "tigers":{
        "option1":"The tiger is the largest species among the Felidae and classified in the genus Panthera"
        "option2":"It is most recognizable for its dark vertical stripes on reddish-orange fur with a lighter underside"
    }
}

let optionValue = 'option1';
let startingWord = 'tigers';
let placement = String(startingWord.optionValue);

//used to read out to ALEXA

const speechText = storylineJSON.placement;
        return handlerInput.responseBuilder
            .speak(speechText)
            .reprompt(speechText)
            .getResponse();
</code>```

The expected result is Alexa to read off the message placed in the json file. If I hard code the path into the path rather than getting user generated data, it works perfectly, but I need it to be able to switch between at the call of the user.

When I try this, it works, but states "undefined". If I place extra text around it, for example, "you just chose, " and then add the variable, it will return "you just chose undefined". I believe this to be a formatting problem that I don't know about Node.JS.

答:
(Posted on behalf of the question author).

The issue was with how I joined all the parts of the path. For variables, I have to wrap them in [], rather than just a simple ..

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get a changeable file link to work. It should be able to take in two variables and place them into a link to fetch some sentence out of a JSON file.

I've tried converting them to a string, which didn't work. When I hard coded the path, it worked, but I want it to be changeable on the fly.

//json parsing code
const url = 'storyline.json';
const fs = require('fs');
let rawdata = fs.readFileSync(url);
let storylineJSON = JSON.parse(rawdata);
//Json code (saved as storyline.json in different file in the same folder).
{
    "tigers":{
        "option1":"The tiger is the largest species among the Felidae and classified in the genus Panthera"
        "option2":"It is most recognizable for its dark vertical stripes on reddish-orange fur with a lighter underside"
    }
}

let optionValue = 'option1';
let startingWord = 'tigers';
let placement = String(startingWord.optionValue);

//used to read out to ALEXA

const speechText = storylineJSON.placement;
        return handlerInput.responseBuilder
            .speak(speechText)
            .reprompt(speechText)
            .getResponse();

The expected result is Alexa to read off the message placed in the json file. If I hard code the path into the path rather than getting user generated data, it works perfectly, but I need it to be able to switch between at the call of the user.

When I try this, it works, but states "undefined". If I place extra text around it, for example, "you just chose, " and then add the variable, it will return "you just chose undefined". I believe this to be a formatting problem that I don't know about Node.JS.


问:
ng build error in cannot read property 'kind' of undefined
I have a project that builds on other machines, but it won't build on a new machine that I am setting up.  I have nodejs installed, I have the angular cli installed, typescript, I have run npm update, I keep getting this error, but there is not stacktrace to tell me where it is and I can't find this anywhere in the project, which tells me it must be something else.

Is this something specific or is there something else that I can try?

答: I usually get this error when changing the branches and there have been many changes. Try to restart the client server with ng serve or node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng serve (in my case). This worked for me.

ContentLicense: CC BY-SA 3.0


问:
TypeError: 'int' object is not callable -1
I a new to object oriented programming. I was trying to create a class that can find distance between two points. I passed points as tuples as coordinates.  I wrote this code but its showing error.

```<code>class Line:
    def __init__(self,coor1,coor2):
        self.coor1= coor1
        self.coor2= coor2
    def distance(self):
        print(((self.coor1[0]-self.coor2[0])**2(self.coor1[1]-self.coor2[1])**2)**0.5)
    def slope (self):
        print((self.coor2[1]-self.coor1[1])/(self.coor2[0]-self.coor1[0]))
coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)
li.distance()
</code>```

I know this could be resolved using tuple unpacking but I want to know why my code is not working?

答:
In the function distance you wrote 2(self.coor1[1]-self.coor2[1]) which asks python to execute the __call__ method of an object(2) of class int. You just have to add another addition/subtraction sign after 2.

In the example I'm assuming you want to add.

```<code>class Line:
    def __init__(self,coor1,coor2):
        self.coor1= coor1
        self.coor2= coor2
    def distance(self):
        print(((self.coor1[0]-self.coor2[0])**2+(self.coor1[1]-self.coor2[1])**2)**0.5)
    def slope (self):
        print((self.coor2[1]-self.coor1[1])/(self.coor2[0]-self.coor1[0]))
coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)
li.distance()
</code>```

Body:
I a new to object oriented programming. I was trying to create a class that can find distance between two points. I passed points as tuples as coordinates.  I wrote this code but its showing error.

class Line:
    def __init__(self,coor1,coor2):
        self.coor1= coor1
        self.coor2= coor2
    def distance(self):
        print(((self.coor1[0]-self.coor2[0])**2(self.coor1[1]-self.coor2[1])**2)**0.5)
    def slope (self):
        print((self.coor2[1]-self.coor1[1])/(self.coor2[0]-self.coor1[0]))
coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)
li.distance()

I know this could be resolved using tuple unpacking but I want to know why my code is not working?

Body:
In the function distance you wrote 2(self.coor1[1]-self.coor2[1]) which asks python to execute the __call__ method of an object(2) of class int. You just have to add another addition/subtraction sign after 2.

In the example I'm assuming you want to add.

class Line:
    def __init__(self,coor1,coor2):
        self.coor1= coor1
        self.coor2= coor2
    def distance(self):
        print(((self.coor1[0]-self.coor2[0])**2+(self.coor1[1]-self.coor2[1])**2)**0.5)
    def slope (self):
        print((self.coor2[1]-self.coor1[1])/(self.coor2[0]-self.coor1[0]))
coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)
li.distance()


问:
https redirect to 127.0.0.1 when using openshift origin web console
I just installed a new centos server with docker

```<code>Client:
 Version:         1.13.1
 API version:     1.26
 Package version: <unknown>
 Go version:      go1.8.3
 Git commit:      774336d/1.13.1
 Built:           Wed Mar  7 17:06:16 2018
 OS/Arch:         linux/amd64

Server:  Version:         1.13.1  API version:     1.26 (minimum
> version 1.12)  Package version: <unknown>  Go version:      go1.8.3
> Git commit:      774336d/1.13.1  Built:           Wed Mar  7 17:06:16
> 2018  OS/Arch:         linux/amd64  Experimental:    false
</code>```

And i can use the command oc cluster up to launch a openshift server

```<code>oc cluster up --host-data-dir /data --public-hostname master.ouatrahim.com --routing-suffix master.ouatrahim.com
</code>```

which gives the output

```<code>Using nsenter mounter for OpenShift volumes
Using 127.0.0.1 as the server IP
Starting OpenShift using openshift/origin:v3.9.0 ...
OpenShift server started.

The server is accessible via web console at:
    https://master.ouatrahim.com:8443

You are logged in as:
    User:     developer
    Password: <any value>

To login as administrator:
    oc login -u system:admin
</code>```

And oc version gives the output

```<code>oc v3.9.0+ba7faec-1
kubernetes v1.9.1+a0ce1bc657
features: Basic-Auth GSSAPI Kerberos SPNEGO

Server https://127.0.0.1:8443
openshift v3.9.0+0e3d24c-14
kubernetes v1.9.1+a0ce1bc657
</code>```

But when i tried to access to the web console via https://master.ouatrahim.com:8443/ i keep getting a http redirect to 127.0.0.1

```<code>https://127.0.0.1:8443/oauth/authorize?client_id=openshift-web-console&response_type=code&state=eyJ0aGVuIjoiLyIsIm5vbmNlIjoiMTUyNTk2NjcwODI1MS0xODg4MTcxMDEyMjU3OTQ1MjM0NjIwNzM5NTQ5ODE0ODk5OTYxMTIxMTI2NDI3ODg3Mjc5MjAwMTgwODI4NTg0MTkyODAxOTA2NTY5NjU2In0&redirect_uri=https%3A%2F%2F127.0.0.1%3A8443%2Fconsole%2Foauth
</code>```

I hope someone can help me solve this

答:
export no_proxy=your vm ip. It should fix the issue.

It seems they use above variable to access the openshift through proxy. So, even if you configure with --public-hostname it is not working.

Body:
I just installed a new centos server with docker

Client:
 Version:         1.13.1
 API version:     1.26
 Package version: <unknown>
 Go version:      go1.8.3
 Git commit:      774336d/1.13.1
 Built:           Wed Mar  7 17:06:16 2018
 OS/Arch:         linux/amd64

Server:  Version:         1.13.1  API version:     1.26 (minimum
> version 1.12)  Package version: <unknown>  Go version:      go1.8.3
> Git commit:      774336d/1.13.1  Built:           Wed Mar  7 17:06:16
> 2018  OS/Arch:         linux/amd64  Experimental:    false

And i can use the command oc cluster up to launch a openshift server

oc cluster up --host-data-dir /data --public-hostname master.ouatrahim.com --routing-suffix master.ouatrahim.com

which gives the output

Using nsenter mounter for OpenShift volumes
Using 127.0.0.1 as the server IP
Starting OpenShift using openshift/origin:v3.9.0 ...
OpenShift server started.

The server is accessible via web console at:
    https://master.ouatrahim.com:8443

You are logged in as:
    User:     developer
    Password: <any value>

To login as administrator:
    oc login -u system:admin

And oc version gives the output

oc v3.9.0+ba7faec-1
kubernetes v1.9.1+a0ce1bc657
features: Basic-Auth GSSAPI Kerberos SPNEGO

Server https://127.0.0.1:8443
openshift v3.9.0+0e3d24c-14
kubernetes v1.9.1+a0ce1bc657

But when i tried to access to the web console via https://master.ouatrahim.com:8443/ i keep getting a http redirect to 127.0.0.1

https://127.0.0.1:8443/oauth/authorize?client_id=openshift-web-console&response_type=code&state=eyJ0aGVuIjoiLyIsIm5vbmNlIjoiMTUyNTk2NjcwODI1MS0xODg4MTcxMDEyMjU3OTQ1MjM0NjIwNzM5NTQ5ODE0ODk5OTYxMTIxMTI2NDI3ODg3Mjc5MjAwMTgwODI4NTg0MTkyODAxOTA2NTY5NjU2In0&redirect_uri=https%3A%2F%2F127.0.0.1%3A8443%2Fconsole%2Foauth

I hope someone can help me solve this


问:
Running background processes in iPhone
Can we run following tasks in the back ground in a iPhone application:</p>

```<code>√ Camera --> Take photo (timer = infinity) (keep on taking photos)
√ Video
√ Backlight --> On for certain duration (Customizable)
√ Flickering --> 5secs (Customizable)
√ Vibration (Background)
√ Voice Call --> Long call or multiple calls (Call duration/Time b/w calls/
</code>```

答:
No iOS multitasking is very restrictive in what you can do.

You could do a voip service in the background, but you won't have access to backlight, camera, vibration motor etc.

More info here

Title: Running background processes in iPhone

Body:
Can we run following tasks in the back ground in a iPhone application:

√ Camera --> Take photo (timer = infinity) (keep on taking photos)
√ Video
√ Backlight --> On for certain duration (Customizable)
√ Flickering --> 5secs (Customizable)
√ Vibration (Background)
√ Voice Call --> Long call or multiple calls (Call duration/Time b/w calls/


问:
How to solve race between pod startup in stateful set and service DNS lookup
I'm trying to write an application where all pods are connected to each other. I have read in documentation:

The Pods’ ordinals, hostnames, SRV records, and A record names have not changed, but the IP addresses associated with the Pods may have changed. In the cluster used for this tutorial, they have. This is why it is important not to configure other applications to connect to Pods in a StatefulSet by IP address.

If you need to find and connect to the active members of a StatefulSet, you should query the CNAME of the Headless Service (nginx.default.svc.cluster.local). The SRV records associated with the CNAME will contain only the Pods in the StatefulSet that are Running and Ready.

If your application already implements connection logic that tests for liveness and readiness, you can use the SRV records of the Pods ( web-0.nginx.default.svc.cluster.local, web-1.nginx.default.svc.cluster.local), as they are stable, and your application will be able to discover the Pods’ addresses when they transition to Running and Ready.

I though I can do it in following way:

Lookup SRV records of service to check which pods are ready

Connect to all ready pods

Open the port which signify the readiness

However when I started implementing it on minikube it seemed to be racy and when I query A/SRV records:

On first node I get no records found error (sounds OK) before I open the port

On second node I sometimes get no records found sometimes one record

On third node I sometimes get one record and sometimes two records

It seems to me that there is a race between updating of DNS records and statefulset startup. I'm not entirely sure what I'm doing wrong and how I misunderstood the documentation.

```<code>apiVersion: v1
kind: Service
metadata:
  name: hello-world-lb
  labels:
    app: hello-world-lb
spec:
  ports:
  - port: 8080
    name: web
  type: LoadBalancer
  selector:
    app: hello-world
---
apiVersion: v1
kind: Service
metadata:
  name: hello-world
  labels:
    app: hello-world
spec:
  ports:
  - port: 8080
    name: web
  - port: 3080
    name: hello-world
  clusterIP: None
  selector:
    app: hello-world
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: hello-world
spec:
  selector:
    matchLabels:
      app: hello-world
  serviceName: "hello-world"
  replicas: 3
  template:
    metadata:
      labels:
        app: hello-world
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: hello-world
        image: hello-world
        imagePullPolicy: Never
        ports:
        - containerPort: 8080
          name: web
        - containerPort: 3080
          name: hello-world
        livenessProbe:
          tcpSocket:
            port: 8080
</code>```

EDIT Currently the code is as follows:

Query A/SRV records of hello-world.default.svc.cluster.local./_hello-world._tcp.hello-world.default.svc.cluster.local. and print them for debug

Bind to 3080 port and start to listen (connecting logic not implemented)

Open 8080 port

I expected that A/SRV records for hello-world-0 will be empty, for hello-world-1 will contain hello-world-0 and for hello-world-N+1 will contain hello-world-0 to hello-world-N. During rolling update A/SRV records would contain all other peers.

However it seems that DNS records are updated asynchronously so even when the lifeness of pod n is detected and pod n + 1 is started it is not guaranteed that pod n + 1 will see address of pod n in DNS.

答:
add the below annotation to service definition</p>

```<code>  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
</code>```

Body:
I'm trying to write an application where all pods are connected to each other. I have read in documentation:

The Pods’ ordinals, hostnames, SRV records, and A record names have not changed, but the IP addresses associated with the Pods may have changed. In the cluster used for this tutorial, they have. This is why it is important not to configure other applications to connect to Pods in a StatefulSet by IP address.

If you need to find and connect to the active members of a StatefulSet, you should query the CNAME of the Headless Service (nginx.default.svc.cluster.local). The SRV records associated with the CNAME will contain only the Pods in the StatefulSet that are Running and Ready.

If your application already implements connection logic that tests for liveness and readiness, you can use the SRV records of the Pods ( web-0.nginx.default.svc.cluster.local, web-1.nginx.default.svc.cluster.local), as they are stable, and your application will be able to discover the Pods’ addresses when they transition to Running and Ready.

I though I can do it in following way:

Lookup SRV records of service to check which pods are ready

Connect to all ready pods

Open the port which signify the readiness

However when I started implementing it on minikube it seemed to be racy and when I query A/SRV records:

On first node I get no records found error (sounds OK) before I open the port

On second node I sometimes get no records found sometimes one record

On third node I sometimes get one record and sometimes two records

It seems to me that there is a race between updating of DNS records and statefulset startup. I'm not entirely sure what I'm doing wrong and how I misunderstood the documentation.

apiVersion: v1
kind: Service
metadata:
  name: hello-world-lb
  labels:
    app: hello-world-lb
spec:
  ports:
  - port: 8080
    name: web
  type: LoadBalancer
  selector:
    app: hello-world
---
apiVersion: v1
kind: Service
metadata:
  name: hello-world
  labels:
    app: hello-world
spec:
  ports:
  - port: 8080
    name: web
  - port: 3080
    name: hello-world
  clusterIP: None
  selector:
    app: hello-world
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: hello-world
spec:
  selector:
    matchLabels:
      app: hello-world
  serviceName: "hello-world"
  replicas: 3
  template:
    metadata:
      labels:
        app: hello-world
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: hello-world
        image: hello-world
        imagePullPolicy: Never
        ports:
        - containerPort: 8080
          name: web
        - containerPort: 3080
          name: hello-world
        livenessProbe:
          tcpSocket:
            port: 8080

EDIT Currently the code is as follows:

Query A/SRV records of hello-world.default.svc.cluster.local./_hello-world._tcp.hello-world.default.svc.cluster.local. and print them for debug

Bind to 3080 port and start to listen (connecting logic not implemented)

Open 8080 port

I expected that A/SRV records for hello-world-0 will be empty, for hello-world-1 will contain hello-world-0 and for hello-world-N+1 will contain hello-world-0 to hello-world-N. During rolling update A/SRV records would contain all other peers.

However it seems that DNS records are updated asynchronously so even when the lifeness of pod n is detected and pod n + 1 is started it is not guaranteed that pod n + 1 will see address of pod n in DNS.

Body:
add the below annotation to service definition

  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"


问:
NullPointerException and Resource directory in JavaFX and Gradle (distributed via a jar file)
I am building a JavaFX application that is produced in Gradle to learn more about the process of building GUI applications in Java. A bump in the road that I have encountered involves accessing a .mp4 file to be displayed in the Media View. The intention is for this app to run through a .jar file, which I have been able to get to work with JavaFX 12 in general aside from the file reference hiccup.

I have referenced this Stack Overflow post and its solution still returns a Null Pointer in my project. Using

```<code>Paths.get("src/main/resources/hellofx/Blend_W-gladRLvno7U.mp4").toUri().toString();
</code>```

does work, but will then yield a Media Exception in the jar format.

The file Structure is as follows:

```<code>.
build.gradle
src
|─── main
     |───java
         |───hellofx
             |─── HelloFX.java
             |─── Launcher.java
     |─── resources
          |─── hellofx
               |─── video.mp4

</code>```

The gradle build file is:

```<code>plugins {
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.7'
}

repositories {
    mavenCentral()
}

sourceSets {
    main {
        resources {
            srcDirs = ["src/main/resources"]
            includes = ["**/*.mp4"]
        }
    }
}

dependencies {
    /* uncomment for cross-platform jar: */
    runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:win"
//    runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:linux"
//    runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:mac"
}

javafx {
    version = "12.0.1"
    modules = [ 'javafx.controls','javafx.fxml','javafx.media' ]
}

mainClassName = 'hellofx.HelloFX'

jar {
    manifest {
        attributes 'Main-Class': 'hellofx.Launcher'
    }
    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
}
</code>```

And the Java Code is:

```<code> public void start(Stage stage) {
        //Parent root = FXMLLoader.load(getClass().getResource("scene.fxml"));

        // Create and set the Scene.
        Scene scene = new Scene(new Group(), 640, 360);
        stage.setScene(scene);

//Returns Null Here (resource)
        final URL resource = HelloFX.class.getResource("imgs/Blend_W-gladRLvno7U.mp4");
//Returns Null here (loc)
        URL loc = this.getClass().getClassLoader().getResource("boop.txt");
        System.out.println(loc);

        String test = Paths.get("src/main/resources/hellofx/Blend_W-gladRLvno7U.mp4").toUri().toString();
        System.out.println(test);
        //Set up Media
        Media media = new Media(test);
        // Create the player and set to play automatically.
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.setAutoPlay(true);

        // Create the view and add it to the Scene.
        MediaView mediaView = new MediaView(mediaPlayer);
        ((Group) scene.getRoot()).getChildren().add(mediaView);

        stage.setTitle("JavaFX and Gradle");
        stage.setScene(scene);
        stage.show();
    }
</code>```

答:
There is a simple explanation for that. You are trying to resolve a path but this is kind of complicated if it is pact into an jar file.

So if you want to get your mp4 file inside the jar do it similar to your boop.txt or Blend_W-gladRLvno7U.mp4 where you are getting it from your resources which will also work inside an packed jar.

So basically something like this:

this.getClass().getClassLoader().getResource("/hellofx/Blend_W-gladRLvno7U.mp4");
```

this should do the trick :)

Body:
I am building a JavaFX application that is produced in Gradle to learn more about the process of building GUI applications in Java. A bump in the road that I have encountered involves accessing a .mp4 file to be displayed in the Media View. The intention is for this app to run through a .jar file, which I have been able to get to work with JavaFX 12 in general aside from the file reference hiccup.

I have referenced this Stack Overflow post and its solution still returns a Null Pointer in my project. Using

Paths.get("src/main/resources/hellofx/Blend_W-gladRLvno7U.mp4").toUri().toString();

does work, but will then yield a Media Exception in the jar format.

The file Structure is as follows:

.
build.gradle
src
|─── main
     |───java
         |───hellofx
             |─── HelloFX.java
             |─── Launcher.java
     |─── resources
          |─── hellofx
               |─── video.mp4

The gradle build file is:

plugins {
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.7'
}

repositories {
    mavenCentral()
}

sourceSets {
    main {
        resources {
            srcDirs = ["src/main/resources"]
            includes = ["**/*.mp4"]
        }
    }
}

dependencies {
    /* uncomment for cross-platform jar: */
    runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:win"
//    runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:linux"
//    runtimeOnly "org.openjfx:javafx-graphics:$javafx.version:mac"
}

javafx {
    version = "12.0.1"
    modules = [ 'javafx.controls','javafx.fxml','javafx.media' ]
}

mainClassName = 'hellofx.HelloFX'

jar {
    manifest {
        attributes 'Main-Class': 'hellofx.Launcher'
    }
    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

And the Java Code is:

 public void start(Stage stage) {
        //Parent root = FXMLLoader.load(getClass().getResource("scene.fxml"));

        // Create and set the Scene.
        Scene scene = new Scene(new Group(), 640, 360);
        stage.setScene(scene);

//Returns Null Here (resource)
        final URL resource = HelloFX.class.getResource("imgs/Blend_W-gladRLvno7U.mp4");
//Returns Null here (loc)
        URL loc = this.getClass().getClassLoader().getResource("boop.txt");
        System.out.println(loc);

        String test = Paths.get("src/main/resources/hellofx/Blend_W-gladRLvno7U.mp4").toUri().toString();
        System.out.println(test);
        //Set up Media
        Media media = new Media(test);
        // Create the player and set to play automatically.
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.setAutoPlay(true);

        // Create the view and add it to the Scene.
        MediaView mediaView = new MediaView(mediaPlayer);
        ((Group) scene.getRoot()).getChildren().add(mediaView);

        stage.setTitle("JavaFX and Gradle");
        stage.setScene(scene);
        stage.show();
    }

Body:
There is a simple explanation for that. You are trying to resolve a path but this is kind of complicated if it is pact into an jar file.

So if you want to get your mp4 file inside the jar do it similar to your boop.txt or Blend_W-gladRLvno7U.mp4 where you are getting it from your resources which will also work inside an packed jar.

So basically something like this:

this.getClass().getClassLoader().getResource("/hellofx/Blend_W-gladRLvno7U.mp4");

this should do the trick :)


问:
How to do a loop for a timer in UWP
I am trying to code a timer in UWP.
I want my timer to do a loop which counts down for example 1 minutes, then counts down a 2 minute pause, all that 5 times in a row, without having to re-press the start button.
I am able to count down the 1 minutes and get into the 2 minute pause but I can't figure out how to get back into the 1 minutes count down. The loop is just stuck in the 2 minute pause.

I have tried to do a IF, ELSE. I have tried bool, true, false..

```<code> public sealed partial class MainPage : Page
    {

         public int x;

        static FenetreParametres infopage = FenetreParametres.Current;
        static int Task = Int32.Parse(infopage.getTmpRound());
        //static int nb = Int32.Parse(infopage.getNbRound());
        //static int pause = Int32.Parse(infopage.getTmpPause());
        MediaPlayer player;

    private int _restsTaken { get; set; }
        private int _currentTime { get; set; }
        private DispatcherTimer _timer { get; set; }
        private TimeSpan _tickInterval { get; set; }
        private TimeSpan _intervalRemainingTime { get; set; }
        private DateTime _intervalEnd { get; set; }
        private bool _isRunning = false;

        private bool verif = false;

        public MainPage()
        {
            this.InitializeComponent();
            _currentTime = 0;
            _tickInterval = TimeSpan.FromSeconds(1);
            this.initializeTimer(_tickInterval.Seconds);

            this.initializeDisplayTimer(0);
            player = new MediaPlayer();

        }

        private void initializeTimer(int tickInterval)
        {
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(tickInterval);
            _timer.Tick += interval_Tick;
        }

        private void initializeDisplayTimer(int intervalTime)
        {
            _intervalRemainingTime = TimeSpan.FromMinutes(intervalTime);
            timerLabel.Text = _intervalRemainingTime.ToString();
        }

        private void interval_Tick(object sender, object e)
        {

            int previousTimeInMinutes = _intervalRemainingTime.Minutes;
            _isRunning = true;
            _intervalRemainingTime = _intervalRemainingTime.Subtract(_tickInterval);
            timerLabel.Text = _intervalRemainingTime.ToString();

            if (previousTimeInMinutes != _intervalRemainingTime.Minutes)
            {
                string timeIndicator = _intervalRemainingTime.Minutes == 0 ? "1 >" : _intervalRemainingTime.Minutes.ToString();

            }
            if (TimeSpan.Equals(_intervalRemainingTime, TimeSpan.Zero))
            {
                playmusic();
                this.initializeDisplayTimer(2);

            }

        }

        private async void playmusic()
        {
            Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets");
            Windows.Storage.StorageFile file = await folder.GetFileAsync("ding.wav");

            player.AutoPlay = false;
            player.Source = MediaSource.CreateFromStorageFile(file);

            player.Play();
        }

        private void trait()
        {

            for (int i = 1; i <= 3; i++)
            {
                //timerLabel.Text = "Pause";
                //x = duree;
                playmusic();
                _currentTime = x;
                this.initializeDisplayTimer(_currentTime);
                x--;
                _intervalEnd = DateTime.Now.Add(_intervalRemainingTime);

                _timer.Start();

            }

        }

        private void Button_Click_Start(object sender, RoutedEventArgs e)
        {

            if (TimeSpan.Equals(_intervalRemainingTime, TimeSpan.Zero))
            {
                playmusic();
                this.initializeDisplayTimer(Task);
                _timer.Start();
            }

        }

        private void Button_Click_Pause(object sender, RoutedEventArgs e)
        {
            _isRunning = false;
            _timer.Stop();

        }

        private void Button_Click_Reset(object sender, RoutedEventArgs e)
        {
            _timer.Stop();

            this.initializeDisplayTimer(_currentTime);
        }
}
</code>```

It's expected to go into the pause for 2 minutes and then get back into the 1 minute countdown, 5 times in a row

答:
Your question actually is a basic c# code logic issue. It's not specific to UWP programming. If you understand the whole logic clearly, it's easy to get your target by c# code logic.

I just made a simple code sample for your reference:

```<code><Grid>
    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
        </Style>
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0" Text="Count Down Time: "></TextBlock>
    <TextBlock x:Name="countDown1" Grid.Column="1"></TextBlock>
    <TextBlock Grid.Row="1" Grid.Column="0" Text="Pause Remaning: "></TextBlock>
    <TextBlock x:Name="pauseRemaning" Grid.Row="1" Grid.Column="1"></TextBlock>
    <TextBlock Grid.Row="2" Grid.Column="0" Text="Looping Times: "></TextBlock>
    <TextBlock x:Name="loop_Times" Grid.Row="2" Grid.Column="1"></TextBlock>
</Grid>
</code>```

```<code>public sealed partial class MainPage : Page
{
    private int countDowm = 60;
    private int RemainingTime = 120;
    private int loopTimes = 0;

    public MainPage()
    {
        this.InitializeComponent();
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    private void Timer_Tick(object sender, object e)
    {
        if (loopTimes == 5)
        {
            countDowm = 60;
            RemainingTime = 120;
            loopTimes = 0;
        }
        else
        {
            if (countDowm <= 0)
            {
                if (RemainingTime <= 0)
                {
                    loopTimes++;
                    countDowm = 60;
                    RemainingTime = 120;
                }
                else
                {
                    RemainingTime--;
                }
            }
            else
            {
                countDowm--;
            }
        }

        countDown1.Text = countDowm.ToString();
        pauseRemaning.Text = RemainingTime.ToString();
        loop_Times.Text = loopTimes.ToString();
    }
}
</code>```

Title: How to do a loop for a timer in UWP

Body:
I am trying to code a timer in UWP.
I want my timer to do a loop which counts down for example 1 minutes, then counts down a 2 minute pause, all that 5 times in a row, without having to re-press the start button.
I am able to count down the 1 minutes and get into the 2 minute pause but I can't figure out how to get back into the 1 minutes count down. The loop is just stuck in the 2 minute pause.

I have tried to do a IF, ELSE. I have tried bool, true, false..

 public sealed partial class MainPage : Page
    {

         public int x;

        static FenetreParametres infopage = FenetreParametres.Current;
        static int Task = Int32.Parse(infopage.getTmpRound());
        //static int nb = Int32.Parse(infopage.getNbRound());
        //static int pause = Int32.Parse(infopage.getTmpPause());
        MediaPlayer player;

    private int _restsTaken { get; set; }
        private int _currentTime { get; set; }
        private DispatcherTimer _timer { get; set; }
        private TimeSpan _tickInterval { get; set; }
        private TimeSpan _intervalRemainingTime { get; set; }
        private DateTime _intervalEnd { get; set; }
        private bool _isRunning = false;

        private bool verif = false;

        public MainPage()
        {
            this.InitializeComponent();
            _currentTime = 0;
            _tickInterval = TimeSpan.FromSeconds(1);
            this.initializeTimer(_tickInterval.Seconds);

            this.initializeDisplayTimer(0);
            player = new MediaPlayer();

        }

        private void initializeTimer(int tickInterval)
        {
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(tickInterval);
            _timer.Tick += interval_Tick;
        }

        private void initializeDisplayTimer(int intervalTime)
        {
            _intervalRemainingTime = TimeSpan.FromMinutes(intervalTime);
            timerLabel.Text = _intervalRemainingTime.ToString();
        }

        private void interval_Tick(object sender, object e)
        {

            int previousTimeInMinutes = _intervalRemainingTime.Minutes;
            _isRunning = true;
            _intervalRemainingTime = _intervalRemainingTime.Subtract(_tickInterval);
            timerLabel.Text = _intervalRemainingTime.ToString();

            if (previousTimeInMinutes != _intervalRemainingTime.Minutes)
            {
                string timeIndicator = _intervalRemainingTime.Minutes == 0 ? "1 >" : _intervalRemainingTime.Minutes.ToString();

            }
            if (TimeSpan.Equals(_intervalRemainingTime, TimeSpan.Zero))
            {
                playmusic();
                this.initializeDisplayTimer(2);

            }

        }

        private async void playmusic()
        {
            Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets");
            Windows.Storage.StorageFile file = await folder.GetFileAsync("ding.wav");

            player.AutoPlay = false;
            player.Source = MediaSource.CreateFromStorageFile(file);

            player.Play();
        }

        private void trait()
        {

            for (int i = 1; i <= 3; i++)
            {
                //timerLabel.Text = "Pause";
                //x = duree;
                playmusic();
                _currentTime = x;
                this.initializeDisplayTimer(_currentTime);
                x--;
                _intervalEnd = DateTime.Now.Add(_intervalRemainingTime);

                _timer.Start();

            }

        }

        private void Button_Click_Start(object sender, RoutedEventArgs e)
        {

            if (TimeSpan.Equals(_intervalRemainingTime, TimeSpan.Zero))
            {
                playmusic();
                this.initializeDisplayTimer(Task);
                _timer.Start();
            }

        }

        private void Button_Click_Pause(object sender, RoutedEventArgs e)
        {
            _isRunning = false;
            _timer.Stop();

        }

        private void Button_Click_Reset(object sender, RoutedEventArgs e)
        {
            _timer.Stop();

            this.initializeDisplayTimer(_currentTime);
        }
}

It's expected to go into the pause for 2 minutes and then get back into the 1 minute countdown, 5 times in a row

Body:
Your question actually is a basic c# code logic issue. It's not specific to UWP programming. If you understand the whole logic clearly, it's easy to get your target by c# code logic.

I just made a simple code sample for your reference:

<Grid>
    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
        </Style>
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0" Text="Count Down Time: "></TextBlock>
    <TextBlock x:Name="countDown1" Grid.Column="1"></TextBlock>
    <TextBlock Grid.Row="1" Grid.Column="0" Text="Pause Remaning: "></TextBlock>
    <TextBlock x:Name="pauseRemaning" Grid.Row="1" Grid.Column="1"></TextBlock>
    <TextBlock Grid.Row="2" Grid.Column="0" Text="Looping Times: "></TextBlock>
    <TextBlock x:Name="loop_Times" Grid.Row="2" Grid.Column="1"></TextBlock>
</Grid>

public sealed partial class MainPage : Page
{
    private int countDowm = 60;
    private int RemainingTime = 120;
    private int loopTimes = 0;

    public MainPage()
    {
        this.InitializeComponent();
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    private void Timer_Tick(object sender, object e)
    {
        if (loopTimes == 5)
        {
            countDowm = 60;
            RemainingTime = 120;
            loopTimes = 0;
        }
        else
        {
            if (countDowm <= 0)
            {
                if (RemainingTime <= 0)
                {
                    loopTimes++;
                    countDowm = 60;
                    RemainingTime = 120;
                }
                else
                {
                    RemainingTime--;
                }
            }
            else
            {
                countDowm--;
            }
        }

        countDown1.Text = countDowm.ToString();
        pauseRemaning.Text = RemainingTime.ToString();
        loop_Times.Text = loopTimes.ToString();
    }
}


问:
Changing the green check when dragging in jstree
I am curious if there is a way to programmatically change the green check icon that appears when you drag a jstree node. I haven't seen anything regarding this in jstrees API.

What I have is 2 jstrees. I want the green check and red X to be used when I drag and drop internally. When a node is dragged across trees I want a different icon to appear instead of the green check.

Thanks,
LL

答:
Change the style of jstree like this:

```<code>#jstree-dnd .jstree-er{ background-image: none !important;}
#jstree-dnd .jstree-er:before{content: "\f05e" !important;font-family: FontAwesome !important; color: #a32020 !important;}
</code>```

Body:
Change the style of jstree like this:

#jstree-dnd .jstree-er{ background-image: none !important;}
#jstree-dnd .jstree-er:before{content: "\f05e" !important;font-family: FontAwesome !important; color: #a32020 !important;}


问:
golang - codecoverage always shows coverage: 0.0% of statements
I created one sample go project and created a unit test cases for the same (In Linux environment, go1.3 version)

When i ran go test the output would be

PASS

  ok      supported_db    0.201s

And i tried to perform code coverage for whole application by using  go test -cover command it shows

go tool: no such tool "cover"; to install:

  go get code.google.com/p/go.tools/cmd/cover

Also i checked the coverage while running a specific test case by running go test -cover CouchDB_test.go command it shows

ok    command-line-arguments  0.158s  coverage: 0.0% of statements

please help me to run code coverage in golang.

答:
It helped me

Just add -coverpkg=./... option if tests are in sub folders:

go test ./... -v -coverpkg=./...
```


问:
How to fix succes Call Back not executing
I am integrating payment gateway to my ionic 3 project. It has successcallback function when the payment made successful. But inside the successcallback function i can only able to alert the result nothing else is working.</p>

```<code>RazorpayCheckout.open(options, this.successCallback, this.cancelCallback);

//this works
successCallback(payment_id)
  {
    alert(pament_id);
  }

//this not working
successCallback(payment_id)
  {

     let loading = this.loadingController.create({
     spinner: 'circles'
  });

  loading.present();

  this.update[ayment(payment_id);

  loading.dismiss();

  }
</code>```

答:
Use arrow functions so that the context of this gets properly binded.

```<code>successCallback = (payment_id) => {

  let loading = this.loadingController.create({
     spinner: 'circles'
  });

  loading.present();
  this.updatePayment(payment_id);
  loading.dismiss();
}
</code>```

Body:
I am integrating payment gateway to my ionic 3 project. It has successcallback function when the payment made successful. But inside the successcallback function i can only able to alert the result nothing else is working.

RazorpayCheckout.open(options, this.successCallback, this.cancelCallback);

//this works
successCallback(payment_id)
  {
    alert(pament_id);
  }

//this not working
successCallback(payment_id)
  {

     let loading = this.loadingController.create({
     spinner: 'circles'
  });

  loading.present();

  this.update[ayment(payment_id);

  loading.dismiss();

  }

Body:
Use arrow functions so that the context of this gets properly binded.

successCallback = (payment_id) => {

  let loading = this.loadingController.create({
     spinner: 'circles'
  });

  loading.present();
  this.updatePayment(payment_id);
  loading.dismiss();
}


问:
What if an object's fields is an object...is there a way to get the latter object's fields?
I'm writing a program wherein I need to check an object's field values. For example, I have a class called Book which has String bookName, String publisher, and Author author. In Author, it has fields such as String firstName, String lastName, String dateOfBirth. I want to get the author's last name and change it to a new last name by looking through the fields of the Book. Also, I have to implement my method in a way wherein any kind of object can be used so method can also be used when changing first name of just the author.

I have used getDeclaredFields() to loop through the fields of my Book object, and am trying to find if one of the fields is its own object.

I have used "instanceof" Author but I need to find a way that doesn't need my hardcoding of the class name "Author"

public ArrayList<String> makeChanges(Object book){
ArrayList<String> changeList= new ArrayList<String>;
try{
Field[] bookFields = book.getClass().getDeclaredFields();

String changes = "";

for (Field field: bookFields){
    field.setAccessible(true);
    if (field.getName().equals("firstName")){
        if (!(field.get(book).equals("Twilight"))){
            changes = field.getName() + changed to "Twilight";
            changeList.add(changes);
        }
    if (field.get(book) instanceof Author){
        List<String> authorChanges = makeChanges(field.get(book));
        changes = Arrays.toString(authorChanges.toArray()).replace("[","").replace("]","");
        changeList.add(changes);
    }
}

catch(Exception e){
System.out.println(e.toString());
}

return changeList;
}
```

Actual result: [bookName changed to "Twilight", author changed to "demo.Address@16f65612"]

Expected result should be: [bookName changed to "Twilight", firstName changed to "Eli"]

答:
You need to check whether the object is primitive data type and wrapper classes. You can check the object using recursive function. Please find below the implementation classes that might suit your needs.

```<code>import java.lang.reflect.Field;
import java.util.ArrayList;

public class BookAuthor {

    public static void main(String[] args) {
        Book book = new Book();
        book.bookName = "Twiligh";
        book.publisher = "Oreilly";
        book.author = new Author();
        book.author.firstName = "";
        book.author.lastName = "Elo";
        ArrayList<String> changeList = new ArrayList<String>();
        System.out.println(makeChanges(book,changeList));
    }

    public static ArrayList<String> makeChanges(Object book,ArrayList<String> changeList) {

        try {
            Field[] bookFields = book.getClass().getDeclaredFields();
            Object object;

            for (Field field : bookFields) {
                field.setAccessible(true);
                object = field.get(book);
                if(object!=null && isWrapperAndPrimitiveType(object.getClass())) {
                    if(field.getName().equals("bookName")) {
                        if(!object.equals("Twilight")) {
                            field.set(book, "Twilight");
                            changeList.add(field.getName()+" changed to Twilight");
                        }
                    }
                    if(field.getName().equals("lastName")) {
                        if(!object.equals("Eli")) {
                            field.set(book, "Eli");
                            changeList.add(field.getName()+" changed to Eli");
                        }
                    }
                }
                if(object!=null && !isWrapperAndPrimitiveType(object.getClass())) {
                    makeChanges(object,changeList);
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        return changeList;
    }

    public static boolean isWrapperAndPrimitiveType(Class<?> clazz) {
        return clazz.equals(Boolean.class) ||
            clazz.equals(Integer.class) ||
            clazz.equals(Character.class) ||
            clazz.equals(Byte.class) ||
            clazz.equals(Short.class) ||
            clazz.equals(Double.class) ||
            clazz.equals(Long.class) ||
            clazz.equals(Float.class)||
            clazz.equals(String.class) ||
            clazz.equals(boolean.class) ||
            clazz.equals(int.class) ||
            clazz.equals(char.class) ||
            clazz.equals(byte.class) ||
            clazz.equals(short.class) ||
            clazz.equals(double.class) ||
            clazz.equals(long.class) ||
            clazz.equals(float.class) ;
    }
}
</code>```

Book class

```<code>public class Book {
    String bookName;
    String publisher;
    Author author;
}
</code>```

Author class

```<code>public class Author {
    String firstName;
    String lastName;
    String dateOfBirth;
}
</code>```

Body:
I'm writing a program wherein I need to check an object's field values. For example, I have a class called Book which has String bookName, String publisher, and Author author. In Author, it has fields such as String firstName, String lastName, String dateOfBirth. I want to get the author's last name and change it to a new last name by looking through the fields of the Book. Also, I have to implement my method in a way wherein any kind of object can be used so method can also be used when changing first name of just the author.

I have used getDeclaredFields() to loop through the fields of my Book object, and am trying to find if one of the fields is its own object.

I have used "instanceof" Author but I need to find a way that doesn't need my hardcoding of the class name "Author"

public ArrayList<String> makeChanges(Object book){
ArrayList<String> changeList= new ArrayList<String>;
try{
Field[] bookFields = book.getClass().getDeclaredFields();

String changes = "";

for (Field field: bookFields){
    field.setAccessible(true);
    if (field.getName().equals("firstName")){
        if (!(field.get(book).equals("Twilight"))){
            changes = field.getName() + changed to "Twilight";
            changeList.add(changes);
        }
    if (field.get(book) instanceof Author){
        List<String> authorChanges = makeChanges(field.get(book));
        changes = Arrays.toString(authorChanges.toArray()).replace("[","").replace("]","");
        changeList.add(changes);
    }
}

catch(Exception e){
System.out.println(e.toString());
}

return changeList;
}

Actual result: [bookName changed to "Twilight", author changed to "demo.Address@16f65612"]

Expected result should be: [bookName changed to "Twilight", firstName changed to "Eli"]

Body:
You need to check whether the object is primitive data type and wrapper classes. You can check the object using recursive function. Please find below the implementation classes that might suit your needs.

import java.lang.reflect.Field;
import java.util.ArrayList;

public class BookAuthor {

    public static void main(String[] args) {
        Book book = new Book();
        book.bookName = "Twiligh";
        book.publisher = "Oreilly";
        book.author = new Author();
        book.author.firstName = "";
        book.author.lastName = "Elo";
        ArrayList<String> changeList = new ArrayList<String>();
        System.out.println(makeChanges(book,changeList));
    }

    public static ArrayList<String> makeChanges(Object book,ArrayList<String> changeList) {

        try {
            Field[] bookFields = book.getClass().getDeclaredFields();
            Object object;

            for (Field field : bookFields) {
                field.setAccessible(true);
                object = field.get(book);
                if(object!=null && isWrapperAndPrimitiveType(object.getClass())) {
                    if(field.getName().equals("bookName")) {
                        if(!object.equals("Twilight")) {
                            field.set(book, "Twilight");
                            changeList.add(field.getName()+" changed to Twilight");
                        }
                    }
                    if(field.getName().equals("lastName")) {
                        if(!object.equals("Eli")) {
                            field.set(book, "Eli");
                            changeList.add(field.getName()+" changed to Eli");
                        }
                    }
                }
                if(object!=null && !isWrapperAndPrimitiveType(object.getClass())) {
                    makeChanges(object,changeList);
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        return changeList;
    }

    public static boolean isWrapperAndPrimitiveType(Class<?> clazz) {
        return clazz.equals(Boolean.class) ||
            clazz.equals(Integer.class) ||
            clazz.equals(Character.class) ||
            clazz.equals(Byte.class) ||
            clazz.equals(Short.class) ||
            clazz.equals(Double.class) ||
            clazz.equals(Long.class) ||
            clazz.equals(Float.class)||
            clazz.equals(String.class) ||
            clazz.equals(boolean.class) ||
            clazz.equals(int.class) ||
            clazz.equals(char.class) ||
            clazz.equals(byte.class) ||
            clazz.equals(short.class) ||
            clazz.equals(double.class) ||
            clazz.equals(long.class) ||
            clazz.equals(float.class) ;
    }
}

Book class

public class Book {
    String bookName;
    String publisher;
    Author author;
}

Author class

public class Author {
    String firstName;
    String lastName;
    String dateOfBirth;
}


问:
python virtualenv on windows: Fatal error in launcher: Unable to create process using '"'
I have created a virtualenv in python 2.7 (Anaconda) on a dev machine and (after package installation) copied it to another windows machine in a PROD setting (no communication to outside). Executing any of the installed ".exe" entry points for a program in the virtualenv produces this error on the target machine however runs fine on the source machine:

```<code>(env) D:\app\pyvenv>env\Scripts\pip.exe
Fatal error in launcher: Unable to create process using '"'
</code>```

The location of python installation on both machines is set to the same folder:  C:\ProgramData\Anaconda2

Also see my additional notes at the bottom of this post. thanks

答:
In my case I uninstalled venv and then installed it again and it worked.
pip uninstall virtualenv to uninstall it and use pip install virtualenv to install it again.

Body:
I have created a virtualenv in python 2.7 (Anaconda) on a dev machine and (after package installation) copied it to another windows machine in a PROD setting (no communication to outside). Executing any of the installed ".exe" entry points for a program in the virtualenv produces this error on the target machine however runs fine on the source machine:

(env) D:\app\pyvenv>env\Scripts\pip.exe
Fatal error in launcher: Unable to create process using '"'

The location of python installation on both machines is set to the same folder:  C:\ProgramData\Anaconda2

Also see my additional notes at the bottom of this post. thanks


问:
the default table name is "votes" for gem acts_as_votable, can I change to whatever name I want? and how?
The default table name is "voter" for gem acts_as_votable, how can I change the table name to whatever I want?

It conflicts with another table name of mine.

答:
I just searched through the gem documentation and I don't see it has any option like that.

You may have to change the table name that's conflicted with the gem if you still wanna use this.

Otherwise, you can build the feature from scratch by this gem's implementation, but I don't think that's a good idea.


问:
Angular: Can't return value
I have API for getting information about one specific restaurant in the database, but I have to get it with a POST request. I successfully get restaurantID from auth.service and another API when the restaurant is logged in, But when I tried to log restaurant in console, I get undefined. Uniformly I don't have permission to show API here. The code:
Informacije component:

```<code>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-informacije',
  templateUrl: './informacije.component.html',
  styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
  restaurant: Restaurant;
  loggedRestaurant: LoggedRestaurant;
  restaurantID = this.authService.currRestaurant[0].id;

  constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }

  getRestaurant() {
    return this.restaurantService.getRestaurant(this.restaurantID).toPromise().then(data => {
      this.loggedRestaurant = data;
    });

 }

  async ngOnInit() {

    await this.restaurantService.getRestaurant(this.restaurantID).subscribe(
      data => {
      this.loggedRestaurant = data;
      console.log(this.loggedRestaurant)
      })

    this.restaurant = this.authService.currRestaurant[0];
    console.log(this.restaurant)
    console.log(this.loggedRestaurant)

    console.log(this.restaurantService.restaurantID)

  }
}

</code>```

restaurant.service

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';

import { AuthService } from './auth.service'

@Injectable({
  providedIn: 'root'
})
export class RestaurantService {

  private restaurantUrl = 'xxxxxx';

  public restaurant: Restaurant;
  public loggedRestaurant: LoggedRestaurant
  public restaurantID = this.authService.currRestaurant[0].id

  constructor(private http: HttpClient, private authService: AuthService) { }

  getRestaurant(ID): Observable<LoggedRestaurant> {

    console.log('ID je razmak' + this.restaurantID);

    return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
  }

}
</code>```

auth.service

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Restaurant } from '../models/Restaurant';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  loginUrl = 'xxxxx';
  errorData: {};

  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(email: string, password: string) {
    var postData = {email: email, password: password};
    return this.http.post<Restaurant>(this.loginUrl, postData)
    .pipe(map(restaurant => {
        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
          return  restaurant;
        }
      }),
      catchError(this.handleError)
    );
  }

  isLoggedIn() {
    if (localStorage.getItem('currentRestaurant')) {
      return true;
    }
      return false;
  }

  getAuthorizationToken() {
    const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
    return currentRestaurant.token;
  }

  logout() {
    localStorage.removeItem('currentRestaurant');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {

      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {

      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

  currRestaurant: Restaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
  currID = this. currRestaurant.id;
}
</code>```

答:
Try like this:

```<code>     import { Component, OnInit } from '@angular/core';
        import { AuthService } from '../services/auth.service';
        import { RestaurantService } from '../services/restaurant.service';
        import { Restaurant } from '../models/Restaurant';
        import { LoggedRestaurant } from '../models/LoggedRestaurant';
        import { Observable } from 'rxjs';

        @Component({
          selector: 'app-informacije',
          templateUrl: './informacije.component.html',
          styleUrls: ['./informacije.component.scss']
        })

        export class InformacijeComponent implements OnInit {
          restaurant: Restaurant;
          loggedRestaurant: LoggedRestaurant;
          restaurantID = this.authService.currRestaurant[0].id;

          constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }

          getRestaurant() {
            return this.restaurantService.getRestaurant(this.restaurantID).toPromise().then(data => {

          this.loggedRestaurant = data;
        });

     }

      ngOnInit() {
                  this.restaurant = this.authService.currRestaurant[0];
this.restaurantService.getRestaurant(this.restaurantID).subscribe(
          data => {
          this.loggedRestaurant = data;
          console.log(this.loggedRestaurant)
          })

        console.log(this.restaurant)
        console.log(this.loggedRestaurant)

        console.log(this.restaurantService.restaurantID)

      }
    }
</code>```

restaurant.service

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';

import { AuthService } from './auth.service'

@Injectable({
  providedIn: 'root'
})
export class RestaurantService {

  private restaurantUrl = 'xxxxxx';

  public restaurant: Restaurant;
  public loggedRestaurant: LoggedRestaurant
  public restaurantID = this.authService.currRestaurant[0].id

  constructor(private http: HttpClient, private authService: AuthService) { }

  getRestaurant(ID): Observable<LoggedRestaurant> {

    console.log('ID je razmak' + this.restaurantID);

    return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
  }

}
</code>```

Title: Angular: Can't return value

Body:
I have API for getting information about one specific restaurant in the database, but I have to get it with a POST request. I successfully get restaurantID from auth.service and another API when the restaurant is logged in, But when I tried to log restaurant in console, I get undefined. Uniformly I don't have permission to show API here. The code:
Informacije component:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-informacije',
  templateUrl: './informacije.component.html',
  styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
  restaurant: Restaurant;
  loggedRestaurant: LoggedRestaurant;
  restaurantID = this.authService.currRestaurant[0].id;

  constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }

  getRestaurant() {
    return this.restaurantService.getRestaurant(this.restaurantID).toPromise().then(data => {
      this.loggedRestaurant = data;
    });

 }

  async ngOnInit() {

    await this.restaurantService.getRestaurant(this.restaurantID).subscribe(
      data => {
      this.loggedRestaurant = data;
      console.log(this.loggedRestaurant)
      })

    this.restaurant = this.authService.currRestaurant[0];
    console.log(this.restaurant)
    console.log(this.loggedRestaurant)

    console.log(this.restaurantService.restaurantID)

  }
}

restaurant.service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';

import { AuthService } from './auth.service'

@Injectable({
  providedIn: 'root'
})
export class RestaurantService {

  private restaurantUrl = 'xxxxxx';

  public restaurant: Restaurant;
  public loggedRestaurant: LoggedRestaurant
  public restaurantID = this.authService.currRestaurant[0].id

  constructor(private http: HttpClient, private authService: AuthService) { }

  getRestaurant(ID): Observable<LoggedRestaurant> {

    console.log('ID je razmak' + this.restaurantID);

    return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
  }

}

auth.service

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Restaurant } from '../models/Restaurant';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  loginUrl = 'xxxxx';
  errorData: {};

  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(email: string, password: string) {
    var postData = {email: email, password: password};
    return this.http.post<Restaurant>(this.loginUrl, postData)
    .pipe(map(restaurant => {
        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
          return  restaurant;
        }
      }),
      catchError(this.handleError)
    );
  }

  isLoggedIn() {
    if (localStorage.getItem('currentRestaurant')) {
      return true;
    }
      return false;
  }

  getAuthorizationToken() {
    const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
    return currentRestaurant.token;
  }

  logout() {
    localStorage.removeItem('currentRestaurant');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {

      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {

      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

  currRestaurant: Restaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
  currID = this. currRestaurant.id;
}

Body:
Try like this:

     import { Component, OnInit } from '@angular/core';
        import { AuthService } from '../services/auth.service';
        import { RestaurantService } from '../services/restaurant.service';
        import { Restaurant } from '../models/Restaurant';
        import { LoggedRestaurant } from '../models/LoggedRestaurant';
        import { Observable } from 'rxjs';

        @Component({
          selector: 'app-informacije',
          templateUrl: './informacije.component.html',
          styleUrls: ['./informacije.component.scss']
        })

        export class InformacijeComponent implements OnInit {
          restaurant: Restaurant;
          loggedRestaurant: LoggedRestaurant;
          restaurantID = this.authService.currRestaurant[0].id;

          constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }

          getRestaurant() {
            return this.restaurantService.getRestaurant(this.restaurantID).toPromise().then(data => {

          this.loggedRestaurant = data;
        });

     }

      ngOnInit() {
                  this.restaurant = this.authService.currRestaurant[0];
this.restaurantService.getRestaurant(this.restaurantID).subscribe(
          data => {
          this.loggedRestaurant = data;
          console.log(this.loggedRestaurant)
          })

        console.log(this.restaurant)
        console.log(this.loggedRestaurant)

        console.log(this.restaurantService.restaurantID)

      }
    }

restaurant.service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';

import { AuthService } from './auth.service'

@Injectable({
  providedIn: 'root'
})
export class RestaurantService {

  private restaurantUrl = 'xxxxxx';

  public restaurant: Restaurant;
  public loggedRestaurant: LoggedRestaurant
  public restaurantID = this.authService.currRestaurant[0].id

  constructor(private http: HttpClient, private authService: AuthService) { }

  getRestaurant(ID): Observable<LoggedRestaurant> {

    console.log('ID je razmak' + this.restaurantID);

    return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
  }

}


问:
How to convert AT TIME ZONE return value to actual datetime value in SQL Server 2016?
I want to convert UTC value to Eastern Time Zone (any time zone) in SQL directly. I am trying below query but getting DATETIMEOFFSET.

I am trying to convert below UTC DateTime into Eastern time zone.

```<code>SELECT CONVERT(DATETIME,'2019-05-27 13:00:00' AT TIME ZONE 'Eastern Standard Time'
</code>```

I am expecting output for above query is '2019-05-27 09:00:00' but the actual output is coming like '2019-05-27 13:00:00 -04:00'

答:
you can do this</p>

```<code> select CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, '2019-05-27 13:00:00'), DATEPART(TZOFFSET,
SYSDATETIMEOFFSET() AT TIME ZONE 'Eastern Standard Time')))
</code>```

Body:
I want to convert UTC value to Eastern Time Zone (any time zone) in SQL directly. I am trying below query but getting DATETIMEOFFSET.

I am trying to convert below UTC DateTime into Eastern time zone.

SELECT CONVERT(DATETIME,'2019-05-27 13:00:00' AT TIME ZONE 'Eastern Standard Time'

I am expecting output for above query is '2019-05-27 09:00:00' but the actual output is coming like '2019-05-27 13:00:00 -04:00'

Body:
you can do this

 select CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, '2019-05-27 13:00:00'), DATEPART(TZOFFSET,
SYSDATETIMEOFFSET() AT TIME ZONE 'Eastern Standard Time')))


问:
How to pass Python variable to the downstream job in pipeline
I have some flow like below in a pipeline.

```<code>    stage('Build') {
                    build job: 'Build'
    }

    stage('Run') {
                  build job: 'Run', parameters: [string(name: 'build_version', value: <to get from Build job>)]
    }
</code>```

I am running a python script inside Build job as  execute batch script.

```<code>```python build.py```
</code>```

"build.py" will have a variable "build_version". I want to pass it to jenkins Job "Build" and inturn to the pipeline and pass the same to "Run" job from pipeline.

How can I do that ?

答:
Not sure this is the efficient solution. But the below method is working for me.

From python script I am creating a property file with the values I need for the next step.
and using EnvInject plugin to push it to environment variables of the build and then with the method "rawBuild.getEnvironment()" in pipeline I am getting it.
Sample code:

```<code>    def param_val = ""
    stage("Build"){
        def build_var = build job: 'Build'
        param_val = build_var.rawBuild.getEnvironment()[<Variable name you defined>]
     }
    stage("Run") {
         build job: 'Run', parameters: [string(name: '<param>', value: param_val)
    }
</code>```

Body:
I have some flow like below in a pipeline.

    stage('Build') {
                    build job: 'Build'
    }

    stage('Run') {
                  build job: 'Run', parameters: [string(name: 'build_version', value: <to get from Build job>)]
    }

I am running a python script inside Build job as  execute batch script.

```python build.py```

"build.py" will have a variable "build_version". I want to pass it to jenkins Job "Build" and inturn to the pipeline and pass the same to "Run" job from pipeline.

How can I do that ?

Body:
Not sure this is the efficient solution. But the below method is working for me.

From python script I am creating a property file with the values I need for the next step.
and using EnvInject plugin to push it to environment variables of the build and then with the method "rawBuild.getEnvironment()" in pipeline I am getting it.
Sample code:

    def param_val = ""
    stage("Build"){
        def build_var = build job: 'Build'
        param_val = build_var.rawBuild.getEnvironment()[<Variable name you defined>]
     }
    stage("Run") {
         build job: 'Run', parameters: [string(name: '<param>', value: param_val)
    }


问:
delete specific user record from mysql database
I have a table with five columns in mysql database. i have designed an android app where the user can delete his/her record but i dont want the user to tamper with another persons record.(id(pk),commid,name,portfolio,contact,address)

I used the sql delete statement to delete the specific user record which was successfully but when the user inputs another id into the editText box i provided in the android app he is able to delete another persons record.

$connect  = mysqli_connect($host,$db_user,$db_password,$db_name);
    $id = $_POST["id"];

```<code>$query = "DELETE FROM community_entry where id='$id'";
</code>```

Record gets deleted successfully for any number the user tries

答: A better approach will be first to check if the user who is requesting to perform the delete operation is the same user whose ID has been passed. If that is true then let the user delete his account else you can return a "Not authorised" error.</p>

Body:
I have a table with five columns in mysql database. i have designed an android app where the user can delete his/her record but i dont want the user to tamper with another persons record.(id(pk),commid,name,portfolio,contact,address)

I used the sql delete statement to delete the specific user record which was successfully but when the user inputs another id into the editText box i provided in the android app he is able to delete another persons record.

$connect  = mysqli_connect($host,$db_user,$db_password,$db_name);
    $id = $_POST["id"];

$query = "DELETE FROM community_entry where id='$id'";

Record gets deleted successfully for any number the user tries


问:
c++ Question with displaying text between two array variables
I always seem to have this problem when I want to display two variables of an array in one iteration of a loop, I'm wondering if there is a nicer way of displaying the array.

The code works if I change ++i to i+1 but I'm wondering why that happens, and I'm wondering if there's a smarter way to do what I want. The error says unsequenced modification and access to 'i' [-Wunsequenced]

```<code>#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    int players = 0,rounds=0;
    bool winnerFound=false;
    cout << "Welcome to my tournament match maker\n";
    cout << "Enter the number of participants in the tournament: ";
    cin >> players;
    rounds=players/2;
    string *pNames = new string[players]; //dynamically allocate
    for (int i = 0;i < players;i++)
    {
        cout << "Enter the name of player " << i + 1<<":";
        cin >> pNames[i];
    }
        random_shuffle(&pNames[0],&pNames[players]);
        for(int i=0;i<rounds;i++)
        {
           cout<<pNames[i]<<" vs "<<pNames[++i]; //
        }
        return 0;
}
</code>```

I'm not sure if that's the best way to do it, any tips would be appreciated.

答:
For the tips, I think it is better to use a STL container instead of a raw array. std::array or std::vector for example. You can change the declaration of pNames as follows:

```<code>std::vector <std::string> pNames(players);
</code>```

Your problem is that you iterate only until rounds. You don't want that, you want to loop over all players, not only half of them.

To make your code work, you need to write:

```<code>for(size_t i = 0; !pNames.empty() && i < pNames.size()-1; ++i)
{
    std::cout << pNames[i] << " vs " << pNames[++i] << std::endl;
}
</code>```

But I think it is a bad way to modify i from inside the loop, you better have to directly increment i by two in the loop statement. This will give:

```<code>for(size_t i = 0; !pNames.empty() && i < pNames.size()-1; i+=2)
{
    std::cout << pNames[i] << " vs " << pNames[i+1] << std::endl;
}
</code>```

Of course, if you have only one player or any odd number of players, you will miss the last one (because you need two opponents to make a vs).

I hope it can help.

Body:
I always seem to have this problem when I want to display two variables of an array in one iteration of a loop, I'm wondering if there is a nicer way of displaying the array.

The code works if I change ++i to i+1 but I'm wondering why that happens, and I'm wondering if there's a smarter way to do what I want. The error says unsequenced modification and access to 'i' [-Wunsequenced]

#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    int players = 0,rounds=0;
    bool winnerFound=false;
    cout << "Welcome to my tournament match maker\n";
    cout << "Enter the number of participants in the tournament: ";
    cin >> players;
    rounds=players/2;
    string *pNames = new string[players]; //dynamically allocate
    for (int i = 0;i < players;i++)
    {
        cout << "Enter the name of player " << i + 1<<":";
        cin >> pNames[i];
    }
        random_shuffle(&pNames[0],&pNames[players]);
        for(int i=0;i<rounds;i++)
        {
           cout<<pNames[i]<<" vs "<<pNames[++i]; //
        }
        return 0;
}

I'm not sure if that's the best way to do it, any tips would be appreciated.

Body:
For the tips, I think it is better to use a STL container instead of a raw array. std::array or std::vector for example. You can change the declaration of pNames as follows:

std::vector <std::string> pNames(players);

Your problem is that you iterate only until rounds. You don't want that, you want to loop over all players, not only half of them.

To make your code work, you need to write:

for(size_t i = 0; !pNames.empty() && i < pNames.size()-1; ++i)
{
    std::cout << pNames[i] << " vs " << pNames[++i] << std::endl;
}

But I think it is a bad way to modify i from inside the loop, you better have to directly increment i by two in the loop statement. This will give:

for(size_t i = 0; !pNames.empty() && i < pNames.size()-1; i+=2)
{
    std::cout << pNames[i] << " vs " << pNames[i+1] << std::endl;
}

Of course, if you have only one player or any odd number of players, you will miss the last one (because you need two opponents to make a vs).

I hope it can help.