问:
Not getting APNS Device token on ios 13
I have issue related to APNS device token . Before I was using Xcode 10.2 and iOS 12.1. At this moment I used to get the device token in delegate method

```<code>-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
</code>```

I am registering for APNS like this  and it was working fine.

```<code>UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
                if(!error){
                    [[UIApplication sharedApplication] registerForRemoteNotifications];
                }
    }];
</code>```

Now when installed iOS 13 to my iPhone device and using Xcode 11 , the delegate method didRegisterForRemoteNotificationsWithDeviceToken is not called. Unable to understand this problem .
I have already done research over this , I know there are some changes in getting token from the delegate method but in my case delegate method is not even called. Again it's working fine for iOS 12.

答:
Logon on https://appleid.apple.com/, then open url "https://developer.apple.com/account/ios/identifier/bundle"
or "https://developer.apple.com/account/resources/certificates/list".

First, Create two New Certificates:
(1)Apple Development
Sign development versions of your iOS, macOS, tvOS, and watchOS apps. For use in Xcode 11 or later.
(2)Apple Distribution
Sign your apps for submission to the App Store or for Ad Hoc distribution. For use with Xcode 11 or later.

Then find menu "Identifiers" via url "https://developer.apple.com/account/resources/identifiers/list".
Edit your Identifiers of your app, make sure that Development SSL Certificate  & Production SSL Certificate is added to the Push Notifications.

Next, open menu "Profiles" via url "https://developer.apple.com/account/resources/profiles/list".
Make sure that the Certificates as type of  DistributionFor which will be used in Xcode 11 or late, and save

Lastly, download the Provisioning Profile file and the CA Certificates files created to your MAC, which will be added to  XCode and key-chain application by double click the files separately.

What's more, remember to reboot your cell phone, and  make sure that you had setup the remote notification correctly.

Title: Not getting APNS Device token on ios 13

Body:
I have issue related to APNS device token . Before I was using Xcode 10.2 and iOS 12.1. At this moment I used to get the device token in delegate method

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

I am registering for APNS like this  and it was working fine.

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
                if(!error){
                    [[UIApplication sharedApplication] registerForRemoteNotifications];
                }
    }];

Now when installed iOS 13 to my iPhone device and using Xcode 11 , the delegate method didRegisterForRemoteNotificationsWithDeviceToken is not called. Unable to understand this problem .
I have already done research over this , I know there are some changes in getting token from the delegate method but in my case delegate method is not even called. Again it's working fine for iOS 12.


来源: stackexchange

问:
Searching in a Bitonic Array becomes infinite loop
I am trying to write a searching algorithm in a bitonic array. Please take a look in the ascending function, where I am printing 'lo'. When I run this code, it keeps print that 'lo' number. I don't understand why it becomes infinite loop there. Here is my code:

```<code>public class bitonicArray {

    public int ascending(int[] a, int key, int lo, int hi) {
        int mid = lo+(hi-lo)/2;
        while(lo<=hi) {
            if (key<a[mid]) hi = mid-1;
            else if (key>a[mid]) {
                lo=mid+1;
                System.out.println(lo);
            }
            else return mid;
        }
        return -1;
    }

    public int descending(int[] a, int key, int lo, int hi) {
        int mid=lo+(hi-lo)/2;
        while(lo<=hi) {
            if(key<a[mid]) lo = mid+1;
            else if(key>a[mid]) {
                hi = mid-1;
            }
            else return mid;
        }
        return -1;
    }

    public int bitonicPoint(int[] a) {
        int hi = a.length-1;
        int lo = 0;
        int mid = (hi-lo)/2;
        while(mid<=hi) {
            if (a[mid-1] < a[mid] && a[mid+1]>a[mid]) mid = mid + 1;
            else if (a[mid-1] > a[mid] && a[mid+1]<a[mid]) mid = mid - 1;
            else if (a[mid-1]<a[mid] && a[mid+1]<a[mid]) return mid;
        }
        return -1;
    }

    public int ind(int[] a, int key) {
        int lo = 0;
        int hi = a.length-1;
        int bit = bitonicPoint(a);
        int asc = ascending(a, key, lo, bit-1);
        System.out.println(asc);
        int desc = descending(a, key, bit+1, hi);
        if (asc != -1) {
            System.out.println(asc);
            return asc;
        }
        else if (desc != -1) return desc;
        else return bit;
    }

    public static void main(String[] args) {
        int n[]= {1,3,4,6,9,14,11,7,2,-4,-9};
        bitonicArray ba = new bitonicArray();
        System.out.println(ba.ind(n, 6));
    }
}
</code>```

Please help with this. I am pretty new in Java. I am a Python user. Trying to learn Java.

答:
In this part of code fragment you are not updating your mid value

```<code>public int ascending(int[] a, int key, int lo, int hi) {
    int mid = lo+(hi-lo)/2;
    while(lo<=hi) {
        if (key<a[mid]) hi = mid-1;
        else if (key>a[mid]) {
            lo=mid+1;
            System.out.println(lo);
        }
        else return mid;
    }
    return -1;
}
</code>```

Initially when this function is called from ind function , value of lo is 0 and hi is 4.
So, mid value is 2.
Because of this in while loop it goes in this part :

```<code> else if (key>a[mid]) {
            lo=mid+1;
            System.out.println(lo);
 }
</code>```

Hence you get your first lo value printed , but then you have updated lo value but not
mid.
Because of which every time mid is at 2 and in while loop each time it goes in same code fragment. You need to update value of mid because it is dependent on lo and hi and in the above else if part you have updated value of lo.

Corrected code is :

```<code>public int ascending(int[] a, int key, int lo, int hi) {
    int mid = 0;
    while(lo<=hi) {
        mid = lo+(hi-lo)/2;
        if (key<a[mid]) hi = mid-1;
        else if (key>a[mid]) {
            lo=mid+1;
            System.out.println(lo);
        }
        else return mid;
    }
    return -1;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a searching algorithm in a bitonic array. Please take a look in the ascending function, where I am printing 'lo'. When I run this code, it keeps print that 'lo' number. I don't understand why it becomes infinite loop there. Here is my code:

public class bitonicArray {

    public int ascending(int[] a, int key, int lo, int hi) {
        int mid = lo+(hi-lo)/2;
        while(lo<=hi) {
            if (keya[mid]) {
                lo=mid+1;
                System.out.println(lo);
            }
            else return mid;
        }
        return -1;
    }

    public int descending(int[] a, int key, int lo, int hi) {
        int mid=lo+(hi-lo)/2;
        while(lo<=hi) {
            if(keya[mid]) {
                hi = mid-1;
            }
            else return mid;
        }
        return -1;
    }

    public int bitonicPoint(int[] a) {
        int hi = a.length-1;
        int lo = 0;
        int mid = (hi-lo)/2;
        while(mid<=hi) {
            if (a[mid-1] a[mid]) mid = mid + 1;
            else if (a[mid-1] > a[mid] && a[mid+1]<a[mid]) mid = mid - 1;
            else if (a[mid-1]<a[mid] && a[mid+1]<a[mid]) return mid;
        }
        return -1;
    }

    public int ind(int[] a, int key) {
        int lo = 0;
        int hi = a.length-1;
        int bit = bitonicPoint(a);
        int asc = ascending(a, key, lo, bit-1);
        System.out.println(asc);
        int desc = descending(a, key, bit+1, hi);
        if (asc != -1) {
            System.out.println(asc);
            return asc;
        }
        else if (desc != -1) return desc;
        else return bit;
    }

    public static void main(String[] args) {
        int n[]= {1,3,4,6,9,14,11,7,2,-4,-9};
        bitonicArray ba = new bitonicArray();
        System.out.println(ba.ind(n, 6));
    }
}

Please help with this. I am pretty new in Java. I am a Python user. Trying to learn Java.

Body:
In this part of code fragment you are not updating your mid value

public int ascending(int[] a, int key, int lo, int hi) {
    int mid = lo+(hi-lo)/2;
    while(lo<=hi) {
        if (key<a[mid]) hi = mid-1;
        else if (key>a[mid]) {
            lo=mid+1;
            System.out.println(lo);
        }
        else return mid;
    }
    return -1;
}

Initially when this function is called from ind function , value of lo is 0 and hi is 4.
So, mid value is 2.
Because of this in while loop it goes in this part :

 else if (key>a[mid]) {
            lo=mid+1;
            System.out.println(lo);
 }

Hence you get your first lo value printed , but then you have updated lo value but not
mid.
Because of which every time mid is at 2 and in while loop each time it goes in same code fragment. You need to update value of mid because it is dependent on lo and hi and in the above else if part you have updated value of lo.

Corrected code is :

public int ascending(int[] a, int key, int lo, int hi) {
    int mid = 0;
    while(lo<=hi) {
        mid = lo+(hi-lo)/2;
        if (key<a[mid]) hi = mid-1;
        else if (key>a[mid]) {
            lo=mid+1;
            System.out.println(lo);
        }
        else return mid;
    }
    return -1;
}


问:
Can't add scopes to my Azure AD application
I am trying to add new permissions to my Azure AD Application, however when I try, it gets stuck on a loading screen that has now lasted for more than half an hour. I tried different browsers (firefox, Chrome, Edge) with no different result.

A screenshot of the loading screen can be seen here.

EDIT:
Aditionally, I tried creating a new App, and I even created a whole new Account, however it didn't work.

答:
It might get stuck on the loading screen due to cache/cookies. I know it's kind of a pain, but you can try deleting the cache/cookies and opening an incognito window which should help it load.

If the issue persists it may require deeper troubleshooting. If you send me an email I can open a support case for you.

I checked Azure Status and it doesn't seem like there are any reported outages that could be causing this.


问:
Why does hello world print twice only and why is a's largest value 2
```<code>#include <stdio.h>
#include <unistd.h>

int main() {
    int a=0;
    int rc=fork();
    a++;
    if(rc=0)
    {
        rc=fork();

        a++;
    }
    else
    {
       a++;
    }
    printf("Hello World");
    printf("%d",a);

    return 0;
}
</code>```

答:
```<code>      int a=0; //a=0
      int rc=fork();
        a++;//a=1
      printf("A before the if else");
      printf("%d",a);// a=1

      if(rc==0)// this was rc=0 it should have been rc==0
        {
            rc=fork();
            a++;//a=2
            printf("A inside the if");
            printf("%d",a);// a=2

        }
        else
        {
            a++;//a=2
            printf("A inside the else");
            printf("%d",a);// a=2

        }
        printf("Hello World");// "Hello World"
        printf("%d",a);// a=2

        return 0;// always returns 0
</code>```

as to why it prints Hello world twice I can't say from the code given but you must be calling main twice. if your language has the ability I would use a stack trace() ( not a c developer )

Body:
      int a=0; //a=0
      int rc=fork();
        a++;//a=1
      printf("A before the if else");
      printf("%d",a);// a=1

      if(rc==0)// this was rc=0 it should have been rc==0
        {
            rc=fork();
            a++;//a=2
            printf("A inside the if");
            printf("%d",a);// a=2

        }
        else
        {
            a++;//a=2
            printf("A inside the else");
            printf("%d",a);// a=2

        }
        printf("Hello World");// "Hello World"
        printf("%d",a);// a=2

        return 0;// always returns 0

as to why it prints Hello world twice I can't say from the code given but you must be calling main twice. if your language has the ability I would use a stack trace() ( not a c developer )


问:
dynamically created mat-checkbox not correctly rendered
I create <mat-checkbox> elements dynamically from incoming data that fetched by API.

component.ts:

```<code>this.content = sanitizer.bypassSecurityTrustHtml(`<mat-checkbox>test</mat-checkbox>`)
</code>```

component.html

```<code><div [innerHTML]="content"></div>
</code>```

but the checkbox input is not rendered, the same issue occures if I used <input type="checkbox"> instead of `

and it rendered correctly if I added <mat-checkbox statically to component.html

please check this repo:
https://stackblitz.com/edit/angular-8heckn

note:

this.content is a string, not an object. because I want to add extra spaces (tabs) before each child input.

for instance:

programming

front-end

Angular

React

Vue

back-end

node.js

express.js

php

答:
"Angular doesn't process HTML added dynamically, it just adds it verbatim except some sanitization to prevent security issues." [see Stackoverflow question How to dynamically add innerHTML with angular 2 components]

To learn about adding Angular components dynamically, see the following:

Dynamically ADDING and REMOVING Components in Angular

Angular2: Insert a dynamic component as child of a container in the DOM

Angular: How to dynamically load a component defined by a string?

Body:
I create <mat-checkbox> elements dynamically from incoming data that fetched by API.

component.ts:

this.content = sanitizer.bypassSecurityTrustHtml(`<mat-checkbox>test</mat-checkbox>`)

component.html

but the checkbox input is not rendered, the same issue occures if I used <input type="checkbox"> instead of `

and it rendered correctly if I added <mat-checkbox statically to component.html

please check this repo:
https://stackblitz.com/edit/angular-8heckn

note:

this.content is a string, not an object. because I want to add extra spaces (tabs) before each child input.

for instance:

programming

front-end

Angular

React

Vue

back-end

node.js

express.js

php


问:
Watch file and write new contents to TableView
How can I watch a file and whenever it is written to insert the added contents to a NSTableView as a new row?</p>

答:
I'm not going to go into all the details of exactly how to do this, but I'm guessing that the sticking point for you is probably how to monitor a file in the filesystem.  If that's the case, the answer to this question should be useful:

Notification of changes to the iPhone's /Documents directory

ContentLicense: CC BY-SA 3.0


问:
Why do I get an error when this type exists in two assemblies even though I qualified the type?
Why do I get an error when this type exists in two assemblies even though I qualified the type?

```<code>loadingMachine = ProtoBuf.Serializer.Deserialize<CustomMachine>(f);
</code>```

Error CS0433  The type 'Serializer' exists in both 'devDept.Geometry.v2020, Version=2020.1.146.0, Culture=neutral, PublicKeyToken=9440825e8b4733bc' and 'protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67'   EyeShot test    J:\Jobb\DotnetDev\EyeShot Test\EyeShot test\EyeShot test\Form1.cs   49  Active

答:
This compiler error happens when there is 2 library referenced to the project, both having the same namespace/class name within, that you attempt to use.

If you cannot rename one, you need to set an alias for one.

Point of interest:

I found a worth to read answer in a related topic: using-directive solution (for inner classes) to prevent compilation error.

Body:
Why do I get an error when this type exists in two assemblies even though I qualified the type?

loadingMachine = ProtoBuf.Serializer.Deserialize<CustomMachine>(f);

Error CS0433  The type 'Serializer' exists in both 'devDept.Geometry.v2020, Version=2020.1.146.0, Culture=neutral, PublicKeyToken=9440825e8b4733bc' and 'protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67'   EyeShot test    J:\Jobb\DotnetDev\EyeShot Test\EyeShot test\EyeShot test\Form1.cs   49  Active


问:
Big O of Ugly Numbers Algorithm (Brute force method)
Link to problem: Ugly Numbers

How would you find the Big O of the brute force (Simple Method Approach) solution for Ugly-Numbers.

I see that for this part of the code:

```<code>    /* Function to check if a number is ugly or not */
int isUgly(int no)
{
  no = maxDivide(no, 2);
  no = maxDivide(no, 3);
  no = maxDivide(no, 5);

  return (no == 1)? 1 : 0;
}
</code>```

Each step takes log_2(x) + log_3(x) + log_5(x) steps, where x = no

So this would mean the runtime is (log_2(x) + log_3(x) + log_5(x))n where x is the result of the output. However, the result of an algorithm can't be a part of the Big O notation right? If it can't, this would be reduced to cn right? Where c > result. What is the proper method of proof for this?

答:
Ugly numbers are also also known as regular numbers. As you can see from the Wikipedia article, it is known that the number of regular numbers up to m is

```<code>(ln(m*sqrt(30))^3 / (6*ln(2)*ln(3)*ln(5)) + O(ln(m))
</code>```

In other words, your getNthUglyNo will call isUgly to get the n-th regular number

```<code>~ 1/sqrt(30) * exp((n*6*ln(2)*ln(3)*ln(5))^(1/3))
</code>```

times.

The probability that a uniform random integer number x between 0 and M is divisible by 2^y is asymptotically1/2^y and so the mean number of times that the loop in the call maxDivide(no, 2); iterates is O(1) and equivalently for maxDivide(no, 3); and maxDivide(no, 5);.

Consequently your algorithm is

```<code>Theta( exp((n*6*ln(2)*ln(3)*ln(5))^(1/3)) )
</code>```

which is approximately

```<code>Theta( exp(1.9446 * n^(1/3)) )
</code>```

Also note that plugging in n = 500 into the asymptotic number of iterations mentioned above does give you 921498, which is pretty close to the number of iterations @sowrov found in their answer (937500).

Body:
Link to problem: Ugly Numbers

How would you find the Big O of the brute force (Simple Method Approach) solution for Ugly-Numbers.

I see that for this part of the code:

    /* Function to check if a number is ugly or not */
int isUgly(int no)
{
  no = maxDivide(no, 2);
  no = maxDivide(no, 3);
  no = maxDivide(no, 5);

  return (no == 1)? 1 : 0;
}

Each step takes log_2(x) + log_3(x) + log_5(x) steps, where x = no

So this would mean the runtime is (log_2(x) + log_3(x) + log_5(x))n where x is the result of the output. However, the result of an algorithm can't be a part of the Big O notation right? If it can't, this would be reduced to cn right? Where c > result. What is the proper method of proof for this?

Body:
Ugly numbers are also also known as regular numbers. As you can see from the Wikipedia article, it is known that the number of regular numbers up to m is

(ln(m*sqrt(30))^3 / (6*ln(2)*ln(3)*ln(5)) + O(ln(m))

In other words, your getNthUglyNo will call isUgly to get the n-th regular number

~ 1/sqrt(30) * exp((n*6*ln(2)*ln(3)*ln(5))^(1/3))

times.

The probability that a uniform random integer number x between 0 and M is divisible by 2^y is asymptotically1/2^y and so the mean number of times that the loop in the call maxDivide(no, 2); iterates is O(1) and equivalently for maxDivide(no, 3); and maxDivide(no, 5);.

Consequently your algorithm is

Theta( exp((n*6*ln(2)*ln(3)*ln(5))^(1/3)) )

which is approximately

Theta( exp(1.9446 * n^(1/3)) )

Also note that plugging in n = 500 into the asymptotic number of iterations mentioned above does give you 921498, which is pretty close to the number of iterations @sowrov found in their answer (937500).


问:
Is it possible to assign a pod of StatefulSet to a specific node of a Kubernetes cluster?
I have a 5 node cluster(1-master/4-worker). Is it possible to configure a StatefulSet where I can make a pod(s) to run on a given node knowing it has sufficient capacity rather Kubernetes Scheduler making this decision?

Lets say, my StatefulSet create 4 pods(replicas: 4) as myapp-0,myapp-1,myapp-2 and myapp-3. Now what I am looking for is:

myapp-0 pod-- get scheduled over---> worker-1

myapp-1 pod-- get scheduled over---> worker-2

myapp-2 pod-- get scheduled over---> worker-3

myapp-3 pod-- get scheduled over---> worker-4

Please let me know if it can be achieved somehow? Because if I add a toleration to pods of a StatefulSet, it will be same for all the pods and all of them will get scheduled over a single node matching the taint.

Thanks, J

答:
You can do this using nodeSelector and node affinity (take a look at this guide https://kubernetes.io/docs/concepts/configuration/assign-pod-node/), anyone can be used to run pods on specific nodes. But if the node has taints (restrictions) then you need to add tolerations for those nodes (more can be found here https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/). Using this approach, you can specify a list of nodes to be used for your pod's scheduling, the catch is if you specify for ex. 3 nodes and you have 5 pods then you don't have control how many pods will run on each of these nodes. They gets distributed as per kube-schedular.
Another relevant use case: If you want to run one pod in each of the specified nodes, you can create a daemonset and select nodes using nodeSelector.


问:
React.js styled-components importing images and using them as div background
I am using styled-components and am trying to set a background image like so

```<code>const HeaderImage= styled.div`
    background-image: url('../../assets/image.png');
';
</code>```

I've also tried without the quotes, like so

```<code>const HeaderImage= styled.div`
        background-image: url(../../assets/image.png);
 ';
</code>```

In both cases, I get the same result

http://localhost:3000/assets/image.png Failed to load resource: the server responded with a status of 404 (Not Found)

I am using Richard Kall's react starter

The file is definitely in the specified location.

Am I loading it incorrectly?

I should mention, I'm very new to this (React, and styled-components)

答:
EDIT : this answer was edited after the question title was updated, due to misleading question title.

Using image as background-image CSS property :

```<code>import LogoSrc from './assets/logo.png';

/* ... */

const LogoDiv = styled.div`
  background-image: url(${LogoSrc});
  /* width and height should be set otherwise container will have either have them as 0 or grow depending on its contents */
`;

/* ... */

<LogoDiv />

</code>```

Normal way of importing and using images :

```<code>import LogoSrc from './assets/logo.png';

/* ... */

const Logo = styled.img`
    width: 30px;
    height: 30px;
    margin: 15px;
`;

/* ... inside the render or return of your component ... */

<Logo src={LogoSrc} />
</code>```

EDIT 2: For reference there is another way to use styled-components, mostly used when using components that you already import (i.e. ant-design components of from other component library) or in case of components that don't work using styled._cp_name_ notation.

NOTE: components need to be compatible with styled-components.

Imagine you would export Logo on a file and import it on another component file :

```<code>const Logo = styled.img`
    width: 30px;
    height: 30px;
    margin: 15px;
`;

export default Logo;
</code>```

Then, on the file where you would import it, you could add more styles by :

```<code>import Logo from '../components/Logo';

const L = styled(Logo)`
   border: 1px dashed black;
`;

/* ... then inside render or return ... */
<L />
</code>```

Body:
I am using styled-components and am trying to set a background image like so

const HeaderImage= styled.div`
    background-image: url('../../assets/image.png');
';

I've also tried without the quotes, like so

const HeaderImage= styled.div`
        background-image: url(../../assets/image.png);
 ';

In both cases, I get the same result

http://localhost:3000/assets/image.png Failed to load resource: the server responded with a status of 404 (Not Found)

I am using Richard Kall's react starter

The file is definitely in the specified location.

Am I loading it incorrectly?

I should mention, I'm very new to this (React, and styled-components)

Body:
EDIT : this answer was edited after the question title was updated, due to misleading question title.

Using image as background-image CSS property :

import LogoSrc from './assets/logo.png';

/* ... */

const LogoDiv = styled.div`
  background-image: url(${LogoSrc});
  /* width and height should be set otherwise container will have either have them as 0 or grow depending on its contents */
`;

/* ... */

<LogoDiv />

Normal way of importing and using images :

import LogoSrc from './assets/logo.png';

/* ... */

const Logo = styled.img`
    width: 30px;
    height: 30px;
    margin: 15px;
`;

/* ... inside the render or return of your component ... */

<Logo src={LogoSrc} />

EDIT 2: For reference there is another way to use styled-components, mostly used when using components that you already import (i.e. ant-design components of from other component library) or in case of components that don't work using styled._cp_name_ notation.

NOTE: components need to be compatible with styled-components.

Imagine you would export Logo on a file and import it on another component file :

const Logo = styled.img`
    width: 30px;
    height: 30px;
    margin: 15px;
`;

export default Logo;

Then, on the file where you would import it, you could add more styles by :

import Logo from '../components/Logo';

const L = styled(Logo)`
   border: 1px dashed black;
`;

/* ... then inside render or return ... */
<L />


问:
How to implement an unordered data structure using set?
I want to build an unordered set for my Face structure, that is

```<code>class myFace
{
public:
    //the three points
    int u;
    int v;
    int k;
    myFace() = default;
    myFace(int u, int v, int k) : u(u), v(v), k(k) {}

    bool operator< (const myFace& e) const
    {
        bool result = true;
        min(u, v, k);
        if ((u == e.u && v == e.v && k == e.k) ||
            (u == e.u && v == e.k && k == e.v) ||
            (u == e.v && v == e.u && k == e.k) ||
            (u == e.v && v == e.k && k == e.u) ||
            (u == e.k && v == e.u && k == e.v) ||
            (u == e.k && v == e.v && k == e.u))
        {
            result = false;
        }
        return result;
    }
};
</code>```

I want to make sure that:

```<code>set<myFace> con;
myFace f1(1,2,3);
myFace f2(2,3,1);
myFace f3(3,1,2);

con.insert(f1);
con.insert(f2);
con.insert(f3);
cout << con.size() << endl;

</code>```

the output should be 1.
Since f1,f2,f3 are same.

Or we can just say how to implement a set for 3 unordered elements, that is 123,132,213,231,312,321 are all same.

答:
I found that use set can achieve the goal: implementing a set for 3 unordered elements, that is 123,132,213,231,312,321 are all same.</p>

```<code>set<int> face;
face.insert(1);
face.insert(2);
face.insert(3);

set<int> face2;
face2.insert(2);
face2.insert(1);
face2.insert(3);

set<int> face3;
face3.insert(3);
face3.insert(1);
face3.insert(2);

set<set<int>> faces;

faces.insert(face);
faces.insert(face2);
faces.insert(face3);
cout << "----" << endl;
cout << faces.size() << endl;
</code>```

Body:
I want to build an unordered set for my Face structure, that is

class myFace
{
public:
    //the three points
    int u;
    int v;
    int k;
    myFace() = default;
    myFace(int u, int v, int k) : u(u), v(v), k(k) {}

    bool operator< (const myFace& e) const
    {
        bool result = true;
        min(u, v, k);
        if ((u == e.u && v == e.v && k == e.k) ||
            (u == e.u && v == e.k && k == e.v) ||
            (u == e.v && v == e.u && k == e.k) ||
            (u == e.v && v == e.k && k == e.u) ||
            (u == e.k && v == e.u && k == e.v) ||
            (u == e.k && v == e.v && k == e.u))
        {
            result = false;
        }
        return result;
    }
};

I want to make sure that:

set<myFace> con;
myFace f1(1,2,3);
myFace f2(2,3,1);
myFace f3(3,1,2);

con.insert(f1);
con.insert(f2);
con.insert(f3);
cout << con.size() << endl;

the output should be 1.
Since f1,f2,f3 are same.

Or we can just say how to implement a set for 3 unordered elements, that is 123,132,213,231,312,321 are all same.

Body:
I found that use set can achieve the goal: implementing a set for 3 unordered elements, that is 123,132,213,231,312,321 are all same.

set<int> face;
face.insert(1);
face.insert(2);
face.insert(3);

set<int> face2;
face2.insert(2);
face2.insert(1);
face2.insert(3);

set<int> face3;
face3.insert(3);
face3.insert(1);
face3.insert(2);

set<set<int>> faces;

faces.insert(face);
faces.insert(face2);
faces.insert(face3);
cout << "----" << endl;
cout << faces.size() << endl;


问:
How can I print this query result on my show.blade.php?
How can I print the result of this query on my show.blade.php? This is what I did on my Controller:

```<code>public function getRating(Request $request){
            $results = DB::select('SELECT AVG(stars) FROM reviews WHERE stars>1', [1])->get();
        }
</code>```

And this is what I tried on my show.blade.php

```<code><li class="nav-item">
     <form action="{{ action('CatalogController@getRating')}}" method="GET">
       <div>
         {{$results}}
       </div>
     </form>
</li>
</code>```

I'm still learning and I looked for this before making this question but I don't know if I couldn't find it or if I wasn't searching for the right thing, thanks.

答:
Are you looking for something like this, perhaps?

RatingsController:

```<code>use DB; // Make sure you call this above the class

public function returnAverageStars()
{
    $results = DB::table('reviews')->where('stars', '>=', 1)->avg('stars');

    return $results;
}

public function show()
{
    return view('show', [
        'reviews' => $this->returnAverageStars()
    ]);
}
</code>```

web.php

```<code>Route::get('/show', 'RatingsController@show');
</code>```

show.blade.php

```<code><ul>
    <li>{{ $reviews }}</li>
</ul>
</code>```

Body:
How can I print the result of this query on my show.blade.php? This is what I did on my Controller:

public function getRating(Request $request){
            $results = DB::select('SELECT AVG(stars) FROM reviews WHERE stars>1', [1])->get();
        }

And this is what I tried on my show.blade.php

     <form action="{{ action('CatalogController@getRating')}}" method="GET">

         {{$results}}

     </form>

I'm still learning and I looked for this before making this question but I don't know if I couldn't find it or if I wasn't searching for the right thing, thanks.

Body:
Are you looking for something like this, perhaps?

RatingsController:

use DB; // Make sure you call this above the class

public function returnAverageStars()
{
    $results = DB::table('reviews')->where('stars', '>=', 1)->avg('stars');

    return $results;
}

public function show()
{
    return view('show', [
        'reviews' => $this->returnAverageStars()
    ]);
}

web.php

Route::get('/show', 'RatingsController@show');

show.blade.php

<ul>
    <li>{{ $reviews }}</li>
</ul>


问:
Vuex issue transforming data into observer
I am using Vuex to manage the state of my application. When I am dispatching an action that calls some data from a server API, and if then this action commits a mutation, somehow my data gets transformed to observer objects instead of the actual data. Is this an expected behaviour or a bug within vuex?

Action:

```<code>async getDataFromApi(context, payload) {
try {
    let data = callApi(foo);
    context.commit("SET_REPORTING_DATA", { data, id: payload })
    return data;
} catch (e) {
  console.log(e.code);
  console.log(e.message);
  return false;
}}
</code>```

Mutation

```<code>SET_STATE(state, data) {
state.list = { ...state.list, [data.id]: data.data }
}
</code>```

The weird part about this is that when I log the data that I get from the API, I get an observer object although I am returning the original data from the api.

答:
That's not an issue but instead a caveat between the browser and Vue's reactivity system. To learn more about Vue's reactivity check their docs on Reactivity in Depth, there they explain how it works and even mention this caveat:

One caveat is that browser consoles format getter/setters differently when converted data objects are logged...

And they recommend to use vue-devtools for a friendlier introspection interface.

However there is a way to see logged variables with their data without having to use vue-devtools, the way is to log them using console.log(JSON.parse(JSON.stringify(data))), as shown below, to verify it correctly use the browser console, as StackOverflow's console already shows without the observer.

var app = new Vue({
  el: '#app',
  data: () => ({
    obj: {
      a: 123
    }
  }),
  created() {
    console.log('Observer');
    console.log(this.obj);
    console.log('Data');
    console.log(JSON.parse(JSON.stringify(this.obj)));
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div></code>```

Body:
I am using Vuex to manage the state of my application. When I am dispatching an action that calls some data from a server API, and if then this action commits a mutation, somehow my data gets transformed to observer objects instead of the actual data. Is this an expected behaviour or a bug within vuex?

Action:

async getDataFromApi(context, payload) {
try {
    let data = callApi(foo);
    context.commit("SET_REPORTING_DATA", { data, id: payload })
    return data;
} catch (e) {
  console.log(e.code);
  console.log(e.message);
  return false;
}}

Mutation

SET_STATE(state, data) {
state.list = { ...state.list, [data.id]: data.data }
}

The weird part about this is that when I log the data that I get from the API, I get an observer object although I am returning the original data from the api.

Body:
That's not an issue but instead a caveat between the browser and Vue's reactivity system. To learn more about Vue's reactivity check their docs on Reactivity in Depth, there they explain how it works and even mention this caveat:

One caveat is that browser consoles format getter/setters differently when converted data objects are logged...

And they recommend to use vue-devtools for a friendlier introspection interface.

However there is a way to see logged variables with their data without having to use vue-devtools, the way is to log them using console.log(JSON.parse(JSON.stringify(data))), as shown below, to verify it correctly use the browser console, as StackOverflow's console already shows without the observer.

var app = new Vue({
  el: '#app',
  data: () => ({
    obj: {
      a: 123
    }
  }),
  created() {
    console.log('Observer');
    console.log(this.obj);
    console.log('Data');
    console.log(JSON.parse(JSON.stringify(this.obj)));
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>


问:
How do I reference AWS GlobalSecondaryIndex name in AWS CloudFormationTemplate for a Lambda
I am trying to write a cloud formation template, where the Global Secondary Index (GSI) name of a DynamoDBTable is available as environment variable in a AWS Lambda. I have the template below and am having trouble getting the reference to the GSI name in the AWS Lambda (last line in the template).

Thanks in advance for your help.

```<code># The AWSTemplateFormatVersion identifies the capabilities of the template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.html
AWSTemplateFormatVersion: 2010-09-09
Description: >-
  temp

Parameters:
  Environment:
    Type: String
    Description: The name of the stage, e.g. "dev", "preprod", "prod"
    Default: ravi

Transform:
  - AWS::Serverless-2016-10-31

Resources:
  customerLambdaDLQ:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub "${Environment}-customer-lambda-dead-letter-queue"
  projectionsLambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - "sts:AssumeRole"
      Path: /
      Policies:
        - PolicyName: !Sub "${Environment}-customer-lambda-role"
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - "sqs:SendMessage*"
                  - "dynamodb:GetItem"
                  - "dynamodb:DeleteItem"
                  - "dynamodb:PutItem"
                  - "dynamodb:Scan"
                  - "dynamodb:Query"
                  - "dynamodb:UpdateItem"
                  - "dynamodb:BatchWriteItem"
                  - "dynamodb:BatchGetItem"
                  - "dynamodb:DescribeTable"
                  - "dynamodb:ConditionCheckItem"
                  - "dynamodb:DescribeStream"
                  - "dynamodb:GetRecords"
                  - "dynamodb:GetShardIterator"
                  - "dynamodb:ListStreams"
                Resource:
                  - !GetAtt customerLambdaDLQ.Arn
  customerTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Sub "${Environment}-customer-table"
      AttributeDefinitions:
        - AttributeName: PK
          AttributeType: S
        - AttributeName: SK
          AttributeType: S
        - AttributeName: indexKey_1
          AttributeType: S
        - AttributeName: indexKey_2
          AttributeType: S
        - AttributeName: customerId
          AttributeType: S
      KeySchema:
        - AttributeName: PK
          KeyType: HASH
        - AttributeName: SK
          KeyType: RANGE
      GlobalSecondaryIndexes:
        - IndexName: customer-index-1
          KeySchema:
            - AttributeName: indexKey_1
              KeyType: HASH
            - AttributeName: indexKey_2
              KeyType: RANGE
          Projection:
            ProjectionType: ALL
        - IndexName: customer-index-2
          KeySchema:
            - AttributeName: customerId
              KeyType: HASH
            - AttributeName: indexKey_2
              KeyType: RANGE
          Projection:
            NonKeyAttributes:
              - first_name
              - last_name
              - city
              - state
              - country
            ProjectionType: INCLUDE
      BillingMode: PAY_PER_REQUEST
      SSESpecification:
        SSEEnabled: true
  primer:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: nodejs12.x
      Role: !GetAtt projectionsLambdaRole.Arn
      Handler: index.handler
      Code:
        ZipFile: |
          var aws = require('aws-sdk')
          var response = require('cfn-response')
          exports.handler = function(event, context) {
              console.log("REQUEST RECEIVED:\n" + JSON.stringify(event))
              // For Delete requests, immediately send a SUCCESS response.
              if (event.RequestType == "Delete") {
                  response.send(event, context, "SUCCESS")
                  return
              }
              var responseStatus = "FAILED"
              var responseData = {}
              var functionName = event.ResourceProperties.FunctionName
              var lambda = new aws.Lambda()
              lambda.invoke({ FunctionName: functionName }, function(err, invokeResult) {
                  if (err) {
                      responseData = {Error: "Invoke call failed"}
                      console.log(responseData.Error + ":\n", err)
                  }
                  else responseStatus = "SUCCESS"
                  response.send(event, context, responseStatus, responseData)
              })
          }
      Description: Invoke a function during stack creation.
      Environment:
        Variables:
          TABLE_NAME: !Ref customerTable
          GSI_1_NAME: !GetAtt customerTable.GlobalSecondaryIndexes.customer-index-1
</code>```

答: The GSI is exactly what you named it, so you can just pass in customer-index-1

Body:
I am trying to write a cloud formation template, where the Global Secondary Index (GSI) name of a DynamoDBTable is available as environment variable in a AWS Lambda. I have the template below and am having trouble getting the reference to the GSI name in the AWS Lambda (last line in the template).

Thanks in advance for your help.

# The AWSTemplateFormatVersion identifies the capabilities of the template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.html
AWSTemplateFormatVersion: 2010-09-09
Description: >-
  temp

Parameters:
  Environment:
    Type: String
    Description: The name of the stage, e.g. "dev", "preprod", "prod"
    Default: ravi

Transform:
  - AWS::Serverless-2016-10-31

Resources:
  customerLambdaDLQ:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub "${Environment}-customer-lambda-dead-letter-queue"
  projectionsLambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - "sts:AssumeRole"
      Path: /
      Policies:
        - PolicyName: !Sub "${Environment}-customer-lambda-role"
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - "sqs:SendMessage*"
                  - "dynamodb:GetItem"
                  - "dynamodb:DeleteItem"
                  - "dynamodb:PutItem"
                  - "dynamodb:Scan"
                  - "dynamodb:Query"
                  - "dynamodb:UpdateItem"
                  - "dynamodb:BatchWriteItem"
                  - "dynamodb:BatchGetItem"
                  - "dynamodb:DescribeTable"
                  - "dynamodb:ConditionCheckItem"
                  - "dynamodb:DescribeStream"
                  - "dynamodb:GetRecords"
                  - "dynamodb:GetShardIterator"
                  - "dynamodb:ListStreams"
                Resource:
                  - !GetAtt customerLambdaDLQ.Arn
  customerTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Sub "${Environment}-customer-table"
      AttributeDefinitions:
        - AttributeName: PK
          AttributeType: S
        - AttributeName: SK
          AttributeType: S
        - AttributeName: indexKey_1
          AttributeType: S
        - AttributeName: indexKey_2
          AttributeType: S
        - AttributeName: customerId
          AttributeType: S
      KeySchema:
        - AttributeName: PK
          KeyType: HASH
        - AttributeName: SK
          KeyType: RANGE
      GlobalSecondaryIndexes:
        - IndexName: customer-index-1
          KeySchema:
            - AttributeName: indexKey_1
              KeyType: HASH
            - AttributeName: indexKey_2
              KeyType: RANGE
          Projection:
            ProjectionType: ALL
        - IndexName: customer-index-2
          KeySchema:
            - AttributeName: customerId
              KeyType: HASH
            - AttributeName: indexKey_2
              KeyType: RANGE
          Projection:
            NonKeyAttributes:
              - first_name
              - last_name
              - city
              - state
              - country
            ProjectionType: INCLUDE
      BillingMode: PAY_PER_REQUEST
      SSESpecification:
        SSEEnabled: true
  primer:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: nodejs12.x
      Role: !GetAtt projectionsLambdaRole.Arn
      Handler: index.handler
      Code:
        ZipFile: |
          var aws = require('aws-sdk')
          var response = require('cfn-response')
          exports.handler = function(event, context) {
              console.log("REQUEST RECEIVED:\n" + JSON.stringify(event))
              // For Delete requests, immediately send a SUCCESS response.
              if (event.RequestType == "Delete") {
                  response.send(event, context, "SUCCESS")
                  return
              }
              var responseStatus = "FAILED"
              var responseData = {}
              var functionName = event.ResourceProperties.FunctionName
              var lambda = new aws.Lambda()
              lambda.invoke({ FunctionName: functionName }, function(err, invokeResult) {
                  if (err) {
                      responseData = {Error: "Invoke call failed"}
                      console.log(responseData.Error + ":\n", err)
                  }
                  else responseStatus = "SUCCESS"
                  response.send(event, context, responseStatus, responseData)
              })
          }
      Description: Invoke a function during stack creation.
      Environment:
        Variables:
          TABLE_NAME: !Ref customerTable
          GSI_1_NAME: !GetAtt customerTable.GlobalSecondaryIndexes.customer-index-1


问:
How to make typescript strict option work completely?
I have enforced strict option but still typescript is not complaining for not defining types for port,req,res in the snippet. I am using Vscode and how to enforce it completely.

```<code>import express from 'express';

const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('Hello !');
});
app.listen(port, err => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});
</code>```

tsconfig.json

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "strict": true,
  "lib": ["es2015"],
  "--isolatedModules":true,
}
</code>```

答:
The --strict compiler option for tsc is a shorthand for a bunch of individual compiler options, none of which require you to annotate variables/parameters everywhere.  The compiler is perfectly happy to infer types for unannotated variables and parameters, and most of the time this is the preferred convention.  The only time --strict will really complain about a missing annotation is if the compiler can't infer a good type for it and falls back to using any.  But that's just the --noImplicitAny trying to save you from accidentally using the unsafe any type, not trying to remind you to annotate everything.

In your code above, the unannotated app constant is inferred to be of type Express; port is inferred as type 3000, and req and res are inferred to be of type Request and Response, as if you had annotated them yourself like this:

```<code>import express, { Express, Request, Response } from 'express';
const app: Express = express();
const port: 3000 = 3000;
app.get('/', (req: Request, res: Response) => {
  res.send('Hello !');
});
</code>```

The only place the compiler is unhappy is in the app.listen() callback of type Function, where there is no contextual type for the  err parameter and the compiler picks any.  So here is the only place you should need to annotate:

```<code>app.listen(port, (err: any) => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});
</code>```

That being said, if you want a complaint for every unannotated variable or parameter, you should use a linter like TSLint or ESLint alongside tsc.

If you use TSLint, you can enable the typedef rule, which "requires type definitions to exist."  There are sub-options specifically targeting the declaration of function parameters ("parameter" and "arrow-parameter") and of variables ("variable-declaration" and "variable-declaration-ignore-function").

If you use ESLint, you can enable its typedef rule, which "requires type annotations to exist".  Again, there are sub-options for function parameters ("parameter" and "arrowParameter") and variable declaration ("variableDeclaration").

Either one of those should get you the behavior you want.  But again, the conventional wisdom is that type inference is a good thing.  As ESLint's typedef docs say: "if you do not consider the cost of writing unnecessary type annotations reasonable, then do not use this rule."

Okay, hope that helps; good luck!

Playground link to code

Body:
I have enforced strict option but still typescript is not complaining for not defining types for port,req,res in the snippet. I am using Vscode and how to enforce it completely.

import express from 'express';

const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('Hello !');
});
app.listen(port, err => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "strict": true,
  "lib": ["es2015"],
  "--isolatedModules":true,
}

Body:
The --strict compiler option for tsc is a shorthand for a bunch of individual compiler options, none of which require you to annotate variables/parameters everywhere.  The compiler is perfectly happy to infer types for unannotated variables and parameters, and most of the time this is the preferred convention.  The only time --strict will really complain about a missing annotation is if the compiler can't infer a good type for it and falls back to using any.  But that's just the --noImplicitAny trying to save you from accidentally using the unsafe any type, not trying to remind you to annotate everything.

In your code above, the unannotated app constant is inferred to be of type Express; port is inferred as type 3000, and req and res are inferred to be of type Request and Response, as if you had annotated them yourself like this:

import express, { Express, Request, Response } from 'express';
const app: Express = express();
const port: 3000 = 3000;
app.get('/', (req: Request, res: Response) => {
  res.send('Hello !');
});

The only place the compiler is unhappy is in the app.listen() callback of type Function, where there is no contextual type for the  err parameter and the compiler picks any.  So here is the only place you should need to annotate:

app.listen(port, (err: any) => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

That being said, if you want a complaint for every unannotated variable or parameter, you should use a linter like TSLint or ESLint alongside tsc.

If you use TSLint, you can enable the typedef rule, which "requires type definitions to exist."  There are sub-options specifically targeting the declaration of function parameters ("parameter" and "arrow-parameter") and of variables ("variable-declaration" and "variable-declaration-ignore-function").

If you use ESLint, you can enable its typedef rule, which "requires type annotations to exist".  Again, there are sub-options for function parameters ("parameter" and "arrowParameter") and variable declaration ("variableDeclaration").

Either one of those should get you the behavior you want.  But again, the conventional wisdom is that type inference is a good thing.  As ESLint's typedef docs say: "if you do not consider the cost of writing unnecessary type annotations reasonable, then do not use this rule."

Okay, hope that helps; good luck!

Playground link to code


问:
Exterior penalty function method
I am trying to implement an exterior penalty function method for minimizing the below problem.

min f(x)=100*(x(2)-x(1)^2)^2+(1-x(1))^2

s.t, x(1)+2x(2)<=1

2x(1)+x(2)=1

First of all, I have found the minimum using fmincon, which the answer is x: array([ 0.4149,  0.1701]) and f(x)=0.34.

Then I am trying to find the minimum using my implementation of exterior penalty function method.
I am using this penalty function:

F(x,a)=f(x)+a*(x(1)+2*x(2)-1)^2+a*(2*x(1)+x(2)-1)^2

with start point x_0=[1,1], a=10 (in each iteration a= a^2) , which gives me x: array([ 0.3333,  0.3333]) and f(x)=5.3.

Where is the mistake in my implementation? Thanks.

答:
Your algorithm solves the following equality constrained problem!

minimize f(x)=100*(x(2)-x(1)^2)^2+(1-x(1))^2

subject to x(1)+2x(2)=1
           2x(1)+x(2)=1

and fmincon (correctly) solved the original problem (with one inequality and one equality constraint).

Title: Exterior penalty function method


问:
a simple mailto: also fires postback on .net. How to prevent the postback?
I've got a simple link

```<code>    <a   href="mailto:test@email.com">test@email.com</a>
</code>```

Problem is in an asp.net page when using Internet Explorer 8 clicking on the link not only opens the email client but also navigates the url to mailto:test@email.com  i've tried adding onclick="return false;"
however this prevents the mailto: from firing at all. so nothing happens in this case.

i think the problem comes from a scriptmanager on the same page (which i kindof need)

again this only happens with IE. I havn't tested with previous versions of IE . But opera, ff, and chrome work just fine

just a quick edit. if i'm uisng a simple html page with IE8. it works just fine

Any ideas how to fix this?

答:
It is firing postback because it is in Anchor so when you click on it try to find href link. You can use javascript or jquery to  solve this problem.

```<code><script type="text/javascript" src="jquery-1.4.1.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
                $('a').attr('href', '#');
            });
</script>
</code>```

Body:
I've got a simple link

    test@email.com

Problem is in an asp.net page when using Internet Explorer 8 clicking on the link not only opens the email client but also navigates the url to mailto:test@email.com  i've tried adding onclick="return false;"
however this prevents the mailto: from firing at all. so nothing happens in this case.

i think the problem comes from a scriptmanager on the same page (which i kindof need)

again this only happens with IE. I havn't tested with previous versions of IE . But opera, ff, and chrome work just fine

just a quick edit. if i'm uisng a simple html page with IE8. it works just fine

Any ideas how to fix this?

Body:
It is firing postback because it is in Anchor so when you click on it try to find href link. You can use javascript or jquery to  solve this problem.

<script type="text/javascript" src="jquery-1.4.1.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
                $('a').attr('href', '#');
            });
</script>


问:
How to set xampp open localhost:8080 instead of just localhost
I use XAMPP 1.7.3. Apache and MySQL installed. Nothing else.

Apache installed on default port 80. Clicking on Admin next to Apache opens http://localhost/xampp/. Which works as expected.

I navigated to xampp/apache/conf/httpd.conf and edited it. Set Listen 8080. Now http://localhost:8080/xampp/ works as expected but the Admin button still opens http://localhost/xampp/ which does not open anything. I have restarted the computer after doing so with no results.

How to make XAMPP apache admin open localhost:8080/xampp ?

答: Open XAMPP look below the X to close the program there is a Config option click it then click service and port settings then under Apache change your main port to whatever you changed it to in the config file then click save and your good to go.</p>


问:
java compare array elements
i have a problem with an exam test.
I have two arrays: int[] a, int[] b, with random values.
E1 return true if there are two elements of b greater then each element of a.
How do I write "there are two elements of b greater than each element of a"?
I can write "there is ONE elements of b greater than each element of a" in this way:

```<code>public static boolean e1(int[] a, int[] b){
    boolean ris = false;
    boolean ogniA = true;
    int i = 0;
    if(a != null && a.length != 0){
        while(ogniA && i<a.length){
            boolean es1= false;
            boolean es2 = false;
            int j = 0;

            if(b!= null && b.length != 0){
                while(!es1 && j < b.length){
                    if(j%2!=0){
                        es1 = a[i] < b[j];
                    }

                    j++;

                }ris = es1 ;
            }
            i++;
        }
    }
    return ris;
</code>```

I need something like this. Thanks for help.

答:
So I would solve this problem, by dividing it into smaller problems.
1st you need to find the 2 biggest values in the first array.
I presume this should be abstract and work for every array

Code (using the example from Andronicus):

"E1 return true if there are two elements of b greater then each element of a"

Basically you need the second greater value of array B and the greater value of the array A

```<code>int[] a = {3, 5, 7, 9};
int[] b = {2, 4, 3, 10, 11};

int secondGreatestOfB = IntStream.of(b).boxed()
            .sorted(Comparator.reverseOrder())
            .limit(2)
            .sorted(Comparator.naturalOrder())
            .limit(1)
            .findFirst().orElse(0);

System.out.println(areTheTwoBiggestNumbersOfArrayBbiggerThanAllValuesFromArrayA(a, secondGreatestOfB));

private static boolean areTheTwoBiggestNumbersOfArrayBbiggerThanAllValuesFromArrayA(int[] a, int secondGreatestOfArrayB) {
    return secondGreatestOfArrayB > IntStream.of(a).max().orElse(0);
}
</code>```

Title: java compare array elements

Body:
i have a problem with an exam test.
I have two arrays: int[] a, int[] b, with random values.
E1 return true if there are two elements of b greater then each element of a.
How do I write "there are two elements of b greater than each element of a"?
I can write "there is ONE elements of b greater than each element of a" in this way:

public static boolean e1(int[] a, int[] b){
    boolean ris = false;
    boolean ogniA = true;
    int i = 0;
    if(a != null && a.length != 0){
        while(ogniA && i<a.length){
            boolean es1= false;
            boolean es2 = false;
            int j = 0;

            if(b!= null && b.length != 0){
                while(!es1 && j < b.length){
                    if(j%2!=0){
                        es1 = a[i] < b[j];
                    }

                    j++;

                }ris = es1 ;
            }
            i++;
        }
    }
    return ris;

I need something like this. Thanks for help.

Body:
So I would solve this problem, by dividing it into smaller problems.
1st you need to find the 2 biggest values in the first array.
I presume this should be abstract and work for every array

Code (using the example from Andronicus):

"E1 return true if there are two elements of b greater then each element of a"

Basically you need the second greater value of array B and the greater value of the array A

int[] a = {3, 5, 7, 9};
int[] b = {2, 4, 3, 10, 11};

int secondGreatestOfB = IntStream.of(b).boxed()
            .sorted(Comparator.reverseOrder())
            .limit(2)
            .sorted(Comparator.naturalOrder())
            .limit(1)
            .findFirst().orElse(0);

System.out.println(areTheTwoBiggestNumbersOfArrayBbiggerThanAllValuesFromArrayA(a, secondGreatestOfB));

private static boolean areTheTwoBiggestNumbersOfArrayBbiggerThanAllValuesFromArrayA(int[] a, int secondGreatestOfArrayB) {
    return secondGreatestOfArrayB > IntStream.of(a).max().orElse(0);
}


问:
Hold promise resolve / reject function reference waiting on user input
Am looking to use a promise to handle a modal window, such that when the modal window is called via the await syntax, the synchronous execution of the calling function is suspended until the user responds to the modal.  The code snippet below extracts the essential elements of the problem.  Although it functions, am not sure whether this is a promise antipattern, or whether I'm introducing hidden complexities should errors be thrown in the onclick handlers.  The closest Q&A I could find ( Resolve promise at a later time ) doesn't quite answer my issue, as the answers don't appear to apply to a promise held in reserve waiting on a user event to occur...

My stripped down Modal class and sample execution includes the following key elements...

class Modal constructs the modal DOM elements, and appends them to the HTML document.

class Modal has a method called show which shows the modal (in this simplified example, three buttons) and sets up a promise.  The resolve and reject functions of the promise are then held as Modal instance attributes, specifically resolveFunction and rejectFunction.

Only when the user hits Okay, Cancel, or CancelThrow is the promise resolved or rejected.

function openModal is the function that sets up and shows the modal, and then suspends waiting on the resolution of the promise created by the modal show() method.

<button onclick='openModal()'>Open Modal</button>

Result:

```
</div>
</div>
</p>

<p>Are there pitfalls to the way I'm handling the <code>resolve</code> and <code>reject</code> functions, and if so, is there a better design pattern to handle this use case?</p>

<p><strong>EDIT</strong></p>

<p>Based on Roamer-1888's guidance, I've arrived at the following cleaner implementation of the deferred promise...  (Note that the test of <code>Cancel w/Throw</code> results in the console showing an <code>Uncaught (in Promise)</code> error, but processing continues as defined...)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html><head>

<style>

#ModalArea {
  display: none;
}

#ModalArea.show {
  display: block;
}

</style>

<script>

class Modal {
  constructor() {

    this.parentNode = document.getElementById( 'ModalArea' );

    this.okay = document.createElement( 'BUTTON' );
    this.okay.innerText = 'Okay';
    this.parentNode.appendChild( this.okay );

    this.cancel = document.createElement( 'BUTTON' );
    this.cancel.innerText = 'Cancel';
    this.parentNode.appendChild( this.cancel );

    this.cancelThrow = document.createElement( 'BUTTON' );
    this.cancelThrow.innerText = 'Cancel w/Throw';
    this.parentNode.appendChild( this.cancelThrow );

  }

  async show() {
    this.parentNode.classList.add( 'show' );

    let modalPromise = new Promise( (resolve, reject) => {
      this.okay.onclick = (event) => {
        resolve( 'Okay' );
      };
      this.cancel.onclick = ( event ) => {
        reject( 'Cancel' );
      };
      this.cancelThrow.onclick = ( event ) => {
        try {
          throw new Error( 'Test of throwing an error!' );
        } catch ( err ) {
          console.log( 'Event caught error' );
          reject( err );
        }
      };
    });

    modalPromise.catch( e => {
      console.log( 'Promise catch fired!' );
    } );

    // Clear out the 'modal' buttons after the promise completes.
    modalPromise.finally( () => {
      this.parentNode.innerHTML = '';
    });

    return modalPromise;
  }

}

async function openModal() {

  // Create new modal buttons...
  let modal = new Modal();
  document.getElementById( 'Result' ).innerHTML =  'Result: ';

  // Show the buttons, but wait for the promise to resolve...
  try {
    document.getElementById( 'Result' ).innerText += await modal.show();
  } catch( err ) {
    document.getElementById( 'Result' ).innerText += err;
  }

  // Now that the promise resolved, append more text to the result.
  document.getElementById( 'Result' ).innerText += ' Done!';
}

</script>

</head><body>

<button onclick='openModal()'>Open Modal</button>
<div id='ModalArea'></div>
<div id='Result'></div>
</body></html></code>```

Something still seems off though.  Having added a promise catch, when selecting Cancel w/Throw, the error propagates through modalPromise.catch, but the console still logs the following error:

Uncaught (in promise) Error: Test of throwing an error!
   at HTMLButtonElement.cancelThrow.onclick

答:
FWIW... After studying error handling of Promises ( https://javascript.info/async-await#error-handling and https://javascript.info/promise-error-handling ) and much experimentation, I've concluded (maybe erroneously) that a deferred Promise reject will result in an Uncaught (in promise) error.

That is, a javascript error, despite being caught and handled within the execution of a deferred Promise, concluded with a Promise reject, will appear as an Uncaught (in promise) error in the console (even with the error being wrapped in a try..catch in both the deferred Promise and the calling function that created the Promise!).

If, though, the javascript error is caught and handled within the execution of a deferred Promise, and concluded with a Promise resolve, then there is no Uncaught (in promise) error.

The following code walks through the variations of resolving/rejecting a deferred Promise. (The console needs to be open to see the sequence of processing and the Uncaught (in promise) error.)

No error (in the deferred Promise) concluding with a Promise resolve.

No error concluding with a Promise reject. (Triggers Uncaught error)

A caught error, concluding with a Promise resolve.

A caught error, concluding with a Promise reject. (Triggers Uncaught error)

Note that even the originating openModal() call makes use of the Promise catch function, in addition to being wrapped with a try..catch, but this still does not trap the reject.

<button onclick="
try {
  openModal()
  .then( x => console.log( 'openModal().THEN fired!' ) )
  .catch( x => console.log( 'openModal().CATCH fired!' ) );
} catch( err ) {
  console.log( [ 'openModal() TRY/CATCH fired!', err ] );
}
">Open Modal</button>

```
</div>
</div>
</p>
<p>So, I'm concluding (again, possibly erroneously) that a <strong>deferred</strong> Promise must only be concluded with a <code>resolve</code> if the desire is to avoid the <code>Uncaught (in promise)</code> error.  Another apparent option is to incorporate an <code>unhandledrejection</code> event handler, but this just seems to add unnecessary complexity if one can avoid the Promise <code>reject</code>...</p>
<p><strong>EDIT:  @hackape's answer points out my flaw</strong></p>
<p>In short, I was not treating <code>then()</code> and <code>finally()</code> as branches of the original promise, that they themselves return a promise!  With that in mind, one can take @hackape's example and tweak it to further hold and pass around these branch promises in as squirrely a way as possible, all the while avoiding the <code>Uncaught (in promise)</code> errors.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Modified version of @hackape's example
function defer() {
  let resolve
  let reject
  const promise = new Promise((rsv, rjt) => {
    resolve = rsv
    reject = rjt
  })

  return {
    promise,
    resolve,
    reject,
  }
}

// 1 uncaught
function case_a( promiseB ) {
  const d = defer()
  d.promise.catch(e => console.log('[catch(a1)]', e))
  d.promise.finally(e => console.log('[finally(a1)]', e)) // uncaught
  d.reject('apple')

  // Let's get squirrely.  Create and return the
  // promiseB finally() promise, which is then passed
  // to case_c, which will handle the associated catch!
  let pbFinally = promiseB.promise.finally(e => console.log('[finally(b1)]', e))
  return pbFinally
}

// all caught!
function case_b() {
  const d = defer()
  d.promise.catch(e => console.log('[catch(b1)]', e))
  d.reject('banana')
  return d
}

// 2 uncaught
function case_c( pb ) {
  const d = defer()
  d.promise.catch(e => console.log('[catch(c1)]', e))
  d.promise.finally(e => console.log('[finally(c1)]', e)).catch(e => console.log('[catch(c2)]', e))
  d.promise.finally(e => console.log('[finally(c2)]', e)) // uncaught
  d.promise.finally(e => console.log('[finally(c3)]', e)) // uncaught

  // Catch associated with case_b finally(), which prevents
  // the case_b finally() promise from throwing an
  // 'Uncaught (in promise)' error!
  pb.catch(e => console.log('[catch(b2)]', e))

  d.reject('cherry')
}

function test() {
  let promiseB = case_b()
  let promiseBFinally = case_a( promiseB )
  case_c( promiseBFinally )
}

test()</code>```

Body:
Am looking to use a promise to handle a modal window, such that when the modal window is called via the await syntax, the synchronous execution of the calling function is suspended until the user responds to the modal.  The code snippet below extracts the essential elements of the problem.  Although it functions, am not sure whether this is a promise antipattern, or whether I'm introducing hidden complexities should errors be thrown in the onclick handlers.  The closest Q&A I could find ( Resolve promise at a later time ) doesn't quite answer my issue, as the answers don't appear to apply to a promise held in reserve waiting on a user event to occur...

My stripped down Modal class and sample execution includes the following key elements...

class Modal constructs the modal DOM elements, and appends them to the HTML document.

class Modal has a method called show which shows the modal (in this simplified example, three buttons) and sets up a promise.  The resolve and reject functions of the promise are then held as Modal instance attributes, specifically resolveFunction and rejectFunction.

Only when the user hits Okay, Cancel, or CancelThrow is the promise resolved or rejected.

function openModal is the function that sets up and shows the modal, and then suspends waiting on the resolution of the promise created by the modal show() method.

<button onclick='openModal()'>Open Modal</button>

Result:

Are there pitfalls to the way I'm handling the resolve and reject functions, and if so, is there a better design pattern to handle this use case?

EDIT

Based on Roamer-1888's guidance, I've arrived at the following cleaner implementation of the deferred promise...  (Note that the test of Cancel w/Throw results in the console showing an Uncaught (in Promise) error, but processing continues as defined...)

<button onclick='openModal()'>Open Modal</button>

Something still seems off though.  Having added a promise catch, when selecting Cancel w/Throw, the error propagates through modalPromise.catch, but the console still logs the following error:

Uncaught (in promise) Error: Test of throwing an error!
   at HTMLButtonElement.cancelThrow.onclick

Body:
FWIW... After studying error handling of Promises ( https://javascript.info/async-await#error-handling and https://javascript.info/promise-error-handling ) and much experimentation, I've concluded (maybe erroneously) that a deferred Promise reject will result in an Uncaught (in promise) error.

That is, a javascript error, despite being caught and handled within the execution of a deferred Promise, concluded with a Promise reject, will appear as an Uncaught (in promise) error in the console (even with the error being wrapped in a try..catch in both the deferred Promise and the calling function that created the Promise!).

If, though, the javascript error is caught and handled within the execution of a deferred Promise, and concluded with a Promise resolve, then there is no Uncaught (in promise) error.

The following code walks through the variations of resolving/rejecting a deferred Promise. (The console needs to be open to see the sequence of processing and the Uncaught (in promise) error.)

No error (in the deferred Promise) concluding with a Promise resolve.

No error concluding with a Promise reject. (Triggers Uncaught error)

A caught error, concluding with a Promise resolve.

A caught error, concluding with a Promise reject. (Triggers Uncaught error)

Note that even the originating openModal() call makes use of the Promise catch function, in addition to being wrapped with a try..catch, but this still does not trap the reject.

<html><head>

<style>
#ModalArea { display: none; }
#ModalArea.show { display: block; }
</style>

<script>

class Modal {
  constructor() {
    this.parentNode = document.getElementById( 'ModalArea' );

    this.okay = document.createElement( 'BUTTON' );
    this.okay.innerText = 'Okay - Promise RESOLVE';
    this.parentNode.appendChild( this.okay );

    this.cancel = document.createElement( 'BUTTON' );
    this.cancel.innerText = 'Cancel - Promise REJECT';
    this.parentNode.appendChild( this.cancel );

    this.cancelThrow1 = document.createElement( 'BUTTON' );
    this.cancelThrow1.innerText = 'Cancel w/Throw - Promise RESOLVE';
    this.parentNode.appendChild( this.cancelThrow1 );

    this.cancelThrow2 = document.createElement( 'BUTTON' );
    this.cancelThrow2.innerText = 'Cancel w/Throw - Promise REJECT';
    this.parentNode.appendChild( this.cancelThrow2 );
  }

  async show() {
    this.parentNode.classList.add( 'show' );

    let modalPromise = new Promise( (resolve, reject) => {
      this.okay.onclick = (event) => {
        resolve( 'Okay via Promise RESOLVE' );
      };
      this.cancel.onclick = ( event ) => {
        reject( 'Cancel via Promise REJECT' );
      };
      this.cancelThrow1.onclick = ( event ) => {
        try {
          throw new Error( 'Throw /catch error concluding with Promise RESOLVE' );
        } catch ( err ) {
          console.log( 'Cancel w/Throw via Promise RESOLVE' );
          resolve( err );
        }
      };
      this.cancelThrow2.onclick = ( event ) => {
        try {
          throw new Error( 'Throw /catch error concluding with Promise resolve' );
        } catch ( err ) {
          console.log( 'Cancel w/Throw via Promise REJECT' );
          reject( err );
        }
      };
    });

    modalPromise.catch( e => {
      console.log( 'Promise CATCH fired!' );
    } );

    // Clear out the 'modal' buttons after the promise completes.
    modalPromise.finally( () => {
      console.log( 'Promise FINALLY fired!' );
      this.parentNode.innerHTML = '';
    });

    return modalPromise;
  }

}

async function openModal() {

  // Create new modal buttons...
  let modal = new Modal();
  document.getElementById( 'Result' ).innerHTML =  'Result: ';

  // Show the buttons, but wait for the promise to resolve...
  try {
    document.getElementById( 'Result' ).innerText += await modal.show();
  } catch( err ) {
    document.getElementById( 'Result' ).innerText += err;
  }

  // Now that the promise resolved, append more text to the result.
  document.getElementById( 'Result' ).innerText += ' - Done!';
}

</script>

</head><body>

<button onclick="
try {
  openModal()
  .then( x => console.log( 'openModal().THEN fired!' ) )
  .catch( x => console.log( 'openModal().CATCH fired!' ) );
} catch( err ) {
  console.log( [ 'openModal() TRY/CATCH fired!', err ] );
}
">Open Modal</button>
<div id='ModalArea'></div>
<div id='Result'></div>
</body></html>

So, I'm concluding (again, possibly erroneously) that a deferred Promise must only be concluded with a resolve if the desire is to avoid the Uncaught (in promise) error.  Another apparent option is to incorporate an unhandledrejection event handler, but this just seems to add unnecessary complexity if one can avoid the Promise reject...

EDIT:  @hackape's answer points out my flaw

In short, I was not treating then() and finally() as branches of the original promise, that they themselves return a promise!  With that in mind, one can take @hackape's example and tweak it to further hold and pass around these branch promises in as squirrely a way as possible, all the while avoiding the Uncaught (in promise) errors.

// Modified version of @hackape's example
function defer() {
  let resolve
  let reject
  const promise = new Promise((rsv, rjt) => {
    resolve = rsv
    reject = rjt
  })

  return {
    promise,
    resolve,
    reject,
  }
}

// 1 uncaught
function case_a( promiseB ) {
  const d = defer()
  d.promise.catch(e => console.log('[catch(a1)]', e))
  d.promise.finally(e => console.log('[finally(a1)]', e)) // uncaught
  d.reject('apple')

  // Let's get squirrely.  Create and return the
  // promiseB finally() promise, which is then passed
  // to case_c, which will handle the associated catch!
  let pbFinally = promiseB.promise.finally(e => console.log('[finally(b1)]', e))
  return pbFinally
}

// all caught!
function case_b() {
  const d = defer()
  d.promise.catch(e => console.log('[catch(b1)]', e))
  d.reject('banana')
  return d
}

// 2 uncaught
function case_c( pb ) {
  const d = defer()
  d.promise.catch(e => console.log('[catch(c1)]', e))
  d.promise.finally(e => console.log('[finally(c1)]', e)).catch(e => console.log('[catch(c2)]', e))
  d.promise.finally(e => console.log('[finally(c2)]', e)) // uncaught
  d.promise.finally(e => console.log('[finally(c3)]', e)) // uncaught

  // Catch associated with case_b finally(), which prevents
  // the case_b finally() promise from throwing an
  // 'Uncaught (in promise)' error!
  pb.catch(e => console.log('[catch(b2)]', e))

  d.reject('cherry')
}

function test() {
  let promiseB = case_b()
  let promiseBFinally = case_a( promiseB )
  case_c( promiseBFinally )
}

test()


问:
Couldn't understand this SWIFT Fucntion
Hope you are doing well. Would anyone please explain this code to me? I am still not getting how we got 120 here. When the parameters were passed to the function, where was it saved? How did it determine max and min before calculating?

Would be really appreciated if anyone could explain it for me please..

答:
You could have also set min and max to 0 ,not to scores[0].

This func is very simple, I think you should read somewhere How functions are working.

For loop is used to go through every element, in your case every element in array scores. In every iteration, variable sum is increased by current element in array. So:

At the beginning of the function : sum = 0
 1. iteration: sum = 0 + 5

 2. iteration: sum = 5 + 3

 3. iteration: sum = 8 + 100

 4. iteration: sum = 108 + 3

 5. iteration: sum = 111 + 9

For loop ends. Sum = 120.

Score in Scores means like every single element in score. So name Score can be whatever you want to name it. You could have also name it element , x, a or whatever you like.

Title: Couldn't understand this SWIFT Fucntion


答:
We can use complete from tidyr

```<code>library(dplyr)

df %>%
  mutate(Time = 1) %>%
  group_by(ID, Age, Weight) %>%
  tidyr::complete(Time = 1:600)

#      ID   Age Weight  Time
#   <int> <int>  <int> <dbl>
# 1     1    25    150     1
# 2     1    25    150     2
# 3     1    25    150     3
# 4     1    25    150     4
# 5     1    25    150     5
# 6     1    25    150     6
# 7     1    25    150     7
# 8     1    25    150     8
# 9     1    25    150     9
#10     1    25    150    10
# … with 1,790 more rows
</code>```

Or in base R using split and transform

```<code>do.call(rbind, lapply(split(df, df$ID), function(x) transform(x, Time = 1:600)))
</code>```

Title: Add a series as a column in R

Body:
I need to expand a dataset and merge with series of time from 1 hr to 600 hr

ID   Age   Weight
1     25     150
2     30     140
3     28     170

to the following format [dots represent continuous count from 4 to 599; with the same ID, Age and Weight values]

ID   Age   Weight  Time
1     25     150    1
1     25     150    2
1     25     150    3
1     25     150    4
..    ..     ...   ..
1     25     150   599
1     25     150   600
2     30     140    1
2     30     140    2
2     30     140    3
2     30     140    4
..    ..     ...    ..
2     30     140    599
2     30     140    600
3     28     170     1
3     28     170     2
3     28     170     3
3     28     170     4
..    ..     ...    ..
3     28     170     599
3     28     170     600

Body:
We can use complete from tidyr

library(dplyr)

df %>%
  mutate(Time = 1) %>%
  group_by(ID, Age, Weight) %>%
  tidyr::complete(Time = 1:600)

#      ID   Age Weight  Time
#   <int> <int>  <int> <dbl>
# 1     1    25    150     1
# 2     1    25    150     2
# 3     1    25    150     3
# 4     1    25    150     4
# 5     1    25    150     5
# 6     1    25    150     6
# 7     1    25    150     7
# 8     1    25    150     8
# 9     1    25    150     9
#10     1    25    150    10
# … with 1,790 more rows

Or in base R using split and transform

do.call(rbind, lapply(split(df, df$ID), function(x) transform(x, Time = 1:600)))


答:
The function returns a tuple of type (min: Int, max: Int, sum: Int).
max and min are not determined before being calculated. When they're first assigned at the top of the function, they just contain the first element of the passed in scores array. But by the time the loop below finishes, they indeed have the correct minimum and maximum values. Those values are then returned in a tuple matching the return type.

Title: Couldn't understand this SWIFT Fucntion

Body:
Hope you are doing well. Would anyone please explain this code to me? I am still not getting how we got 120 here. When the parameters were passed to the function, where was it saved? How did it determine max and min before calculating?

Would be really appreciated if anyone could explain it for me please..


问:
im beginner in c++ i want to know how can i get the duplicate values in 2D vector
```<code>int main()
{
    int N{};
    int T {};
    cin >> N >> T;
    int col = 2 ;
    int row = N ;
    vector<vector<int> > v1(row, vector<int>(col, 0));

    for (size_t i = 0; i < v1.size(); i++)
        {
        for (size_t j = 0; j < v1[i].size(); j++) {
            cin >> v1[i][j];
        }
    }
    cout << "2D vector elements..." << endl;
    for (size_t i = 0; i < v1.size(); i++) {
        for (size_t j = 0; j < v1[i].size(); j++)
            cout << v1[i][j] << " ";
        cout << endl;
    }
    system("PAUSE");
}
</code>```

<p>"So this the output this from code matrix N rows and two columns what i want to is find the duplicate values in the second column , for example in first row i have [100 1 ] sec row [200 3] third [400 3] what i want do to take 100 and 400 and sum them and ignore 200 because 200 and 400 have the same value 3 so i want to take the bigger value how can i do that in 2dvector and take the sum of [100 1] [400 3]  </p>

答:
Your problem seems better suited to a std::map<int, int> because you have several pairs of things (in this case both ints), where you want one of the elements of the pair to maintain uniqueness among all pairs, but the other element can be duplicated. In your particular case, your second item input at each pair would be the key of the map, and your first item input at each pair would be the value associated with that key.

During insertions, you

Check if that key already exists in the map

If it doesn't, insert the key: value pair

If it does exist, compare the value in the map against your currently-inserting value

If the new value is greater, replace it, otherwise leave the old value

Then you are guaranteed to have a container with unique keys, where each value is the greatest of all values inserted at that key.

Something like:

```<code>std::size_t number_pairs;
std::cin >> number_pairs;

std::map<int, int> max_value_map{};

for (std::size_t i = 0; i < number_pairs; i++)
{
    int key, value;
    std::cin >> value >> key; // normally we input keys before values, but this ordering mimics your current setup
    if (max_value_map.count(key) == 0)
    {
        // The key doesn't exist in this map, so the current value is guaranteed to be greatest
        max_value_map[key] = value;
    }
    else if (...check if the input value is greater than the currently mapped value...)
    {
        max_value_map[key] = value;
    }
}

...iterate through the map to add all values and output them...
</code>```

Body:
int main()
{
    int N{};
    int T {};
    cin >> N >> T;
    int col = 2 ;
    int row = N ;
    vector<vector<int> > v1(row, vector<int>(col, 0));

    for (size_t i = 0; i < v1.size(); i++)
        {
        for (size_t j = 0; j < v1[i].size(); j++) {
            cin >> v1[i][j];
        }
    }
    cout << "2D vector elements..." << endl;
    for (size_t i = 0; i < v1.size(); i++) {
        for (size_t j = 0; j < v1[i].size(); j++)
            cout << v1[i][j] << " ";
        cout << endl;
    }
    system("PAUSE");
}

"So this the output this from code matrix N rows and two columns what i want to is find the duplicate values in the second column , for example in first row i have [100 1 ] sec row [200 3] third [400 3] what i want do to take 100 and 400 and sum them and ignore 200 because 200 and 400 have the same value 3 so i want to take the bigger value how can i do that in 2dvector and take the sum of [100 1] [400 3]

Body:
Your problem seems better suited to a std::map<int, int> because you have several pairs of things (in this case both ints), where you want one of the elements of the pair to maintain uniqueness among all pairs, but the other element can be duplicated. In your particular case, your second item input at each pair would be the key of the map, and your first item input at each pair would be the value associated with that key.

During insertions, you

Check if that key already exists in the map

If it doesn't, insert the key: value pair

If it does exist, compare the value in the map against your currently-inserting value

If the new value is greater, replace it, otherwise leave the old value

Then you are guaranteed to have a container with unique keys, where each value is the greatest of all values inserted at that key.

Something like:

std::size_t number_pairs;
std::cin >> number_pairs;

std::map<int, int> max_value_map{};

for (std::size_t i = 0; i < number_pairs; i++)
{
    int key, value;
    std::cin >> value >> key; // normally we input keys before values, but this ordering mimics your current setup
    if (max_value_map.count(key) == 0)
    {
        // The key doesn't exist in this map, so the current value is guaranteed to be greatest
        max_value_map[key] = value;
    }
    else if (...check if the input value is greater than the currently mapped value...)
    {
        max_value_map[key] = value;
    }
}

...iterate through the map to add all values and output them...


问:
Determining Filetype with PHP. What is Magic Database?
I'm trying to determine if some files are actually images (using PHP).
I've been advised to use finfo and i'm trying to understand how it works.

What I don't get is - what is a magic numbers database and how does it work? I'm a bit puzzled - does each file have certain "magic number" that you compare against that database?

Also - I have it on my debian squeeze - but will it also be available on WIN platform? or would one have to attach that database along with the app?

```<code><?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>
</code>```

答: Would an alternate solution be to see if exif_imagetype returns false?

Body:
I'm trying to determine if some files are actually images (using PHP).
I've been advised to use finfo and i'm trying to understand how it works.

What I don't get is - what is a magic numbers database and how does it work? I'm a bit puzzled - does each file have certain "magic number" that you compare against that database?

Also - I have it on my debian squeeze - but will it also be available on WIN platform? or would one have to attach that database along with the app?

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>


问:
What can i use as a device identifier in flutter?
I'm building an app and I need a unique identifier for each device and I don't want it to change even if the user uninstalls the app, what should I use? I don't know what I should look for. I searched a bit and I found something named deviceid is it good enough?
https://pub.dev/packages/device_id

答:
Apparently device_id plugin have some bugs with newest versions of flutter. You can use device_info instead.
Here is an example:</p>

```<code> static Future<List<String>> getDeviceDetails() async {
  String deviceName;
  String deviceVersion;
  String identifier;
  final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
  try {
  if (Platform.isAndroid) {
    var build = await deviceInfoPlugin.androidInfo;
    deviceName = build.model;
    deviceVersion = build.version.toString();
    identifier = build.androidId;  //UUID for Android
  } else if (Platform.isIOS) {
    var data = await deviceInfoPlugin.iosInfo;
    deviceName = data.name;
    deviceVersion = data.systemVersion;
    identifier = data.identifierForVendor;  //UUID for iOS
  }
} on PlatformException {
  print('Failed to get platform version');
}

//if (!mounted) return;
return [deviceName, deviceVersion, identifier];
}
</code>```

Body:
Apparently device_id plugin have some bugs with newest versions of flutter. You can use device_info instead.
Here is an example:

 static Future<List<String>> getDeviceDetails() async {
  String deviceName;
  String deviceVersion;
  String identifier;
  final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
  try {
  if (Platform.isAndroid) {
    var build = await deviceInfoPlugin.androidInfo;
    deviceName = build.model;
    deviceVersion = build.version.toString();
    identifier = build.androidId;  //UUID for Android
  } else if (Platform.isIOS) {
    var data = await deviceInfoPlugin.iosInfo;
    deviceName = data.name;
    deviceVersion = data.systemVersion;
    identifier = data.identifierForVendor;  //UUID for iOS
  }
} on PlatformException {
  print('Failed to get platform version');
}

//if (!mounted) return;
return [deviceName, deviceVersion, identifier];
}


问:
Where is the geography search type in Tomtom android SDK
I'm trying to do a search with the tomtom sdk in android.

```<code>SearchApi searchApi = OnlineSearchApi.create(Activity.this);

    searchApi.search(new FuzzySearchQueryBuilder(mSearchBar.getText().toString().trim())
            .withPosition(new com.tomtom.online.sdk.common.location.LatLng(myLocation.getLatitude(), myLocation.getLongitude()))
            .withTypeAhead(true)
            .withLimit(10)
            .build(), new FuzzySearchResultListener() {
        @Override
        public void onSearchResult(FuzzySearchResponse fuzzySearchResponse) {}

        @Override
        public void onSearchError(SearchError searchError) {}
    });
</code>```

My response has results not matching my query with field "Type" = "POI" (Points of interest i assume). I want to display non-points-of-interest locations and show only addresses ("Type" = "Point Address") or cities ("Type" = "Geography") matching my query.

How do I achieve this?

答:
Use

```<code>.withIdx('Geo,PAD')
</code>```

This parameter defines which indexes to be queried.

Body:
I'm trying to do a search with the tomtom sdk in android.

SearchApi searchApi = OnlineSearchApi.create(Activity.this);

    searchApi.search(new FuzzySearchQueryBuilder(mSearchBar.getText().toString().trim())
            .withPosition(new com.tomtom.online.sdk.common.location.LatLng(myLocation.getLatitude(), myLocation.getLongitude()))
            .withTypeAhead(true)
            .withLimit(10)
            .build(), new FuzzySearchResultListener() {
        @Override
        public void onSearchResult(FuzzySearchResponse fuzzySearchResponse) {}

        @Override
        public void onSearchError(SearchError searchError) {}
    });

My response has results not matching my query with field "Type" = "POI" (Points of interest i assume). I want to display non-points-of-interest locations and show only addresses ("Type" = "Point Address") or cities ("Type" = "Geography") matching my query.

How do I achieve this?

Body:
Use

.withIdx('Geo,PAD')

This parameter defines which indexes to be queried.


问:
Running node behind apache displays page (code) instead of executing page
I have spent many hours reading tutorials and solutions showing how to get node working behind apache using the ProxyPass directive, but when the site is visited, it displays the page contents (code) instead of executing it.  Here's some background:
- here is my apache vhost file:

```<code><VirtualHost *:80>
        ServerName mysite.com
        DocumentRoot /var/www/mysite
        DirectoryIndex app.js
        <proxy>
          Order deny,allow
          Allow from all
        </proxy>
        ProxyPreserveHost on
        ProxyRequests off
        <Location /var/www/mysite>
          ProxyPass http://localhost:3000
          ProxyPassReverse http://localhost:3000
        </Location>
        ErrorLog ${APACHE_LOG_DIR}/mysite.error.log
        CustomLog ${APACHE_LOG_DIR}/mysite.access.log combined
</VirtualHost>
</code>```

I am loading these modules into Apache: proxy_module and proxy_http_module.  (I even tried loading proxy_http2_module and that did nothing.)

For this test, I am running node by loading express: "node app.js".  Here is the code at the bottom of app.js that runs the server:

```<code><snip>
//Start server
app.listen(process.env.PORT || 3000, function () {
    console.log("Server started on port 3000");
});
</code>```

When I access the site from the command line on the server using lynx at http://localhost:3000, the site does load!

There doesn't appear to be any information on this - help would be appreciated.

答: I decided to install and use nginx instead and it works.</p>

Body:
I have spent many hours reading tutorials and solutions showing how to get node working behind apache using the ProxyPass directive, but when the site is visited, it displays the page contents (code) instead of executing it.  Here's some background:
- here is my apache vhost file:

<VirtualHost *:80>
        ServerName mysite.com
        DocumentRoot /var/www/mysite
        DirectoryIndex app.js
        <proxy>
          Order deny,allow
          Allow from all
        </proxy>
        ProxyPreserveHost on
        ProxyRequests off
        <Location /var/www/mysite>
          ProxyPass http://localhost:3000
          ProxyPassReverse http://localhost:3000
        </Location>
        ErrorLog ${APACHE_LOG_DIR}/mysite.error.log
        CustomLog ${APACHE_LOG_DIR}/mysite.access.log combined
</VirtualHost>

I am loading these modules into Apache: proxy_module and proxy_http_module.  (I even tried loading proxy_http2_module and that did nothing.)

For this test, I am running node by loading express: "node app.js".  Here is the code at the bottom of app.js that runs the server:

<snip>
//Start server
app.listen(process.env.PORT || 3000, function () {
    console.log("Server started on port 3000");
});

When I access the site from the command line on the server using lynx at http://localhost:3000, the site does load!

There doesn't appear to be any information on this - help would be appreciated.


问:
merge multiple small json files using pyspark in s3
I am a newbie in spark.

I have multiple small json files (1kb) in subdirectories of my  s3 bucket. I want to merge all the files present in a single directory. Is there any optimized way in doing this using pyspark.

Directory structure:
region/year/month/day/hour/multiple_json_files

I have many directories as indicated above and want to merge all files in a single directory.

P.S: I have tried using python but its taking more time, tried s3distcp but its the same result.

Can anyone please help me in this

答:
you can achieve by below code

First we need to make sure the hadoop aws package is available when we load spark:

```<code>import os

os.environ['PYSPARK_SUBMIT_ARGS'] = "--packages=org.apache.hadoop:hadoop-aws:2.7.3 pyspark-shell"
</code>```

Next we need to make pyspark available in the jupyter notebook:

```<code>import findspark
findspark.init()
from pyspark.sql import SparkSession
</code>```

We need the aws credentials in order to be able to access the s3 bucket. We can use the configparser package to read the credentials from the standard aws file.

```<code> import configparser
 config = configparser.ConfigParser()
 config.read(os.path.expanduser("~/.aws/credentials"))
 access_id = config.get(aws_profile, "aws_access_key_id")
 access_key = config.get(aws_profile, "aws_secret_access_key")
</code>```

We can start the spark session and pass the aws credentials to the hadoop configuration:

```<code> sc=spark.sparkContext
 hadoop_conf=sc._jsc.hadoopConfiguration()
 hadoop_conf.set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
 hadoop_conf.set("fs.s3n.awsAccessKeyId", access_id)
 hadoop_conf.set("fs.s3n.awsSecretAccessKey", access_key)
</code>```

Finally we can read the data and display it:

```<code> df=spark.read.json("s3n://path_of_location/*.json")
 df.show()
</code>```

Body:
you can achieve by below code

First we need to make sure the hadoop aws package is available when we load spark:

import os

os.environ['PYSPARK_SUBMIT_ARGS'] = "--packages=org.apache.hadoop:hadoop-aws:2.7.3 pyspark-shell"

Next we need to make pyspark available in the jupyter notebook:

import findspark
findspark.init()
from pyspark.sql import SparkSession

We need the aws credentials in order to be able to access the s3 bucket. We can use the configparser package to read the credentials from the standard aws file.

 import configparser
 config = configparser.ConfigParser()
 config.read(os.path.expanduser("~/.aws/credentials"))
 access_id = config.get(aws_profile, "aws_access_key_id")
 access_key = config.get(aws_profile, "aws_secret_access_key")

We can start the spark session and pass the aws credentials to the hadoop configuration:

 sc=spark.sparkContext
 hadoop_conf=sc._jsc.hadoopConfiguration()
 hadoop_conf.set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
 hadoop_conf.set("fs.s3n.awsAccessKeyId", access_id)
 hadoop_conf.set("fs.s3n.awsSecretAccessKey", access_key)

Finally we can read the data and display it:

 df=spark.read.json("s3n://path_of_location/*.json")
 df.show()