问:
chaining c# async / await tasks, recreating them as they complete
Aesthetic question really.

Given this code (polling unavoidable):

```<code>protected override async Task ExecuteAsync(CancellationToken ct)
{
    // move the loop here somehow?
    await Task.WhenAll(
        Task.Run(async () => await this.PollA(ct), ct),
        Task.Run(async () => await this.PollB(ct), ct),
        Task.Run(async () => await this.PollC(ct), ct))
        .ConfigureAwait(false);
}
</code>```

the polling methods look like this at the moment, each one has a different delay.

```<code>private async Task Poll(CancellationToken ct)
{
    while (!ct.IsCancellationRequested)
    {
        await Task.Delay(Math.Max(1000, CONFIGA), ct);
        this._logger.StartAction("poll A status");
        this._logger.StopAction("poll A status");
    }
}
</code>```

Is there a way to structure a continuation that removes the loop in each of the Poll methods

```<code>private async Task Poll(CancellationToken ct)
{
    await Task.Delay(Math.Max(1000, CONFIGA), ct);
    this._logger.StartAction("poll A status");
    this._logger.StopAction("poll A status");
}
</code>```

This might not even be the right pattern, but it seems better than having three infinite loops.

```<code>Task.WhenAny([A,B,C]) =>
// recreate any complete task as soon as it returns
// and await the new "continuation"?
</code>```

答:
I have an Aesthetic solution, that is probably not advisable to be used since it will probably cause stack overflow eventually.
It maybe demonstrates why the loop is a better option.

I must admit do not really understand your example in a real world context.
In my mind almost all code that executes for a long time will do it in a finite loop, and thus to check for cancellation after each loop iteration sounds like a good idea to me.

Unless you want your code just to run infinitely until the task is canceled, in which case my aesthetic solution will probably cause a stack overflow if left to long, but it was fun none the less coming up with this code.

I created a Extension method:

```<code>public static class Extensions
{
    public static async Task ContinueWithInfinitly(this Task task, Func<Task> continuationAction, CancellationToken cancellationToken)
    {
        await task;
        if (!cancellationToken.IsCancellationRequested)
        {
            var newTask = continuationAction.Invoke();
            await newTask.ContinueWithInfinitly(continuationAction, cancellationToken);
        }
    }
}
</code>```

Which Base on your code will then be called as follows:

```<code>await Task.WhenAll(
                Task.Run(async () => await this.PollA(ct).ContinueWithInfinitly(() => PollA(ct), ct)),
                Task.Run(async () => await this.PollB(ct).ContinueWithInfinitly(() => PollB(ct), ct)),
                Task.Run(async () => await this.PollC(ct).ContinueWithInfinitly(() => PollC(ct), ct)))
                .ConfigureAwait(false);
</code>```

Although I dont see the point of wrapping each method again in a Task.Run.
So i can also just be

```<code>await Task.WhenAll(
                this.PollA(ct).ContinueWithInfinitly(() => PollA(ct), ct),
                this.PollB(ct).ContinueWithInfinitly(() => PollB(ct), ct),
                this.PollC(ct).ContinueWithInfinitly(() => PollC(ct), ct))
                .ConfigureAwait(false);
</code>```

Body:
Aesthetic question really.

Given this code (polling unavoidable):

protected override async Task ExecuteAsync(CancellationToken ct)
{
    // move the loop here somehow?
    await Task.WhenAll(
        Task.Run(async () => await this.PollA(ct), ct),
        Task.Run(async () => await this.PollB(ct), ct),
        Task.Run(async () => await this.PollC(ct), ct))
        .ConfigureAwait(false);
}

the polling methods look like this at the moment, each one has a different delay.

private async Task Poll(CancellationToken ct)
{
    while (!ct.IsCancellationRequested)
    {
        await Task.Delay(Math.Max(1000, CONFIGA), ct);
        this._logger.StartAction("poll A status");
        this._logger.StopAction("poll A status");
    }
}

Is there a way to structure a continuation that removes the loop in each of the Poll methods

private async Task Poll(CancellationToken ct)
{
    await Task.Delay(Math.Max(1000, CONFIGA), ct);
    this._logger.StartAction("poll A status");
    this._logger.StopAction("poll A status");
}

This might not even be the right pattern, but it seems better than having three infinite loops.

Task.WhenAny([A,B,C]) =>
// recreate any complete task as soon as it returns
// and await the new "continuation"?

Body:
I have an Aesthetic solution, that is probably not advisable to be used since it will probably cause stack overflow eventually.
It maybe demonstrates why the loop is a better option.

I must admit do not really understand your example in a real world context.
In my mind almost all code that executes for a long time will do it in a finite loop, and thus to check for cancellation after each loop iteration sounds like a good idea to me.

Unless you want your code just to run infinitely until the task is canceled, in which case my aesthetic solution will probably cause a stack overflow if left to long, but it was fun none the less coming up with this code.

I created a Extension method:

public static class Extensions
{
    public static async Task ContinueWithInfinitly(this Task task, Func<Task> continuationAction, CancellationToken cancellationToken)
    {
        await task;
        if (!cancellationToken.IsCancellationRequested)
        {
            var newTask = continuationAction.Invoke();
            await newTask.ContinueWithInfinitly(continuationAction, cancellationToken);
        }
    }
}

Which Base on your code will then be called as follows:

await Task.WhenAll(
                Task.Run(async () => await this.PollA(ct).ContinueWithInfinitly(() => PollA(ct), ct)),
                Task.Run(async () => await this.PollB(ct).ContinueWithInfinitly(() => PollB(ct), ct)),
                Task.Run(async () => await this.PollC(ct).ContinueWithInfinitly(() => PollC(ct), ct)))
                .ConfigureAwait(false);

Although I dont see the point of wrapping each method again in a Task.Run.
So i can also just be

await Task.WhenAll(
                this.PollA(ct).ContinueWithInfinitly(() => PollA(ct), ct),
                this.PollB(ct).ContinueWithInfinitly(() => PollB(ct), ct),
                this.PollC(ct).ContinueWithInfinitly(() => PollC(ct), ct))
                .ConfigureAwait(false);


来源: stackexchange

问:
Plot the Percent of time played together
I am hoping someone can give me an idea or a solution to the problem I have below. I have been trying to figure out how I can find the percentage a player played with another based off start time, end time, and period(or any other stat I did not mention). I can sum the duration of each player in a pivot table to see the full ice time of a player But for the life of me I cannot seem to figure out the other. Whether it needs to be in R, Excel, or a python script I have exhausted my ideas. I know this is not a straight forward scripting question but I can't think of a better spot to pose the question. I can clearly see in example 1 Suter and Dumba played together twice in the small snippet of data i provided. But to plot that on a graph or just find the percentage is where I am asking for any ideas. Below are 2 examples of how i can access OnIce data.

Example 1.   At the end of the period/game I can get the prior Line Shift data. LastName of player will appear multiple times throughout the df.

```<code>    LastName  StartTime  EndTime  Duration ShiftNumber Period
    Foligno      0:00       0:40    0:40           1    1
    Suter        0:00       0:40    0:40           1    1
    Staal        0:00       0:40    0:40           1    1
    Niederreiter 0:00       0:40    0:40           1    1
    Dubnyk       0:00       20:00   20:00          1    1
    Dumba        0:00       0:40    0:40           1    1
    Zucker       0:40       1:26    0:46           1    1
    Koivu        0:40       1:34    0:54           1    1
    Murphy       0:40       1:26    0:46           1    1
    Brodin       0:40       1:26    0:46           1    1
    Granlund     0:40       1:39    0:59           1    1
    Reilly       1:26       2:09    0:43           1    1
    Winnik       1:26       2:18    0:52           1    1
    Coyle        1:34       2:16    0:42           1    1
    Stewart      1:39       2:13    0:34           1    1
    Dumba        2:09       2:39    0:30           2    1
    Suter        2:09       2:39    0:30           2    1
</code>```

Example 2. I can run a script every couple seconds and save to a csv what player id's are OnIce at the same time.

```<code>HomePlayerId HomeDuration
8475744        94
8471702        74
8477944        69
8475163        74
8474651        623
8477043        74
HomePlayerId HomeDuration
8475744        111
8471702        91
8477944        86
8475163        91
8474651        640
8477043        91
</code>```

答:
The plain Python code below computes the total amount of overlapping time for each pair of players. The core idea is that given a (start1, end1) interval for player1 and (start2, end2) for player2 then the overlap of those two intervals is

```<code>overlap = min(end1, end2) - max(start1, start2)
</code>```

if overlap <= 0 then there's no overlap for those intervals. We need to perform that computation for every pair of intervals for each pair of players.

from itertools import combinations, product

#LastName   StartTime  EndTime  Duration ShiftNumber Period
data = '''\
Foligno       0:00      0:40    0:40           1    1
Suter         0:00      0:40    0:40           1    1
Staal         0:00      0:40    0:40           1    1
Niederreiter  0:00      0:40    0:40           1    1
Dubnyk        0:00      20:00   20:00          1    1
Dumba         0:00      0:40    0:40           1    1
Zucker        0:40      1:26    0:46           1    1
Koivu         0:40      1:34    0:54           1    1
Murphy        0:40      1:26    0:46           1    1
Brodin        0:40      1:26    0:46           1    1
Granlund      0:40      1:39    0:59           1    1
Reilly        1:26      2:09    0:43           1    1
Winnik        1:26      2:18    0:52           1    1
Coyle         1:34      2:16    0:42           1    1
Stewart       1:39      2:13    0:34           1    1
Dumba         2:09      2:39    0:30           2    1
Suter         2:09      2:39    0:30           2    1
'''.splitlines()

def to_secs(ms):
    ''' Convert a mm:ss string to seconds '''
    m, s = map(int, ms.split(':'))
    return 60 * m + s

# Store a list of (start, end) times for each player
players = {}
for row in data:
    name, start, end = row.split(None, 3)[:3]
    times = to_secs(start), to_secs(end)
    players.setdefault(name, []).append(times)

for t in players.items():
    print(t)
print()

# Determine the amount of overlapping time for each pair of players
for p1, p2 in combinations(sorted(players), 2):
    total = 0
    # Check each pair of times for this pair of players
    for t1, t2 in product(players[p1], players[p2]):
        # Compute the overlap in this pair of times and
        # add it to the total for this pair of players
        start, end = zip(t1, t2)
        total += max(0, min(end) - max(start))
    if total:
        print(p1, p2, total)
```

<p><strong>output</strong></p>

```('Foligno', [(0, 40)])
('Suter', [(0, 40), (129, 159)])
('Staal', [(0, 40)])
('Niederreiter', [(0, 40)])
('Dubnyk', [(0, 1200)])
('Dumba', [(0, 40), (129, 159)])
('Zucker', [(40, 86)])
('Koivu', [(40, 94)])
('Murphy', [(40, 86)])
('Brodin', [(40, 86)])
('Granlund', [(40, 99)])
('Reilly', [(86, 129)])
('Winnik', [(86, 138)])
('Coyle', [(94, 136)])
('Stewart', [(99, 133)])

Brodin Dubnyk 46
Brodin Granlund 46
Brodin Koivu 46
Brodin Murphy 46
Brodin Zucker 46
Coyle Dubnyk 42
Coyle Dumba 7
Coyle Granlund 5
Coyle Reilly 35
Coyle Stewart 34
Coyle Suter 7
Coyle Winnik 42
Dubnyk Dumba 70
Dubnyk Foligno 40
Dubnyk Granlund 59
Dubnyk Koivu 54
Dubnyk Murphy 46
Dubnyk Niederreiter 40
Dubnyk Reilly 43
Dubnyk Staal 40
Dubnyk Stewart 34
Dubnyk Suter 70
Dubnyk Winnik 52
Dubnyk Zucker 46
Dumba Foligno 40
Dumba Niederreiter 40
Dumba Staal 40
Dumba Stewart 4
Dumba Suter 70
Dumba Winnik 9
Foligno Niederreiter 40
Foligno Staal 40
Foligno Suter 40
Granlund Koivu 54
Granlund Murphy 46
Granlund Reilly 13
Granlund Winnik 13
Granlund Zucker 46
Koivu Murphy 46
Koivu Reilly 8
Koivu Winnik 8
Koivu Zucker 46
Murphy Zucker 46
Niederreiter Staal 40
Niederreiter Suter 40
Reilly Stewart 30
Reilly Winnik 43
Staal Suter 40
Stewart Suter 4
Stewart Winnik 34
Suter Winnik 9
```

ContentLicense: CC BY-SA 3.0

Body:
I am hoping someone can give me an idea or a solution to the problem I have below. I have been trying to figure out how I can find the percentage a player played with another based off start time, end time, and period(or any other stat I did not mention). I can sum the duration of each player in a pivot table to see the full ice time of a player But for the life of me I cannot seem to figure out the other. Whether it needs to be in R, Excel, or a python script I have exhausted my ideas. I know this is not a straight forward scripting question but I can't think of a better spot to pose the question. I can clearly see in example 1 Suter and Dumba played together twice in the small snippet of data i provided. But to plot that on a graph or just find the percentage is where I am asking for any ideas. Below are 2 examples of how i can access OnIce data.

Example 1.   At the end of the period/game I can get the prior Line Shift data. LastName of player will appear multiple times throughout the df.

    LastName  StartTime  EndTime  Duration ShiftNumber Period
    Foligno      0:00       0:40    0:40           1    1
    Suter        0:00       0:40    0:40           1    1
    Staal        0:00       0:40    0:40           1    1
    Niederreiter 0:00       0:40    0:40           1    1
    Dubnyk       0:00       20:00   20:00          1    1
    Dumba        0:00       0:40    0:40           1    1
    Zucker       0:40       1:26    0:46           1    1
    Koivu        0:40       1:34    0:54           1    1
    Murphy       0:40       1:26    0:46           1    1
    Brodin       0:40       1:26    0:46           1    1
    Granlund     0:40       1:39    0:59           1    1
    Reilly       1:26       2:09    0:43           1    1
    Winnik       1:26       2:18    0:52           1    1
    Coyle        1:34       2:16    0:42           1    1
    Stewart      1:39       2:13    0:34           1    1
    Dumba        2:09       2:39    0:30           2    1
    Suter        2:09       2:39    0:30           2    1

Example 2. I can run a script every couple seconds and save to a csv what player id's are OnIce at the same time.

HomePlayerId HomeDuration
8475744        94
8471702        74
8477944        69
8475163        74
8474651        623
8477043        74
HomePlayerId HomeDuration
8475744        111
8471702        91
8477944        86
8475163        91
8474651        640
8477043        91

Body:
The plain Python code below computes the total amount of overlapping time for each pair of players. The core idea is that given a (start1, end1) interval for player1 and (start2, end2) for player2 then the overlap of those two intervals is

overlap = min(end1, end2) - max(start1, start2)

if overlap <= 0 then there's no overlap for those intervals. We need to perform that computation for every pair of intervals for each pair of players.

from itertools import combinations, product

#LastName   StartTime  EndTime  Duration ShiftNumber Period
data = '''\
Foligno       0:00      0:40    0:40           1    1
Suter         0:00      0:40    0:40           1    1
Staal         0:00      0:40    0:40           1    1
Niederreiter  0:00      0:40    0:40           1    1
Dubnyk        0:00      20:00   20:00          1    1
Dumba         0:00      0:40    0:40           1    1
Zucker        0:40      1:26    0:46           1    1
Koivu         0:40      1:34    0:54           1    1
Murphy        0:40      1:26    0:46           1    1
Brodin        0:40      1:26    0:46           1    1
Granlund      0:40      1:39    0:59           1    1
Reilly        1:26      2:09    0:43           1    1
Winnik        1:26      2:18    0:52           1    1
Coyle         1:34      2:16    0:42           1    1
Stewart       1:39      2:13    0:34           1    1
Dumba         2:09      2:39    0:30           2    1
Suter         2:09      2:39    0:30           2    1
'''.splitlines()

def to_secs(ms):
    ''' Convert a mm:ss string to seconds '''
    m, s = map(int, ms.split(':'))
    return 60 * m + s

# Store a list of (start, end) times for each player
players = {}
for row in data:
    name, start, end = row.split(None, 3)[:3]
    times = to_secs(start), to_secs(end)
    players.setdefault(name, []).append(times)

for t in players.items():
    print(t)
print()

# Determine the amount of overlapping time for each pair of players
for p1, p2 in combinations(sorted(players), 2):
    total = 0
    # Check each pair of times for this pair of players
    for t1, t2 in product(players[p1], players[p2]):
        # Compute the overlap in this pair of times and
        # add it to the total for this pair of players
        start, end = zip(t1, t2)
        total += max(0, min(end) - max(start))
    if total:
        print(p1, p2, total)

output

('Foligno', [(0, 40)])
('Suter', [(0, 40), (129, 159)])
('Staal', [(0, 40)])
('Niederreiter', [(0, 40)])
('Dubnyk', [(0, 1200)])
('Dumba', [(0, 40), (129, 159)])
('Zucker', [(40, 86)])
('Koivu', [(40, 94)])
('Murphy', [(40, 86)])
('Brodin', [(40, 86)])
('Granlund', [(40, 99)])
('Reilly', [(86, 129)])
('Winnik', [(86, 138)])
('Coyle', [(94, 136)])
('Stewart', [(99, 133)])

Brodin Dubnyk 46
Brodin Granlund 46
Brodin Koivu 46
Brodin Murphy 46
Brodin Zucker 46
Coyle Dubnyk 42
Coyle Dumba 7
Coyle Granlund 5
Coyle Reilly 35
Coyle Stewart 34
Coyle Suter 7
Coyle Winnik 42
Dubnyk Dumba 70
Dubnyk Foligno 40
Dubnyk Granlund 59
Dubnyk Koivu 54
Dubnyk Murphy 46
Dubnyk Niederreiter 40
Dubnyk Reilly 43
Dubnyk Staal 40
Dubnyk Stewart 34
Dubnyk Suter 70
Dubnyk Winnik 52
Dubnyk Zucker 46
Dumba Foligno 40
Dumba Niederreiter 40
Dumba Staal 40
Dumba Stewart 4
Dumba Suter 70
Dumba Winnik 9
Foligno Niederreiter 40
Foligno Staal 40
Foligno Suter 40
Granlund Koivu 54
Granlund Murphy 46
Granlund Reilly 13
Granlund Winnik 13
Granlund Zucker 46
Koivu Murphy 46
Koivu Reilly 8
Koivu Winnik 8
Koivu Zucker 46
Murphy Zucker 46
Niederreiter Staal 40
Niederreiter Suter 40
Reilly Stewart 30
Reilly Winnik 43
Staal Suter 40
Stewart Suter 4
Stewart Winnik 34
Suter Winnik 9


问:
How do I make JAR and WAR on IntelliJ IDEA?
I want to develop a new java webservice to be deployed on AWS Lambda, but I also want to be able to easily test it.

My idea is to code my webservice using Jersey and be able to compile it into a war file, so I can test it localy and also be able to compile it into a jar for the Serverless Java container from AWS.

My first thought was to create 2 modules on IntelliJ IDEA 2017.3 Ultimate, one for the warand one for the jar, all using Maven, with the 2 modules sharing the same code base for the Jersey REST Resources (the webservice classes). But unfortunately I am too new to IntelliJ IDEA and I can't put this to work.

Is there a way to achieve this?

答:
Solution you provided is workable but IMO overcomplicated a bit. I did something similar for my project: first I made a module with all the sources and tests, then I sliced it to different artifacts. It's not the cleanest solution though - you have a risk of placing dependent classes to different artifacts and cause classloading issues in runtime.

In your case it is simpler - you only need to repackage same content to another artifact, if I get it right. In simplest case, one module would be enough. You can just add a plugin for assembling WAR archive, like that:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>jarwar</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>war</goal>
                        </goals>
                        <configuration>
                            <classifier>web</classifier>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

The example above will compile the sources, assemble jar and war archives from them at packaging phase, and attach them for further installation and deployment. Main idea here is to execute both maven-jar-plugin:jar and maven-war-plugin:war goals at packaging phase, when all the sources are compiled. The first goal is bound at jar default packaging, and the second one is bound explicitly.

One more important detail is classifier: it should be specified on one of the artifact to mark it as supplementary. Otherwise the artifacts won't be installed to repositories correctly.

Body:
Solution you provided is workable but IMO overcomplicated a bit. I did something similar for my project: first I made a module with all the sources and tests, then I sliced it to different artifacts. It's not the cleanest solution though - you have a risk of placing dependent classes to different artifacts and cause classloading issues in runtime.

In your case it is simpler - you only need to repackage same content to another artifact, if I get it right. In simplest case, one module would be enough. You can just add a plugin for assembling WAR archive, like that:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>jarwar</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>war</goal>
                        </goals>
                        <configuration>
                            <classifier>web</classifier>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

The example above will compile the sources, assemble jar and war archives from them at packaging phase, and attach them for further installation and deployment. Main idea here is to execute both maven-jar-plugin:jar and maven-war-plugin:war goals at packaging phase, when all the sources are compiled. The first goal is bound at jar default packaging, and the second one is bound explicitly.

One more important detail is classifier: it should be specified on one of the artifact to mark it as supplementary. Otherwise the artifacts won't be installed to repositories correctly.


问:
Deploy small change to google app engine
I want to deploy a change in my app.yaml file to google app engine. Is there a simple way to do this without redeploying the whole app? Is there a way of changing the app.yaml file on the google cloud directly? Or just deploying one file from my Windows directory?

My app is working fine in the virtual environment but I'm having some issues on the google cloud platform. The whole deploying process takes quite a while so I'm looking for a faster way to make a change and test it.

答:
You can try using gcloud app deploy inside the directory where your application is located in order to upload the file you need.

Specifying no files with the command deploys only the app.yaml file of a given service.

This command will only upload to the cloud the files where there are changes, so if you have only modified the app.yaml file, it should not take too much time for the upload. However, as that is the configuration file of your application, it might need to be re-deployed completely, as the changes made in that file might affect the behaviour of the whole app. That is the reason why it might be taking longer than expected.

On the other side, you may want to know that if you are using App Engine Flexible environment, the deployment will always be slower than in a Standard environment, as resources have to be deployed before launching the application itself.


问:
How to get runtime status of queue triggered azure function?
My azure function is calculating results of certain request jobs (cca. 5s-5min) where each job has unique jobId based on the hash of the request message. Execution leads to deterministic results. So it is functionally "pure function". Therefore we are caching results of already evaluated jobs in a blob storage based on the jobId. All great so far.

Now if a request for jobId comes three scenarios are possible.

Result is in the cache already => then it is served from the cache.

Result is not in the cache and no function is running the evaluation => new invocation

Result is not in the cache, but some function is already working on it => wait for result

We do some custom table storage based progress tracking magic to tell if function is working on given jobId or not yet.

It works somehow, up to the point of 5 x restart -> poison queue scenarios. There we are quite hopeless.

I feel like we are hacking around some of already reliably implemented feature of Azure Functions internals, because exactly the same info can be seen in the monitor page in azure portal or used to be visible in kudu webjobs monitor page.

How to reliably find out in c# if a given message (jobId) is currently being processed by some function and when it is not?

答:
Azure Durable Functions provide a mechanism how to track progress of execution of smaller tasks.

https://learn.microsoft.com/en-us/azure/azure-functions/durable-functions-overview

Accroding to the "Pattern #3: Async HTTP APIs" the orchestrator can provide information about the function status in form like this:

```<code>  {"runtimeStatus":"Running","lastUpdatedTime":"2017-03-16T21:20:47Z", ...}
</code>```

This solves my problem about finding if given message is being processed.

Body:
Azure Durable Functions provide a mechanism how to track progress of execution of smaller tasks.

https://learn.microsoft.com/en-us/azure/azure-functions/durable-functions-overview

Accroding to the "Pattern #3: Async HTTP APIs" the orchestrator can provide information about the function status in form like this:

  {"runtimeStatus":"Running","lastUpdatedTime":"2017-03-16T21:20:47Z", ...}

This solves my problem about finding if given message is being processed.


问:
JSF 1.1 : passing parameter from commandButton
I'm blocked with an application on JSF 1.1

I have a c:foreach loop and I want on my loop to pass my object into my function behind an h:commandButton

```<code><c:forEach var="userConnect" items="${connectedUsersManagedBean.listUsers}">
    <tr onclick="testNico(this)">
        <td>${userConnect.login}</td>
        <td>${userConnect.ip}</td>
        <td>
            <h:commandButton id="deleteSelectedUser"
                actionListener="#{connectedUsersManagedBean.disconnectUser}"
                value="Déconnecter"
                styleClass="commandButton btnCancel">
                <f:attribute name="userAttribute" value="#{userConnect.login}" />
                <!-- <fparam name="id" value="{userConnect.login}" /> -->
                <!--<set var="testnico" value="testnico" scope="request" /> -->
            </h:commandButton>
        </td>
    </tr>
</c:forEach>
</code>```

With f:param it was okay for a string, but when I try to pass my userConnect to the function, it doesn't work.

Any idea ?

Thanks in advance.

答:
Have you tried invoking userConnect.login from your controller - connectedUsersManagedBean ?

```<code>action="#{connectedUsersManagedBean.loginUser(userConnect)}"
</code>```

with a function inside the connectedUsersManagedBean:

```<code>public void loginUser(yourtype userConnect) {
    userConnect.login();
}
</code>```

this should work assuming you have a Servlet 3.0 compatible container (such as Tomcat 7 or glassfish 3)

Body:
I'm blocked with an application on JSF 1.1

I have a c:foreach loop and I want on my loop to pass my object into my function behind an h:commandButton

<c:forEach var="userConnect" items="${connectedUsersManagedBean.listUsers}">

        ${userConnect.login}
        ${userConnect.ip}

            <h:commandButton id="deleteSelectedUser"
                actionListener="#{connectedUsersManagedBean.disconnectUser}"
                value="Déconnecter"
                styleClass="commandButton btnCancel">
                <f:attribute name="userAttribute" value="#{userConnect.login}" />

            </h:commandButton>

</c:forEach>

With f:param it was okay for a string, but when I try to pass my userConnect to the function, it doesn't work.

Any idea ?

Thanks in advance.

Body:
Have you tried invoking userConnect.login from your controller - connectedUsersManagedBean ?

action="#{connectedUsersManagedBean.loginUser(userConnect)}"

with a function inside the connectedUsersManagedBean:

public void loginUser(yourtype userConnect) {
    userConnect.login();
}

this should work assuming you have a Servlet 3.0 compatible container (such as Tomcat 7 or glassfish 3)


问:
Why can't i extend(Inherit) the properties of PrintStream class to a newly derived class
I want to override the println(int) by extending the PrintStream class into a newly defined class.

```<code>import java.io.PrintStream;

 class Newer extends PrintStream
{ public void println(int x) {

System.out.println(x);
}

public static void main(String[] args)
{
Newer n=new Newer();

n.println(2);
}

}
</code>```

I have got compilation error saying

```<code>extendsprintstream.java:3: cannot find symbol
symbol  : constructor PrintStream()
location: class java.io.PrintStream
class Newer extends PrintStream
^
1 error
</code>```

Why am I not able to inherit class PrintStream ?

答:
Newer doesn't have a constructor at all, so it gets a default no-args constructor, created by the compiler, that calls super(), i.e. the no-args constructor of the base class.

The base class is PrintStream, and it doesn't have a no-args constructor.

So you get a compilation error. You need to provide a constructor for Newer() that calls one of the existing constructors of PrintStream, via super(...). For example:

```<code>public Newer()
{
    super(System.out);
}
</code>```

Then you don't need to override println() at all.

Why you're doing this at all is another mystery. You don't need Newer at all: you only need System.out.

Body:
I want to override the println(int) by extending the PrintStream class into a newly defined class.

import java.io.PrintStream;

 class Newer extends PrintStream
{ public void println(int x) {

System.out.println(x);
}

public static void main(String[] args)
{
Newer n=new Newer();

n.println(2);
}

}

I have got compilation error saying

extendsprintstream.java:3: cannot find symbol
symbol  : constructor PrintStream()
location: class java.io.PrintStream
class Newer extends PrintStream
^
1 error

Why am I not able to inherit class PrintStream ?

Body:
Newer doesn't have a constructor at all, so it gets a default no-args constructor, created by the compiler, that calls super(), i.e. the no-args constructor of the base class.

The base class is PrintStream, and it doesn't have a no-args constructor.

So you get a compilation error. You need to provide a constructor for Newer() that calls one of the existing constructors of PrintStream, via super(...). For example:

public Newer()
{
    super(System.out);
}

Then you don't need to override println() at all.

Why you're doing this at all is another mystery. You don't need Newer at all: you only need System.out.


问:
MySql: SELECT where a field value contains ' and "?
I want to retrieve a record where the value contains single quote and double quote.

Tried The following:

select * from Table1 where id = '' . ~";:><?/\!@#$%^*()_+|/ \?' ;
`

答:
Use LIKE in WHERE clause to check whether it contains single quotes(') and double quotes(").

Query

```<code>select * from `your_table_name`
where `id` like '%''%'
or `id` like '%"%';
</code>```

Find a demo here

Body:
Use LIKE in WHERE clause to check whether it contains single quotes(') and double quotes(").

Query

select * from `your_table_name`
where `id` like '%''%'
or `id` like '%"%';

Find a demo here


问:
Pass through server / proxy
I'm looking for advice on how this can be done. I want to have a server sit in between the client and the actual server. For example:

```<code>Client -> Proxy Type Server -> Web Server.
</code>```

So in return the web server would pass results to the proxy server which in return give the results back to the client. For example:

```<code>Client <- Proxy Type Server <- Web Server
</code>```

Here is a diagram if it makes life easier:

If it was just simple GET requests not a problem but I'm not sure how it would work if the client was posting data. I hope someone can advise me on this. Thank you if you can!

答:
I'm not sure what your question is... If you set up a proxy server between your client and the application server, then it will be just that: a proxy server. So it will proxy requests to the application server, just as you've shown in your diagram. If a client POSTs data to the proxy, the proxy server will POST that same data to the application server and return the response to the client...

Are you asking how to set up something like this?

EDIT: I'm going to take a wild guess here...

If it was just simple GET requests not a problem but I'm not sure how it would work if the client was posting data

Do you mean that the client is POSTing to a PHP or Ruby script on the "Proxy Server", and not an actual proxy server like Squid or Apache's mod_proxy? If so, are you asking how, using PHP, to send that POST data to the application server? If that's your question, here's the answer:

```<code><?php

$application_server = '1.2.3.4'; // replace with IP or hostname of application server
$uri = $_SERVER['REQUEST_URI']; // you may need to change this, not sure from your question.

$curl = curl_init("http://{$application_server}{$uri}");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$_POST);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

$data = curl_exec($curl);

// do something with $data, transform it however you want...

echo $data;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Pass through server / proxy

Body:
I'm looking for advice on how this can be done. I want to have a server sit in between the client and the actual server. For example:

Client -> Proxy Type Server -> Web Server.

So in return the web server would pass results to the proxy server which in return give the results back to the client. For example:

Client <- Proxy Type Server <- Web Server

Here is a diagram if it makes life easier:

If it was just simple GET requests not a problem but I'm not sure how it would work if the client was posting data. I hope someone can advise me on this. Thank you if you can!

Body:
I'm not sure what your question is... If you set up a proxy server between your client and the application server, then it will be just that: a proxy server. So it will proxy requests to the application server, just as you've shown in your diagram. If a client POSTs data to the proxy, the proxy server will POST that same data to the application server and return the response to the client...

Are you asking how to set up something like this?

EDIT: I'm going to take a wild guess here...

If it was just simple GET requests not a problem but I'm not sure how it would work if the client was posting data

Do you mean that the client is POSTing to a PHP or Ruby script on the "Proxy Server", and not an actual proxy server like Squid or Apache's mod_proxy? If so, are you asking how, using PHP, to send that POST data to the application server? If that's your question, here's the answer:

<?php

$application_server = '1.2.3.4'; // replace with IP or hostname of application server
$uri = $_SERVER['REQUEST_URI']; // you may need to change this, not sure from your question.

$curl = curl_init("http://{$application_server}{$uri}");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$_POST);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

$data = curl_exec($curl);

// do something with $data, transform it however you want...

echo $data;


问:
Duplicate key value violates unique constraint "hibernate_sequences_pkey" exception by Postgres
My Spring Data (JPA/Hibernate) based application raises on increased load when persisting new entities in the Postgres the following exception:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "hibernate_sequences_pkey"

The strategy for id is defined as follows:

```<code>@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "ID")
public Long getId() {
    return id;
}
</code>```

I know that this strategy is not the perfect solution for Postgres, however is it the reason for the exception above?

The load is generated using Apache Camel route with splitter running inserts in parallel on multiple threads.

答:
After some tests it seems indeed that the problem is caused by the strategy = GenerationType.TABLE. With the change to strategy = GenerationType.SEQUENCE the problems described above with duplicated keys were gone.

```<code>@Id
@SequenceGenerator(name = Consts.VEHICLE_ATTR_ID_SEQ,
        sequenceName = Consts.VEHICLE_ATTR_ID_SEQ,
        allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
        generator = Consts.VEHICLE_ATTR_ID_SEQ)
@Column(name = "ID", updatable = false)
public Long getId() {
    return id;
}
</code>```

Body:
My Spring Data (JPA/Hibernate) based application raises on increased load when persisting new entities in the Postgres the following exception:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "hibernate_sequences_pkey"

The strategy for id is defined as follows:

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "ID")
public Long getId() {
    return id;
}

I know that this strategy is not the perfect solution for Postgres, however is it the reason for the exception above?

The load is generated using Apache Camel route with splitter running inserts in parallel on multiple threads.

Body:
After some tests it seems indeed that the problem is caused by the strategy = GenerationType.TABLE. With the change to strategy = GenerationType.SEQUENCE the problems described above with duplicated keys were gone.

@Id
@SequenceGenerator(name = Consts.VEHICLE_ATTR_ID_SEQ,
        sequenceName = Consts.VEHICLE_ATTR_ID_SEQ,
        allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
        generator = Consts.VEHICLE_ATTR_ID_SEQ)
@Column(name = "ID", updatable = false)
public Long getId() {
    return id;
}


问:
Apache AJP, ProxyPass : How to set the Host header
I'm trying to figure out a way to set the "Host" header content during a ProxyPass for AJP.

Here is my working conf with HTTP :

```<code><VirtualHost *:80>
    ProxyRequests off
    ProxyPreserveHost off

    ServerName my-external-domain

    ErrorLog /var/log/httpd/error.log
    CustomLog /var/log/httpd/access.log combined

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel error

    <Location />
        ProxyPass http://my-internal-tomcat:8080/
        ProxyPassReverse http://my-internal-tomcat:8080/
        Order allow,deny
        Allow from all
    </Location>

</VirtualHost>
</code>```

On the tomcat, the servername detected is my-internal-tomcat (the behaviour that I want).

Here is my second conf with AJP :

```<code><VirtualHost *:80>
    ProxyRequests off
    ProxyPreserveHost off

    ServerName my-external-domain

    ErrorLog /var/log/httpd/error.log
    CustomLog /var/log/httpd/access.log combined

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel error

    <Location />
        ProxyPass ajp://my-internal-tomcat:8009/
        ProxyPassReverse ajp://my-internal-tomcat:8009/
        Order allow,deny
        Allow from all
    </Location>

</VirtualHost>
</code>```

With this conf, on the servername detected is not my-internal-tomcat

Do you have any idea why?

答:
My answer may be wrong, please correct me if not.

You simply can't do that with AJP.

Body:
I'm trying to figure out a way to set the "Host" header content during a ProxyPass for AJP.

Here is my working conf with HTTP :

<VirtualHost *:80>
    ProxyRequests off
    ProxyPreserveHost off

    ServerName my-external-domain

    ErrorLog /var/log/httpd/error.log
    CustomLog /var/log/httpd/access.log combined

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel error

    <Location />
        ProxyPass http://my-internal-tomcat:8080/
        ProxyPassReverse http://my-internal-tomcat:8080/
        Order allow,deny
        Allow from all
    </Location>

</VirtualHost>

On the tomcat, the servername detected is my-internal-tomcat (the behaviour that I want).

Here is my second conf with AJP :

<VirtualHost *:80>
    ProxyRequests off
    ProxyPreserveHost off

    ServerName my-external-domain

    ErrorLog /var/log/httpd/error.log
    CustomLog /var/log/httpd/access.log combined

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel error

    <Location />
        ProxyPass ajp://my-internal-tomcat:8009/
        ProxyPassReverse ajp://my-internal-tomcat:8009/
        Order allow,deny
        Allow from all
    </Location>

</VirtualHost>

With this conf, on the servername detected is not my-internal-tomcat

Do you have any idea why?


问:
app crashing when trying to move to a cardview activity
i suddently get the following error in my app and it crashes. i dont get any specific errors from my code, so i cannot find anything in the code to fix.

```<code>E/UncaughtException: java.lang.NoSuchMethodError: No static method getScreenWidthDp(Landroid/content/res/Resources;)I in class Landroid/support/v4/content/res/ConfigurationHelper; or its super classes (declaration of 'android.support.v4.content.res.ConfigurationHelper' appears in /data/app/tsakiris.com.aggelies-1/split_lib_dependencies_apk.apk:classes2.dex)
                         at android.support.design.widget.FloatingActionButton.getSizeDimension(FloatingActionButton.java:442)
                         at android.support.design.widget.FloatingActionButton.getSizeDimension(FloatingActionButton.java:434)
                         at android.support.design.widget.FloatingActionButton.onMeasure(FloatingActionButton.java:189)
                         at android.view.View.measure(View.java:17496)
                         at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
                         at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                         at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
                         at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
                         at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
                         at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
                         at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                         at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2636)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2031)
                         at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1193)
                         at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
                         at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1078)
                         at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5875)
                         at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                         at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                         at android.view.Choreographer.doFrame(Choreographer.java:550)
                         at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                         at android.os.Handler.handleCallback(Handler.java:739)
                         at android.os.Handler.dispatchMessage(Handler.java:95)
                         at android.os.Looper.loop(Looper.java:135)
                         at android.app.ActivityThread.main(ActivityThread.java:5351)
                         at java.lang.reflect.Method.invoke(Native Method)
                         at java.lang.reflect.Method.invoke(Method.java:372)
                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
</code>```

do you have any ideas what might be going wrong?

答:
I solved this problem by using the same version of compileSdkVersion and dependency version.
compileSdkVersion 26
implementation 'com.android.support:appcompat-v7:26.0.1'

Body:
i suddently get the following error in my app and it crashes. i dont get any specific errors from my code, so i cannot find anything in the code to fix.

E/UncaughtException: java.lang.NoSuchMethodError: No static method getScreenWidthDp(Landroid/content/res/Resources;)I in class Landroid/support/v4/content/res/ConfigurationHelper; or its super classes (declaration of 'android.support.v4.content.res.ConfigurationHelper' appears in /data/app/tsakiris.com.aggelies-1/split_lib_dependencies_apk.apk:classes2.dex)
                         at android.support.design.widget.FloatingActionButton.getSizeDimension(FloatingActionButton.java:442)
                         at android.support.design.widget.FloatingActionButton.getSizeDimension(FloatingActionButton.java:434)
                         at android.support.design.widget.FloatingActionButton.onMeasure(FloatingActionButton.java:189)
                         at android.view.View.measure(View.java:17496)
                         at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
                         at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                         at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
                         at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
                         at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
                         at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
                         at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                         at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2636)
                         at android.view.View.measure(View.java:17496)
                         at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2031)
                         at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1193)
                         at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
                         at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1078)
                         at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5875)
                         at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                         at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                         at android.view.Choreographer.doFrame(Choreographer.java:550)
                         at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                         at android.os.Handler.handleCallback(Handler.java:739)
                         at android.os.Handler.dispatchMessage(Handler.java:95)
                         at android.os.Looper.loop(Looper.java:135)
                         at android.app.ActivityThread.main(ActivityThread.java:5351)
                         at java.lang.reflect.Method.invoke(Native Method)
                         at java.lang.reflect.Method.invoke(Method.java:372)
                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

do you have any ideas what might be going wrong?


问:
Restricting access to Excel source data

I have an Excel template which reads data from a source Excel file using vlookups and Index/Match functions. I there a way to prevent the end user from accessing the source data file/sheet? e.g. by storing the source file on a remote location and make the vlookups read from there..
</p>

答:
No, it's not possible.

Moreover, you absolutely NEED these files open to refresh the values in formulas that refer them. When you open a file with external references, their values will be calculated from local cache (which may not be equal to actual remote file contents). When you open the remote files, the values will refresh.

Title: Restricting access to Excel source data


问:
PHP MySQL - Detect if missing row in array query
I am looking up an array of values. Whenever a value in the lookup array is not found in the database, I want to set a value inside the results array to "notFound".

How would I accomplish this?

Code:

```<code>$sql = "SELECT country FROM customers WHERE name IN ('Adam', 'David', 'Frank', 'Mike')";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $countryArray[] = $row['country'];
    }
}
</code>```

Current output:

```<code>+----- -+---------+
| Name  | Country |
+------------+----+
| Adam  |      UK |
| David |      AU |
| Mike  |      CN |
+-------+---------+
</code>```

Desired output:

```<code>+----- -+-------------+
| Name  |     Country |
+------------+--------+
| Adam  |          UK |
| David |          AU |
| Frank |     NotFound|
| Mike  |          CN |
+-------+-------------+
</code>```

In the example above, if frank is not found in database, I want the result array to return "NotFound".

答:
Not the most efficient/elegant, but should work. Assumes that your $names array contains exactly the same names as the DB (case-sensitive).

```<code>$names = array('Adam', 'David', 'Frank', 'Mike');
$not_found_array = array_fill_keys($names, 'NotFound');

$sql = "SELECT name, country FROM customers WHERE name IN ('".implode("','", $names)."')";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $countryArray[$row['name']] = $row['country'];
    }
}

$countryArray = array_merge($not_found_array, $countryArray);
</code>```

Body:
I am looking up an array of values. Whenever a value in the lookup array is not found in the database, I want to set a value inside the results array to "notFound".

How would I accomplish this?

Code:

$sql = "SELECT country FROM customers WHERE name IN ('Adam', 'David', 'Frank', 'Mike')";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $countryArray[] = $row['country'];
    }
}

Current output:

+----- -+---------+
| Name  | Country |
+------------+----+
| Adam  |      UK |
| David |      AU |
| Mike  |      CN |
+-------+---------+

Desired output:

+----- -+-------------+
| Name  |     Country |
+------------+--------+
| Adam  |          UK |
| David |          AU |
| Frank |     NotFound|
| Mike  |          CN |
+-------+-------------+

In the example above, if frank is not found in database, I want the result array to return "NotFound".

Body:
Not the most efficient/elegant, but should work. Assumes that your $names array contains exactly the same names as the DB (case-sensitive).

$names = array('Adam', 'David', 'Frank', 'Mike');
$not_found_array = array_fill_keys($names, 'NotFound');

$sql = "SELECT name, country FROM customers WHERE name IN ('".implode("','", $names)."')";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $countryArray[$row['name']] = $row['country'];
    }
}

$countryArray = array_merge($not_found_array, $countryArray);


问:
Swipe Delete in UItableviewCell
in my iPad app swipe deleting not working properly. after swipe deleting it shows the delete button on cell and this not disappearing.

答:
To delete row from UITableView implement UITableViewDataSource method:

Swift

```<code>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete{
       // enter your datasource updation logic hare & delete table cell
       tableview.deleteRows(at: [indexPath], with: .fade)
    }
}
</code>```

Title: Swipe Delete in UItableviewCell

Body:
To delete row from UITableView implement UITableViewDataSource method:

Swift

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete{
       // enter your datasource updation logic hare & delete table cell
       tableview.deleteRows(at: [indexPath], with: .fade)
    }
}


问:
How to migrate a WebYep website to Wordpress?
I had a website which was built using the CMS WebYep. Now I want to shift it to WordPress. Can anyone tell me how to do that?
Thanks is advance :)
Regards,
Ryan</p>

答:
I'm afraid there is no automatic process for most CMS.

You can either do it manually, or write a program (or hire somebody to write it) to help do the job.

In most cases the manual way is preferred. Different content management systems work quite differently, so there's usually not a universal way to set things up. Recognizing the differences and how to achieve a similar result is an easy thing to do for a human but a very hard thing to do for a computer. Plus, from my experience, with a relaunch usually comes a re-structuring. When you're moving to a new house, you might just get rid of that old broken sofa while you're at it, basically.

When you have a very large website with lots of similar content, a developer can certainly write scripts to aid in the process of moving your content over to WP. This will usually not be cheap, so it's not a smart idea for a site that consists of a dozen pages or where the content isn't very homogenous.


问:
How to increment Dates and use them with operators like '>' or '<' in SQL server?
How can I increment date in WHILE LOOP in a loop like this:

```<code>DECLARE @StartDate Datetime = some_date;
DECLARE @EndDate Datetime = other_date;
DECLARE @FinishDate Datetime = last_date;
    WHILE @EndDate < @FinishDate
      BEGIN
         [something happens]
        SET @StartDate = [ plus 1 day to @EndDate ]
        SET @EndDate = [ plus 8 days to itself]
      END
</code>```

And can I use an operator < in an expression lik this @EndDate < @FinishDate ?
By the way, I've tried to use DATEADD but it doesn't work. If i set data-type DATETIME2 it returns with ERROR 8117.

答:
I think it must work if you use SQLServer

```<code>SET @StartDate = DATEADD(DAY,1,@EndDate)
SET @EndDate = DATEADD(DAY,8,@EndDate)
</code>```

Test

```<code>DECLARE @StartDate Datetime = '20171201';
DECLARE @EndDate Datetime = '20171205';
DECLARE @FinishDate Datetime = '20171231';
    WHILE @EndDate < @FinishDate
      BEGIN
        SET @StartDate = DATEADD(DAY,1,@EndDate)
        SET @EndDate = DATEADD(DAY,8,@EndDate)

        PRINT CONVERT(varchar(10),@StartDate,120)+' - '+CONVERT(varchar(10),@EndDate,120)
      END
</code>```

Body:
How can I increment date in WHILE LOOP in a loop like this:

DECLARE @StartDate Datetime = some_date;
DECLARE @EndDate Datetime = other_date;
DECLARE @FinishDate Datetime = last_date;
    WHILE @EndDate < @FinishDate
      BEGIN
         [something happens]
        SET @StartDate = [ plus 1 day to @EndDate ]
        SET @EndDate = [ plus 8 days to itself]
      END

And can I use an operator < in an expression lik this @EndDate < @FinishDate ?
By the way, I've tried to use DATEADD but it doesn't work. If i set data-type DATETIME2 it returns with ERROR 8117.

Body:
I think it must work if you use SQLServer

SET @StartDate = DATEADD(DAY,1,@EndDate)
SET @EndDate = DATEADD(DAY,8,@EndDate)

Test

DECLARE @StartDate Datetime = '20171201';
DECLARE @EndDate Datetime = '20171205';
DECLARE @FinishDate Datetime = '20171231';
    WHILE @EndDate < @FinishDate
      BEGIN
        SET @StartDate = DATEADD(DAY,1,@EndDate)
        SET @EndDate = DATEADD(DAY,8,@EndDate)

        PRINT CONVERT(varchar(10),@StartDate,120)+' - '+CONVERT(varchar(10),@EndDate,120)
      END


问:
How do I download zip file in C#?
I use HTTP GET that downloads a zip file in a browser, something like  https://example.com/up/DBID/a/rRID/eFID/vVID (not the exact url)

Now, when I try to do the same download in C# code(same GET method as above) for a desktop application, the zip file downloaded is not a valid archive file. When I opened this file in notepad, it was some HTML page.

I think I'm not setting some header correctly. I looked around for examples. I'd found several wrt uploads, but did not see anything for downloads.

Code:

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/zip";
try
{
    HttpWebResponse res = (HttpWebResponse)request.GetResponse();
    using (StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))
    {
        StreamWriter oWriter = new StreamWriter(@"D:\Downloads\1.zip");
        oWriter.Write(sr.ReadToEnd());
        oWriter.Close();
    }
    res.Close();
}
catch (Exception ex)
{
}
</code>```

答:
It's mainly because you use a StreamWriter : TextWriter  to handle a binary Zip file.  A StreamWriter expects text and will apply an Encoding. And even the simple ASCII Encoder might try to 'fix' what it thinks are invalid line-endings.

You can replace all your code with:

```<code>  using (var client = new WebClient())
  {
    client.DownloadFile("http://something",  @"D:\Downloads\1.zip");
  }
</code>```

Note that for new code you should look at HttpClient instead of WebClient.

And then don't use using( ) { }

Title: How do I download zip file in C#?

Body:
I use HTTP GET that downloads a zip file in a browser, something like  https://example.com/up/DBID/a/rRID/eFID/vVID (not the exact url)

Now, when I try to do the same download in C# code(same GET method as above) for a desktop application, the zip file downloaded is not a valid archive file. When I opened this file in notepad, it was some HTML page.

I think I'm not setting some header correctly. I looked around for examples. I'd found several wrt uploads, but did not see anything for downloads.

Code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/zip";
try
{
    HttpWebResponse res = (HttpWebResponse)request.GetResponse();
    using (StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))
    {
        StreamWriter oWriter = new StreamWriter(@"D:\Downloads\1.zip");
        oWriter.Write(sr.ReadToEnd());
        oWriter.Close();
    }
    res.Close();
}
catch (Exception ex)
{
}

Body:
It's mainly because you use a StreamWriter : TextWriter  to handle a binary Zip file.  A StreamWriter expects text and will apply an Encoding. And even the simple ASCII Encoder might try to 'fix' what it thinks are invalid line-endings.

You can replace all your code with:

  using (var client = new WebClient())
  {
    client.DownloadFile("http://something",  @"D:\Downloads\1.zip");
  }

Note that for new code you should look at HttpClient instead of WebClient.

And then don't use using( ) { }

ContentLicense: CC BY-SA 4.0


问:
Retrieve entire HTML with urlopen(url)
I have noticed if I request a url using

```<code>urllib.request.urlopen([my_url]).read()
</code>```

I get something like this:

```<code> <html>
<head>
</head>
<body>
    <span>...</span>
<body>
<script>
</script>

</html>
</code>```

All the info I want for beautifulsoup is in that ... section.  If I use a webdriver, then that section is included.  But a webdriver seems to take longer, and causes my code to be a bit more messy.  Is there way to retrieve the entirety of the HTML doc without using a webdriver?

答:
Here is a much simpler and easy to read solution to parse the contents of the  tag :

```<code>import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq

my_url = 'https://www.foo.com'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")
span_content = page_soup.findAll("span",{"<attribute_name>":"<attribute_value>"})
print(span_content.text)
</code>```

Title: Retrieve entire HTML with urlopen(url)

Body:
I have noticed if I request a url using

urllib.request.urlopen([my_url]).read()

I get something like this:

    ...

All the info I want for beautifulsoup is in that ... section.  If I use a webdriver, then that section is included.  But a webdriver seems to take longer, and causes my code to be a bit more messy.  Is there way to retrieve the entirety of the HTML doc without using a webdriver?

Body:
Here is a much simpler and easy to read solution to parse the contents of the <span> tag :

import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq

my_url = 'https://www.foo.com'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")
span_content = page_soup.findAll("span",{"<attribute_name>":"<attribute_value>"})
print(span_content.text)


问:
jQuery & fullPage.js - Not working in mobile
I am creating a site with the fullPage.js plugin. I got it to work on the desktop browser but it's not working as expected in mobile.

this is my HTML

```<code><div id="fullpage">
    <section id="red" class="section"></section>
    <section id="blue" class="section"></section>
    <section id="green" class="section"></section>
</div>
</code>```

and this is my jquery

```<code>$(document).ready(function(){
   $('#fullpage').fullpage({
       navigation: true,
   });
});
</code>```

while navigation:true I can skip (i wouldn't say scroll) to different sections by touching the navigation dots. I can swipe to scroll up from there as seen in this video. it works in the chrome device emulator though

video of scroll in the works

P.S. I don't think scrollOverflow:true would serve my purpose as there is not much content to scroll in the site.

答:
I figured out the problem. it was not with fullPage.js. In my HTML, I included jquery.slim.min.js instead of regular jquery.min.js

Apparently, fullPage.js only works with jquery.min.js

Body:
I am creating a site with the fullPage.js plugin. I got it to work on the desktop browser but it's not working as expected in mobile.

this is my HTML

and this is my jquery

$(document).ready(function(){
   $('#fullpage').fullpage({
       navigation: true,
   });
});

while navigation:true I can skip (i wouldn't say scroll) to different sections by touching the navigation dots. I can swipe to scroll up from there as seen in this video. it works in the chrome device emulator though

video of scroll in the works

P.S. I don't think scrollOverflow:true would serve my purpose as there is not much content to scroll in the site.


问:
403 : Daily Limit for Unauthenticated Use Exceeded youtube api v3 java
I Know this question has been asked multiple times, but I couldn't find one working for me.

Basically I am trying to get a youtube video basic info which I get the proper result for that but then when I trigger to get the comments of that video the error pops out saying:

There was a service error: 403 : Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.

My code:

```<code>public String getyoutubeitemfull_details(String URI) throws SQLException, IOException{
    try {
        YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("APP_ID").build();

        String apiKey = "API Key";
        YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
        listVideosRequest.setId("qUvPzjSWMSM");
        listVideosRequest.setKey(apiKey);
        VideoListResponse listResponse = listVideosRequest.execute();

        Video video = listResponse.getItems().get(0);

        BigInteger viewCount = video.getStatistics().getViewCount();
        BigInteger Likes = video.getStatistics().getLikeCount();
        BigInteger DisLikes = video.getStatistics().getDislikeCount();
        BigInteger Comments = video.getStatistics().getCommentCount();
        System.out.println("[View Count] " + viewCount);
        System.out.println("[Likes] " + Likes);
        System.out.println("[Dislikes] " + DisLikes);
        System.out.println("[Comments] " + Comments);

        CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads()
                .list("snippet").setVideoId("qUvPzjSWMSM").setMaxResults(50l).setTextFormat("plainText").execute();

        List<CommentThread> videoComments = videoCommentsListResponse.getItems();

            for (CommentThread videoComment : videoComments) {
                CommentSnippet  snippet = videoComment.getSnippet().getTopLevelComment().getSnippet();
                System.out.println("  - Author: " + snippet.getAuthorDisplayName());
                System.out.println("  - Comment: " + snippet.getTextDisplay());
                System.out.println("\n-------------------------------------------------------------\n");
            }

    } catch (GoogleJsonResponseException e) {
        System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return null;
}
</code>```

FYI: So much of question that I have been through so far talk about adding listVideosRequest.setKey(apiKey); which I have it done. I also Have enable OAuth 2.0 enabled in my google console.

答:
Thanks to @DalmTo for throwing to its direction.

Basically Api Key doesn't have priviledges to retrieve comments and things like that. for deep priviledges I had to use Oauth, which basically is being created the same was as  API Key but in Oauth you receive a client_secrets.json file containing: client secret, client ID and etc...

Then you call that in you code.

Note: Their is verious ways of calling you client_secrets.json file but it depends on your need.

My way: Reader clientSecretReader = new InputStreamReader(
                new FileInputStream("/home/Downloads/src/client_secrets.json"));

Body:
I Know this question has been asked multiple times, but I couldn't find one working for me.

Basically I am trying to get a youtube video basic info which I get the proper result for that but then when I trigger to get the comments of that video the error pops out saying:

There was a service error: 403 : Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.

My code:

public String getyoutubeitemfull_details(String URI) throws SQLException, IOException{
    try {
        YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("APP_ID").build();

        String apiKey = "API Key";
        YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
        listVideosRequest.setId("qUvPzjSWMSM");
        listVideosRequest.setKey(apiKey);
        VideoListResponse listResponse = listVideosRequest.execute();

        Video video = listResponse.getItems().get(0);

        BigInteger viewCount = video.getStatistics().getViewCount();
        BigInteger Likes = video.getStatistics().getLikeCount();
        BigInteger DisLikes = video.getStatistics().getDislikeCount();
        BigInteger Comments = video.getStatistics().getCommentCount();
        System.out.println("[View Count] " + viewCount);
        System.out.println("[Likes] " + Likes);
        System.out.println("[Dislikes] " + DisLikes);
        System.out.println("[Comments] " + Comments);

        CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads()
                .list("snippet").setVideoId("qUvPzjSWMSM").setMaxResults(50l).setTextFormat("plainText").execute();

        List<CommentThread> videoComments = videoCommentsListResponse.getItems();

            for (CommentThread videoComment : videoComments) {
                CommentSnippet  snippet = videoComment.getSnippet().getTopLevelComment().getSnippet();
                System.out.println("  - Author: " + snippet.getAuthorDisplayName());
                System.out.println("  - Comment: " + snippet.getTextDisplay());
                System.out.println("\n-------------------------------------------------------------\n");
            }

    } catch (GoogleJsonResponseException e) {
        System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return null;
}

FYI: So much of question that I have been through so far talk about adding listVideosRequest.setKey(apiKey); which I have it done. I also Have enable OAuth 2.0 enabled in my google console.


问:
Java streams: Add to map but avoid mutation
I often find myself in a situation where I need to create a Map of objects from a Set or List.
The key is usually some String or Enum or the like, and the value is some new object with data lumped together.
The usual way of doing this, for my part, is by first creating the Map<String, SomeKeyValueObject> and then iterating over the Set or List I get in and mutate my newly created map.

Like the following example:

```<code>class Example {
   Map<String, GroupedDataObject> groupData(final List<SomeData> list){
      final Map<String, GroupedDataObject> map = new HashMap<>();
      for(final SomeData data : list){
         final String key = data.valueToGroupBy();
         map.put(key, GroupedDataObject.of(map.get(key), data.displayName(), data.data()));
      }
      return map;
   }

}

class SomeData {
   private final String valueToGroupBy;
   private final Object data;
   private final String displayName;

   public SomeData(final String valueToGroupBy, final String displayName, final Object data) {
      this.valueToGroupBy = valueToGroupBy;
      this.data = data;
      this.displayName = displayName;
   }

   public String valueToGroupBy() {
      return valueToGroupBy;
   }

   public Object data() {
      return data;
   }

   public String displayName() {
      return displayName;
   }
}

class GroupedDataObject{

   private final String key;
   private final List<Object> datas;

   private GroupedDataObject(final String key, final List<Object> list) {
      this.key = key;
      this.datas = list;
   }

   public static GroupedDataObject of(final GroupedDataObject groupedDataObject, final String key, final Object data) {
      final List<Object> list = new ArrayList<>();
      if(groupedDataObject != null){
         list.addAll(groupedDataObject.datas());
      }
      list.add(data);
      return new GroupedDataObject(key, list);
   }

   public String key() {
      return key;
   }

   public List<Object> datas() {
      return datas;
   }
}
</code>```

This feels very unclean. We create a map, and then mutate it over and over.

I've taken a liking to java 8s use of Streams and creating non-mutating data structures (or rather, you don't see the mutation). So is there a way to turn this grouping of data into something that uses a declarative approach rather than the imperative way?

I tried to implement the suggestion in https://stackoverflow.com/a/34453814/3478016 but I seem to be stumbling. Using the approach in the answer (the suggestion of using Collectors.groupingBy and Collectors.mapping) I'm able to get the data sorted into a map. But I can't group the "datas" into one and the same object.

Is there some way to do it in a declarative way, or am I stuck with the imperative?

答:
You can use Collectors.toMap with a merge function instead of Collectors.groupingBy.

```<code>Map<String, GroupedDataObject> map =
    list.stream()
        .collect(Collectors.toMap(SomeData::valueToGroupBy,
                                  d -> {
                                     List<Object> l = new ArrayList<>();
                                     l.add(d.data());
                                     return new GroupedDataObject(d.valueToGroupBy(), l);
                                  },
                                  (g1,g2) -> {
                                      g1.datas().addAll(g2.datas());
                                      return g1;
                                  }));
</code>```

The GroupedDataObject constructor must be made accessible in order for this to work.

Body:
I often find myself in a situation where I need to create a Map of objects from a Set or List.
The key is usually some String or Enum or the like, and the value is some new object with data lumped together.
The usual way of doing this, for my part, is by first creating the Map<String, SomeKeyValueObject> and then iterating over the Set or List I get in and mutate my newly created map.

Like the following example:

class Example {
   Map<String, GroupedDataObject> groupData(final List<SomeData> list){
      final Map<String, GroupedDataObject> map = new HashMap<>();
      for(final SomeData data : list){
         final String key = data.valueToGroupBy();
         map.put(key, GroupedDataObject.of(map.get(key), data.displayName(), data.data()));
      }
      return map;
   }

}

class SomeData {
   private final String valueToGroupBy;
   private final Object data;
   private final String displayName;

   public SomeData(final String valueToGroupBy, final String displayName, final Object data) {
      this.valueToGroupBy = valueToGroupBy;
      this.data = data;
      this.displayName = displayName;
   }

   public String valueToGroupBy() {
      return valueToGroupBy;
   }

   public Object data() {
      return data;
   }

   public String displayName() {
      return displayName;
   }
}

class GroupedDataObject{

   private final String key;
   private final List<Object> datas;

   private GroupedDataObject(final String key, final List<Object> list) {
      this.key = key;
      this.datas = list;
   }

   public static GroupedDataObject of(final GroupedDataObject groupedDataObject, final String key, final Object data) {
      final List<Object> list = new ArrayList<>();
      if(groupedDataObject != null){
         list.addAll(groupedDataObject.datas());
      }
      list.add(data);
      return new GroupedDataObject(key, list);
   }

   public String key() {
      return key;
   }

   public List<Object> datas() {
      return datas;
   }
}

This feels very unclean. We create a map, and then mutate it over and over.

I've taken a liking to java 8s use of Streams and creating non-mutating data structures (or rather, you don't see the mutation). So is there a way to turn this grouping of data into something that uses a declarative approach rather than the imperative way?

I tried to implement the suggestion in https://stackoverflow.com/a/34453814/3478016 but I seem to be stumbling. Using the approach in the answer (the suggestion of using Collectors.groupingBy and Collectors.mapping) I'm able to get the data sorted into a map. But I can't group the "datas" into one and the same object.

Is there some way to do it in a declarative way, or am I stuck with the imperative?

Body:
You can use Collectors.toMap with a merge function instead of Collectors.groupingBy.

Map<String, GroupedDataObject> map =
    list.stream()
        .collect(Collectors.toMap(SomeData::valueToGroupBy,
                                  d -> {
                                     List<Object> l = new ArrayList<>();
                                     l.add(d.data());
                                     return new GroupedDataObject(d.valueToGroupBy(), l);
                                  },
                                  (g1,g2) -> {
                                      g1.datas().addAll(g2.datas());
                                      return g1;
                                  }));

The GroupedDataObject constructor must be made accessible in order for this to work.


问:
How to correctly set the spellfile in VIM?
I'm trying to use spellchecker in vim; if I want to add a word to the internal dictionary (so that it is not highlighted as wrong) by the zg command, it says "option spellfile is not set".

I tried to type :set spellfile=PATH.../.vim.spell,

but I always get "Invalid argument: spellfile=PATH.../.vim.spell". Any hint please?

I'm using linux Ubuntu 12.04.

答:
Maybe you should just do mkdir ~/.vim.

By default, the spell files are stored there. But if vim could not find that folder, it will complain with this error message.


问:
URL rewriting for Magento module
I have created a New Module in Magento and named it as "article". It has two Front end controllers index and article.

And in the article controller i have an action called "archives" to list the articles on the front end / website based on the archives. Everything is fine except the URL.

The Working URL right now is : [http://]mydemostore/article/article/archives/01/2011

What i actually need is   http://mydemostore/article/archives/01/2011

I don't want to have an extra "article" (the controller name)

I know since my module name and controller name are same i am getting this. If i would have placed my actions inside the indexcontroller, i would have got this done. But it was not working.

So what i need right now is I don't want to move my actions from "article" to "index" controllers rather i just want to change

from

[http://]mydemostore/article/article/archives/01/2011 to

to

[http://]mydemostore/article/archives/01/2011

using Zend routing or basic PHP URL rewriting on .htaccess file.

Kindly help me how to get this done by using either of these two ways or both the ways.

Thanks a lot in advance for checking with my question !!!

答:
Something like this in .htaccess

```<code>RewriteEngine On
RewriteRule ^(article/)* article/ [L]
</code>```

May remove duplicates, but I wouldn't opt for it

A more general case for duplicates:

```<code>RewriteEngine On
RewriteRule ^([^/]+/)* $1 [L]
</code>```

Title: URL rewriting for Magento module

Body:
Something like this in .htaccess

RewriteEngine On
RewriteRule ^(article/)* article/ [L]

May remove duplicates, but I wouldn't opt for it

A more general case for duplicates:

RewriteEngine On
RewriteRule ^([^/]+/)* $1 [L]


答:
You can try the following code.</p>

```<code>$sql = "SELECT name, country FROM customers WHERE name IN ('Adam', 'David', 'Frank', 'Mike')";
$result = $conn->query($sql);
$nameArray = array("Adam","David","Frank","Mike");
$dataArray = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $dataArray["Name"][] = $row['name'];
        $dataArray["Country"][$row['name']] = $row['country'];
    }
}

echo 'Name|Country';
foreach($nameArray as $val)
{
    echo $val.'|'.((empty($dataArray[$val]))?'Not Found':$dataArray[$val]);
    // There you can also assign a array for the same.
}
</code>```

Title: PHP MySQL - Detect if missing row in array query

Body:
You can try the following code.

$sql = "SELECT name, country FROM customers WHERE name IN ('Adam', 'David', 'Frank', 'Mike')";
$result = $conn->query($sql);
$nameArray = array("Adam","David","Frank","Mike");
$dataArray = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $dataArray["Name"][] = $row['name'];
        $dataArray["Country"][$row['name']] = $row['country'];
    }
}

echo 'Name|Country';
foreach($nameArray as $val)
{
    echo $val.'|'.((empty($dataArray[$val]))?'Not Found':$dataArray[$val]);
    // There you can also assign a array for the same.
}


问:
why is this behaviour of strtof() changes with respect to the change in stdlib.h?
With <stdlib.h> included the following code gives the output of 123.34.

```<code>#include<stdlib.h>
int main()
{
    char *str="123.34";
    float f= strtof(str,NULL);
    printf("%f",f);
}
</code>```

But without <stdlib.h> it produces the output of 33.000000.

What is the role of <stdlib.h> here and why did the value 33.00000 occur when it is nowhere in the code?

答:
The <stdlib.h> header tells the compiler that strtof() returns a float(); in its absence, the compiler is forced to assume it returns an int.  Modern C compilers (GCC 5 and above) complain about the absence of a declaration for strtof() and/or a conflict with its internal memorized declaration for strtof().

If you omit <stdlib.h>, your code is unacceptable in C99 and C11 because you didn't declare strtof() before using it.  Since you omit <stdio.h>, it is invalid in C90, let alone C99 or C11.  You must declare variadic functions such as printf() before using them.

Body:
With <stdlib.h> included the following code gives the output of 123.34.

#include<stdlib.h>
int main()
{
    char *str="123.34";
    float f= strtof(str,NULL);
    printf("%f",f);
}

But without <stdlib.h> it produces the output of 33.000000.

What is the role of <stdlib.h> here and why did the value 33.00000 occur when it is nowhere in the code?


问:
Inline React JS For Loop For Pagination
I am trying to make a inline for loop for my pagination in react js but it doesn't seem to be working im curious to if anyone has an idea of how to do it.

currently I am doing this:

```<code><ul class="pagination">
  <li>
    <a href="#" aria-label="Previous">
      <span aria-hidden="true">«</span>
    </a>
  </li>
  {this.state.searching ?
    ''
    :

    Code for page buttons here

    }
    <li>
      <a href="#" aria-label="Next">
        <span aria-hidden="true">»</span>
      </a>
    </li>
  </ul>
</code>```

I am using the bootstrap pagination so i dont really need any styles but the problem is i want it to dynamically change how many pages are displayed based on how many things the search returns.

I want to display 3 results per page and the amount of results is stored in my state as amountofjobs

TL:DR Create loop to dynamically display pagination page buttons based on search not working.

i was trying to do this:

```<code>for(i = 0; i < this.state.amountofjobs / 3; i++){
  with normal jsx/html here to display but it kept saying i was missing an expression
}
</code>```

答:
You can return an array

Document.

```<code>class Hello extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {

        var pagesArray = [];
        for (var i = 0; i < this.props.pages; i++) {
            pagesArray.push(<li>{i}</li>);
        }

        return(
            <li>
                 {pagesArray}
            </li>
        );
    }
}

ReactDOM.render(
  <Hello pages={5} />,
      document.getElementById('container')
);
</code>```

Working fiddle

Title: Inline React JS For Loop For Pagination

Body:
I am trying to make a inline for loop for my pagination in react js but it doesn't seem to be working im curious to if anyone has an idea of how to do it.

currently I am doing this:

      «

  {this.state.searching ?
    ''
    :

    Code for page buttons here

    }

        »

I am using the bootstrap pagination so i dont really need any styles but the problem is i want it to dynamically change how many pages are displayed based on how many things the search returns.

I want to display 3 results per page and the amount of results is stored in my state as amountofjobs

TL:DR Create loop to dynamically display pagination page buttons based on search not working.

i was trying to do this:

for(i = 0; i < this.state.amountofjobs / 3; i++){
  with normal jsx/html here to display but it kept saying i was missing an expression
}

Body:
You can return an array

Document.

class Hello extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {

        var pagesArray = [];
        for (var i = 0; i < this.props.pages; i++) {
            pagesArray.push(<li>{i}</li>);
        }

        return(
            <li>
                 {pagesArray}
            </li>
        );
    }
}

ReactDOM.render(
  <Hello pages={5} />,
      document.getElementById('container')
);

Working fiddle


问:
Why can't i extend(Inherit) the properties of PrintStream class to a newly derived class
I want to override the println(int) by extending the PrintStream class into a newly defined class.

```<code>import java.io.PrintStream;

 class Newer extends PrintStream
{ public void println(int x) {

System.out.println(x);
}

public static void main(String[] args)
{
Newer n=new Newer();

n.println(2);
}

}
</code>```

I have got compilation error saying

```<code>extendsprintstream.java:3: cannot find symbol
symbol  : constructor PrintStream()
location: class java.io.PrintStream
class Newer extends PrintStream
^
1 error
</code>```

Why am I not able to inherit class PrintStream ?

答:
The problem here is no with extends but with the fact that you don't use super fir your class constructor.
You can't extends another class and overlook this class initialization.

In Java what actually happens when you don't have a constructor-Java compiler makes a default one which call an empty super() call-so it's actually looks like:

```<code>public Newer{
super();
}
</code>```

And because in your case PrintStream doesn't have an empty constructor only the ones you can find in Oracle help center  you will get compilation error.

Body:
I want to override the println(int) by extending the PrintStream class into a newly defined class.

import java.io.PrintStream;

 class Newer extends PrintStream
{ public void println(int x) {

System.out.println(x);
}

public static void main(String[] args)
{
Newer n=new Newer();

n.println(2);
}

}

I have got compilation error saying

extendsprintstream.java:3: cannot find symbol
symbol  : constructor PrintStream()
location: class java.io.PrintStream
class Newer extends PrintStream
^
1 error

Why am I not able to inherit class PrintStream ?

Body:
The problem here is no with extends but with the fact that you don't use super fir your class constructor.
You can't extends another class and overlook this class initialization.

In Java what actually happens when you don't have a constructor-Java compiler makes a default one which call an empty super() call-so it's actually looks like:

public Newer{
super();
}

And because in your case PrintStream doesn't have an empty constructor only the ones you can find in Oracle help center  you will get compilation error.


问:
tensorflow: "trying to mutate a frozen object", bazel
MacOS high sierra, MBP 2016, in terminal.

I'm following the directions here:
https://github.com/tensorflow/models/tree/master/research/syntaxnet
All options for ./configure chosen as default (and all python directories double-checked.). All steps have completed cleanly until this:

```<code>bazel test ...
# On Mac, run the following:
bazel test --linkopt=-headerpad_max_install_names \
  dragnn/... syntaxnet/... util/utf8/...
</code>```

I assume I'm supposed to run the latter line ("bazel test --linkopt" etc.).  But I get the same result either way, interestingly.

This throws about 10 errors, each of the same type "trying to mutate a frozen object", and concludes tests not run, error loading package dragnn/protos, and couldn't start build.

This is the general form of the errors:

syntaxnet>> bazel test --linkopt=-headerpad_max_install_names
  dragnn/... syntaxnet/... util/utf8/...

.

ERROR:
  /Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/dragnn/protos/BUILD:35:1:
  Traceback (most recent call last): File
  "/Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/dragnn/protos/BUILD",
  line 35 tf_proto_library_py(name = "data_py_pb2", srcs = ["dat..."])
  File
  "/Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/syntaxnet/syntaxnet.bzl",
  line 53, in tf_proto_library_py py_proto_library(name = name, srcs =
  srcs, srcs_versi...", <5 more arguments>) File
  "/private/var/tmp/_bazel_XXX/f74e5a21c3ad09aeb110d9de15110035/external/protobuf_archive/protobuf.bzl",
  line 374, in py_proto_library py_libs += [default_runtime] trying to
  mutate a frozen object ERROR: package contains errors: dragnn/protos

... [same error for various 'name = "...pb2"' files] ...

INFO: Elapsed time: 0.709s FAILED: Build did NOT complete successfully
  (17 packages loaded) ERROR: Couldn't start the build. Unable to run
  tests

Any idea what could be doing this?  Thanks.

答:
This error indicates a bug in the py_proto_library rule implementation.

tf_proto_library_py is defined in syntaxnet.bzl. It is a wrapper around py_proto_library, which is defined by the tf_workspace macro's protobuf_archive rule.

"protobuf_archive" downloads Protobuf 3.3.0, which contains //:protobuf.bzl with the buggy py_proto_library rule implementation: in line #374 it tries to mutate an immutable object py_libs.

Make sure you use the latest Bazel version, currently that's 0.8.1.

If the problem still persists, then:

I suggest filing a bug with:

Protobuf, to fix the py_proto_library rule

TensorFlow, to update their Protobuf version in tf_workspace, and

Syntaxnet to update their TF submodule reference in //research/syntaxnet to the bugfixed version.

As a workaround, perhaps you can patch protobuf.bzl.

The patch is to change these lines:

```<code>   373    if default_runtime and not default_runtime in py_libs + deps:
   374      py_libs += [default_runtime]
   375
   376    native.py_library(
   377        name=name,
   378        srcs=outs+py_extra_srcs,
   379        deps=py_libs+deps,
   380        imports=includes,
   381        **kargs)
</code>```

to these:

```<code>   373    if default_runtime and not default_runtime in py_libs + deps:
   374      py_libs2 = py_libs + [default_runtime]
   375    else:
   376      py_libs2 = py_libs
   377
   378    native.py_library(
   379        name=name,
   380        srcs=outs+py_extra_srcs,
   381        deps=py_libs2+deps,
   382        imports=includes,
   383        **kargs)
</code>```

Disclaimer: this is a "blind" fix; I have not tried whether it works.

Body:
MacOS high sierra, MBP 2016, in terminal.

I'm following the directions here:
https://github.com/tensorflow/models/tree/master/research/syntaxnet
All options for ./configure chosen as default (and all python directories double-checked.). All steps have completed cleanly until this:

bazel test ...
# On Mac, run the following:
bazel test --linkopt=-headerpad_max_install_names \
  dragnn/... syntaxnet/... util/utf8/...

I assume I'm supposed to run the latter line ("bazel test --linkopt" etc.).  But I get the same result either way, interestingly.

This throws about 10 errors, each of the same type "trying to mutate a frozen object", and concludes tests not run, error loading package dragnn/protos, and couldn't start build.

This is the general form of the errors:

syntaxnet>> bazel test --linkopt=-headerpad_max_install_names
  dragnn/... syntaxnet/... util/utf8/...

.

ERROR:
  /Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/dragnn/protos/BUILD:35:1:
  Traceback (most recent call last): File
  "/Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/dragnn/protos/BUILD",
  line 35 tf_proto_library_py(name = "data_py_pb2", srcs = ["dat..."])
  File
  "/Users/XXX/Desktop/NLP/syntaxnet/models/research/syntaxnet/syntaxnet/syntaxnet.bzl",
  line 53, in tf_proto_library_py py_proto_library(name = name, srcs =
  srcs, srcs_versi...", <5 more arguments>) File
  "/private/var/tmp/_bazel_XXX/f74e5a21c3ad09aeb110d9de15110035/external/protobuf_archive/protobuf.bzl",
  line 374, in py_proto_library py_libs += [default_runtime] trying to
  mutate a frozen object ERROR: package contains errors: dragnn/protos

... [same error for various 'name = "...pb2"' files] ...

INFO: Elapsed time: 0.709s FAILED: Build did NOT complete successfully
  (17 packages loaded) ERROR: Couldn't start the build. Unable to run
  tests

Any idea what could be doing this?  Thanks.

Body:
This error indicates a bug in the py_proto_library rule implementation.

tf_proto_library_py is defined in syntaxnet.bzl. It is a wrapper around py_proto_library, which is defined by the tf_workspace macro's protobuf_archive rule.

"protobuf_archive" downloads Protobuf 3.3.0, which contains //:protobuf.bzl with the buggy py_proto_library rule implementation: in line #374 it tries to mutate an immutable object py_libs.

Make sure you use the latest Bazel version, currently that's 0.8.1.

If the problem still persists, then:

I suggest filing a bug with:

Protobuf, to fix the py_proto_library rule

TensorFlow, to update their Protobuf version in tf_workspace, and

Syntaxnet to update their TF submodule reference in //research/syntaxnet to the bugfixed version.

As a workaround, perhaps you can patch protobuf.bzl.

The patch is to change these lines:

   373    if default_runtime and not default_runtime in py_libs + deps:
   374      py_libs += [default_runtime]
   375
   376    native.py_library(
   377        name=name,
   378        srcs=outs+py_extra_srcs,
   379        deps=py_libs+deps,
   380        imports=includes,
   381        **kargs)

to these:

   373    if default_runtime and not default_runtime in py_libs + deps:
   374      py_libs2 = py_libs + [default_runtime]
   375    else:
   376      py_libs2 = py_libs
   377
   378    native.py_library(
   379        name=name,
   380        srcs=outs+py_extra_srcs,
   381        deps=py_libs2+deps,
   382        imports=includes,
   383        **kargs)

Disclaimer: this is a "blind" fix; I have not tried whether it works.