问:
How to notify an object that an event of another object? Java
I have a Java class, named Main, which instances several classes with name Subscriber. Subscriber obtains data from the internet and when it obtains a new data it stores it in a variable. When a new data is saved I want it to notify Main, or that it detects it. How could I do it?

I have thought about using the Observer pattern but in my case I have an observer and many observed

答:
Try this.</p>

```<code>public class Stack1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Producer p = new A();
        for (int i = 0; i < 10; i++) {
            Subscriber s = new B(p);
        }
        p.sendAll(new Data(1));
        p.sendAll(new Data(2));
        p.sendAll(new Data(3));
        p.sendAll(new Data(4));

    }

    public static class Data implements Serializable {

        private static final long serialVersionUID = 3897786191139169609L;

        private Integer value;

        public Data(Integer value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "Data{" + "value=" + value + '}';
        }

    }

    public interface Subscriber {

        public void doSomething(Data data);
    }

    public interface Producer {

        public void addSubscriber(Subscriber subscriber);

        public void sendAll(Data data);
    }

    public static class A implements Producer {

        private List<Subscriber> lst = new ArrayList<>();

        @Override
        public void addSubscriber(Subscriber subscriber) {
            lst.add(subscriber);
        }

        @Override
        public void sendAll(Data data) {
            for (Subscriber subscriber : lst) {
                subscriber.doSomething(data);
            }
        }

    }

    public static class B implements Subscriber {

        private final String id;

        public B(Producer producer) {
            producer.addSubscriber(this);
            id = UUID.randomUUID().toString();
        }

        @Override
        public void doSomething(Data data) {
            System.out.println(id.concat(" it.bookingexpert.test.Stack1.B.doSomething() ".concat(data.toString())));
        }

    }

}
</code>```

Body:
Try this.

public class Stack1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Producer p = new A();
        for (int i = 0; i < 10; i++) {
            Subscriber s = new B(p);
        }
        p.sendAll(new Data(1));
        p.sendAll(new Data(2));
        p.sendAll(new Data(3));
        p.sendAll(new Data(4));

    }

    public static class Data implements Serializable {

        private static final long serialVersionUID = 3897786191139169609L;

        private Integer value;

        public Data(Integer value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "Data{" + "value=" + value + '}';
        }

    }

    public interface Subscriber {

        public void doSomething(Data data);
    }

    public interface Producer {

        public void addSubscriber(Subscriber subscriber);

        public void sendAll(Data data);
    }

    public static class A implements Producer {

        private List<Subscriber> lst = new ArrayList<>();

        @Override
        public void addSubscriber(Subscriber subscriber) {
            lst.add(subscriber);
        }

        @Override
        public void sendAll(Data data) {
            for (Subscriber subscriber : lst) {
                subscriber.doSomething(data);
            }
        }

    }

    public static class B implements Subscriber {

        private final String id;

        public B(Producer producer) {
            producer.addSubscriber(this);
            id = UUID.randomUUID().toString();
        }

        @Override
        public void doSomething(Data data) {
            System.out.println(id.concat(" it.bookingexpert.test.Stack1.B.doSomething() ".concat(data.toString())));
        }

    }

}


来源: stackexchange

问:
template template member inheritance with 'using'
The following classes implement CRTP. I would like for class Derived to use the constructor provided by Base, so I write using. However, I get the error message, "can only inherit constructor from direct base". Equivalently for the member variable x.

template<template<typename, size_t> typename G, typename F, size_t U>
struct Base
{
    double x;
    Base(double x) : x{ x } {}
    double gimme_x()
    {
        return (*static_cast<G<F, U>*>(this)).gimme_x();
    }
};

template<typename F, size_t U>
struct Derived : Base<Derived, double, U>
{
    using Base<Derived, double, U>::Base;
    using Base<Derived, double, U>::x;

    double gimme_x()
    {
        return x + 1.8;
    }
};

```

<p>This problem can be mitigated by changing the template-template implementation of <code>Base</code> to just use a regular template.</p>

<pre class="lang-cpp prettyprint-override"><code>
template<typename G, typename F, size_t U>
struct Base
{
    double x;
    Base(double x) : x{ x } {}
    double gimme_x()
    {
        return (*static_cast<G*>(this)).gimme_x();
    }
};

template<typename F, size_t U>
struct Derived : Base<Derived<F, U>, double, U>
{
    using Base<Derived<F, U>, double, U>::Base;
    using Base<Derived<F, U>, double, U>::x;

    double gimme_x()
    {
        return x + 1.8;
    }
};

</code>```

While the second one looks a bit more verbose, it seems like it should be equivalent to the first one in this case. What's the difference and why does the implementation of the first one fail?

答:
Simpler work-around to avoid injected-class-name is to use full name ::Derived.

```<code>template<typename F, size_t U>
struct Derived : Base<Derived, double, U>
{
    using Base<::Derived, double, U>::Base;
    using Base<::Derived, double, U>::x;

    double gimme_x()
    {
        return x + 1.8;
    }
};
</code>```

Demo

Code compiles correctly with both gcc/clang Demo.

It is a msvc bug, as

In the following cases, the injected-class-name is treated as a template-name of the class template itself:

it is followed by <

it is used as a template argument that corresponds to a template template parameter

it is the final identifier in the elaborated class specifier of a friend class template declaration.

ContentLicense: CC BY-SA 4.0

Body:
The following classes implement CRTP. I would like for class Derived to use the constructor provided by Base, so I write using. However, I get the error message, "can only inherit constructor from direct base". Equivalently for the member variable x.

template<template<typename, size_t> typename G, typename F, size_t U>
struct Base
{
    double x;
    Base(double x) : x{ x } {}
    double gimme_x()
    {
        return (*static_cast<G<F, U>*>(this)).gimme_x();
    }
};

template<typename F, size_t U>
struct Derived : Base<Derived, double, U>
{
    using Base<Derived, double, U>::Base;
    using Base<Derived, double, U>::x;

    double gimme_x()
    {
        return x + 1.8;
    }
};

This problem can be mitigated by changing the template-template implementation of Base to just use a regular template.

template<typename G, typename F, size_t U>
struct Base
{
    double x;
    Base(double x) : x{ x } {}
    double gimme_x()
    {
        return (*static_cast<G*>(this)).gimme_x();
    }
};

template<typename F, size_t U>
struct Derived : Base<Derived<F, U>, double, U>
{
    using Base<Derived<F, U>, double, U>::Base;
    using Base<Derived<F, U>, double, U>::x;

    double gimme_x()
    {
        return x + 1.8;
    }
};

While the second one looks a bit more verbose, it seems like it should be equivalent to the first one in this case. What's the difference and why does the implementation of the first one fail?

Body:
Simpler work-around to avoid injected-class-name is to use full name ::Derived.

template<typename F, size_t U>
struct Derived : Base<Derived, double, U>
{
    using Base<::Derived, double, U>::Base;
    using Base<::Derived, double, U>::x;

    double gimme_x()
    {
        return x + 1.8;
    }
};

Demo

Code compiles correctly with both gcc/clang Demo.

It is a msvc bug, as

In the following cases, the injected-class-name is treated as a template-name of the class template itself:

it is followed by <

it is used as a template argument that corresponds to a template template parameter

it is the final identifier in the elaborated class specifier of a friend class template declaration.


问:
What is the proper way to set MDC for logging in grpc-java with ServerInterceptor?
I want to use ThreadContext from log4j2 for setting MDC context keys like request-id, user-id to trace request information in logs for debugging.

I have written an MdcInterceptor which does the following:

public class MdcInterceptor implements ServerInterceptor {

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                                                                 ServerCallHandler<ReqT, RespT> next) {
        ThreadContext.put("rid", generateId());
        return next.startCall(call, headers);
    }
}
```

Unfortunately it doesn't work as it seems that different callbacks may be called from different threads from Server executor with different ThreadContexts.

I've found some solution posted here https://github.com/grpc/grpc-java/issues/1949#issuecomment-226884288 that says that ThreadContext should be set in every callback in SimpleForwardingServerCallListener.

The fact is that in my case some additional information should be added if possible in different UserInfoInterceptor which is called after MdcInterceptor (some auth user info which requires token validation and etc.). How should I add this information to request-scoped ThreadContext properly?

Is the posted solution the only possible variant? It looks little strange that I put try-finally block around each super-call in SimpleForwardingServerCallListener not to mention that I should set context not once but in each callback.

答: You can use io.grpc.Context, which handles the propagation of RPC specific information into your callbacks.   Before calling any of the events on your ClientCall.Listener (and StreamObserver), the gRPC library will install the correct context.  Ray Tsang has made a good example of how to use the API.

Body:
I want to use ThreadContext from log4j2 for setting MDC context keys like request-id, user-id to trace request information in logs for debugging.

I have written an MdcInterceptor which does the following:

public class MdcInterceptor implements ServerInterceptor {

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                                                                 ServerCallHandler<ReqT, RespT> next) {
        ThreadContext.put("rid", generateId());
        return next.startCall(call, headers);
    }
}

Unfortunately it doesn't work as it seems that different callbacks may be called from different threads from Server executor with different ThreadContexts.

I've found some solution posted here https://github.com/grpc/grpc-java/issues/1949#issuecomment-226884288 that says that ThreadContext should be set in every callback in SimpleForwardingServerCallListener.

The fact is that in my case some additional information should be added if possible in different UserInfoInterceptor which is called after MdcInterceptor (some auth user info which requires token validation and etc.). How should I add this information to request-scoped ThreadContext properly?

Is the posted solution the only possible variant? It looks little strange that I put try-finally block around each super-call in SimpleForwardingServerCallListener not to mention that I should set context not once but in each callback.


问:
How to fill an array with dictionary-type elements
I need to fill an array with elements which are dictionaries. For example:

```<code>a = np.empty(2,2)
</code>```

and I need to fill it in this way (which is not allowed)

```<code>for i in range(2):
   for j in range(2):
      a[i,j] = {'x': b[i], 'y': c[j]}
</code>```

where band c are other lists/arrays or columns of a dataframe.

Body:
I need to fill an array with elements which are dictionaries. For example:

a = np.empty(2,2)

and I need to fill it in this way (which is not allowed)

for i in range(2):
   for j in range(2):
      a[i,j] = {'x': b[i], 'y': c[j]}

where band c are other lists/arrays or columns of a dataframe.

Body:
If you create an object dtype array, you can put anything in the slots:

In [9]: a = np.empty((2,2), object)
In [10]: a
Out[10]:
array([[None, None],                  # empty() fills with None
       [None, None]], dtype=object)
In [11]: for i in range(2):
    ...:     for j in range(2):
    ...:         a[i,j] = {'x':b[i], 'y':c[j]}
    ...:
In [12]: a
Out[12]:
array([[{'x': 1, 'y': 4}, {'x': 1, 'y': 3}],
       [{'x': 3, 'y': 4}, {'x': 3, 'y': 3}]], dtype=object)

But a list comprehension works just as well

In [13]: [[{'x':b[i],'y':c[j]} for j in range(2)] for i in range(2)]
Out[13]: [[{'x': 1, 'y': 4}, {'x': 1, 'y': 3}], [{'x': 3, 'y': 4}, {'x': 3, 'y': 3}]]
In [14]: np.array(_)
Out[14]:
array([[{'x': 1, 'y': 4}, {'x': 1, 'y': 3}],
       [{'x': 3, 'y': 4}, {'x': 3, 'y': 3}]], dtype=object)

Or you could start with a flat list, and reshape the array:

In [15]: [{'x':b[i],'y':c[j]} for j in range(2) for i in range(2)]
Out[15]: [{'x': 1, 'y': 4}, {'x': 3, 'y': 4}, {'x': 1, 'y': 3}, {'x': 3, 'y': 3}]
In [16]: np.array(_)
Out[16]:
array([{'x': 1, 'y': 4}, {'x': 3, 'y': 4}, {'x': 1, 'y': 3},
       {'x': 3, 'y': 3}], dtype=object)
In [18]: _.reshape(2,2)
Out[18]:
array([[{'x': 1, 'y': 4}, {'x': 3, 'y': 4}],
       [{'x': 1, 'y': 3}, {'x': 3, 'y': 3}]], dtype=object)

This array of dictionaries won't be any easier or faster to use than the list(s).

Alternatively we could create a structured array with 2 named fields.  Start with a list of tuples:

In [19]: [(b[i],c[j]) for j in range(2) for i in range(2)]
Out[19]: [(1, 4), (3, 4), (1, 3), (3, 3)]
In [20]: np.array(_, dtype=[('x',int),('y',int)])
Out[20]: array([(1, 4), (3, 4), (1, 3), (3, 3)], dtype=[('x', '<i8'), ('y', '<i8')])
In [21]: _.reshape(2,2)
Out[21]:
array([[(1, 4), (3, 4)],
       [(1, 3), (3, 3)]], dtype=[('x', '<i8'), ('y', '<i8')])
In [22]: _['x']
Out[22]:
array([[1, 3],
       [1, 3]])

In contrast to get all the x values from the 2d object array:

In [24]: [i['x'] for i in a.flat]
Out[24]: [1, 1, 3, 3]


问:
Azure AD OAuth 2.0 Auth Code Token Exchange using cert
The docs for the OAuth2 auth code to token exchange show making a request using client_id and client_secret. However is there a way to do this using cert based auth for the azure app?</p>

答:
Yes you can acquire tokens using a certificate instead of using client secret as well. It's covered as part of Client Credentials Grant.

Azure AD V1 Endpoint

Here is a detailed code sample - It makes use of a self signed certificate and uses Azure AD V1 endpoint

Authenticating to Azure AD in daemon apps with certificates

```<code>certCred = new ClientAssertionCertificate(clientId, cert);
result = await authContext.AcquireTokenAsync(todoListResourceId, certCred);
</code>```

In case you're looking to make direct REST based calls (not using ADAL Library) here's a sample. You can read more details on each of the parameters here on Microsoft Docs:

Access token request with a certificate

```<code>POST /<tenant_id>/oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

resource=https%3A%2F%contoso.onmicrosoft.com%2Ffc7664b4-cdd6-43e1-9365-c2e1c4e1b3bf&client_id=97e0a5b7-d745-40b6-94fe-5f77d35c6e05&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion=eyJhbGciOiJSUzI1NiIsIng1dCI6Imd4OHRHeXN5amNScUtqRlBuZDdSRnd2d1pJMCJ9.eyJ{a lot of characters here}M8U3bSUKKJDEg&grant_type=client_credentials
</code>```

Azure AD V2 Endpoint

Using MSAL.NET Library you can do it like this. Both client secret and Certificate Credentials variations are shown here. (Certificate is covered in the else case)

More details available here - Client credential flows in MSAL.NET

```<code>// Even if this is a console application here, a daemon application is a confidential client application
IConfidentialClientApplication app;

#if !VariationWithCertificateCredentials
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
           .WithTenantId("{tenantID}")
           .WithClientSecret(config.ClientSecret)
           .Build();
#else
// Building the client credentials from a certificate
X509Certificate2 certificate = ReadCertificate(config.CertificateName);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
    .WithTenantId("{tenantID}")
    .WithCertificate(certificate)
    .Build();
#endif

// With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
// application permissions need to be set statically (in the portal or by PowerShell), and then granted by
// a tenant administrator
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

AuthenticationResult result = null;
try
{
 result = await app.AcquireTokenForClient(scopes)
                   .ExecuteAsync();
}
catch(MsalServiceException ex)
{
 // Case when ex.Message contains:
 // AADSTS70011 Invalid scope. The scope has to be of the form "https://resourceUrl/.default"
 // Mitigation: change the scope to be as expected
}
</code>```

Again in case you're interested in making direct REST based calss (not using MSAL Library) here's a sample.You can read more details on each of the parameters here on Microsoft Docs:

Access token request with a certificate

```<code>POST /{tenant}/oauth2/v2.0/token HTTP/1.1               // Line breaks for clarity
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_id=97e0a5b7-d745-40b6-94fe-5f77d35c6e05
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=eyJhbGciOiJSUzI1NiIsIng1dCI6Imd4OHRHeXN5amNScUtqRlBuZDdSRnd2d1pJMCJ9.eyJ{a lot of characters here}M8U3bSUKKJDEg
&grant_type=client_credentials
</code>```

Body:
Yes you can acquire tokens using a certificate instead of using client secret as well. It's covered as part of Client Credentials Grant.

Azure AD V1 Endpoint

Here is a detailed code sample - It makes use of a self signed certificate and uses Azure AD V1 endpoint

Authenticating to Azure AD in daemon apps with certificates

certCred = new ClientAssertionCertificate(clientId, cert);
result = await authContext.AcquireTokenAsync(todoListResourceId, certCred);

In case you're looking to make direct REST based calls (not using ADAL Library) here's a sample. You can read more details on each of the parameters here on Microsoft Docs:

Access token request with a certificate

POST /<tenant_id>/oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

resource=https%3A%2F%contoso.onmicrosoft.com%2Ffc7664b4-cdd6-43e1-9365-c2e1c4e1b3bf&client_id=97e0a5b7-d745-40b6-94fe-5f77d35c6e05&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion=eyJhbGciOiJSUzI1NiIsIng1dCI6Imd4OHRHeXN5amNScUtqRlBuZDdSRnd2d1pJMCJ9.eyJ{a lot of characters here}M8U3bSUKKJDEg&grant_type=client_credentials

Azure AD V2 Endpoint

Using MSAL.NET Library you can do it like this. Both client secret and Certificate Credentials variations are shown here. (Certificate is covered in the else case)

More details available here - Client credential flows in MSAL.NET

// Even if this is a console application here, a daemon application is a confidential client application
IConfidentialClientApplication app;

#if !VariationWithCertificateCredentials
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
           .WithTenantId("{tenantID}")
           .WithClientSecret(config.ClientSecret)
           .Build();
#else
// Building the client credentials from a certificate
X509Certificate2 certificate = ReadCertificate(config.CertificateName);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
    .WithTenantId("{tenantID}")
    .WithCertificate(certificate)
    .Build();
#endif

// With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
// application permissions need to be set statically (in the portal or by PowerShell), and then granted by
// a tenant administrator
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

AuthenticationResult result = null;
try
{
 result = await app.AcquireTokenForClient(scopes)
                   .ExecuteAsync();
}
catch(MsalServiceException ex)
{
 // Case when ex.Message contains:
 // AADSTS70011 Invalid scope. The scope has to be of the form "https://resourceUrl/.default"
 // Mitigation: change the scope to be as expected
}

Again in case you're interested in making direct REST based calss (not using MSAL Library) here's a sample.You can read more details on each of the parameters here on Microsoft Docs:

Access token request with a certificate

POST /{tenant}/oauth2/v2.0/token HTTP/1.1               // Line breaks for clarity
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_id=97e0a5b7-d745-40b6-94fe-5f77d35c6e05
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=eyJhbGciOiJSUzI1NiIsIng1dCI6Imd4OHRHeXN5amNScUtqRlBuZDdSRnd2d1pJMCJ9.eyJ{a lot of characters here}M8U3bSUKKJDEg
&grant_type=client_credentials


问:
create-react-app build/serve environment variables
Relatively new to working with react.   I have an application that is working fine in local docker.   I populate a bunch of REACT_APP_ environment variables by exporting them to the environment before starting the docker container.

Now, I'm trying to deploy this to a kubernetes pod by running a yarn build and then serving up the build.  I see that the environment variables are available on the pod itself by looking at printenv but the application doesn't appear to be picking them up.

Is there something special with serving a production build of a react-app to get it to see the exported environment variables that I'm missing?

I don't want to embed an .env file into the built docker image for security reasons, so I'm hoping that running a react build via serve can still pick up exported REACT_APP_ environment variables that are set via kubernetes secrets.

答:
So apparently, whenever you build a react application with npm, static files are produced that don't know anything about any environment variables you may try to inject at runtime with Kubernetes.

The article below does a good job of explaining this and why they choose to attach the environment variables to the JavaScript window object since it has application-scope available to it.

Making a React application container environment-aware at Kubernetes deployment


问:
Async to wait for a key in F#?
I would like to block async execution until the users presses any key in the console.

Here is what I have come up with:

```<code>let waitForAnyKey = async {
  do!
    new Task (fun () ->
      printfn "%s" "waiting for a key"
      Console.ReadKey () |> ignore
      printfn "%s" "got a key"
    )
    |> Async.AwaitTask
}
</code>```

Used like this:

```<code>async {
  printfn "%s" "Press any key... "
  do! waitForAnyKey
  printfn "%s" "You pressed a key. "
}
</code>```

However, the Task is never run.

How should I write this in F#?

Can I avoid creating a Task for this entirely?

答:
You can write waitForAnyKey without the Task<->Async interop bits:

let waitForAnyKey = async {
  do Console.ReadKey () |> ignore
}
```

You can then call it any time you'd like to wait for input.  Your usage example would work just fine with this implementation.

Title: Async to wait for a key in F#?

Body:
I would like to block async execution until the users presses any key in the console.

Here is what I have come up with:

let waitForAnyKey = async {
  do!
    new Task (fun () ->
      printfn "%s" "waiting for a key"
      Console.ReadKey () |> ignore
      printfn "%s" "got a key"
    )
    |> Async.AwaitTask
}

Used like this:

async {
  printfn "%s" "Press any key... "
  do! waitForAnyKey
  printfn "%s" "You pressed a key. "
}

However, the Task is never run.

How should I write this in F#?

Can I avoid creating a Task for this entirely?

Body:
You can write waitForAnyKey without the Task<->Async interop bits:

let waitForAnyKey = async {
  do Console.ReadKey () |> ignore
}

You can then call it any time you'd like to wait for input.  Your usage example would work just fine with this implementation.


问:
How to filter on joined fields? (performance issues)

Prerequisites

I've created database with two generated collections: users and notes. Each contains ~1M documents.

Here are the structures:

user: (the name field uses skiplist index):

```<code>{
    "name": "Some user name"
}
</code>```

note: (the authors field contains _keys to the documents from users collection):

```<code>{
    "title": "Some title",
    "authors": [
        "12345", "12346", "12347", ...
    ]
}
</code>```

Problem

I need to join the users collection on authors field and then filter by user name but it takes too long. It's ~3.5s on my local. The Specific name value occurs only once.

```<code>let specificUsers = (
    for user in users
        filter user.name == 'Specific name'
        return user
)

for note in notes

    let authors = (
        for user in specificUsers
            filter user._key in (note.authors != null ? note.authors : [])
            return user
    )

    filter count(authors) > 0

//    filter 'Specific name' in (authors[*].name) // this way takes even longer

    limit 10

    return merge(note, {
        authors: authors
    })

</code>```

If I omit the count filter or do filtering on "owned" attributes, it loads fast, of course. But the need is to actually do filtering on joined collection. Just like in relational databases.

Question

Am I doing something wrong or ArangoDB is not supposed to perform well in this case?

Please let me know if I need to provide more details.

答:
So, two things I missed:

I didn't add index on authors[*].

I was using the (note.authors != null ? note.authors : []). (I guess, it's better to ensure the authors attribute is always array)

Body:
Prerequisites

I've created database with two generated collections: users and notes. Each contains ~1M documents.

Here are the structures:

user: (the name field uses skiplist index):

{
    "name": "Some user name"
}

note: (the authors field contains _keys to the documents from users collection):

{
    "title": "Some title",
    "authors": [
        "12345", "12346", "12347", ...
    ]
}

Problem

I need to join the users collection on authors field and then filter by user name but it takes too long. It's ~3.5s on my local. The Specific name value occurs only once.

let specificUsers = (
    for user in users
        filter user.name == 'Specific name'
        return user
)

for note in notes

    let authors = (
        for user in specificUsers
            filter user._key in (note.authors != null ? note.authors : [])
            return user
    )

    filter count(authors) > 0

//    filter 'Specific name' in (authors[*].name) // this way takes even longer

    limit 10

    return merge(note, {
        authors: authors
    })

If I omit the count filter or do filtering on "owned" attributes, it loads fast, of course. But the need is to actually do filtering on joined collection. Just like in relational databases.

Question

Am I doing something wrong or ArangoDB is not supposed to perform well in this case?

Please let me know if I need to provide more details.


问:
CSS BEM children of a modifier
I'm new into BEM methodology, and I have a question targeting a child of a modifier.

Lets say I have this HTML:

```<code><div class="block-container">
    <div class="block-container__element"></div>
</div>
</code>```

At block-container I add a modifier block-container--modifier.

And the CSS would be:

```<code>.block-container {
    ...
}
.block-container__element {
    ...
}
.block-container--modifier {
    ...
}
</code>```

And my question here is: how I can change some CSS attributes of the __element when the modifier is applied?

As far as I read, we have to avoid using nested children, but I think that sometimes that rule must be broken to achieve this kind of things, I'm right?

I'm using pure CSS, no LESS, no SASS.

答:
In general cascades should be avoided, but not in this case.

If you are sure that the block block-container is never recursively included in another block-container, then you can do:

```<code>.block-container--modifier .block-container__element {
}
</code>```

Otherwise you have to put another modifier on the element: block-container__element--modifier.

There is a third solution but it is unorthodox. In some case, I suggest to use the child selector if you are sure that, at the DOM level, the element is a direct child of the block (for example if the block always is a
 and the elements are the
 children). Then you can do:

```<code>.block-container--modifier > .block-container__element {
}
</code>```

Title: CSS BEM children of a modifier

Body:
I'm new into BEM methodology, and I have a question targeting a child of a modifier.

Lets say I have this HTML:

At block-container I add a modifier block-container--modifier.

And the CSS would be:

.block-container {
    ...
}
.block-container__element {
    ...
}
.block-container--modifier {
    ...
}

And my question here is: how I can change some CSS attributes of the __element when the modifier is applied?

As far as I read, we have to avoid using nested children, but I think that sometimes that rule must be broken to achieve this kind of things, I'm right?

I'm using pure CSS, no LESS, no SASS.

Body:
In general cascades should be avoided, but not in this case.

If you are sure that the block block-container is never recursively included in another block-container, then you can do:

.block-container--modifier .block-container__element {
}

Otherwise you have to put another modifier on the element: block-container__element--modifier.

There is a third solution but it is unorthodox. In some case, I suggest to use the child selector if you are sure that, at the DOM level, the element is a direct child of the block (for example if the block always is a <ul> and the elements are the <li> children). Then you can do:

.block-container--modifier > .block-container__element {
}


问:
Unable to get $_GET values from form
I cannot retrieve the $_GET['id'] nor $_GET['action'] from a form and input in this page:

```<code><?php
include "common.php";
var_dump($_GET['quantity']);
var_dump($_GET['action']);
var_dump($_GET['id']);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>es6.1.6</title>
    <style type="text/css">
        input {
            margin: 10px;
        }
    </style>
</head>
<body>
<ul>
    <?php
    for($i=1; $i<=sizeof($names); $i++) {
        echo "<form method='get' action='shop.php?action=add&id=$i'>";
        echo "<li><a href='description.php?item=$i'> ",$names[$i],"</a></li>";
        echo "<input type='number' name='quantity'>";
        echo "</form>";
    }
    ?>
</ul>

<br><br>
<form action="summary.php">
    <input type="submit" value="Add to cart">
</form>

</body>
</html>
</code>```

only $_GET['quantity'] will be set after inserting a number and pressing Enter into any input form

答:
try adding action and id as hidden input fields with the values you need

edit:
change your code to look like this:

```<code>for($i=1; $i<=sizeof($names); $i++) {
        echo "<form method='get' action='shop.php'>";
        echo "<li><a href='description.php?item=$i'> ",$names[$i],"</a></li>";
        echo "<input type='number' name='quantity'>";
        echo "<input type='hidden' name='action' value='add'>";
        echo "<input type='hidden' name='id' value='" . $i . "'>";
        echo "</form>";
    }
</code>```

Title: Unable to get $_GET values from form

Body:
I cannot retrieve the $_GET['id'] nor $_GET['action'] from a form and input in this page:

<?php
include "common.php";
var_dump($_GET['quantity']);
var_dump($_GET['action']);
var_dump($_GET['id']);

?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>es6.1.6</title>

    <?php
    for($i=1; $i<=sizeof($names); $i++) {
        echo "<form method='get' action='shop.php?action=add&id=$i'>";
        echo "
 ",$names[$i],"
";
        echo "<input type='number' name='quantity'>";
        echo "</form>";
    }
    ?>

<form action="summary.php">
    <input type="submit" value="Add to cart">
</form>

only $_GET['quantity'] will be set after inserting a number and pressing Enter into any input form

Body:
try adding action and id as hidden input fields with the values you need

edit:
change your code to look like this:

for($i=1; $i<=sizeof($names); $i++) {
        echo "<form method='get' action='shop.php'>";
        echo "<li><a href='description.php?item=$i'> ",$names[$i],"</a></li>";
        echo "<input type='number' name='quantity'>";
        echo "<input type='hidden' name='action' value='add'>";
        echo "<input type='hidden' name='id' value='" . $i . "'>";
        echo "</form>";
    }


问:
What techniques can be used to measure performance of pandas/numpy solutions

Question

How do I measure the performance of the various functions below in a concise and comprehensive way.

Example

Consider the dataframe df

```<code>df = pd.DataFrame({
        'Group': list('QLCKPXNLNTIXAWYMWACA'),
        'Value': [29, 52, 71, 51, 45, 76, 68, 60, 92, 95,
                  99, 27, 77, 54, 39, 23, 84, 37, 99, 87]
    })
</code>```

I want to sum up the Value column grouped by distinct values in Group.  I have three methods for doing it.

```<code>import pandas as pd
import numpy as np
from numba import njit

def sum_pd(df):
    return df.groupby('Group').Value.sum()

def sum_fc(df):
    f, u = pd.factorize(df.Group.values)
    v = df.Value.values
    return pd.Series(np.bincount(f, weights=v).astype(int), pd.Index(u, name='Group'), name='Value').sort_index()

@njit
def wbcnt(b, w, k):
    bins = np.arange(k)
    bins = bins * 0
    for i in range(len(b)):
        bins[b[i]] += w[i]
    return bins

def sum_nb(df):
    b, u = pd.factorize(df.Group.values)
    w = df.Value.values
    bins = wbcnt(b, w, u.size)
    return pd.Series(bins, pd.Index(u, name='Group'), name='Value').sort_index()
</code>```

Are they the same?

```<code>print(sum_pd(df).equals(sum_nb(df)))
print(sum_pd(df).equals(sum_fc(df)))

True
True
</code>```

How fast are they?

```<code>%timeit sum_pd(df)
%timeit sum_fc(df)
%timeit sum_nb(df)

1000 loops, best of 3: 536 µs per loop
1000 loops, best of 3: 324 µs per loop
1000 loops, best of 3: 300 µs per loop
</code>```

答:
They might not classify as "simple frameworks" because they are third-party modules that need to be installed but there are two frameworks I often use:

simple_benchmark (I'm the author of that package)

perfplot

For example the simple_benchmark library allows to decorate the functions to benchmark:

```<code>from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()

import pandas as pd
import numpy as np
from numba import njit

@b.add_function()
def sum_pd(df):
    return df.groupby('Group').Value.sum()

@b.add_function()
def sum_fc(df):
    f, u = pd.factorize(df.Group.values)
    v = df.Value.values
    return pd.Series(np.bincount(f, weights=v).astype(int), pd.Index(u, name='Group'), name='Value').sort_index()

@njit
def wbcnt(b, w, k):
    bins = np.arange(k)
    bins = bins * 0
    for i in range(len(b)):
        bins[b[i]] += w[i]
    return bins

@b.add_function()
def sum_nb(df):
    b, u = pd.factorize(df.Group.values)
    w = df.Value.values
    bins = wbcnt(b, w, u.size)
    return pd.Series(bins, pd.Index(u, name='Group'), name='Value').sort_index()
</code>```

Also decorate a function that produces the values for the benchmark:

```<code>from string import ascii_uppercase

def creator(n):  # taken from another answer here
    letters = list(ascii_uppercase)
    np.random.seed([3,1415])
    df = pd.DataFrame(dict(
            Group=np.random.choice(letters, n),
            Value=np.random.randint(100, size=n)
        ))
    return df

@b.add_arguments('Rows in DataFrame')
def argument_provider():
    for exponent in range(4, 22):
        size = 2**exponent
        yield size, creator(size)
</code>```

And then all you need to run the benchmark is:

```<code>r = b.run()
</code>```

After that you can inspect the results as plot (you need the matplotlib library for this):

```<code>r.plot()
</code>```

In case the functions are very similar in run-time the percentage difference instead of absolute numbers could be more important:

```<code>r.plot_difference_percentage(relative_to=sum_nb)
</code>```

Or get the times for the benchmark as DataFrame (this needs pandas)

```<code>r.to_pandas_dataframe()
</code>```

           sum_pd    sum_fc    sum_nb
16       0.000796  0.000515  0.000502
32       0.000702  0.000453  0.000454
64       0.000702  0.000454  0.000456
128      0.000711  0.000456  0.000458
256      0.000714  0.000461  0.000462
512      0.000728  0.000471  0.000473
1024     0.000746  0.000512  0.000513
2048     0.000825  0.000515  0.000514
4096     0.000902  0.000609  0.000640
8192     0.001056  0.000731  0.000755
16384    0.001381  0.001012  0.000936
32768    0.001885  0.001465  0.001328
65536    0.003404  0.002957  0.002585
131072   0.008076  0.005668  0.005159
262144   0.015532  0.011059  0.010988
524288   0.032517  0.023336  0.018608
1048576  0.055144  0.040367  0.035487
2097152  0.112333  0.080407  0.072154
```

<p>In case you don't like the decorators you could also setup everything in one call (in that case you don't need the <code>BenchmarkBuilder</code> and the <code>add_function</code>/<code>add_arguments</code> decorators):</p>

```from simple_benchmark import benchmark
r = benchmark([sum_pd, sum_fc, sum_nb], {2**i: creator(2**i) for i in range(4, 22)}, "Rows in DataFrame")
```

<p>Here <code>perfplot</code> offers a very similar interface (and result):</p>

```import perfplot
r = perfplot.bench(
    setup=creator,
    kernels=[sum_pd, sum_fc, sum_nb],
    n_range=[2**k for k in range(4, 22)],
    xlabel='Rows in DataFrame',
    )
import matplotlib.pyplot as plt
plt.loglog()
r.plot()
```

Body:
Question

How do I measure the performance of the various functions below in a concise and comprehensive way.

Example

Consider the dataframe df

df = pd.DataFrame({
        'Group': list('QLCKPXNLNTIXAWYMWACA'),
        'Value': [29, 52, 71, 51, 45, 76, 68, 60, 92, 95,
                  99, 27, 77, 54, 39, 23, 84, 37, 99, 87]
    })

I want to sum up the Value column grouped by distinct values in Group.  I have three methods for doing it.

import pandas as pd
import numpy as np
from numba import njit

def sum_pd(df):
    return df.groupby('Group').Value.sum()

def sum_fc(df):
    f, u = pd.factorize(df.Group.values)
    v = df.Value.values
    return pd.Series(np.bincount(f, weights=v).astype(int), pd.Index(u, name='Group'), name='Value').sort_index()

@njit
def wbcnt(b, w, k):
    bins = np.arange(k)
    bins = bins * 0
    for i in range(len(b)):
        bins[b[i]] += w[i]
    return bins

def sum_nb(df):
    b, u = pd.factorize(df.Group.values)
    w = df.Value.values
    bins = wbcnt(b, w, u.size)
    return pd.Series(bins, pd.Index(u, name='Group'), name='Value').sort_index()

Are they the same?

print(sum_pd(df).equals(sum_nb(df)))
print(sum_pd(df).equals(sum_fc(df)))

True
True

How fast are they?

%timeit sum_pd(df)
%timeit sum_fc(df)
%timeit sum_nb(df)

1000 loops, best of 3: 536 µs per loop
1000 loops, best of 3: 324 µs per loop
1000 loops, best of 3: 300 µs per loop

Body:
They might not classify as "simple frameworks" because they are third-party modules that need to be installed but there are two frameworks I often use:

simple_benchmark (I'm the author of that package)

perfplot

For example the simple_benchmark library allows to decorate the functions to benchmark:

from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()

import pandas as pd
import numpy as np
from numba import njit

@b.add_function()
def sum_pd(df):
    return df.groupby('Group').Value.sum()

@b.add_function()
def sum_fc(df):
    f, u = pd.factorize(df.Group.values)
    v = df.Value.values
    return pd.Series(np.bincount(f, weights=v).astype(int), pd.Index(u, name='Group'), name='Value').sort_index()

@njit
def wbcnt(b, w, k):
    bins = np.arange(k)
    bins = bins * 0
    for i in range(len(b)):
        bins[b[i]] += w[i]
    return bins

@b.add_function()
def sum_nb(df):
    b, u = pd.factorize(df.Group.values)
    w = df.Value.values
    bins = wbcnt(b, w, u.size)
    return pd.Series(bins, pd.Index(u, name='Group'), name='Value').sort_index()

Also decorate a function that produces the values for the benchmark:

from string import ascii_uppercase

def creator(n):  # taken from another answer here
    letters = list(ascii_uppercase)
    np.random.seed([3,1415])
    df = pd.DataFrame(dict(
            Group=np.random.choice(letters, n),
            Value=np.random.randint(100, size=n)
        ))
    return df

@b.add_arguments('Rows in DataFrame')
def argument_provider():
    for exponent in range(4, 22):
        size = 2**exponent
        yield size, creator(size)

And then all you need to run the benchmark is:

r = b.run()

After that you can inspect the results as plot (you need the matplotlib library for this):

r.plot()

In case the functions are very similar in run-time the percentage difference instead of absolute numbers could be more important:

r.plot_difference_percentage(relative_to=sum_nb)

Or get the times for the benchmark as DataFrame (this needs pandas)

r.to_pandas_dataframe()

           sum_pd    sum_fc    sum_nb
16       0.000796  0.000515  0.000502
32       0.000702  0.000453  0.000454
64       0.000702  0.000454  0.000456
128      0.000711  0.000456  0.000458
256      0.000714  0.000461  0.000462
512      0.000728  0.000471  0.000473
1024     0.000746  0.000512  0.000513
2048     0.000825  0.000515  0.000514
4096     0.000902  0.000609  0.000640
8192     0.001056  0.000731  0.000755
16384    0.001381  0.001012  0.000936
32768    0.001885  0.001465  0.001328
65536    0.003404  0.002957  0.002585
131072   0.008076  0.005668  0.005159
262144   0.015532  0.011059  0.010988
524288   0.032517  0.023336  0.018608
1048576  0.055144  0.040367  0.035487
2097152  0.112333  0.080407  0.072154

In case you don't like the decorators you could also setup everything in one call (in that case you don't need the BenchmarkBuilder and the add_function/add_arguments decorators):

from simple_benchmark import benchmark
r = benchmark([sum_pd, sum_fc, sum_nb], {2**i: creator(2**i) for i in range(4, 22)}, "Rows in DataFrame")

Here perfplot offers a very similar interface (and result):

import perfplot
r = perfplot.bench(
    setup=creator,
    kernels=[sum_pd, sum_fc, sum_nb],
    n_range=[2**k for k in range(4, 22)],
    xlabel='Rows in DataFrame',
    )
import matplotlib.pyplot as plt
plt.loglog()
r.plot()


问:
RPM + cant find rpm after rpm install
please advice why I cant find the rpm that I installed.
I am try to check by rpm -qa | grep test ( see the example in install the rpm: )
but seems that rpm isnt installed why?

build the RPM:

```<code> [root@linux /usr/src/redhat/SOURCES]#  rpm -ba   /usr/src/redhat/SPECS/my_spec.spec
 Checking for unpackaged file(s): /usr/lib/rpm/check-files /var/tmp/test.sh
 Wrote: /root/rpmbuild/SRPMS/test.sh-6.2-2.src.rpm
</code>```

install the rpm:

```<code>   [root@linux /usr/src/redhat/RPMS/i386]# rpm -Uvh  /root/rpmbuild/SRPMS/test.sh-6.2-2.src.rpm
   1:test.sh                ########################################### [100%]

   [root@linux /usr/src/redhat/RPMS/i386]# rpm -qa | grep test

   no results ?
</code>```

the spec file:

```<code>  Summary: An example tool. To show a simple rpm build of the tool.
  Name: test.sh
  Version: 6.2
  Release: 2
  Source:/root/test.sh
  Group: Development/Debuggers
  BuildRoot:/var/tmp/test.sh
  License: OtherLicense
  %description
</code>```

答:
You installed the source rpm instead of the actual rpm:</p>

```<code>rpm -Uvh /root/rpmbuild/RPMS/test.sh-6.2-2.rpm
</code>```

ContentLicense: CC BY-SA 3.0

Title: RPM + cant find rpm after rpm install

Body:
please advice why I cant find the rpm that I installed.
I am try to check by rpm -qa | grep test ( see the example in install the rpm: )
but seems that rpm isnt installed why?

build the RPM:

 [root@linux /usr/src/redhat/SOURCES]#  rpm -ba   /usr/src/redhat/SPECS/my_spec.spec
 Checking for unpackaged file(s): /usr/lib/rpm/check-files /var/tmp/test.sh
 Wrote: /root/rpmbuild/SRPMS/test.sh-6.2-2.src.rpm

install the rpm:

   [root@linux /usr/src/redhat/RPMS/i386]# rpm -Uvh  /root/rpmbuild/SRPMS/test.sh-6.2-2.src.rpm
   1:test.sh                ########################################### [100%]

   [root@linux /usr/src/redhat/RPMS/i386]# rpm -qa | grep test

   no results ?

the spec file:

  Summary: An example tool. To show a simple rpm build of the tool.
  Name: test.sh
  Version: 6.2
  Release: 2
  Source:/root/test.sh
  Group: Development/Debuggers
  BuildRoot:/var/tmp/test.sh
  License: OtherLicense
  %description

Body:
You installed the source rpm instead of the actual rpm:

rpm -Uvh /root/rpmbuild/RPMS/test.sh-6.2-2.rpm


问:
Writing a CTE query the records are duplicated and in the wrong order
I have a table that has the data in rows and the data needs to be summarized in columns. Currently the data does go in columns but the data duplicates and is in the wrong order. Also when I enter more than one server name I will get the server 1 column with info Server 2 column will be null and server 3 column will have data.

I have looked at answers on stackoverflow, social.msdn.microsoft.com , sqlservercentral.com and sqlshack.com

```<code>WITH
cte (Captivate_Id, Building_Name ,Server_Name,Server_Number)
as

   (
     SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
     ,(s.Server_Name) as Server_Name
     ,ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
      FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
      join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b on
      s.building_id = b.building_id
      WHERE s.Server_Name IS NULL
      UNION ALL
      SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
      ,(s.Server_Name) as Server_Name
      ,ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
       FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
       join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b on
        s.building_id = b.building_id

        AND b.Captivate_Id IN
        (
          'FFF1234'
         )
         )

SELECT Captivate_ID as ID,Building_Name as Building_Name,
(SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name
AND ct.Server_Number=1) Server1,    -----, -- works but order wrong
(SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name
AND ct.Server_Number=2) Server2, -- works but order wrong
(SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name
AND ct.Server_Number=3) Server3

FROM cte
</code>```

Output

```<code>ID  Building_Name   Server1     Server2     Server3
FFF1234 some name   servername1 servername2 NULL
FFF1234 some name   servername1 servername2 NULL
</code>```

I expect the output to be

```<code>ID  Building_Name   Server1     Server2     Server3
FFF1234 some name   servername1 servername2 blank
</code>```

答:
You have a misconception on how ROW_NUMBER() works. With two distinct ROW_NUMBER() commands, you have two separate row number sequences. You can correct your issue by changing your CTE like this:

```<code>WITH cte1 (Captivate_Id, Building_Name ,Server_Name)
    AS (
        SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
            ,'' as Server_Name    -- If you want a blank servername, make it so
        FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
        join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b
            on     s.building_id = b.building_id
        WHERE s.Server_Name IS NULL

        UNION ALL

        SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
            ,(s.Server_Name) as Server_Name
        FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
        join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b
            on s.building_id = b.building_id
        AND b.Captivate_Id IN (
            'FFF1234'
            )
    ),
cte (Captivate_Id, Building_Name ,Server_Name, Server_Number)
    as (
        SELECT Captivate_ID,
            Building_Name,
            Server_Name,
            ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
        FROM cte1
    )

SELECT Captivate_ID as ID,Building_Name as Building_Name,
    (SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name AND ct.Server_Number=1) Server1,-----, -- works but order wrong
    (SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name AND ct.Server_Number=2) Server2, -- works but order wrong
    (SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name AND ct.Server_Number=3) Server3
FROM cte
</code>```

SPOILER - Original bad code

 WITH
  cte (Captivate_Id, Building_Name ,Server_Name, Server_Number)
 as (
  SELECT Captivate_ID,
      Building_Name,
      Server_Name,
      ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
  FROM (
      SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
          ,'' as Server_Name      -- If you want a blank servername, make it so
  --      ,ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
      FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
      join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b
          on  s.building_id = b.building_id
      WHERE s.Server_Name IS NULL
      UNION ALL
      SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
          ,(s.Server_Name) as Server_Name
  --      ,ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
      FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
      join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b
                 on s.building_id = b.building_id
                 AND b.Captivate_Id IN (
                     'FFF1234'
                     )
                 )
  )

Body:
I have a table that has the data in rows and the data needs to be summarized in columns. Currently the data does go in columns but the data duplicates and is in the wrong order. Also when I enter more than one server name I will get the server 1 column with info Server 2 column will be null and server 3 column will have data.

I have looked at answers on stackoverflow, social.msdn.microsoft.com , sqlservercentral.com and sqlshack.com

WITH
cte (Captivate_Id, Building_Name ,Server_Name,Server_Number)
as

   (
     SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
     ,(s.Server_Name) as Server_Name
     ,ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
      FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
      join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b on
      s.building_id = b.building_id
      WHERE s.Server_Name IS NULL
      UNION ALL
      SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
      ,(s.Server_Name) as Server_Name
      ,ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
       FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
       join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b on
        s.building_id = b.building_id

        AND b.Captivate_Id IN
        (
          'FFF1234'
         )
         )

SELECT Captivate_ID as ID,Building_Name as Building_Name,
(SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name
AND ct.Server_Number=1) Server1,    -----, -- works but order wrong
(SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name
AND ct.Server_Number=2) Server2, -- works but order wrong
(SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name
AND ct.Server_Number=3) Server3

FROM cte

Output

ID  Building_Name   Server1     Server2     Server3
FFF1234 some name   servername1 servername2 NULL
FFF1234 some name   servername1 servername2 NULL

I expect the output to be

ID  Building_Name   Server1     Server2     Server3
FFF1234 some name   servername1 servername2 blank

Body:
You have a misconception on how ROW_NUMBER() works. With two distinct ROW_NUMBER() commands, you have two separate row number sequences. You can correct your issue by changing your CTE like this:

WITH cte1 (Captivate_Id, Building_Name ,Server_Name)
    AS (
        SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
            ,'' as Server_Name    -- If you want a blank servername, make it so
        FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
        join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b
            on     s.building_id = b.building_id
        WHERE s.Server_Name IS NULL

        UNION ALL

        SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
            ,(s.Server_Name) as Server_Name
        FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
        join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b
            on s.building_id = b.building_id
        AND b.Captivate_Id IN (
            'FFF1234'
            )
    ),
cte (Captivate_Id, Building_Name ,Server_Name, Server_Number)
    as (
        SELECT Captivate_ID,
            Building_Name,
            Server_Name,
            ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
        FROM cte1
    )

SELECT Captivate_ID as ID,Building_Name as Building_Name,
    (SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name AND ct.Server_Number=1) Server1,-----, -- works but order wrong
    (SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name AND ct.Server_Number=2) Server2, -- works but order wrong
    (SELECT Server_Name FROM CTE ct WHERE ct.Building_Name=cte.Building_Name AND ct.Server_Number=3) Server3
FROM cte

SPOILER - Original bad code

 WITH
  cte (Captivate_Id, Building_Name ,Server_Name, Server_Number)
 as (
  SELECT Captivate_ID,
      Building_Name,
      Server_Name,
      ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
  FROM (
      SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
          ,'' as Server_Name      -- If you want a blank servername, make it so
  --      ,ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
      FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
      join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b
          on  s.building_id = b.building_id
      WHERE s.Server_Name IS NULL
      UNION ALL
      SELECT b.[Captivate_Id], b.[Building_Name] as Building_Name
          ,(s.Server_Name) as Server_Name
  --      ,ROW_NUMBER() OVER(ORDER BY s.Server_Name DESC) AS Server_Number
      FROM [CAP-CORPCRM02].[CAP_ProductionED].dbo.server s
      join [CAP-CORPCRM02].[CAP_ProductionED].dbo.building b
                 on s.building_id = b.building_id
                 AND b.Captivate_Id IN (
                     'FFF1234'
                     )
                 )
  )


问:
How to run the same parameter to 22 similar databases?
I have been pulling data from a single database that stores the data for 22 facilities together. The database has now been redesigned and there are 22 separate databases (similar) for each of the facilities that we have. How can use the same code and run it against all these databases at the same time? Like, how can I pass the same parameter and pull data from all 22 databases?</p>

答:
You can use CURSOR to achieve your requirement. Here I placed a sample Dynamic Insert Script which you can adjust as per your requirement. One manual task is you have to insert one by one 22 database name using script in a temporary table. The facility is that is is a one time work and you can re use the script when ever it is required.</p>

```<code>--The first step will be creating a Table variable
--where you will INSERT all your database names
--for a further loop as below-

DECLARE @DbName VARCHAR(200)
DECLARE @DatabaseList TABLE (DbName VARCHAR(200))

INSERT INTO @DatabaseList (DbName) VALUES('db_name_1')
INSERT INTO @DatabaseList (DbName) VALUES('db_name_2')
--.......................
INSERT INTO @DatabaseList (DbName) VALUES('db_name_22')

--Now you can use CURSOR to generate the loop
--and execute your required script as shown below

DECLARE db_cursor CURSOR FOR
SELECT DbName FROM @DatabaseList

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @DbName

WHILE @@FETCH_STATUS = 0
BEGIN

    --HERE You need to write your script That you
    --Execute for all your database. I have added
    --a sample script for your reference only

    -- You can see the Database Name inserted in the Script Dynamically from the Loop.
    --The script could be INSERT/Update/DELETE As per requirement

    EXEC
    (
        'INSERT INTO '+@DbName+'.dbo.<Your_table_Name_Here>
        SELECT * FROM  master.dbo.<Your_table_Name_Here> '
    )

    --END OF Dynamic Part

    FETCH NEXT FROM db_cursor INTO @DbName
END

CLOSE db_cursor
DEALLOCATE db_cursor
</code>```

Body:
You can use CURSOR to achieve your requirement. Here I placed a sample Dynamic Insert Script which you can adjust as per your requirement. One manual task is you have to insert one by one 22 database name using script in a temporary table. The facility is that is is a one time work and you can re use the script when ever it is required.

--The first step will be creating a Table variable
--where you will INSERT all your database names
--for a further loop as below-

DECLARE @DbName VARCHAR(200)
DECLARE @DatabaseList TABLE (DbName VARCHAR(200))

INSERT INTO @DatabaseList (DbName) VALUES('db_name_1')
INSERT INTO @DatabaseList (DbName) VALUES('db_name_2')
--.......................
INSERT INTO @DatabaseList (DbName) VALUES('db_name_22')

--Now you can use CURSOR to generate the loop
--and execute your required script as shown below

DECLARE db_cursor CURSOR FOR
SELECT DbName FROM @DatabaseList

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @DbName

WHILE @@FETCH_STATUS = 0
BEGIN

    --HERE You need to write your script That you
    --Execute for all your database. I have added
    --a sample script for your reference only

    -- You can see the Database Name inserted in the Script Dynamically from the Loop.
    --The script could be INSERT/Update/DELETE As per requirement

    EXEC
    (
        'INSERT INTO '+@DbName+'.dbo.<Your_table_Name_Here>
        SELECT * FROM  master.dbo.<Your_table_Name_Here> '
    )

    --END OF Dynamic Part

    FETCH NEXT FROM db_cursor INTO @DbName
END

CLOSE db_cursor
DEALLOCATE db_cursor


问:
Type Punning with Unions and Heap
I have read a lot about type punning and how it is not good to just use a cast.

```<code>oldType* data = malloc(sizeof(oldType));
((newtype*)data)->newElement;
</code>```

This results in undefined behavior. So the solution is to use union so that the compiler knows that these two pointers are linked to one another so it doesn't do funny things with strict aliasing.

That being said the unions also looked like:

```<code>union testing
{
    struct test1 e;
    struct test2 f;
}
</code>```

Is it defined behavior if pointers are used in the union?

```<code>union testing
{
    struct test1* e;
    struct test2* f;
}
</code>```

Here is a full example:

```<code>#include <stdio.h>
#include <stdlib.h>

struct test1
{
    int a;
    char b;
};

struct test2
{
    int c;
    char d;
};

union testing
{
    struct test1* e;
    struct test2* f;
};

void printer(const struct test2* value);

int main()
{
    struct test1* aQuickTest = malloc(sizeof(struct test1));
    aQuickTest->a = 42;
    aQuickTest->b = 'a';
    printer(((union testing)aQuickTest).f);
    ((union testing)aQuickTest.f)->c = 111; // using -> not .
    return 0;
}

void printer(const struct test2* value)
{
    printf("Int: %i Char: %c",value->c, value->d);
}
</code>```

Or would I need to use unions without pointers. And then use printer(&(((union testing)aQuickTest).f)); (with the &) to get the address of f.

答:
It is non-conforming to cast to a union type, as your code does:

```<code>    printer(((union testing)aQuickTest).f);
</code>```

For that reason, your code does have undefined behavior as far as the Standard is concerned.

More directly to the point, however, no, your approach of putting pointers into a union does not avoid strict aliasing violations with respect to the pointed-to types, even without the casting issue.  In your case, the effect is that where your union testing is in scope, implementations cannot assume that objects of type struct test1 ** and struct test2 ** do not alias each other.  That does not prevent undefined defined behavior resulting from accessing an object with effective type struct test1 through an lvalue of type struct test2.

Title: Type Punning with Unions and Heap

Body:
I have read a lot about type punning and how it is not good to just use a cast.

oldType* data = malloc(sizeof(oldType));
((newtype*)data)->newElement;

This results in undefined behavior. So the solution is to use union so that the compiler knows that these two pointers are linked to one another so it doesn't do funny things with strict aliasing.

That being said the unions also looked like:

union testing
{
    struct test1 e;
    struct test2 f;
}

Is it defined behavior if pointers are used in the union?

union testing
{
    struct test1* e;
    struct test2* f;
}

Here is a full example:

#include <stdio.h>
#include <stdlib.h>

struct test1
{
    int a;
    char b;
};

struct test2
{
    int c;
    char d;
};

union testing
{
    struct test1* e;
    struct test2* f;
};

void printer(const struct test2* value);

int main()
{
    struct test1* aQuickTest = malloc(sizeof(struct test1));
    aQuickTest->a = 42;
    aQuickTest->b = 'a';
    printer(((union testing)aQuickTest).f);
    ((union testing)aQuickTest.f)->c = 111; // using -> not .
    return 0;
}

void printer(const struct test2* value)
{
    printf("Int: %i Char: %c",value->c, value->d);
}

Or would I need to use unions without pointers. And then use printer(&(((union testing)aQuickTest).f)); (with the &) to get the address of f.

Body:
It is non-conforming to cast to a union type, as your code does:

    printer(((union testing)aQuickTest).f);

For that reason, your code does have undefined behavior as far as the Standard is concerned.

More directly to the point, however, no, your approach of putting pointers into a union does not avoid strict aliasing violations with respect to the pointed-to types, even without the casting issue.  In your case, the effect is that where your union testing is in scope, implementations cannot assume that objects of type struct test1 ** and struct test2 ** do not alias each other.  That does not prevent undefined defined behavior resulting from accessing an object with effective type struct test1 through an lvalue of type struct test2.


问:
How to relocate Moment variables to state from render
I'd like to know how I can better store the variables I am using for moment in my react component.

I've already tried just declaring the variables in the constructor below the setState, but these variables are not changeable. I then tried to store the variables in the state, as key value pairs but since one of the values is dependent on another, it did not work.

Here is my current constructor:

```<code>constructor(props) {
super(props);
this.state = {
  scooter: props.scooter,
  header: props.header,
  reservation: ""
};
}

componentWillReceiveProps(nextProps) {
this.setState({
  scooter: nextProps.scooter,
  header: nextProps.header
});
}
</code>```

Some items will have to be called as well in componentsWillRecieveProps as the item will change with next props.

variables below

```<code>render() {
const reservation = this.state.scooter.state.LastAdminReservation;
var a = moment();
const c = moment(reservation.PendingDate);
const d = moment(reservation.EndDate);
const duration = d.from(c, true);
var timeSince = a.from(d, true);
const date = moment(reservation.DownloadAckDate).format("DD.MM.YYYY
HH:mm");
</code>```

I'd like to be able to call these variables in my return and have var a and var timeSince be updated on next props while not storing them in my render as this is bad practice. Thanks!

答:
You can do like this (putting in the state only variable that will be used inside other methods.</p>

```<code>constructor() {
    super();

    const a = moment();
    const c = moment(new Date());
    const d = moment(new Date());
    const duration = d.from(c, true);
    const timeSince = a.from(d, true);

    this.state = {
      name: 'React',
      timeSince
    };
  }
</code>```

Body:
I'd like to know how I can better store the variables I am using for moment in my react component.

I've already tried just declaring the variables in the constructor below the setState, but these variables are not changeable. I then tried to store the variables in the state, as key value pairs but since one of the values is dependent on another, it did not work.

Here is my current constructor:

constructor(props) {
super(props);
this.state = {
  scooter: props.scooter,
  header: props.header,
  reservation: ""
};
}

componentWillReceiveProps(nextProps) {
this.setState({
  scooter: nextProps.scooter,
  header: nextProps.header
});
}

Some items will have to be called as well in componentsWillRecieveProps as the item will change with next props.

variables below

render() {
const reservation = this.state.scooter.state.LastAdminReservation;
var a = moment();
const c = moment(reservation.PendingDate);
const d = moment(reservation.EndDate);
const duration = d.from(c, true);
var timeSince = a.from(d, true);
const date = moment(reservation.DownloadAckDate).format("DD.MM.YYYY
HH:mm");

I'd like to be able to call these variables in my return and have var a and var timeSince be updated on next props while not storing them in my render as this is bad practice. Thanks!

Body:
You can do like this (putting in the state only variable that will be used inside other methods.

constructor() {
    super();

    const a = moment();
    const c = moment(new Date());
    const d = moment(new Date());
    const duration = d.from(c, true);
    const timeSince = a.from(d, true);

    this.state = {
      name: 'React',
      timeSince
    };
  }


问:
How to create a pandas dataframe where columns are filled with random strings?
I want to create a Pandas dataframe with 2 columns and x number rows that contain random strings.

I have found code to generate a pandas dataframe with random ints and a random stringer generator. I still don't see a clear path to create a pandas data frame with random strings.

Code for random int dataframe

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
```

<p>Code for random strings</p>

<pre class="lang-py prettyprint-override"><code>import string
import random
def id_generator(size=1500, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

id_generator()
</code>```

I would like destiredDataframe.head() to output two columns of random text and x number of rows.

答:
Try this:</p>

```<code>num_rows = 10

data = np.array([id_generator() for i in range(2*num_rows)]).reshape(-1,2)
pd.DataFrame(data)
</code>```

Body:
I want to create a Pandas dataframe with 2 columns and x number rows that contain random strings.

I have found code to generate a pandas dataframe with random ints and a random stringer generator. I still don't see a clear path to create a pandas data frame with random strings.

Code for random int dataframe

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Code for random strings

import string
import random
def id_generator(size=1500, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

id_generator()

I would like destiredDataframe.head() to output two columns of random text and x number of rows.

Body:
Try this:

num_rows = 10

data = np.array([id_generator() for i in range(2*num_rows)]).reshape(-1,2)
pd.DataFrame(data)


问:
Self Updating Powershell script
What would be the best way to have a self updating (from SVN) Powershell script?

It should be able to start a new process and then call SVN update $script; './$script', after making sure the current process has ended.

```<code>if ((svn st -u --quiet $script) -match "\*"){
     $scriptToRun = 'SVN update $script; "./$script"'
     ##start new process that will end this process and execute $scriptToRun
}
</code>```

答:
I'm not sure it's a good idea to have a script update itself. You might try doing it from the Task Scheduler or if the script must do it then break it into 2 parts the first one is what the user runs. Keep this small and simple. The second part is what you update out of svn and it should do the bulk of the work.

Basically small user script that handles arguments and autoupdate. Second part that does the bulk of the work and gets autoupdated.

Title: Self Updating Powershell script

Body:
What would be the best way to have a self updating (from SVN) Powershell script?

It should be able to start a new process and then call SVN update $script; './$script', after making sure the current process has ended.

if ((svn st -u --quiet $script) -match "\*"){
     $scriptToRun = 'SVN update $script; "./$script"'
     ##start new process that will end this process and execute $scriptToRun
}


问:
How do I make my function run on a schedule instead of an API call using AWS SAM
I have just starting using AWS SAM and I need to run my Lambda function on a schedule as apposed to an API call

here is my yaml template that I am using

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  shed

  Sample SAM Template for shed

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs8.10
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn
</code>```

How do I get my HelloWorldFunction to run on a schedule say every Friday at 17:00?

答:
you need to change your yaml file the Resources section needs to be changed to:</p>

```<code>
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs8.10
      Events:
        EveryFriDay:
          Type: Schedule
          Properties:
            Schedule: cron(0 0 17 ? * FRI *)
</code>```

Body:
I have just starting using AWS SAM and I need to run my Lambda function on a schedule as apposed to an API call

here is my yaml template that I am using

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  shed

  Sample SAM Template for shed

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs8.10
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

How do I get my HelloWorldFunction to run on a schedule say every Friday at 17:00?

Body:
you need to change your yaml file the Resources section needs to be changed to:

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs8.10
      Events:
        EveryFriDay:
          Type: Schedule
          Properties:
            Schedule: cron(0 0 17 ? * FRI *)


问:
How do I limit the results to 20?
Need to the limit the results of this to the first 20.

Is there another way I can loop this to get 20 results at a time?

```<code>$Array = @()
#Fill $Array with Data
$List = $Array | ForEach-Object {"$_`n"}
</code>```

答:
Personally, I would limit ther returned results prior to the looping construct. My example uses the names of service objects, but I needed something to use...

```<code>$TOlist = (Get-Service).Name
$TOlist | Select-Object -First 20 | ForEach-Object {
    $_
}
</code>```

You'll need to use at least two lines here. As far as I'm aware, you can't both assign your $TOlist variable and start sending each value down the pipeline.

Title: How do I limit the results to 20?

Body:
Need to the limit the results of this to the first 20.

Is there another way I can loop this to get 20 results at a time?

$Array = @()
#Fill $Array with Data
$List = $Array | ForEach-Object {"$_`n"}

Body:
Personally, I would limit ther returned results prior to the looping construct. My example uses the names of service objects, but I needed something to use...

$TOlist = (Get-Service).Name
$TOlist | Select-Object -First 20 | ForEach-Object {
    $_
}

You'll need to use at least two lines here. As far as I'm aware, you can't both assign your $TOlist variable and start sending each value down the pipeline.


问:
How to initialize a two-dimensional array?
I'm having trouble initializing an array. When I try to draw the Array I'm getting a NullPointerException.

I need to access the class where I've declared the array from another class, that's why it's static.

Here's my code:

```<code>static int[][] DayOfTheMonth = new int[3][10];

public static void ArrayValue() {
    for (int column = 0; DayOfTheMonth.length < 4; column++) {
        for (int row = 10; DayOfTheMonth[column].length < 10; row++) {
            if (DaysofTheMonth <= Tag.MaximumDaysOfAMonth()) {

                DayOfTheMonth.[column][row] = Date.getDate() + DaysofTheMonth;
                DaysofTheMonth++;

            } else if (DaysofTheMonth > Tag.MaxDay()) {
                DaysofTheMonth = 1;

                if (Month != 12)
                    Month++;
                else {
                    Month = 0;
                    Year++;

                }
            }
        }
    }
}
</code>```

Another problem is that, when I try to access the method trough my main class, it says:

```<code>Exception in thread "Main" java.lang.ArrayIndexOutOfBoundsException: 3
</code>```

答:
ArrayIndexOutOfBoundsException states you are trying to access an Element from and Index that does not exists so,

In this line:

```<code>for (int column = 0;  DayOfTheMonth.length < 4; column++)
</code>```

You have specified to go For Loop to go infinite because the length will always be less than 4 so you need to have column in condition like

```<code>for (int column = 0;  column < DayOfTheMonth.length; column++)
</code>```

So Make it loop until 3, as it will start from 0 and go up to 3.

And 1 more thing for your clarity the 1st Thing is Row and Second is column, so you have 3 rows and 10 columns although its just related to naming-problem but you should be clear about it.

Body:
I'm having trouble initializing an array. When I try to draw the Array I'm getting a NullPointerException.

I need to access the class where I've declared the array from another class, that's why it's static.

Here's my code:

static int[][] DayOfTheMonth = new int[3][10];

public static void ArrayValue() {
    for (int column = 0; DayOfTheMonth.length < 4; column++) {
        for (int row = 10; DayOfTheMonth[column].length < 10; row++) {
            if (DaysofTheMonth <= Tag.MaximumDaysOfAMonth()) {

                DayOfTheMonth.[column][row] = Date.getDate() + DaysofTheMonth;
                DaysofTheMonth++;

            } else if (DaysofTheMonth > Tag.MaxDay()) {
                DaysofTheMonth = 1;

                if (Month != 12)
                    Month++;
                else {
                    Month = 0;
                    Year++;

                }
            }
        }
    }
}

Another problem is that, when I try to access the method trough my main class, it says:

Exception in thread "Main" java.lang.ArrayIndexOutOfBoundsException: 3

Body:
ArrayIndexOutOfBoundsException states you are trying to access an Element from and Index that does not exists so,

In this line:

for (int column = 0;  DayOfTheMonth.length < 4; column++)

You have specified to go For Loop to go infinite because the length will always be less than 4 so you need to have column in condition like

for (int column = 0;  column < DayOfTheMonth.length; column++)

So Make it loop until 3, as it will start from 0 and go up to 3.

And 1 more thing for your clarity the 1st Thing is Row and Second is column, so you have 3 rows and 10 columns although its just related to naming-problem but you should be clear about it.


问:
Laravel Elixer not able to minify and version javascript files
i am using laravel 5.1 elixer to manage, version, minify my application css and js

Below is my gulpfile.js

```<code>elixir(function (mix) {
    mix.less([
        'app.less',
        'creative.less',
        'mixins.less',
        'variables.less'
    ]).less([
        'dashboard.less',
        'component.less',
        'app-variables.less'
    ], 'public/css/dashboard.css')

    mix.scriptsIn('public/js/angular/controller', 'public/js/angular/appControllers.min.js');
    mix.scriptsIn('public/js/angular/service', 'public/js/angular/appServices.min.js');
    mix.scriptsIn('public/js/angular/directive', 'public/js/angular/appDerictives.min.js');

    mix.version([
        'public/css/dashboard.css',
        'public/css/app.css',
        'public/js/angular/appControllers.min.js',
        'public/js/angular/appServices.min.js',
        'public/js/angular/appDerictives.min.js'
    ]);
});
</code>```

Everything works fine when i run the command gulp, i get the compiled files and also the versions files are now in the build folder.

The problem starts when i use gulp --production, When laravel starts the process is breaks when starting with scripts, below is the error -

```<code>events.js:141
 throw er; // Unhandled 'error' event
 ^
Error at new JS_Parse_Error (eval at <anonymous (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:1534:18)
at js_error (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:1542:11)
at croak (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2089:9)
at token_error (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2097:9)
at unexpected (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2103:9)
at expr_atom (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2630:9)
at maybe_unary (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2792:19)
at expr_ops (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2827:24)
at maybe_conditional (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2832:20)
at maybe_assign (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2856:20)
</code>```

The problem is surely with the scriptsIn part of gulp file, or i could say that gulp is not able to minify the js files.

I have tried debugging this through multiple ways, but still not able to find the problem. Tried to update/downgrade the relevant packages, but even that didn't help.

Any help would be appreciated.

答:
Just ran into this working on an old Laravel 5.1 project.

Mostly this seems to be caused by some new ECMAScript 6+ code you added that uglyfijs is not able to parse. To fix this you need to either use buble or babel to automatically convert the code when you run gulp, or change the code in question to 'regular' js.

See this issue: https://github.com/JeffreyWay/laravel-elixir-webpack-official/issues/34

Use babel to auto convert your code when runing gulp:

source: https://laravel.com/docs/5.1/elixir#babel

```<code>elixir(function(mix) {
    mix.babel([
        'order.js',
        'product.js'
    ]);
});
</code>```

or Fix your code, use the following to figure out which script is the culprit:

./node_modules/.bin/uglifyjs path/to/resources/assets/js/some_script.js

Do this for every script until it complains. If it throws an error it will point you to the line number.

Body:
i am using laravel 5.1 elixer to manage, version, minify my application css and js

Below is my gulpfile.js

elixir(function (mix) {
    mix.less([
        'app.less',
        'creative.less',
        'mixins.less',
        'variables.less'
    ]).less([
        'dashboard.less',
        'component.less',
        'app-variables.less'
    ], 'public/css/dashboard.css')

    mix.scriptsIn('public/js/angular/controller', 'public/js/angular/appControllers.min.js');
    mix.scriptsIn('public/js/angular/service', 'public/js/angular/appServices.min.js');
    mix.scriptsIn('public/js/angular/directive', 'public/js/angular/appDerictives.min.js');

    mix.version([
        'public/css/dashboard.css',
        'public/css/app.css',
        'public/js/angular/appControllers.min.js',
        'public/js/angular/appServices.min.js',
        'public/js/angular/appDerictives.min.js'
    ]);
});

Everything works fine when i run the command gulp, i get the compiled files and also the versions files are now in the build folder.

The problem starts when i use gulp --production, When laravel starts the process is breaks when starting with scripts, below is the error -

events.js:141
 throw er; // Unhandled 'error' event
 ^
Error at new JS_Parse_Error (eval at <anonymous (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:1534:18)
at js_error (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:1542:11)
at croak (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2089:9)
at token_error (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2097:9)
at unexpected (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2103:9)
at expr_atom (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2630:9)
at maybe_unary (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2792:19)
at expr_ops (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2827:24)
at maybe_conditional (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2832:20)
at maybe_assign (eval at <anonymous> (/Users/apple/code/hireajackal/node_modules/gulp-uglify/node_modules/uglify-js/tools/node.js:28:1), <anonymous>:2856:20)

The problem is surely with the scriptsIn part of gulp file, or i could say that gulp is not able to minify the js files.

I have tried debugging this through multiple ways, but still not able to find the problem. Tried to update/downgrade the relevant packages, but even that didn't help.

Any help would be appreciated.

Body:
Just ran into this working on an old Laravel 5.1 project.

Mostly this seems to be caused by some new ECMAScript 6+ code you added that uglyfijs is not able to parse. To fix this you need to either use buble or babel to automatically convert the code when you run gulp, or change the code in question to 'regular' js.

See this issue: https://github.com/JeffreyWay/laravel-elixir-webpack-official/issues/34

Use babel to auto convert your code when runing gulp:

source: https://laravel.com/docs/5.1/elixir#babel

elixir(function(mix) {
    mix.babel([
        'order.js',
        'product.js'
    ]);
});

or Fix your code, use the following to figure out which script is the culprit:

./node_modules/.bin/uglifyjs path/to/resources/assets/js/some_script.js

Do this for every script until it complains. If it throws an error it will point you to the line number.


问:
Android AsynkTask problem with HttpUtilities class
I want to tell you about the structure of my classes.

I have an HttpUtilities class, from which I am doing requests(send and get JSON objects) to server. It's a public class with private constructor and static methods.

I have also user class which manipulates data(set string to JSON, and JSON to ...).

Within my activity I have declared the instance of user class.
There are some methods(SignIn, SignOut, InserToListView) there which call corresponding methods of httpUtilities.

Now, I want, that for each event of user, using AsynkTask do request to server and change ui.
I want to call method(for example InserToListview) of user class within new Thread using AsynkTask.

答:
It would be easier if you tried your hand at this first and then asked questions later, but here is some general advice to get you started:

Subclass AsyncTask.

Implement doInBackground, calling your insert method.

(Wherever you are calling your insert method now) instantiate your subclass of AsyncTask.

Call the execute method on your new custom AsyncTask object.

Store your AsyncTask in an instance variable so you can cancel it later on.

OwnerDisplayName: newprog


问:
Validating a record to see if it only contains digits
I am validating VAT codes. The codes include GB in front of them but i would like to not include that and see if the rest of the vat code only includes numbers. </p>

```<code>select KUNNR,VAT_CODE,REPLACE(VAT_CODE,'GB',''),
       CASE WHEN REPLACE(VAT_CODE,'GB','') LIKE '%[^0-9]%'   THEN 'Yes' ELSE 'No' END as VAT_MATCH
FROM  CUSTOMER_TBL;

"customer"  "VAT"           "REPLACE(VAT,'GB','')"  "VAT_MATCH"
"0063591544"    "GB111111111"   "111111111"           "No"
</code>```

答:
This is how I would do it:

```<code>-- Sample Data
DECLARE @CUSTOMER_TBL TABLE (VAT_CODE VARCHAR(36));
INSERT @CUSTOMER_TBL VALUES ('GB123111GB'),('GB9999111'),('GBB9999111'),('GGB7777222'),
                            ('553399444'),('GB22223366'),('GB22223366X')

-- solution
SELECT t.VAT_CODE, VAT_MATCH = IIF(f.H = 'GB' AND PATINDEX('%[^0-9]%',f.B) = 0,'Yes','No')
FROM        @CUSTOMER_TBL AS t
CROSS APPLY (VALUES (SUBSTRING(t.VAT_CODE,1,2),SUBSTRING(t.VAT_CODE,3,8000))) AS f(H,B);

/* For pre-2012 systems:
   VAT_MATCH = CASE WHEN f.H = 'GB' AND PATINDEX('%[^0-9]%',f.B) = 0 THEN 'Yes' ELSE 'No' END */;
</code>```

Results

```<code>VAT_CODE                             VAT_MATCH
------------------------------------ ---------
GB123111GB                           No
GB9999111                            Yes
GBB9999111                           No
GGB7777222                           No
553399444                            No
GB22223366                           Yes
GB22223366X                          No
</code>```

Body:
I am validating VAT codes. The codes include GB in front of them but i would like to not include that and see if the rest of the vat code only includes numbers.

select KUNNR,VAT_CODE,REPLACE(VAT_CODE,'GB',''),
       CASE WHEN REPLACE(VAT_CODE,'GB','') LIKE '%[^0-9]%'   THEN 'Yes' ELSE 'No' END as VAT_MATCH
FROM  CUSTOMER_TBL;

"customer"  "VAT"           "REPLACE(VAT,'GB','')"  "VAT_MATCH"
"0063591544"    "GB111111111"   "111111111"           "No"

Body:
This is how I would do it:

-- Sample Data
DECLARE @CUSTOMER_TBL TABLE (VAT_CODE VARCHAR(36));
INSERT @CUSTOMER_TBL VALUES ('GB123111GB'),('GB9999111'),('GBB9999111'),('GGB7777222'),
                            ('553399444'),('GB22223366'),('GB22223366X')

-- solution
SELECT t.VAT_CODE, VAT_MATCH = IIF(f.H = 'GB' AND PATINDEX('%[^0-9]%',f.B) = 0,'Yes','No')
FROM        @CUSTOMER_TBL AS t
CROSS APPLY (VALUES (SUBSTRING(t.VAT_CODE,1,2),SUBSTRING(t.VAT_CODE,3,8000))) AS f(H,B);

/* For pre-2012 systems:
   VAT_MATCH = CASE WHEN f.H = 'GB' AND PATINDEX('%[^0-9]%',f.B) = 0 THEN 'Yes' ELSE 'No' END */;

Results

VAT_CODE                             VAT_MATCH
------------------------------------ ---------
GB123111GB                           No
GB9999111                            Yes
GBB9999111                           No
GGB7777222                           No
553399444                            No
GB22223366                           Yes
GB22223366X                          No


问:
Using aggregate function value again in the query
I would like to use the value of count() in the same query inside greatest(). Is there a way to do this?

I tried count(id) as my_count, greatest(my_count, 7) but it gives an error:
 ERROR 1054 (42S22): Unknown column 'my_count' in 'field list'

If I use greatest(count(id), 7) will it increase the query time?

Also can I do the same in JPA @Query?

答:
You cannot use aliases from a SELECT within the same SELECT, aliases from a subquery's SELECT can be used in an outer query. I'm not sure if MySQL optimizes multiple identical COUNT expressions in a single select, but I'd hope so.

When I've been really concerned about needing the same expression twice, and the possible performance implications of repeating it (or, more often, the impact on readability/maintainablity of repeated lengthy expressions), I've found turning the "main" query into a subquery, and using the alias repeatedly in a wrapping query to be helpful.

In the general form, something like this

SELECT stuff, long_equation AS r1, long_equation_with_extra_operations AS r2 FROM tables

becomes

```<code>SELECT mainQ.*, r1_with_extra_operations AS r2
FROM (SELECT stuff, long_equation AS r1 FROM tables) AS mainQ
</code>```

For this question's particular case, the following would be the application of the above tactic:

```<code>SELECT my_count, GREATEST(my_count, 7)
FROM (SELECT COUNT(*) AS my_count ....) AS mainQ
</code>```

Note: the subquery will obviously have to include any fields used in the "extra operations" portion, so depending on the specifics of the original query  this tactic is not always possible or at least may not be as straightforward to use.

(GREATEST, in a SELECT expression, should have very little performance impact; it is the equivalent of CASE WHEN a IS NULL OR b IS NULL THEN NULL WHEN a > b THEN a ELSE b END. However, using it in a WHERE or ON clause could hurt performance significantly since MySQL cannot cannot take advantage of indexes on fields in such cases.

Body:
You cannot use aliases from a SELECT within the same SELECT, aliases from a subquery's SELECT can be used in an outer query. I'm not sure if MySQL optimizes multiple identical COUNT expressions in a single select, but I'd hope so.

When I've been really concerned about needing the same expression twice, and the possible performance implications of repeating it (or, more often, the impact on readability/maintainablity of repeated lengthy expressions), I've found turning the "main" query into a subquery, and using the alias repeatedly in a wrapping query to be helpful.

In the general form, something like this

SELECT stuff, long_equation AS r1, long_equation_with_extra_operations AS r2 FROM tables

becomes

SELECT mainQ.*, r1_with_extra_operations AS r2
FROM (SELECT stuff, long_equation AS r1 FROM tables) AS mainQ

For this question's particular case, the following would be the application of the above tactic:

SELECT my_count, GREATEST(my_count, 7)
FROM (SELECT COUNT(*) AS my_count ....) AS mainQ

Note: the subquery will obviously have to include any fields used in the "extra operations" portion, so depending on the specifics of the original query  this tactic is not always possible or at least may not be as straightforward to use.

(GREATEST, in a SELECT expression, should have very little performance impact; it is the equivalent of CASE WHEN a IS NULL OR b IS NULL THEN NULL WHEN a > b THEN a ELSE b END. However, using it in a WHERE or ON clause could hurt performance significantly since MySQL cannot cannot take advantage of indexes on fields in such cases.


问:
Xamarin, is there a way to update list on picker when user changes it's mind?
without hitting Done. for example user selects 2 first, so list updates 1,3,4 are available on picker 2, but when i changes it to 1 then hit done 3 and 4 are the only ones available.  It's triggering to update list everytime even when DONE is not pressed yet on Picker.

I can't seem to find the right or come close to a solution

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace demo
{
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(true)]
public partial class MainPage : ContentPage
{
List<string> list;

public MainPage()
{
InitializeComponent();
list = new List<string>();

list.Add("1");
list.Add("2");
list.Add("3");
list.Add("4");
drainxy1();
drainxy2();
drainxy3();
drainxy4();

drainlocationPicker1.SelectedIndexChanged +=
drain1Handle_SelectedIndexChanged;
drainlocationPicker2.SelectedIndexChanged +=
drain2Handle_SelectedIndexChanged;
drainlocationPicker3.SelectedIndexChanged +=
drain3Handle_SelectedIndexChanged;
drainlocationPicker4.SelectedIndexChanged +=
drain4Handle_SelectedIndexChanged;
}

private void drain4Handle_SelectedIndexChanged(object sender, EventArgs e)
{

}

private void drain3Handle_SelectedIndexChanged(object sender, EventArgs e)
{
drainlocationPicker1.IsEnabled = false;
drainlocationPicker2.IsEnabled = false;
drainlocationPicker4.Items.Remove((string)drainlocationPicker3.SelectedIte
m);

}

private void drain2Handle_SelectedIndexChanged(object sender, EventArgs e)
{
drainlocationPicker1.IsEnabled = false;

drainlocationPicker3.Items.Remove((string)drainlocationPicker2.SelectedIte
m);
drainlocationPicker4.Items.Remove((string)drainlocationPicker2.SelectedIte
m);

}

private void drain1Handle_SelectedIndexChanged(object sender, EventArgs e)
{

drainlocationPicker2.Items.Remove((string)drainlocationPicker1.SelectedItem);
drainlocationPicker3.Items.Remove((string)drainlocationPicker1.SelectedItem);
drainlocationPicker4.Items.Remove((string)drainlocationPicker1.SelectedItem);
}

void drainxy1()
{
foreach (var item in list)
{
    drainlocationPicker1.Items.Add(item);
}
}
void drainxy2()
{

foreach (var item in list)
{
    drainlocationPicker2.Items.Add(item);
}
}
void drainxy3()
{

foreach (var item in list)
{
    drainlocationPicker3.Items.Add(item);
}
}
void drainxy4()
{

foreach (var item in list)
{
drainlocationPicker4.Items.Add(item);
}
}
}
}
```

答:
This is the default behavior for pickers on iOS. If you want it to update only once "Done" is tapped you need to add this for every picker:

pickerName.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished); where pickerName is the x:Name="pickerName" assigned to the picker in your xaml.

This can also be done in the xaml, but its a little messy and adds a permanent blue squiggle which annoys me.

Edit: See Picker Item Selection for doing it in xaml.

Now that picker will not change the value until done is pressed.