问:
Printing the lowest and second lowest values in an array using methods (Java)
I am new to Java and have been given an assignment that asks:

Description

A group of friends decide to run the Boston Marathon. Their names and times (in minutes) are below:

```<code>Name       Time(minutes)

Elena       341
Thomas      273
Hamilton    278
Suzie       329
Phil        445
Matt        402
Alex        388
Emma        275
John        243
James       334
Jane        412
Emily       393
Daniel      299
Neda        343
Aaron       317
Kate        265
</code>```

Find the fastest runner. Print the name and his/her time (in minutes).

Find the second fastest runner. Print the name and his/her time (in minutes).

Instructions

Write a method that takes as input an array of integers and returns the index corresponding to the
person with the lowest time. Run this method on the array of times. Print out the name and time
corresponding to the returned index.
Write a second method to find the second‐best runner. The second method should use the first method
to determine the best runner, and then loop through all values to find the second‐best (second lowest)
time.
Here is a program skeleton to get started:

```<code>class Marathon {
 public static void main (String[] arguments){
 String[] names ={
 "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
 "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
 "Aaron", "Kate"
};
 int[] times ={
 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
 343, 317, 265
 };
 int i1 = fastestIndex(times);
 int i2 = secondFastestIndex(times);
 //
 // your output based on the index i1 and i2
 //
 }
 // your two Java methods:
 // fastestIndex() and secondFastestIndex()
}
</code>```

I wrote a program that prints the first and second place times and names but now I am starting to think I didn't follow the instructions correctly. Could anyone help me figure out what I should do differently?

Here is my amateur code:

```<code>public class Lab
{
    public static void main(String[] args)
    {
        String[] names = {
            "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt",
            "Alex", "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate"
        };

        int[] times = {
            341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265
        };

        int firstplace = times[0];
        String firstname = names[0];

        int secondplace = times[0];
        String secondname = names[0];

        for (int counter = 0; counter < times.length; counter++)
        {
            if (times[counter] < firstplace) {
                firstplace = times[counter];
                firstname = names[counter]; }
        }

        for (int counter = 0; counter < times.length; counter++)
        {
            if (times[counter] > firstplace)
                if (times[counter] < secondplace) {
                    secondplace = times[counter];
                    secondname = names[counter]; }
        }
            System.out.printf("The fastest runner is: %s (%d Minutes)%n", firstname, firstplace);
            System.out.printf("The second fastest runner is: %s (%d Minutes)%n", secondname, secondplace);
        } // end main
    } // end class Lab
</code>```

This is what it prints:

```<code>The fastest runner is: John (243 Minutes)
The second fastest runner is: Kate (265 Minutes)
</code>```

答:
You should consider also the case when the fastest is in place one. Then, you cannot equal secondfastestIndex to 0 in the first place.
(For example, in the case of 70, 250, 300, 450). Pay attention to the method to find the second fastest. Previous comments are wrong in terms of secondFastest

```<code>package mitJava2010;

public class As3_Marathon {
    public static void main(String[] arguments) {
        String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James",
                "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate" };
        int[] times = { 70, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 };

        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i] + ": " + times[i]);
        }

        int f = findTheFastest(times);
        int sf = find2fastest(times);
        System.out.println("The fastest is " + names[f] + " with " + times[f] + " minutes");

        System.out.println("The second fastest is " + names[sf] + " with " + times[sf] + " minutes");
    }

    private static int find2fastest(int[] times) {
        int f = findTheFastest(times);
        int sf = (f != 0) ? 0 : 1;
        for (int i = sf + 1; i < times.length; i++) {
            if (times[i] < times[sf] && i != f)
                sf = i;

        }
        return sf;
    }

    private static int findTheFastest(int[] times) {
        int minIn = 0;
        for (int i = 1; i < times.length; i++) {
            if (times[i] < times[minIn])
                minIn = i;
        }
        return minIn;

    }
}
</code>```

Body:
I am new to Java and have been given an assignment that asks:

Description

A group of friends decide to run the Boston Marathon. Their names and times (in minutes) are below:

Name       Time(minutes)

Elena       341
Thomas      273
Hamilton    278
Suzie       329
Phil        445
Matt        402
Alex        388
Emma        275
John        243
James       334
Jane        412
Emily       393
Daniel      299
Neda        343
Aaron       317
Kate        265

Find the fastest runner. Print the name and his/her time (in minutes).

Find the second fastest runner. Print the name and his/her time (in minutes).

Instructions

Write a method that takes as input an array of integers and returns the index corresponding to the
person with the lowest time. Run this method on the array of times. Print out the name and time
corresponding to the returned index.
Write a second method to find the second‐best runner. The second method should use the first method
to determine the best runner, and then loop through all values to find the second‐best (second lowest)
time.
Here is a program skeleton to get started:

class Marathon {
 public static void main (String[] arguments){
 String[] names ={
 "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
 "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
 "Aaron", "Kate"
};
 int[] times ={
 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
 343, 317, 265
 };
 int i1 = fastestIndex(times);
 int i2 = secondFastestIndex(times);
 //
 // your output based on the index i1 and i2
 //
 }
 // your two Java methods:
 // fastestIndex() and secondFastestIndex()
}

I wrote a program that prints the first and second place times and names but now I am starting to think I didn't follow the instructions correctly. Could anyone help me figure out what I should do differently?

Here is my amateur code:

public class Lab
{
    public static void main(String[] args)
    {
        String[] names = {
            "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt",
            "Alex", "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate"
        };

        int[] times = {
            341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265
        };

        int firstplace = times[0];
        String firstname = names[0];

        int secondplace = times[0];
        String secondname = names[0];

        for (int counter = 0; counter < times.length; counter++)
        {
            if (times[counter] < firstplace) {
                firstplace = times[counter];
                firstname = names[counter]; }
        }

        for (int counter = 0; counter < times.length; counter++)
        {
            if (times[counter] > firstplace)
                if (times[counter] < secondplace) {
                    secondplace = times[counter];
                    secondname = names[counter]; }
        }
            System.out.printf("The fastest runner is: %s (%d Minutes)%n", firstname, firstplace);
            System.out.printf("The second fastest runner is: %s (%d Minutes)%n", secondname, secondplace);
        } // end main
    } // end class Lab

This is what it prints:

The fastest runner is: John (243 Minutes)
The second fastest runner is: Kate (265 Minutes)

Body:
You should consider also the case when the fastest is in place one. Then, you cannot equal secondfastestIndex to 0 in the first place.
(For example, in the case of 70, 250, 300, 450). Pay attention to the method to find the second fastest. Previous comments are wrong in terms of secondFastest

package mitJava2010;

public class As3_Marathon {
    public static void main(String[] arguments) {
        String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James",
                "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate" };
        int[] times = { 70, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 };

        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i] + ": " + times[i]);
        }

        int f = findTheFastest(times);
        int sf = find2fastest(times);
        System.out.println("The fastest is " + names[f] + " with " + times[f] + " minutes");

        System.out.println("The second fastest is " + names[sf] + " with " + times[sf] + " minutes");
    }

    private static int find2fastest(int[] times) {
        int f = findTheFastest(times);
        int sf = (f != 0) ? 0 : 1;
        for (int i = sf + 1; i < times.length; i++) {
            if (times[i] < times[sf] && i != f)
                sf = i;

        }
        return sf;
    }

    private static int findTheFastest(int[] times) {
        int minIn = 0;
        for (int i = 1; i < times.length; i++) {
            if (times[i] < times[minIn])
                minIn = i;
        }
        return minIn;

    }
}


来源: stackexchange

问:
Can I get every month of the year even if there is not data for that month in DB
I want to get a statistic for every month of the years i have in DB

```<code>SELECT      monthname(created_at) AS month, YEAR(created_at) AS year, count(*) AS number
FROM        tableName
WHERE       type_of_user = "someType"
GROUP BY    year, month(created_at)
ORDER BY    created_at DESC
</code>```

Now it gives me only month that I have, but I need to get statistics  for every month, even if I don't have any stored data for that month

答:
```<code>SELECT month(created_at) as month
FROM tableName
RIGHT JOIN (select row_number() over (order by 1) as i
       from someTableWithMoreThan12Records limit 12) x
    ON x.i=month(created_at)
ORDER BY I;
</code>```

JOINing with a table that has all the records will give you every month.

ContentLicense: CC BY-SA 4.0

Body:
I want to get a statistic for every month of the years i have in DB

SELECT      monthname(created_at) AS month, YEAR(created_at) AS year, count(*) AS number
FROM        tableName
WHERE       type_of_user = "someType"
GROUP BY    year, month(created_at)
ORDER BY    created_at DESC

Now it gives me only month that I have, but I need to get statistics  for every month, even if I don't have any stored data for that month

Body:
SELECT month(created_at) as month
FROM tableName
RIGHT JOIN (select row_number() over (order by 1) as i
       from someTableWithMoreThan12Records limit 12) x
    ON x.i=month(created_at)
ORDER BY I;

JOINing with a table that has all the records will give you every month.


问:
How to pass a third param to EventHandler()
I wanted to generate a userControl from another, after preparing the userControl to receive Data, i am struggling with passing an int value to know which Card has been clicked to use it's data.

I know the code below is false i need a solution please help

```<code> private BunifuThinButton2 generatetAributeStandBtn(int i)
    {
        BunifuThinButton2 button = new BunifuThinButton2();
        button.Name = "attributeBtn_" + i.ToString();
        button.Click += new EventHandler(this.button_Click);
        button.Size = new Size(114, 39);
        button.Location = new Point(30,150);

        return button;
    }

    private void button_Click(object sender, System.EventArgs e, int i)
    {
        Console.WriteLine(" Parents Name" +);
        //actualModal = new confirmStandsModal();
        //this.Controls.Add(actualModal);
    }[Code Screen ][1]
</code>```

答:
The sender parameter is the Control instance that has triggered the event, in your case the BunifuThinButton2 instance. So you could either create a custom filed within that class (or derive a custom class first) or try to extract the ID from the Name property.

```<code>private void button_Click(object sender, System.EventArgs e)
{
    var btn = sender as BunifuThinButton2;
    var id = int.Parse(btn.Name.Split(new [] {'_'})[1]);
}
</code>```

Body:
I wanted to generate a userControl from another, after preparing the userControl to receive Data, i am struggling with passing an int value to know which Card has been clicked to use it's data.

I know the code below is false i need a solution please help

 private BunifuThinButton2 generatetAributeStandBtn(int i)
    {
        BunifuThinButton2 button = new BunifuThinButton2();
        button.Name = "attributeBtn_" + i.ToString();
        button.Click += new EventHandler(this.button_Click);
        button.Size = new Size(114, 39);
        button.Location = new Point(30,150);

        return button;
    }

    private void button_Click(object sender, System.EventArgs e, int i)
    {
        Console.WriteLine(" Parents Name" +);
        //actualModal = new confirmStandsModal();
        //this.Controls.Add(actualModal);
    }[Code Screen ][1]

Body:
The sender parameter is the Control instance that has triggered the event, in your case the BunifuThinButton2 instance. So you could either create a custom filed within that class (or derive a custom class first) or try to extract the ID from the Name property.

private void button_Click(object sender, System.EventArgs e)
{
    var btn = sender as BunifuThinButton2;
    var id = int.Parse(btn.Name.Split(new [] {'_'})[1]);
}


问:
Push ViewController in UITabBarController
I have a general question: I have set up a TabBar in my app. When I click on item 1, the TabBar shows a ViewController (VC 1) embedded in a NavigationController. This VC is supposed to push another VC (VC 2) when the user logs out (using firebase   and addStateDidChangeListener). It works great : When I log out the VC1 push VC 2. However when I click again on the item 1 on the tab bar. Guess what? I can see VC 1 while there is no user. I think I have to dismiss VC 1 somehow but I do not know how to implement this function. Can you help me?

答:
You can override window rootviewcontroller new tabbar controller. So in future you dont have any bugs with new development (new screen hierarchy).</p>

```<code>    //Login
    let navigation = UINavigationController.init(rootViewController: vc1)
    let tabVC = UITabBarController()
    tabVC.viewControllers?.append(navigation)
    self.appDelegate?.window?.rootViewController = navigation

    //Logout
    let navigation = UINavigationController.init(rootViewController: vc2)
    let tabVC = UITabBarController()
    tabVC.viewControllers?.append(navigation)
    self.appDelegate?.window?.rootViewController = navigation
</code>```

Body:
You can override window rootviewcontroller new tabbar controller. So in future you dont have any bugs with new development (new screen hierarchy).

    //Login
    let navigation = UINavigationController.init(rootViewController: vc1)
    let tabVC = UITabBarController()
    tabVC.viewControllers?.append(navigation)
    self.appDelegate?.window?.rootViewController = navigation

    //Logout
    let navigation = UINavigationController.init(rootViewController: vc2)
    let tabVC = UITabBarController()
    tabVC.viewControllers?.append(navigation)
    self.appDelegate?.window?.rootViewController = navigation


问:
Calling a base abstract method in an override of that method
If I have the following:

e.g.

```<code>public abstract class ClassA
{
     protected abstract void ValidateTransaction();
}

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}
</code>```

So I did not find usages on ClassC's ValidateTransaction.  I don't see it being called anywhere.

So then I guess how does this work?  I mean it's calling the method at the top of the stack here (calls the ClassB's override method and then includes logic in my ClassC's override of ClassB's method?)

This doesn't make sense to me why or how this works or the intention here.

UPDATED

Ok so I did find a spot where ClassA's PerformTransaction() method is called from a lot of sub classes in our project.

So ClassA now looks like this with more details for you here:

```<code>public abstract class ClassA
{
     public void PerformTransaction()
     {
           ValidateTransaction();
           // and calls some other code here.
     }

     protected abstract void ValidateTransaction();
}
</code>```

Ok then we still have:

```<code>public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

public class SomeAbritraryClass : ClassC
{
      ClassA.PerformTransaction();
      ...
 }
</code>```

so ClassA.PerformTransaction() is being called in some classes that inherit ClassC.

答:
When the C class override is called, it will first call into B's override and execute some logic there, which will then be extended by C's logic.

They could for all I know be working with the same variables, data.  I don't know, cause I don't have all the data.

ContentLicense: CC BY-SA 3.0

Body:
If I have the following:

e.g.

public abstract class ClassA
{
     protected abstract void ValidateTransaction();
}

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

So I did not find usages on ClassC's ValidateTransaction.  I don't see it being called anywhere.

So then I guess how does this work?  I mean it's calling the method at the top of the stack here (calls the ClassB's override method and then includes logic in my ClassC's override of ClassB's method?)

This doesn't make sense to me why or how this works or the intention here.

UPDATED

Ok so I did find a spot where ClassA's PerformTransaction() method is called from a lot of sub classes in our project.

So ClassA now looks like this with more details for you here:

public abstract class ClassA
{
     public void PerformTransaction()
     {
           ValidateTransaction();
           // and calls some other code here.
     }

     protected abstract void ValidateTransaction();
}

Ok then we still have:

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

public class SomeAbritraryClass : ClassC
{
      ClassA.PerformTransaction();
      ...
 }

so ClassA.PerformTransaction() is being called in some classes that inherit ClassC.


问:
How to check logs for deployment?
I am trying to deploy one spring boot application which uses postgres database.

I used this tutorial :
https://github.com/mkjelland/spring-boot-postgres-on-k8s-sample

But when I did this commmand

```<code> kubectl expose deployment spring-boot-postgres-sample --type=LoadBalancer --
  port=8080
</code>```

So it giving External-IP status as  for around 30 minute

So i patch this by using

```<code>kubectl patch svc <svc-name> -n <namespace> -p '{"spec": {"type": "LoadBalancer", "externalIPs":["172.31.71.218"]}}'
</code>```

So when I tried to access http://172.31.71.218:8080 which is getting timeout.

I want to check logs what happening behind the scenes.

I also tried using cluster-IP service by using yaml file

```<code>    apiVersion: v1
kind: Service
metadata:
  labels:
    app: spring-boot-postgres-sample
  name: spring-boot-postgres-sample
  namespace: default
spec:
  ports:
  - nodePort: 30500
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: spring-boot-postgres-sample
  type: NodePort
</code>```

Used following commands :-

```<code>kubectl create -f service.yaml
</code>```

Then tried to access
  http://myhostip:30500/

but still getting timedOut
how do i check it logs

here is output of kubectl describe pod podname

```<code>    Name:               spring-boot-postgres-sample-7f7c7479d9-fclwb
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               ip-172-31-11-87/172.31.11.87
Start Time:         Thu, 30 May 2019 11:50:24 +0000
Labels:             app=spring-boot-postgres-sample
                    pod-template-hash=7f7c7479d9
Annotations:        <none>
Status:             Running
IP:                 192.168.1.28
Controlled By:      ReplicaSet/spring-boot-postgres-sample-7f7c7479d9
Containers:
  spring-boot-postgres-sample:
    Container ID:  docker://a1278cc26a66eb3b977cf1946d1490c7c5066e9fe0db8c468fd0e8dc47de5ca2
    Image:         djtijare/a2i-web:v1
    Image ID:      docker-pullable://djtijare/a2i-web@sha256:cbeac029eb3b65760b904e93ced0b417eca349280ba5a809de713d5fbb2d608f
    Port:          <none>
    Host Port:     <none>
    Command:
      /bin/bash
      -ce
      tail -f /dev/null
    State:          Running
      Started:      Thu, 30 May 2019 11:50:46 +0000
    Ready:          True
    Restart Count:  0
    Environment:
      POSTGRES_USER:      <set to the key 'postgres_user' of config map 'postgres-config'>      Optional: false
      POSTGRES_PASSWORD:  <set to the key 'postgres_password' of config map 'postgres-config'>  Optional: false
      POSTGRES_HOST:      <set to the key 'postgres_host' of config map 'hostname-config'>      Optional: false
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-6pksq (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-6pksq:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-6pksq
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:          <none>
aquilak8suser@ip-172-31-6-149:~/a2i-web$ kubectl describe pod spring-boot-postgres-sample-7f7c7479d9-fclwb
Name:               spring-boot-postgres-sample-7f7c7479d9-fclwb
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               ip-172-31-11-87/172.31.11.87
Start Time:         Thu, 30 May 2019 11:50:24 +0000
Labels:             app=spring-boot-postgres-sample
                    pod-template-hash=7f7c7479d9
Annotations:        <none>
Status:             Running
IP:                 192.168.1.28
Controlled By:      ReplicaSet/spring-boot-postgres-sample-7f7c7479d9
Containers:
  spring-boot-postgres-sample:
    Container ID:  docker://a1278cc26a66eb3b977cf1946d1490c7c5066e9fe0db8c468fd0e8dc47de5ca2
    Image:         djtijare/a2i-web:v1
    Image ID:      docker-pullable://djtijare/a2i-web@sha256:cbeac029eb3b65760b904e93ced0b417eca349280ba5a809de713d5fbb2d608f
    Port:          <none>
    Host Port:     <none>
    Command:
      /bin/bash
      -ce
      tail -f /dev/null
    State:          Running
      Started:      Thu, 30 May 2019 11:50:46 +0000
    Ready:          True
    Restart Count:  0
    Environment:
      POSTGRES_USER:      <set to the key 'postgres_user' of config map 'postgres-config'>      Optional: false
      POSTGRES_PASSWORD:  <set to the key 'postgres_password' of config map 'postgres-config'>  Optional: false
      POSTGRES_HOST:      <set to the key 'postgres_host' of config map 'hostname-config'>      Optional: false
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-6pksq (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-6pksq:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-6pksq
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:          <none>
</code>```

答:
You can get the deployment logs with the following command

```<code>kubectl logs -f deployment/spring-boot-postgres-sample
</code>```

Or if you want the logs for an specific pod

```<code>kubectl logs -f spring-boot-postgres-sample-7f7c7479d9-fclwb
</code>```

Title: How to check logs for deployment?

Body:
I am trying to deploy one spring boot application which uses postgres database.

I used this tutorial :
https://github.com/mkjelland/spring-boot-postgres-on-k8s-sample

But when I did this commmand

 kubectl expose deployment spring-boot-postgres-sample --type=LoadBalancer --
  port=8080

So it giving External-IP status as  for around 30 minute

So i patch this by using

kubectl patch svc <svc-name> -n <namespace> -p '{"spec": {"type": "LoadBalancer", "externalIPs":["172.31.71.218"]}}'

So when I tried to access http://172.31.71.218:8080 which is getting timeout.

I want to check logs what happening behind the scenes.

I also tried using cluster-IP service by using yaml file

    apiVersion: v1
kind: Service
metadata:
  labels:
    app: spring-boot-postgres-sample
  name: spring-boot-postgres-sample
  namespace: default
spec:
  ports:
  - nodePort: 30500
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: spring-boot-postgres-sample
  type: NodePort

Used following commands :-

kubectl create -f service.yaml

Then tried to access
  http://myhostip:30500/

but still getting timedOut
how do i check it logs

here is output of kubectl describe pod podname

    Name:               spring-boot-postgres-sample-7f7c7479d9-fclwb
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               ip-172-31-11-87/172.31.11.87
Start Time:         Thu, 30 May 2019 11:50:24 +0000
Labels:             app=spring-boot-postgres-sample
                    pod-template-hash=7f7c7479d9
Annotations:        <none>
Status:             Running
IP:                 192.168.1.28
Controlled By:      ReplicaSet/spring-boot-postgres-sample-7f7c7479d9
Containers:
  spring-boot-postgres-sample:
    Container ID:  docker://a1278cc26a66eb3b977cf1946d1490c7c5066e9fe0db8c468fd0e8dc47de5ca2
    Image:         djtijare/a2i-web:v1
    Image ID:      docker-pullable://djtijare/a2i-web@sha256:cbeac029eb3b65760b904e93ced0b417eca349280ba5a809de713d5fbb2d608f
    Port:          <none>
    Host Port:     <none>
    Command:
      /bin/bash
      -ce
      tail -f /dev/null
    State:          Running
      Started:      Thu, 30 May 2019 11:50:46 +0000
    Ready:          True
    Restart Count:  0
    Environment:
      POSTGRES_USER:      <set to the key 'postgres_user' of config map 'postgres-config'>      Optional: false
      POSTGRES_PASSWORD:  <set to the key 'postgres_password' of config map 'postgres-config'>  Optional: false
      POSTGRES_HOST:      <set to the key 'postgres_host' of config map 'hostname-config'>      Optional: false
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-6pksq (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-6pksq:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-6pksq
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:          <none>
aquilak8suser@ip-172-31-6-149:~/a2i-web$ kubectl describe pod spring-boot-postgres-sample-7f7c7479d9-fclwb
Name:               spring-boot-postgres-sample-7f7c7479d9-fclwb
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               ip-172-31-11-87/172.31.11.87
Start Time:         Thu, 30 May 2019 11:50:24 +0000
Labels:             app=spring-boot-postgres-sample
                    pod-template-hash=7f7c7479d9
Annotations:        <none>
Status:             Running
IP:                 192.168.1.28
Controlled By:      ReplicaSet/spring-boot-postgres-sample-7f7c7479d9
Containers:
  spring-boot-postgres-sample:
    Container ID:  docker://a1278cc26a66eb3b977cf1946d1490c7c5066e9fe0db8c468fd0e8dc47de5ca2
    Image:         djtijare/a2i-web:v1
    Image ID:      docker-pullable://djtijare/a2i-web@sha256:cbeac029eb3b65760b904e93ced0b417eca349280ba5a809de713d5fbb2d608f
    Port:          <none>
    Host Port:     <none>
    Command:
      /bin/bash
      -ce
      tail -f /dev/null
    State:          Running
      Started:      Thu, 30 May 2019 11:50:46 +0000
    Ready:          True
    Restart Count:  0
    Environment:
      POSTGRES_USER:      <set to the key 'postgres_user' of config map 'postgres-config'>      Optional: false
      POSTGRES_PASSWORD:  <set to the key 'postgres_password' of config map 'postgres-config'>  Optional: false
      POSTGRES_HOST:      <set to the key 'postgres_host' of config map 'hostname-config'>      Optional: false
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-6pksq (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-6pksq:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-6pksq
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:          <none>

Body:
You can get the deployment logs with the following command

kubectl logs -f deployment/spring-boot-postgres-sample

Or if you want the logs for an specific pod

kubectl logs -f spring-boot-postgres-sample-7f7c7479d9-fclwb


问:
Zipping files from a set using zipfile
I need to zip specific files on a path all together.
I need to find certain files (for instance: AAA.txt, BBB.inf and etc) with exception to the ones that contain SFF in the name, and then zip them all together.

Every time I run this, I end up with my DB.zip with only CCC.txt inside. It means that every time the script finds a file from the set, it creates a new DB.zip with that new file inside, overwriting the previous one. How can I fix this?

```<code>import os
import zipfile

pr_directory = r'C:\Users\vijo9001\Desktop\Infact'
pr_path = os.listdir(pr_directory)
dst = r'C:\Users\vijo9001\Desktop\Infact'
os.chdir(r'C:\Users\vijo9001\Desktop\Infact')

my_set = {
"AAA",
"BBB",
"CCC"
}

for file in pr_path:
    zip_file = pr_directory + '/' + 'DB.zip'
    for x in my_set:
        if 'SFF' in file:
            continue
        if (str(x)) in file:
           zip = zipfile.ZipFile(zip_file, "w",)
           zip.write(file, compress_type=zipfile.ZIP_DEFLATED)
           zip.close()
</code>```

答:
There are a couple of things about your code I spotted which you might want to  optimize/correct:

zip is instantiated within each iteration through the for loops, overriding each other.
Meaning you will generate a DB.zip file for a file "AAA1.txt", then overwrite it with a DB.zip containing only a file "AAA2.txt", and so on. By initiating zip before the for loops you will add each file in turn, generating a single DB.zip containing all files.

Instead of having a for loop for every element in my_set, you can use a simple if-statement with the following condition:  if any(x in file_split for x in my_set)

zip_file would only need to be moved before the for loops to correctly declar zip

zip shadows the zip library, for better clarity and to avoid mistakes it would be better to rename the variable (I used zip_dir in the code below)

I played around with your code a bit and came up with the following snippet:

```<code>my_set = {"AAA", "BBB", "CCC"}

zip_file = pr_directory + '/' + 'DB.zip'
zip_dir = zipfile.ZipFile(zip_file, "w",)

for file in pr_path:
    if 'SFF' in file:
        continue
    if any(x in file for x in my_set):
        zip_dir.write(file, compress_type=zipfile.ZIP_DEFLATED)

zip_dir.close()
</code>```

This seems to work fine for me. Hope I was of help.

Title: Zipping files from a set using zipfile

Body:
I need to zip specific files on a path all together.
I need to find certain files (for instance: AAA.txt, BBB.inf and etc) with exception to the ones that contain SFF in the name, and then zip them all together.

Every time I run this, I end up with my DB.zip with only CCC.txt inside. It means that every time the script finds a file from the set, it creates a new DB.zip with that new file inside, overwriting the previous one. How can I fix this?

import os
import zipfile

pr_directory = r'C:\Users\vijo9001\Desktop\Infact'
pr_path = os.listdir(pr_directory)
dst = r'C:\Users\vijo9001\Desktop\Infact'
os.chdir(r'C:\Users\vijo9001\Desktop\Infact')

my_set = {
"AAA",
"BBB",
"CCC"
}

for file in pr_path:
    zip_file = pr_directory + '/' + 'DB.zip'
    for x in my_set:
        if 'SFF' in file:
            continue
        if (str(x)) in file:
           zip = zipfile.ZipFile(zip_file, "w",)
           zip.write(file, compress_type=zipfile.ZIP_DEFLATED)
           zip.close()

Body:
There are a couple of things about your code I spotted which you might want to  optimize/correct:

zip is instantiated within each iteration through the for loops, overriding each other.
Meaning you will generate a DB.zip file for a file "AAA1.txt", then overwrite it with a DB.zip containing only a file "AAA2.txt", and so on. By initiating zip before the for loops you will add each file in turn, generating a single DB.zip containing all files.

Instead of having a for loop for every element in my_set, you can use a simple if-statement with the following condition:  if any(x in file_split for x in my_set)

zip_file would only need to be moved before the for loops to correctly declar zip

zip shadows the zip library, for better clarity and to avoid mistakes it would be better to rename the variable (I used zip_dir in the code below)

I played around with your code a bit and came up with the following snippet:

my_set = {"AAA", "BBB", "CCC"}

zip_file = pr_directory + '/' + 'DB.zip'
zip_dir = zipfile.ZipFile(zip_file, "w",)

for file in pr_path:
    if 'SFF' in file:
        continue
    if any(x in file for x in my_set):
        zip_dir.write(file, compress_type=zipfile.ZIP_DEFLATED)

zip_dir.close()

This seems to work fine for me. Hope I was of help.


问:
How do I center a PDFSelection within the overall View?
I'm trying to use PDFKit with Swift in iOS 11. I have a PDFView and a PDFSelection that I would like to scroll to, zoom in to, and center within the overall view. I'm able to scroll to the PDFView's currentSelection with the function scrollSelectionToVisible(_ sender: Any?), but the selection always appear in the upper left of the screen.

How can I reposition the page to make the selection be at the center?

I know a PDFSelection has a bounds(for: PDFPage) function that returns a CGRect, in page space. But I don't know what to do with it beyond that.

What I currently see with after pdfView.scrollSelectionToVisible() (currentSelection in green upper left):

What I'd like to see (currentSelection in center of view):

This:

```<code>pdfView.currentSelection = selection
pdfView.scrollSelectionToVisible(nil)
</code>```

And this:

```<code>pdfView.currentSelection = selection
let pdfPage = pdfView.document!.page(at: 0)!
let cgRect = pdfView.currentSelection!.bounds(for: pdfPage)
pdfView.go(to: cgRect, on: pdfPage)
</code>```

are producing the same effect (the effect in the first image).

答:
After you create the PDFviewer center the view like this</p>

```<code>let pdfView = PDFView(frame: viewFA.view.bounds)
pdfView.center.y = viewFA.view.center.y - 100
</code>```

Body:
I'm trying to use PDFKit with Swift in iOS 11. I have a PDFView and a PDFSelection that I would like to scroll to, zoom in to, and center within the overall view. I'm able to scroll to the PDFView's currentSelection with the function scrollSelectionToVisible(_ sender: Any?), but the selection always appear in the upper left of the screen.

How can I reposition the page to make the selection be at the center?

I know a PDFSelection has a bounds(for: PDFPage) function that returns a CGRect, in page space. But I don't know what to do with it beyond that.

What I currently see with after pdfView.scrollSelectionToVisible() (currentSelection in green upper left):

What I'd like to see (currentSelection in center of view):

This:

pdfView.currentSelection = selection
pdfView.scrollSelectionToVisible(nil)

And this:

pdfView.currentSelection = selection
let pdfPage = pdfView.document!.page(at: 0)!
let cgRect = pdfView.currentSelection!.bounds(for: pdfPage)
pdfView.go(to: cgRect, on: pdfPage)

are producing the same effect (the effect in the first image).

Body:
After you create the PDFviewer center the view like this

let pdfView = PDFView(frame: viewFA.view.bounds)
pdfView.center.y = viewFA.view.center.y - 100


问:
How to exit a python script called in a Flask app?
I have a flask app where I am reusing a function in a python script (poll_servers.py). I can import the function and run it but I want to put a check in place that exits the function if it's running.

Here is my code in the python script:

```<code>import os
import sys

# check if lock file exists, exit
if os.path.exists('static/poll.lock'):
    sys.exit(1)

if not os.path.exists('static/poll.lock'):
    with open('static/poll.lock', 'w'): pass
</code>```

In my app.py I have:

```<code>from poll_servers import poll

@app.route('/poll_servers', methods=['GET'])
def poll_servers():

    response = json.dumps({'status':'OK'})

    poll()

    return response
</code>```

I get an error on the sys.exit(1) in poll_servers.py:

```<code>File "app.py", line 109, in poll_servers
  poll()
File ".../poll_servers.py", line 262, in poll
  sys.exit(1)
File ".../venv/lib/python2.7/site.py", line 403, in __call__
  raise SystemExit(code)
SystemExit: None
</code>```

Any ideas? If I run the poll_servers.py on its own the sys.exit(1) works fine.

答:
Then just don't do anything or flip the order of your if statement:

```<code>import os
import sys

if not os.path.exists('static/poll.lock'):

    with open('static/poll.lock', 'w'):

        pass

else:

    pass
    # do something
</code>```

Body:
I have a flask app where I am reusing a function in a python script (poll_servers.py). I can import the function and run it but I want to put a check in place that exits the function if it's running.

Here is my code in the python script:

import os
import sys

# check if lock file exists, exit
if os.path.exists('static/poll.lock'):
    sys.exit(1)

if not os.path.exists('static/poll.lock'):
    with open('static/poll.lock', 'w'): pass

In my app.py I have:

from poll_servers import poll

@app.route('/poll_servers', methods=['GET'])
def poll_servers():

    response = json.dumps({'status':'OK'})

    poll()

    return response

I get an error on the sys.exit(1) in poll_servers.py:

File "app.py", line 109, in poll_servers
  poll()
File ".../poll_servers.py", line 262, in poll
  sys.exit(1)
File ".../venv/lib/python2.7/site.py", line 403, in __call__
  raise SystemExit(code)
SystemExit: None

Any ideas? If I run the poll_servers.py on its own the sys.exit(1) works fine.

Body:
Then just don't do anything or flip the order of your if statement:

import os
import sys

if not os.path.exists('static/poll.lock'):

    with open('static/poll.lock', 'w'):

        pass

else:

    pass
    # do something


问:
Set a specific environment for ng e2e tests in angular 7 without serving the app
I recently upgraded my application to angular 7. I am trying to run my ng e2e tests using a specific environment. Also, I do not wish to run a new server every time I run e2e tests for the application.

When using angular 5, I used to do it the following way using CLI:

```<code>ng e2e -e test --config protractor.conf.test.js --no-serve
</code>```

where my test environment was set in the environment.test.ts file and protractor configurations (baseURL and headless browser) were set in the protractor.conf.test.js file. I used the no-serve flag to stop running a new server everytime the e2e tests are run.

For angular 7, I made the following changes in the angular.json file:

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "sample-app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": ["src/assets", "src/favicon.ico"],
            "styles": ["src/styles.css"],
            "scripts": []
          },
          "configurations": {
            "production": {
                ...
            },
            "test": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.test.ts"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "sample-app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "sample-app:build:production"
            },
            "test": {
              "browserTarget": "sample-app:build:test"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "sample-app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [],
            "styles": ["src/styles.css"],
            "assets": ["src/assets", "src/favicon.ico"]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": ["src/tsconfig.app.json",
"src/tsconfig.spec.json"],
            "exclude": ["**/node_modules/**"]
          }
        }
      }
    },
    "sample-app-e2e": {
      "root": "e2e",
      "sourceRoot": "e2e",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "./protractor.conf.js",
            "devServerTarget": "sample-app:serve"
          },
          "configurations": {
            "test": {
              "protractorConfig": "./protractor.conf.test.js",
              "devServerTarget": ""
            },
            "production": {
              "protractorConfig": "./protractor.conf.prod.js",
              "devServerTarget": ""
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": ["e2e/tsconfig.e2e.json"],
            "exclude": ["**/node_modules/**"]
          }
        }
      }
    }
  },
  "defaultProject": "sample-app",
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "styleext": "css"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}
</code>```

I set the "test" configuration under build configurations and the browserTarget under serve configurations.

Coming to the sample-app-e2e JSON:

protractorConfig: points to the relevant protractor config file (protractor.conf.test.js).

empty devServerTarget: equivalent to the --no-serve flag.

Then I run the e2e test using the CLI as:

```<code>ng e2e --configuration=test
</code>```

Now, how do I set a specific environment to use for e2e tests? I know one way it can be set is through the devServerTarget property. For e.g.:

```<code>"devServerTarget": "sample-app:serve:test"
</code>```

but this will also mean that the --no-serve flag will not be honored.

Is there any way to achieve both outcomes (specific environment + no-serve)? Appreciate the help.

答:
Simply put, you have to ignore totally the angular cli. I went insane, nothing works and in my case I have an extremely large project. I have to wait several minutes each time.

Run a shell with ng serve and run another shell with protractor e2e/your-conf.js

Body:
I recently upgraded my application to angular 7. I am trying to run my ng e2e tests using a specific environment. Also, I do not wish to run a new server every time I run e2e tests for the application.

When using angular 5, I used to do it the following way using CLI:

ng e2e -e test --config protractor.conf.test.js --no-serve

where my test environment was set in the environment.test.ts file and protractor configurations (baseURL and headless browser) were set in the protractor.conf.test.js file. I used the no-serve flag to stop running a new server everytime the e2e tests are run.

For angular 7, I made the following changes in the angular.json file:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "sample-app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": ["src/assets", "src/favicon.ico"],
            "styles": ["src/styles.css"],
            "scripts": []
          },
          "configurations": {
            "production": {
                ...
            },
            "test": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.test.ts"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "sample-app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "sample-app:build:production"
            },
            "test": {
              "browserTarget": "sample-app:build:test"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "sample-app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [],
            "styles": ["src/styles.css"],
            "assets": ["src/assets", "src/favicon.ico"]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": ["src/tsconfig.app.json",
"src/tsconfig.spec.json"],
            "exclude": ["**/node_modules/**"]
          }
        }
      }
    },
    "sample-app-e2e": {
      "root": "e2e",
      "sourceRoot": "e2e",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "./protractor.conf.js",
            "devServerTarget": "sample-app:serve"
          },
          "configurations": {
            "test": {
              "protractorConfig": "./protractor.conf.test.js",
              "devServerTarget": ""
            },
            "production": {
              "protractorConfig": "./protractor.conf.prod.js",
              "devServerTarget": ""
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": ["e2e/tsconfig.e2e.json"],
            "exclude": ["**/node_modules/**"]
          }
        }
      }
    }
  },
  "defaultProject": "sample-app",
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "styleext": "css"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}

I set the "test" configuration under build configurations and the browserTarget under serve configurations.

Coming to the sample-app-e2e JSON:

protractorConfig: points to the relevant protractor config file (protractor.conf.test.js).

empty devServerTarget: equivalent to the --no-serve flag.

Then I run the e2e test using the CLI as:

ng e2e --configuration=test

Now, how do I set a specific environment to use for e2e tests? I know one way it can be set is through the devServerTarget property. For e.g.:

"devServerTarget": "sample-app:serve:test"

but this will also mean that the --no-serve flag will not be honored.

Is there any way to achieve both outcomes (specific environment + no-serve)? Appreciate the help.


问:
Every minute changing and taking data from an array that follows a random path each day
How to, Every minute changing and taking data from an array that follows a random path each day.

In fact every single minute in a day will change a key.
And every day will follow a random path, not the same thing.

I tried something below, "Of course this is completely exemplary"

```<code>$pattern_1 = array(1,0,2,4,3);
$pattern_2 = array(0,4,1,3,2);
$pattern_3 = array(2,1,3,0,4);
...
$pattern_31 = array(0,4,3,1,2);

$key = array("key1","key2","key3","key4","key5");

$pattern = array($patternt_1, $patternt_2, $patternt_3, ... $patternt_31);

$day = date('j'); // 0 - 31

$hour = date('G'); // 0 - 24

echo $key[$pattern[$day][$hour]];
</code>```

答:
You can use rand function. For example

$keys = ["key1", "key2", ... "keyn"];
echo $keys[rand(0, count($keys) - 1)];
```

UPD

If you just want to generate random string please take a look on this answer

Body:
How to, Every minute changing and taking data from an array that follows a random path each day.

In fact every single minute in a day will change a key.
And every day will follow a random path, not the same thing.

I tried something below, "Of course this is completely exemplary"

$pattern_1 = array(1,0,2,4,3);
$pattern_2 = array(0,4,1,3,2);
$pattern_3 = array(2,1,3,0,4);
...
$pattern_31 = array(0,4,3,1,2);

$key = array("key1","key2","key3","key4","key5");

$pattern = array($patternt_1, $patternt_2, $patternt_3, ... $patternt_31);

$day = date('j'); // 0 - 31

$hour = date('G'); // 0 - 24

echo $key[$pattern[$day][$hour]];

Body:
You can use rand function. For example

$keys = ["key1", "key2", ... "keyn"];
echo $keys[rand(0, count($keys) - 1)];

UPD

If you just want to generate random string please take a look on this answer


问:
WebRTC H264 connection - strange profile-level-id
I'm trying to establish WebRTC connection between an RTSP camera and a browser.
The cam creates a nice h264 stream which plays well in VLC player.
For WebRTC I'm using Janus.

The camera stream is not playing in either Chrome, either FF, because it offers a strange profile-level-id: ffffc028.

If I force Janus to offer a well-known profile-level-id (which is obviously a hack!), Chrome could play the stream but FF crashes immediately after the first keyframe reception.

Camera stream is created by v4l2rtspserver.

Please help me to identify where this profile-level-id.

Is it valid at all?

答: Browsers can / should be able to decode pretty much any H264 stream via WebRTC, encoded with any profile-level, so the issue seems to be with Firefox's H264 decoder. Forcing well-known profile-level-id is the right thing to do, from my experience; this is just WebRTC formalism. The decoder figures correct profile-level from the actual H264 bytestream. Make sure you configure your encoder to attach correct SPS-PPS nalus to every key frame.</p>


问:
Unit testing, statics, and factories
I am implementing a model in Java which requires iterating over a collection and going through a number of identification stages, it involves for loops, while loops etc. It is the sort of thing I want to test at a fine-grained level so that I have confidence it has been implemented properly.

I have used it as an opportunity to start unit testing, as it is something I recognise as being beneficial to my code. I have since been reading a forest of books to get up to speed with JUnit and unit testing.

Basically my question comes down to two conflicting pieces of advice I have received:

1) Statics are evil. Do not touch statics. Do not test privates either, you probably want a class there instead.

2) Use factories for creation to allow dependency injection using parameters - potentially allowing use of mocks and stubs for isolation.

In my example I am looking to perform an operation along the lines of:

```<code>double height = 223.42; // this was set iterating over a collection of doubles
//blah
HeightBounds b = HeightBounds.getHeightBounds(height);
//more blah
</code>```

I have done this in order to avoid building up what would become a very long and complicated block of code, which I can only test in its entirety. This way I have public accessible objects that I can test to ensure the system components all perform correctly.

Common sense says to me there is nothing wrong with static factories, and that they are easily tested, but am I missing something blindingly obvious given I am learning test-driven design?

Thank you

答:
Static methods are not evil per se. Look in JDK how many of them are there. Static methods also need to be unit tested, so if you have any go on and test them.

So it's not true that static methods kill unit testing.

But if you make statics only to write less code in unit tests then it is a wrong path since as others have stated you should better use your objects using your usual API - since this is what you want to test.

And full ACK for writing tests first - it will also help you design better API, cut you classes right.

Title: Unit testing, statics, and factories

Body:
I am implementing a model in Java which requires iterating over a collection and going through a number of identification stages, it involves for loops, while loops etc. It is the sort of thing I want to test at a fine-grained level so that I have confidence it has been implemented properly.

I have used it as an opportunity to start unit testing, as it is something I recognise as being beneficial to my code. I have since been reading a forest of books to get up to speed with JUnit and unit testing.

Basically my question comes down to two conflicting pieces of advice I have received:

1) Statics are evil. Do not touch statics. Do not test privates either, you probably want a class there instead.

2) Use factories for creation to allow dependency injection using parameters - potentially allowing use of mocks and stubs for isolation.

In my example I am looking to perform an operation along the lines of:

double height = 223.42; // this was set iterating over a collection of doubles
//blah
HeightBounds b = HeightBounds.getHeightBounds(height);
//more blah

I have done this in order to avoid building up what would become a very long and complicated block of code, which I can only test in its entirety. This way I have public accessible objects that I can test to ensure the system components all perform correctly.

Common sense says to me there is nothing wrong with static factories, and that they are easily tested, but am I missing something blindingly obvious given I am learning test-driven design?

Thank you


问:
Deserialize Newtonsoft Json data with Dynamic property name - C#
I have referred to this question, which is similar to my issue but unable to fix the issue completely since the data structure is different and I am not able to figure-out how to apply this solution to my example data given below:

```<code>{
    "result": {
        "RITM2572913": {
            "number": "RITM2572913",
            "state": "1",
            "stage": "fulfillment",
            "Sys_ID": "220e89681b31b384e3a0a79b2d4bcbf3",
            "requested_for": "1d1673c4dbda5b0072a85099dc9619b0",
            "Contoso_requested_for": "requested_for:1d1673c4dbda5b0072a85099dc9619b0,var_name_arr:",
            "Contoso_sc_Purposeofthef5request": "Add",
            "Contoso_Sc_Contactinfo": "Contact ",
            "Contoso_sc_Appname": "Application ",
            "Contoso_sc_Description": "Description",
            "Contoso_special_instructions": "special_instructions:",
            "business_justification": "Justification ",
            "Contoso_business_justification": "busess_justification:Justification",
            "Contoso_catalog_item_footer": "owner_info:"
        }
    }
}
</code>```

I have the response data like this and need to de-serialize it to fit in the object model given below:

```<code>public class RITMGETRequestResponse
{
    public RITMDetails result { get; set; }

    public class RITMDetails
    {
        public string business_justification { get; set; }
        public string number { get; set; }
        public string requested_for { get; set; }
        public string stage { get; set; }
        public string state { get; set; }
        public string Sys_ID { get; set; }
        public string var_name_arr { get; set; }
        public string Contoso_business_justification { get; set; }
        public string Contoso_catalog_item_footer { get; set; }
        public string Contoso_requested_for { get; set; }
        public string Contoso_sc_Appname { get; set; }
        public string Contoso_Sc_Contactinfo { get; set; }
        public string Contoso_sc_Description { get; set; }
        public string Contoso_sc_Purposeofthef5request { get; set; }
        public string Contoso_special_instructions { get; set; }
    }
}
</code>```

In this case RITM number is dynamic. I need to get the Sys_ID and other properties of this JSON. How do I de-serialize this JSON response to get these values?

答:
straightforward example:

used a JSONProperty attribute to map result values of a dynamic property name

```<code>class Program
{
    static void Main(string[] args)
    {
        var deserialise = JsonConvert.DeserializeObject<RITMRequestResponse>("{\"result\": {\"123\" : { \"number\" : \"123\" }}}");

        Console.WriteLine(deserialise);
        Console.ReadLine();
    }
}

public class RITMRequestResponse
{
    [JsonProperty(PropertyName = "result")]
    public Dictionary<string, RITMDetails> RITMDetails { get; set; }
}

public class RITMDetails
{
    public string Number { get; set; }
}
</code>```

Body:
I have referred to this question, which is similar to my issue but unable to fix the issue completely since the data structure is different and I am not able to figure-out how to apply this solution to my example data given below:

{
    "result": {
        "RITM2572913": {
            "number": "RITM2572913",
            "state": "1",
            "stage": "fulfillment",
            "Sys_ID": "220e89681b31b384e3a0a79b2d4bcbf3",
            "requested_for": "1d1673c4dbda5b0072a85099dc9619b0",
            "Contoso_requested_for": "requested_for:1d1673c4dbda5b0072a85099dc9619b0,var_name_arr:",
            "Contoso_sc_Purposeofthef5request": "Add",
            "Contoso_Sc_Contactinfo": "Contact ",
            "Contoso_sc_Appname": "Application ",
            "Contoso_sc_Description": "Description",
            "Contoso_special_instructions": "special_instructions:",
            "business_justification": "Justification ",
            "Contoso_business_justification": "busess_justification:Justification",
            "Contoso_catalog_item_footer": "owner_info:"
        }
    }
}

I have the response data like this and need to de-serialize it to fit in the object model given below:

public class RITMGETRequestResponse
{
    public RITMDetails result { get; set; }

    public class RITMDetails
    {
        public string business_justification { get; set; }
        public string number { get; set; }
        public string requested_for { get; set; }
        public string stage { get; set; }
        public string state { get; set; }
        public string Sys_ID { get; set; }
        public string var_name_arr { get; set; }
        public string Contoso_business_justification { get; set; }
        public string Contoso_catalog_item_footer { get; set; }
        public string Contoso_requested_for { get; set; }
        public string Contoso_sc_Appname { get; set; }
        public string Contoso_Sc_Contactinfo { get; set; }
        public string Contoso_sc_Description { get; set; }
        public string Contoso_sc_Purposeofthef5request { get; set; }
        public string Contoso_special_instructions { get; set; }
    }
}

In this case RITM number is dynamic. I need to get the Sys_ID and other properties of this JSON. How do I de-serialize this JSON response to get these values?

Body:
straightforward example:

used a JSONProperty attribute to map result values of a dynamic property name

class Program
{
    static void Main(string[] args)
    {
        var deserialise = JsonConvert.DeserializeObject<RITMRequestResponse>("{\"result\": {\"123\" : { \"number\" : \"123\" }}}");

        Console.WriteLine(deserialise);
        Console.ReadLine();
    }
}

public class RITMRequestResponse
{
    [JsonProperty(PropertyName = "result")]
    public Dictionary<string, RITMDetails> RITMDetails { get; set; }
}

public class RITMDetails
{
    public string Number { get; set; }
}


问:
Azure Sphere MT3620 retry later to send to IoT hub
Trying to find any information regarding storing local information on Azure Sphere MT3620 device if the connection was lost. Some sort of failback storage for later retry?

Example

```<code>Try to send a timestamp that the button was press to Azure IoT Hub
Connection failed due to the wifi router was unplugged.
Save that event to some type of on non-volatile storage.
When the chip does comes online the ship send all of the data that it was unable to send when it was offline.
</code>```

Read that the chip has two cores, is it possible to set one to log and the other to send if failure so that core does not block the io events?

答:
You can use mutable storage type of Azure Sphere. Mutable storage stores data that persists when a device reboots. See here how to do it.

[Edit] The Azure Sphere 19.05 release unlocked the real-time capable cores that reside on the MT3620 (ARM Cortex-M4F). The OS and SDK support development, deployment, and debugging SPI, I2C, GPIO, UART and ADC real-time capable apps on the MT3620’s two M4 cores.

Body:
Trying to find any information regarding storing local information on Azure Sphere MT3620 device if the connection was lost. Some sort of failback storage for later retry?

Example

Try to send a timestamp that the button was press to Azure IoT Hub
Connection failed due to the wifi router was unplugged.
Save that event to some type of on non-volatile storage.
When the chip does comes online the ship send all of the data that it was unable to send when it was offline.

Read that the chip has two cores, is it possible to set one to log and the other to send if failure so that core does not block the io events?


问:
How to set 'X-Frame-Options' on iframe?
If I create an iframe like this:

```<code>var dialog = $('<div id="' + dialogId + '" align="center"><iframe id="' + frameId + '" src="' + url + '" width="100%" frameborder="0" height="'+frameHeightForIe8+'" data-ssotoken="' + token + '"></iframe></div>').dialog({
</code>```

How can I fix the error:

Refused to display 'https://www.google.com.ua/?gws_rd=ssl' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

with JavaScript?

答:
you can do it in tomcat instance level config file (web.xml)
need to add the 'filter' and filter-mapping' in web.xml config file.
this will add the [X-frame-options = DENY] in all the page as it is a global setting.</p>

```<code><filter>
        <filter-name>httpHeaderSecurity</filter-name>
        <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
          <param-name>antiClickJackingEnabled</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <param-name>antiClickJackingOption</param-name>
          <param-value>DENY</param-value>
        </init-param>
    </filter>

  <filter-mapping>
    <filter-name>httpHeaderSecurity</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

Title: How to set 'X-Frame-Options' on iframe?

Body:
If I create an iframe like this:

var dialog = $('

').dialog({

How can I fix the error:

Refused to display 'https://www.google.com.ua/?gws_rd=ssl' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

with JavaScript?

Body:
you can do it in tomcat instance level config file (web.xml)
need to add the 'filter' and filter-mapping' in web.xml config file.
this will add the [X-frame-options = DENY] in all the page as it is a global setting.

<filter>
        <filter-name>httpHeaderSecurity</filter-name>
        <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
          <param-name>antiClickJackingEnabled</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <param-name>antiClickJackingOption</param-name>
          <param-value>DENY</param-value>
        </init-param>
    </filter>

  <filter-mapping>
    <filter-name>httpHeaderSecurity</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


问:
Ignoring merge commits for prepare-commit-msg git hook
I came up with the following prepare-commit-msg git hook:

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

BRANCH=`git branch | grep '^*' | sed -e 's/^\* //'`
MESSAGE=`cat "$1"`
JIRA_ID=$(echo "$BRANCH" | grep -Eo "[A-Z0-9]{1,10}-?[A-Z0-9]+-\d+")

if [ -z "$JIRA_ID" ]; then
    echo "$MESSAGE" > "$1"
else
    echo "[$JIRA_ID] $MESSAGE" > "$1"
fi
</code>```

It does its job by adding branch name (which is in a form of BRANCH-123) to every commit message. However, I don't want this to work with merge commits which have auto-generate commit messages s.a. Merge branch 'master' into BRANCH-123. Which with my hook converts into BRANCH-123 Merge branch 'master' into BRANCH-123

I need to edit the script to somehow ignore (not apply the hook) commits starting with Merge branch.

答:
As the document of prepare-commit-msg says,

It takes one to three parameters. The first is the name of the file
that contains the commit log message. The second is the source of the
commit message, and can be: message (if a -m or -F option was given);
template (if a -t option was given or the configuration option
commit.template is set); merge (if the commit is a merge or a
.git/MERGE_MSG file exists); squash (if a .git/SQUASH_MSG file
exists); or commit, followed by a commit SHA-1 (if a -c, -C or --amend
option was given).

We can test the 2nd parameter and exit with 0 if it's merge:

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

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

if [ "${COMMIT_SOURCE}" = merge ];then
    exit 0
fi
</code>```

Body:
I came up with the following prepare-commit-msg git hook:

#!/bin/sh

BRANCH=`git branch | grep '^*' | sed -e 's/^\* //'`
MESSAGE=`cat "$1"`
JIRA_ID=$(echo "$BRANCH" | grep -Eo "[A-Z0-9]{1,10}-?[A-Z0-9]+-\d+")

if [ -z "$JIRA_ID" ]; then
    echo "$MESSAGE" > "$1"
else
    echo "[$JIRA_ID] $MESSAGE" > "$1"
fi

It does its job by adding branch name (which is in a form of BRANCH-123) to every commit message. However, I don't want this to work with merge commits which have auto-generate commit messages s.a. Merge branch 'master' into BRANCH-123. Which with my hook converts into BRANCH-123 Merge branch 'master' into BRANCH-123

I need to edit the script to somehow ignore (not apply the hook) commits starting with Merge branch.

Body:
As the document of prepare-commit-msg says,

It takes one to three parameters. The first is the name of the file
that contains the commit log message. The second is the source of the
commit message, and can be: message (if a -m or -F option was given);
template (if a -t option was given or the configuration option
commit.template is set); merge (if the commit is a merge or a
.git/MERGE_MSG file exists); squash (if a .git/SQUASH_MSG file
exists); or commit, followed by a commit SHA-1 (if a -c, -C or --amend
option was given).

We can test the 2nd parameter and exit with 0 if it's merge:

#!/bin/bash

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

if [ "${COMMIT_SOURCE}" = merge ];then
    exit 0
fi


问:
Cakephp 3 giving date and time fields in frozentime object
I am using cakephp 3.2 and when i am retrieving data by find query it is giving date fields in this format

```<code>Array
(
[0] => Cake\I18n\FrozenDate Object
    (
        [date] => 2016-08-01 00:00:00
        [timezone_type] => 3
        [timezone] => UTC
    )
)
</code>```

and time fields in frozentime

```<code>Cake\I18n\FrozenTime Object
(
 [date] => 2016-10-11 10:00:00
 [timezone_type] => 3
 [timezone] => UTC
)
</code>```

I need a common setting or global solution for complete site. So when i fetch the data by find query from database it should give me date time in simple format without any frozendate object.

like this

```<code>Array(
 [0] => 2016-08-01
)
</code>```

答:
Simply call ->format('Y-m-d') on your Cake\I18n\FrozenDate object.

There's no need for Cake\I18n\FrozenDate::setToStringFormat() or $this->Time->format()

Body:
I am using cakephp 3.2 and when i am retrieving data by find query it is giving date fields in this format

Array
(
[0] => Cake\I18n\FrozenDate Object
    (
        [date] => 2016-08-01 00:00:00
        [timezone_type] => 3
        [timezone] => UTC
    )
)

and time fields in frozentime

Cake\I18n\FrozenTime Object
(
 [date] => 2016-10-11 10:00:00
 [timezone_type] => 3
 [timezone] => UTC
)

I need a common setting or global solution for complete site. So when i fetch the data by find query from database it should give me date time in simple format without any frozendate object.

like this

Array(
 [0] => 2016-08-01
)


答:
You don't tell us for which use you need an ever changing code, but why don't you simply use a proper random function as mt_rand() to generate a random code?

Then, if you need it to remain the same for one minute, you can save it in a php file with its timestamp, and then you always load it, check if a minute has passed and generate a new one if that is the case, then save it back:

```<code>$stamp=time();
$key=mt_rand(0,4);

include("store.php");

if (time()-$stamp>60):
   $stamp=time();
   $key=mt_rand(0,4);
endif;

file_put_contents("store.php","<"."?php $"."stamp=".$stamp.";$"."key=".$key.";");
</code>```

Title: Every minute changing and taking data from an array that follows a random path each day

Body:
You don't tell us for which use you need an ever changing code, but why don't you simply use a proper random function as mt_rand() to generate a random code?

Then, if you need it to remain the same for one minute, you can save it in a php file with its timestamp, and then you always load it, check if a minute has passed and generate a new one if that is the case, then save it back:

$stamp=time();
$key=mt_rand(0,4);

include("store.php");

if (time()-$stamp>60):
   $stamp=time();
   $key=mt_rand(0,4);
endif;

file_put_contents("store.php","<"."?php $"."stamp=".$stamp.";$"."key=".$key.";");