问:
How to change counter in bash to appending different strings to file
i need to get information, which users have connected to facebook from my proxy. I have a 2 loops.

```<code>#i have format og logs, like squid.log.12.10.2017
#with `ls squid.log*` i am working with all squid logs, day by day
for i in `ls squid.log*`; do
    echo "There is log $i, that we need to check"
    #i am getting count of ip addresses, that were on fb.com and i am writing them to ~/temp_cache
    # like this:
    # 25 192.168.110.5
    # 41 192.168.110.2
    # where 192.168.110.5 have connected to fb.com 25 times
    # and 192.168.110.2 have connected to fb.com 41 times
    zgrep fb.com /var/log/$i | cut -d " " -f1 | sort | uniq -c | sort -n -k 1 >> ~/temp_cache

    #i am getting only list of ip, without count of connections to facebook
    # like this:
    # 192.168.110.5
    # 192.168.110.2
    ip=$(zgrep fb.com /var/log/$i | cut -d " " -f1 | sort | uniq -c | sort -n -k 1 | awk '{print $2}')
    for y in $ip; do
        echo "Users from $y:"
        # i have system, that we are using for projects, in this system we have log ip-addresses and logins, from these ip addresses
        # like for this ip 192.168.110.5, i am getting name of user duke
        # main result, like this:
        # duke
        # the_rock
        redmine_users=$(tail -n 500000 /usr/share/redmine/log/production.log | grep -A 3 "$y" | grep "Current user" | awk '{print $3}' | head -n 1)

        # i am appending to lines, name of users for these lines
        # in a result it should be like this:
        # 25 192.168.110.5 duke
        # 41 192.168.110.2 the rock
        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
    done
    # Delimiter for each day of logs
    echo "------------------------------------------------" >> ~/temp_cache
done
</code>```

For the first looking it works. But it works only for one day. If script is going to second log, i mean squid.log.13.10.2017, it make something like this:

```<code>        25 192.168.110.5 duke
        41 192.168.110.2 the rock
        ______________________________ hogan
        33 192.168.110.1
</code>```

But i want to do this:

```<code>        25 192.168.110.5 duke
        41 192.168.110.2 the rock
        ______________________________
        33 192.168.110.1 hogan
</code>```

I tried to run script manually for one day, with existsing line ______________________________ and with changing

```<code>        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
</code>```

to

```<code>        counter=1
        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
</code>```

But in a result i have:

```<code>        ______________________________
        25 192.168.110.5 duke the rock
        41 192.168.110.2
</code>```

How to do, what i want, at least:

```<code>        ______________________________
        25 192.168.110.5 duke
        41 192.168.110.2 the rock
</code>```

How to change counter in this construction:

```<code>        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
</code>```

答:
If I understand correctly, you are trying to get it so the name is on the same line as the count and ip?

Assuming this is correct, you simply need to increase your counter after adding the ---- as well as where it currently is.

I do have multiple other issues with the code but I think this answers the main question.  Let me know if I have missed the mark?

Body:
i need to get information, which users have connected to facebook from my proxy. I have a 2 loops.

#i have format og logs, like squid.log.12.10.2017
#with `ls squid.log*` i am working with all squid logs, day by day
for i in `ls squid.log*`; do
    echo "There is log $i, that we need to check"
    #i am getting count of ip addresses, that were on fb.com and i am writing them to ~/temp_cache
    # like this:
    # 25 192.168.110.5
    # 41 192.168.110.2
    # where 192.168.110.5 have connected to fb.com 25 times
    # and 192.168.110.2 have connected to fb.com 41 times
    zgrep fb.com /var/log/$i | cut -d " " -f1 | sort | uniq -c | sort -n -k 1 >> ~/temp_cache

    #i am getting only list of ip, without count of connections to facebook
    # like this:
    # 192.168.110.5
    # 192.168.110.2
    ip=$(zgrep fb.com /var/log/$i | cut -d " " -f1 | sort | uniq -c | sort -n -k 1 | awk '{print $2}')
    for y in $ip; do
        echo "Users from $y:"
        # i have system, that we are using for projects, in this system we have log ip-addresses and logins, from these ip addresses
        # like for this ip 192.168.110.5, i am getting name of user duke
        # main result, like this:
        # duke
        # the_rock
        redmine_users=$(tail -n 500000 /usr/share/redmine/log/production.log | grep -A 3 "$y" | grep "Current user" | awk '{print $3}' | head -n 1)

        # i am appending to lines, name of users for these lines
        # in a result it should be like this:
        # 25 192.168.110.5 duke
        # 41 192.168.110.2 the rock
        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
    done
    # Delimiter for each day of logs
    echo "------------------------------------------------" >> ~/temp_cache
done

For the first looking it works. But it works only for one day. If script is going to second log, i mean squid.log.13.10.2017, it make something like this:

        25 192.168.110.5 duke
        41 192.168.110.2 the rock
        ______________________________ hogan
        33 192.168.110.1

But i want to do this:

        25 192.168.110.5 duke
        41 192.168.110.2 the rock
        ______________________________
        33 192.168.110.1 hogan

I tried to run script manually for one day, with existsing line ______________________________ and with changing

        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache

to

        counter=1
        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache

But in a result i have:

        ______________________________
        25 192.168.110.5 duke the rock
        41 192.168.110.2

How to do, what i want, at least:

        ______________________________
        25 192.168.110.5 duke
        41 192.168.110.2 the rock

How to change counter in this construction:

        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache


来源: stackexchange

问:
localhost prefix Angular 2 development
I am working on an angular project where I am currently trying to access an online api. The problem is that when I use Angular 2 token and set the apiBase to the url, it gets prefixed with http://localhost:4200. The apiBase doesn't work with any prefix. Is there any way to drop the prefix so it can be a basic url?
An example of what I get is:

```<code>http://localhost:4200/google.com
</code>```

when I need it to be just

```<code>google.com
</code>```

And this is the variable i'm working with.

```<code>export const environment = {
  production: false,
  token_auth_config: {
    apiBase: 'google.com'
  }
};
</code>```

答:
Your apiBase is defined as a relative url. Change url to include protocol like http://google.com and it will work. However you will probably encounter CORS restrictions. But that's another topic.

You could also use Proxy to Backend if your API listens really on relative url.

ContentLicense: CC BY-SA 3.0

Title: localhost prefix Angular 2 development

Body:
I am working on an angular project where I am currently trying to access an online api. The problem is that when I use Angular 2 token and set the apiBase to the url, it gets prefixed with http://localhost:4200. The apiBase doesn't work with any prefix. Is there any way to drop the prefix so it can be a basic url?
An example of what I get is:

http://localhost:4200/google.com

when I need it to be just

google.com

And this is the variable i'm working with.

export const environment = {
  production: false,
  token_auth_config: {
    apiBase: 'google.com'
  }
};


问:
Array being mysteriously converted to object immediately before usort() sees it
I'm getting a good laugh out of this situation. It's in a giant application, so I can't just upload everything, but here is the local, relevant part of my code:

```</p>

```public function reallyCustomSort($thing, $options='')
{
    die('dying. gettype results for our param: '.gettype($thing));
    //Gives us "array." So why does usort complain about "object given?"
    die('dying. get_class results for our param: '.get_class($thing)); // Gives us "get_class() expects parameter 1 to be object, array given.
    usort($thing, 'AppBundle\Twig\CustomSort::customCompare'); // Gives us "Warning: usort() expects parameter 1 to be array, object given"
    die('We are done here.');
    return($thing);
}

public function someRandomFunction($thing){
    die('dying in someRandomFunction. gettype results for our param: '.gettype($thing)); //Gives us "array."
}
```

<p>```

In other words, two function calls that analyze my variable both agree that it's an array, and then a line later, my usort() function thinks that the variable contains an object.

Has anyone ever encountered this behavior before? If so, how did you get around it?

A few things I've already tried:

Inserting a sleep() call to see if race conditions are involved. (See
gist below.) No luck.

Passing the $thing variable to a different function just to see if
for some strange reason the mere passing of the $thing to a
function was causing a conversion. No luck.

Clearing various caches in my app. No luck.

A gist with some more (commented out) code showing things I've tried:

https://gist.github.com/patrickmaynard/7c3c7f0695e223e6903fd729172b4c21

答:
I got around the issue by just writing a custom function, based heavily on an SO answer elsewhere. Here's the gist:

https://gist.github.com/patrickmaynard/922cf7cfa7533c655ec1c5eb4303345a

(The array I'm sorting is an array of objects, each of which has a getName() method. So the logic in this gist works relatively well for my use case. It will probably require some adaptation for others.)

====

Edit: Someone I respect also noticed that my method was being called more than once, which meant that a standalone die() function was not the best way to debug it. It was receiving an array the first time around, then receiving an object the second or third time. So while the workaround above "works," we were able to find a more elegant solution by observing the object type that was being passed during those later method calls, then using that object's toArray() method.

Body:
I'm getting a good laugh out of this situation. It's in a giant application, so I can't just upload everything, but here is the local, relevant part of my code:

```</p>

<pre><code>public function reallyCustomSort($thing, $options='')
{
    die('dying. gettype results for our param: '.gettype($thing));
    //Gives us "array." So why does usort complain about "object given?"
    die('dying. get_class results for our param: '.get_class($thing)); // Gives us "get_class() expects parameter 1 to be object, array given.
    usort($thing, 'AppBundle\Twig\CustomSort::customCompare'); // Gives us "Warning: usort() expects parameter 1 to be array, object given"
    die('We are done here.');
    return($thing);
}

public function someRandomFunction($thing){
    die('dying in someRandomFunction. gettype results for our param: '.gettype($thing)); //Gives us "array."
}
</code></pre>

<p>```

In other words, two function calls that analyze my variable both agree that it's an array, and then a line later, my usort() function thinks that the variable contains an object.

Has anyone ever encountered this behavior before? If so, how did you get around it?

A few things I've already tried:

Inserting a sleep() call to see if race conditions are involved. (See
gist below.) No luck.

Passing the $thing variable to a different function just to see if
for some strange reason the mere passing of the $thing to a
function was causing a conversion. No luck.

Clearing various caches in my app. No luck.

A gist with some more (commented out) code showing things I've tried:

https://gist.github.com/patrickmaynard/7c3c7f0695e223e6903fd729172b4c21


问:
What pandas operation will help me do a groupby and aggregate by column combinations?
Here's an example of what I am trying to do:

```<code>   bar  foo   o1   o2 thing
0    1    1  0.0  3.3     a
1    1    1  1.1  4.4     a
2    3    2  2.2  5.5     b
   foo_1_bar_3_o1  foo_1_bar_3_o2  foo_2_bar_3_o1  foo_2_bar_3_o2  \
0             NaN             NaN             NaN             NaN
1             NaN             NaN             2.2             5.5

   foo_1_bar_1_o1  foo_1_bar_1_o2  foo_2_bar_1_o1  foo_2_bar_1_o2 thing
0             1.1             7.7             NaN             NaN     a
1             NaN             NaN             NaN             NaN     b
</code>```

The first is my input DataFrame and the second is my desired output DataFrame (NaNs could be substituted with 0's).

This should be some sort of a groupby (on column thing) and then some kind of an aggregating function on values in the columns o1 and o2 that aggregate based on all possible combinations of the values of foo and bar. Notice that foo_1_bar_2_o2 is 7.7 because it is the sum over the column o2 when foo == 1 && bar == 2 for the group 'a'.

I've tried researching dcast, crosstab, and pivot in pandas but none seem to satisfy what I am trying to do.

I wrote base Python code that does what I want, but, again, I would like to translate it to a more friendly format using already existing functions. I don't believe my use-case is obscure enough for this to not be possible.

Below is the base Python code for this operation.

```<code>import pandas as pd
import numpy as np
import itertools

df = pd.DataFrame({'thing': ['a', 'a', 'b'],
                   'foo': [1, 1, 2],
                   'bar': [1, 1, 3],
                   'o1': [0.0, 1.1, 2.2],
                   'o2': [3.3, 4.4, 5.5]})

key_columns = ['foo', 'bar']

key_value_pairs = [df[key].values.tolist() for key in key_columns]

key_value_pairs = list(set(itertools.product(*key_value_pairs)))

output_columns = ['o1', 'o2']

def aggregate(df):
  new_columns = []
  for pair in key_value_pairs:
    pair = list(zip(key_columns, pair))
    new_column = '_'.join(['%s_%d' % (key, value) for key, value in pair])
    for o in output_columns:
      criteria = list()
      for key, value in pair:
        criterion = (df[key] == value)
        criteria.append(criterion)
      new_columns.append('%s_%s' % (new_column, o))
      df[new_columns[-1]] = df[np.logical_and.reduce(criteria)][o].sum()
  return df.head(1)[new_columns + ['thing']]

things = df['thing'].value_counts().index.tolist()

groups = df.groupby('thing')

dfs = []
for thing in things:
  dfs.append(aggregate(groups.get_group(thing).reset_index()))
  #print(aggregate(groups.get_group(thing).reset_index(drop=True)))

print(df)
print(pd.concat(dfs).reset_index(drop=True))
</code>```

答:
I try create dynamic solution:

```<code>key_columns = ['foo', 'bar']
output_columns = ['o1', 'o2']
</code>```

First add key_columns strings to values with radd:

```<code>df[key_columns] = (df[key_columns].astype(str)
                                  .radd(pd.Series(key_columns,index=key_columns) + '_'))

print (df)
     bar    foo   o1   o2 thing
0  bar_1  foo_1  0.0  3.3     a
1  bar_1  foo_1  1.1  4.4     a
2  bar_3  foo_2  2.2  5.5     b
</code>```

Then aggregate by sum and reshape by unstack - get MultiIndex in columns:

```<code>df = df.groupby(['thing'] + key_columns)[output_columns].sum().unstack(key_columns)
print (df)
         o1          o2
bar   bar_1 bar_3 bar_1 bar_3
foo   foo_1 foo_2 foo_1 foo_2
thing
a       1.1   NaN   7.7   NaN
b       NaN   2.2   NaN   5.5
</code>```

Create all possible combinations by MultiIndex.from_product for reindex, then reorder_levels and sort_index:

```<code>mux = pd.MultiIndex.from_product(df.columns.levels, names=df.columns.names)
print (mux)
MultiIndex(levels=[['o1', 'o2'], ['foo_1', 'foo_2'], ['bar_1', 'bar_3']],
           labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1],
                   [0, 1, 0, 1, 0, 1, 0, 1]],
           names=[None, 'foo', 'bar'])

df = df.reindex(columns=mux).reorder_levels(key_columns + [None], axis=1).sort_index(axis=1)
</code>```

Last remove MultiIndex by map with join:

```<code>df.columns = df.columns.map('_'.join)
df = df.reset_index()
print (df)
  thing  foo_1_bar_1_o1  foo_1_bar_1_o2  foo_1_bar_3_o1  foo_1_bar_3_o2  \
0     a             1.1             7.7             NaN             NaN
1     b             NaN             NaN             NaN             NaN

   foo_2_bar_1_o1  foo_2_bar_1_o2  foo_2_bar_3_o1  foo_2_bar_3_o2
0             NaN             NaN             NaN             NaN
1             NaN             NaN             2.2             5.5
</code>```

Body:
Here's an example of what I am trying to do:

   bar  foo   o1   o2 thing
0    1    1  0.0  3.3     a
1    1    1  1.1  4.4     a
2    3    2  2.2  5.5     b
   foo_1_bar_3_o1  foo_1_bar_3_o2  foo_2_bar_3_o1  foo_2_bar_3_o2  \
0             NaN             NaN             NaN             NaN
1             NaN             NaN             2.2             5.5

   foo_1_bar_1_o1  foo_1_bar_1_o2  foo_2_bar_1_o1  foo_2_bar_1_o2 thing
0             1.1             7.7             NaN             NaN     a
1             NaN             NaN             NaN             NaN     b

The first is my input DataFrame and the second is my desired output DataFrame (NaNs could be substituted with 0's).

This should be some sort of a groupby (on column thing) and then some kind of an aggregating function on values in the columns o1 and o2 that aggregate based on all possible combinations of the values of foo and bar. Notice that foo_1_bar_2_o2 is 7.7 because it is the sum over the column o2 when foo == 1 && bar == 2 for the group 'a'.

I've tried researching dcast, crosstab, and pivot in pandas but none seem to satisfy what I am trying to do.

I wrote base Python code that does what I want, but, again, I would like to translate it to a more friendly format using already existing functions. I don't believe my use-case is obscure enough for this to not be possible.

Below is the base Python code for this operation.

import pandas as pd
import numpy as np
import itertools

df = pd.DataFrame({'thing': ['a', 'a', 'b'],
                   'foo': [1, 1, 2],
                   'bar': [1, 1, 3],
                   'o1': [0.0, 1.1, 2.2],
                   'o2': [3.3, 4.4, 5.5]})

key_columns = ['foo', 'bar']

key_value_pairs = [df[key].values.tolist() for key in key_columns]

key_value_pairs = list(set(itertools.product(*key_value_pairs)))

output_columns = ['o1', 'o2']

def aggregate(df):
  new_columns = []
  for pair in key_value_pairs:
    pair = list(zip(key_columns, pair))
    new_column = '_'.join(['%s_%d' % (key, value) for key, value in pair])
    for o in output_columns:
      criteria = list()
      for key, value in pair:
        criterion = (df[key] == value)
        criteria.append(criterion)
      new_columns.append('%s_%s' % (new_column, o))
      df[new_columns[-1]] = df[np.logical_and.reduce(criteria)][o].sum()
  return df.head(1)[new_columns + ['thing']]

things = df['thing'].value_counts().index.tolist()

groups = df.groupby('thing')

dfs = []
for thing in things:
  dfs.append(aggregate(groups.get_group(thing).reset_index()))
  #print(aggregate(groups.get_group(thing).reset_index(drop=True)))

print(df)
print(pd.concat(dfs).reset_index(drop=True))

Body:
I try create dynamic solution:

key_columns = ['foo', 'bar']
output_columns = ['o1', 'o2']

First add key_columns strings to values with radd:

df[key_columns] = (df[key_columns].astype(str)
                                  .radd(pd.Series(key_columns,index=key_columns) + '_'))

print (df)
     bar    foo   o1   o2 thing
0  bar_1  foo_1  0.0  3.3     a
1  bar_1  foo_1  1.1  4.4     a
2  bar_3  foo_2  2.2  5.5     b

Then aggregate by sum and reshape by unstack - get MultiIndex in columns:

df = df.groupby(['thing'] + key_columns)[output_columns].sum().unstack(key_columns)
print (df)
         o1          o2
bar   bar_1 bar_3 bar_1 bar_3
foo   foo_1 foo_2 foo_1 foo_2
thing
a       1.1   NaN   7.7   NaN
b       NaN   2.2   NaN   5.5

Create all possible combinations by MultiIndex.from_product for reindex, then reorder_levels and sort_index:

mux = pd.MultiIndex.from_product(df.columns.levels, names=df.columns.names)
print (mux)
MultiIndex(levels=[['o1', 'o2'], ['foo_1', 'foo_2'], ['bar_1', 'bar_3']],
           labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1],
                   [0, 1, 0, 1, 0, 1, 0, 1]],
           names=[None, 'foo', 'bar'])

df = df.reindex(columns=mux).reorder_levels(key_columns + [None], axis=1).sort_index(axis=1)

Last remove MultiIndex by map with join:

df.columns = df.columns.map('_'.join)
df = df.reset_index()
print (df)
  thing  foo_1_bar_1_o1  foo_1_bar_1_o2  foo_1_bar_3_o1  foo_1_bar_3_o2  \
0     a             1.1             7.7             NaN             NaN
1     b             NaN             NaN             NaN             NaN

   foo_2_bar_1_o1  foo_2_bar_1_o2  foo_2_bar_3_o1  foo_2_bar_3_o2
0             NaN             NaN             NaN             NaN
1             NaN             NaN             2.2             5.5


问:
Hyperledger composer playground error on IBM Blockchain Platform
I am trying to learn about hyperledger composer by going through the tutorials. Everything works on the playground so I followed the tutorial and created a cluster with bluemix.

http://184.172.229.160:31080/

I was testing the hosted playground and I notice all transactions, even if deployed with a sample network like trade-network, returns error saying the asset or participant does not exist

Error: Object with ID 'tradingSymbol:ABC' in collection with ID 'Asset:org.acme.trading.Commodity' does not exist

Any advice on troubleshooting the above error?

答: The most likely explanation is that you don't need the tradingSymbol: prefix and that your asset ID is just ABC.


问:
React setState - Add array to nested object with multiple arrays
I'm currently working on a new application in React. This is the first time I'm creating something in React. The application will display our own promotions.

My initial state is as follows:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510558814960,
        "endDateTimeStamp": 1510558814960,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

This is created from my defaultPromotion constant. This constant is stored in a separate file, which I call api.js

```<code>export const defaultPromotion = {
  name: '',
  campaign: '',
  url: 'https://',
  position: 0,
  periods: [
    {
      startDateTimeStamp: Date.now(),
      endDateTimeStamp: Date.now(),
      variants: [
        {
          title: '',
          text: '',
          image: '',
        },
      ]
    },
  ]
}
</code>```

In my createPromotion component it's created as followed

```<code>let promotionState = api.promotions.defaultPromotion;

this.state = {
  promotion: promotionState
};
</code>```

I can add a new period with the following:

```<code>addPromotion() {
    let promotion = this.state.promotion;
    promotion.periods.push( api.promotions.defaultPromotion.periods[0] );
    this.forceUpdate();
}
</code>```

After that, a new period is added as expected. Suggestions to do this with setState() are very welcome! So, my new state is now:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

Now, I want to add a new variant for this promotion period, this is where I'm stuck for 2 days now.

I'm adding a new period as follows:

```<code>addVariant( periodKey ) {
  const promotion = this.state.promotion;
  promotion.periods[periodKey].variants.push(api.promotions.defaultPromotion.periods[0].variants[0]);
  this.setState({ promotion: promotion });
}
</code>```

periodKey is here "1", so, I'm expecting that there will be added a new variant for periods[1], but, it's added to both periods. State is now as follows:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

Can someone explain me why this is happening and how I can add a new variant the right way?

Many, many thanks in advance!

UPDATE 1

Based on the answers from bennygenel and Patrick Hübl-Neschkudla, my implementation is now as follows:

Setting the initial state:

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

      let promotionState = api.promotions.defaultPromotion;
      this.state = { ...promotionState };

}
</code>```

Method:

```<code>addVariant( periodKey ) {
  this.setState((prevState) => {
    const { periods } = prevState;

    periods[periodKey].variants.push(
      Object.assign({}, { ...periods[periodKey].variants, api.promotions.defaultPromotion.periods[0].variants[0]})
    );

    return { periods };
  });
}
</code>```

But this still is setting the new variant in all the periods. I've also tried the exact code from Benny, but with the same results. The method is called as

```<code>this.props.addVariant( this.props.periodKey );
</code>```

Even when I call it as:

```<code>this.props.addVariant(2);
</code>```

The same behaviour is happening.

UPDATE 2

I now have rewritten everything to redux, this is so I have access to my promotion in every component the easy way, instead off passing them through certain components. Based on the answer of @mersocarlin, I now have the following reducer cases:

Add period

```<code>case PROMOTION_ADD_PERIOD:
    const { periods } = { ...state };
    periods.push(api.promotions.defaultPromotion.periods[0]);

    state = {
        ...state,
        periods: periods
    };
    break;
</code>```

Add a period variant

```<code>case PROMOTION_ADD_PERIOD_VARIANT :

  state = {
    ...state,
    periods: [
      ...state.periods[action.payload.period],
      {
        variants: [
          ...state.periods[action.payload.period].variants,
          api.promotions.defaultPromotion.periods[0].variants[0]
        ]
      }
    ]
  };

  break;
</code>```

The following case:
Add a new variant, works, state:

```<code>{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "startDateTimeStamp": 1510599968588,
      "endDateTimeStamp": 1510599968588,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    },
    {
      "startDateTimeStamp": 1510599968594,
      "endDateTimeStamp": 1510599968594,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}
</code>```

After that, adding a new variant, kinda works, well, the variant is added, but I'm losing my 2nd period. State:

```<code>{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        },
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}
</code>```

I think this is a small thing I'm not see'ing. Does someone have the solution for the "PROMOTION_ADD_PERIOD_VARIANT" case?

Update 3
Changed the "PROMOTION_ADD_PERIOD" case as follows:

```<code>case PROMOTION_ADD_PERIOD:
    state = {
        ...state,
        periods: [
            ...state.periods,
            initialState.periods[0]
        ]
    };

    break;
</code>```

Update 4
Finaly found the solution. See the final code for PROMOTION_ADD_PERIOD_VARIANT below:

```<code>state = {
  ...state,
  periods: [
    ...state.periods.map((item, index) => {
      if ( index !== action.payload.period ) {
        return item;
      }

      return {
        ...item,
        variants: [
          ...item.variants,
          initialState.periods[0].variants[0]
        ]
      }
    })
  ]
};
</code>```

Thank you all so much for your help!!

答:
So, what's happening here is that you have an array with two references to the same object.

Imagine it like this:

```<code>myArray[0] = reference to defaultPromotion
myArray[1] = reference to defaultPromotion
</code>```

That's actually a wonderful example of why immutability concepts got so much attention in the past few years :)

What you'd want to do here is instead of adding the defaultPromotion object to the promotions array, you create a new object with the same props as this object and add it. It would look something like this (depending on your ES version etc.)

promotion.periods.push(
  Object.assign({}, api.promotions.defaultPromotion.periods[0])
);

This way, you're creating a new object and pass this to the array instead of a reference to the already existing one.

Body:
I'm currently working on a new application in React. This is the first time I'm creating something in React. The application will display our own promotions.

My initial state is as follows:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510558814960,
        "endDateTimeStamp": 1510558814960,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

This is created from my defaultPromotion constant. This constant is stored in a separate file, which I call api.js

export const defaultPromotion = {
  name: '',
  campaign: '',
  url: 'https://',
  position: 0,
  periods: [
    {
      startDateTimeStamp: Date.now(),
      endDateTimeStamp: Date.now(),
      variants: [
        {
          title: '',
          text: '',
          image: '',
        },
      ]
    },
  ]
}

In my createPromotion component it's created as followed

let promotionState = api.promotions.defaultPromotion;

this.state = {
  promotion: promotionState
};

I can add a new period with the following:

addPromotion() {
    let promotion = this.state.promotion;
    promotion.periods.push( api.promotions.defaultPromotion.periods[0] );
    this.forceUpdate();
}

After that, a new period is added as expected. Suggestions to do this with setState() are very welcome! So, my new state is now:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

Now, I want to add a new variant for this promotion period, this is where I'm stuck for 2 days now.

I'm adding a new period as follows:

addVariant( periodKey ) {
  const promotion = this.state.promotion;
  promotion.periods[periodKey].variants.push(api.promotions.defaultPromotion.periods[0].variants[0]);
  this.setState({ promotion: promotion });
}

periodKey is here "1", so, I'm expecting that there will be added a new variant for periods[1], but, it's added to both periods. State is now as follows:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

Can someone explain me why this is happening and how I can add a new variant the right way?

Many, many thanks in advance!

UPDATE 1

Based on the answers from bennygenel and Patrick Hübl-Neschkudla, my implementation is now as follows:

Setting the initial state:

constructor(props) {
      super(props);

      let promotionState = api.promotions.defaultPromotion;
      this.state = { ...promotionState };

}

Method:

addVariant( periodKey ) {
  this.setState((prevState) => {
    const { periods } = prevState;

    periods[periodKey].variants.push(
      Object.assign({}, { ...periods[periodKey].variants, api.promotions.defaultPromotion.periods[0].variants[0]})
    );

    return { periods };
  });
}

But this still is setting the new variant in all the periods. I've also tried the exact code from Benny, but with the same results. The method is called as

this.props.addVariant( this.props.periodKey );

Even when I call it as:

this.props.addVariant(2);

The same behaviour is happening.

UPDATE 2

I now have rewritten everything to redux, this is so I have access to my promotion in every component the easy way, instead off passing them through certain components. Based on the answer of @mersocarlin, I now have the following reducer cases:

Add period

case PROMOTION_ADD_PERIOD:
    const { periods } = { ...state };
    periods.push(api.promotions.defaultPromotion.periods[0]);

    state = {
        ...state,
        periods: periods
    };
    break;

Add a period variant

case PROMOTION_ADD_PERIOD_VARIANT :

  state = {
    ...state,
    periods: [
      ...state.periods[action.payload.period],
      {
        variants: [
          ...state.periods[action.payload.period].variants,
          api.promotions.defaultPromotion.periods[0].variants[0]
        ]
      }
    ]
  };

  break;

The following case:
Add a new variant, works, state:

{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "startDateTimeStamp": 1510599968588,
      "endDateTimeStamp": 1510599968588,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    },
    {
      "startDateTimeStamp": 1510599968594,
      "endDateTimeStamp": 1510599968594,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}

After that, adding a new variant, kinda works, well, the variant is added, but I'm losing my 2nd period. State:

{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        },
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}

I think this is a small thing I'm not see'ing. Does someone have the solution for the "PROMOTION_ADD_PERIOD_VARIANT" case?

Update 3
Changed the "PROMOTION_ADD_PERIOD" case as follows:

case PROMOTION_ADD_PERIOD:
    state = {
        ...state,
        periods: [
            ...state.periods,
            initialState.periods[0]
        ]
    };

    break;

Update 4
Finaly found the solution. See the final code for PROMOTION_ADD_PERIOD_VARIANT below:

state = {
  ...state,
  periods: [
    ...state.periods.map((item, index) => {
      if ( index !== action.payload.period ) {
        return item;
      }

      return {
        ...item,
        variants: [
          ...item.variants,
          initialState.periods[0].variants[0]
        ]
      }
    })
  ]
};

Thank you all so much for your help!!

Body:
So, what's happening here is that you have an array with two references to the same object.

Imagine it like this:

myArray[0] = reference to defaultPromotion
myArray[1] = reference to defaultPromotion

That's actually a wonderful example of why immutability concepts got so much attention in the past few years :)

What you'd want to do here is instead of adding the defaultPromotion object to the promotions array, you create a new object with the same props as this object and add it. It would look something like this (depending on your ES version etc.)

promotion.periods.push(
  Object.assign({}, api.promotions.defaultPromotion.periods[0])
);

This way, you're creating a new object and pass this to the array instead of a reference to the already existing one.


问:
Converting a result of Integer to String or Word in C
so i have a problem here. I am working on my class assignment which is create a calculator but every result must be in a word, example :

```<code>int a,b,c;
printf("Input first number:");
scanf("%d", &a);
printf("Input second number:"):
scanf("%d", &b);
c=a+b;
printf("The result are: %d", c);
printf("If in words, it is  = ");
switch(c){
case 0:printf("abcdef");break;
case 1:printf("bc");break;
case 2:printf("abged");break;
case 3:printf("abgcd");break;
case 4:printf("fbgc");break;
case 5:printf("afgod");break;
case 6:printf("fgcde");break;
case 7:printf("abc");break;
case 8:printf("abcdefg");break;
case 9:printf("abcdfg");break;
default :printf("error");break;
</code>```

So the result from this when im running it is :

Input first number : 12

input second number : 12

The result are: 24

If in words, it is = error

so what I'm confused here is how I did print the c result as a word? so what i want from my output is

Input first number : 12

input second number : 12

The result are : 24

If in words, it is = abged fbcg

so far I'm searching for answers but I cannot find it. If anyone here can help me, please do.

Thanks in advance

*edited

答:
ok, so you mean you want to print a string for each digit of a number, which is the result of whatever math function?

Try [untested]

```<code>int d = c;
do {
    switch (d % 10) { /* your replacement-text-switch goes here */ }
    d /= 10;
} while (d != 0)
</code>```

This will print out the number in reverse.
If you want to print it out the other way, then you have to know about the maximum number you are going to calculate. (Or, being advanced you can use logarithm to determine the length of a number.)

Body:
so i have a problem here. I am working on my class assignment which is create a calculator but every result must be in a word, example :

int a,b,c;
printf("Input first number:");
scanf("%d", &a);
printf("Input second number:"):
scanf("%d", &b);
c=a+b;
printf("The result are: %d", c);
printf("If in words, it is  = ");
switch(c){
case 0:printf("abcdef");break;
case 1:printf("bc");break;
case 2:printf("abged");break;
case 3:printf("abgcd");break;
case 4:printf("fbgc");break;
case 5:printf("afgod");break;
case 6:printf("fgcde");break;
case 7:printf("abc");break;
case 8:printf("abcdefg");break;
case 9:printf("abcdfg");break;
default :printf("error");break;

So the result from this when im running it is :

Input first number : 12

input second number : 12

The result are: 24

If in words, it is = error

so what I'm confused here is how I did print the c result as a word? so what i want from my output is

Input first number : 12

input second number : 12

The result are : 24

If in words, it is = abged fbcg

so far I'm searching for answers but I cannot find it. If anyone here can help me, please do.

Thanks in advance

*edited

Body:
ok, so you mean you want to print a string for each digit of a number, which is the result of whatever math function?

Try [untested]

int d = c;
do {
    switch (d % 10) { /* your replacement-text-switch goes here */ }
    d /= 10;
} while (d != 0)

This will print out the number in reverse.
If you want to print it out the other way, then you have to know about the maximum number you are going to calculate. (Or, being advanced you can use logarithm to determine the length of a number.)


问:
Scraper doesn't stop clicking on the next page button
I've written a script in python in combination with selenium to get some names and corresponding addresses displayed upon a search and the search keyword is "Saskatoon". However, the data, in this case, traverse multiple pages. My script almost does everything except for one thing.

It still runs even though there are no more pages to traverse. The last page also holds ">" sign for next page option and is not grayed out.

Here is the link: Page_link

Search_keyword: Saskatoon (in the city/town field).

Here is what I've written:

```<code>from selenium import webdriver; import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get("above_link")
time.sleep(3)

search_input = driver.find_element_by_id("cityField")
search_input.clear()
search_input.send_keys("Saskatoon")
search_input.send_keys(Keys.ENTER)

while True:
    try:
        wait.until(EC.visibility_of_element_located((By.LINK_TEXT, "›"))).click()
        time.sleep(2)
    except:
        break
driver.quit()
</code>```

BTW, I've just taken out the name and address part form this script which I suppose is not relevant here. Thanks.

答:
You can use class attribute of > button as on last page it is "ng-scope disabled" while on rest pages - "ng-scope":

```<code>wait.until(EC.visibility_of_element_located((By.XPATH, "//li[@class='ng-scope']/a[.='›']"))).click()
</code>```

Body:
I've written a script in python in combination with selenium to get some names and corresponding addresses displayed upon a search and the search keyword is "Saskatoon". However, the data, in this case, traverse multiple pages. My script almost does everything except for one thing.

It still runs even though there are no more pages to traverse. The last page also holds ">" sign for next page option and is not grayed out.

Here is the link: Page_link

Search_keyword: Saskatoon (in the city/town field).

Here is what I've written:

from selenium import webdriver; import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get("above_link")
time.sleep(3)

search_input = driver.find_element_by_id("cityField")
search_input.clear()
search_input.send_keys("Saskatoon")
search_input.send_keys(Keys.ENTER)

while True:
    try:
        wait.until(EC.visibility_of_element_located((By.LINK_TEXT, "›"))).click()
        time.sleep(2)
    except:
        break
driver.quit()

BTW, I've just taken out the name and address part form this script which I suppose is not relevant here. Thanks.

Body:
You can use class attribute of > button as on last page it is "ng-scope disabled" while on rest pages - "ng-scope":

wait.until(EC.visibility_of_element_located((By.XPATH, "//li[@class='ng-scope']/a[.='›']"))).click()


问:
View not showing full results when data has already been loaded
I am currently trying to combine one of my template(test.blade.php) to a new view page which contain a button where it will show a pop up form when clicked. But for some reason when I do that nothing only a few information taken from test.blade.php. Even the button is missing but if I were to place the include('test') at another location, it will show the button but even lesser information being shown.

Here is the code:

evaltest.blade.php (div_show this will display the form)

```<code>  <html>
    <head>
        <title>Popup form </title>
        <meta name="robots" content="noindex, nofollow">
        <link href="{{ asset('css/elements.css') }}" rel="stylesheet">
        <script type="text/javascript">
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-43981329-1']);
        _gaq.push(['_trackPageview']);
        (function () {
        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
        })();
    </script>
    </head>
     <!-- body starts here -->
     <body id ="bdy" style="overflow:hidden;">

     <div id="abc">

         <!-- Popup div starts here -->
     <div id="popupContact">

        <!-- contact us form -->
             <form class="form-horizontal" method="post" action="{{ url('/evaltest/'.$data0->id) }}">
            {{ csrf_field() }}
            <img id ="close" src="{{ URL::to('/image') }}/3.png" onclick ="div_hide()">
             <input type="hidden" name="user_id" value="{{$data0->id}}">

         <div class="form-group">
            <label class="col-md-2"><b>Recommendation:</b></label>
          <div class="col-md-6">
            <input type="radio" id ="recommendation" name="recommendation" value="Yes"> Yes<br>
            <input type="radio" id ="recommendation" name="recommendation" value="No"> No<br>
          </div>
      </div>
            <div class="form-group">
                <div class="col-md-6-offset-2">
                  <input id= "submit" type="submit" href="javascript: check_empty()" class="btn btn-primary" value="Save">
                </div>
              </div>
            </form>
     </div>
    <!-- Popup Div Ends Here -->
    </div>
    <!-- Display Popup Button -->
//this will show a few info but no button
@include('test')
    <h1>Click Button to Evaluate</h1>
    <button id="popup" onclick="div_show()">Popup</button>
        <script src="{{ asset('/js/my_js.js') }}"></script>
//this will show even lesser info but button is shown
//@include('test')
    </body>
    </html>
</code>```

test.blade.php (there are more information inside but I only put some as an example of how I got the information)

```<code>@foreach ($data as $object)
    <b>Name: </b>{{ $object->Name }}<br><br>
    <b>Alias: </b>{{ $object->Alias }}<br><br>
    <b>Email: </b>{{$object->Email}}<br><br>
@endforeach
</code>```

This is the screenshot I am facing right now:

This is the screenshot of test.blade.php which I want it to be together with evaltest.blade.php

As you can see in the test.blade.php, there is a scroll bar which contain other kind of information and it also contain many other information but evaltest.blade.php only show a few but when I view page source for evaltest.blade.php, it shows that all the data have already been loaded

答: The problem must be in your elements.css file. There's a style rule there fixing the height or something similar.

Body:
I am currently trying to combine one of my template(test.blade.php) to a new view page which contain a button where it will show a pop up form when clicked. But for some reason when I do that nothing only a few information taken from test.blade.php. Even the button is missing but if I were to place the include('test') at another location, it will show the button but even lesser information being shown.

Here is the code:

evaltest.blade.php (div_show this will display the form)

        <title>Popup form </title>
        <meta name="robots" content="noindex, nofollow">
        <link href="{{ asset('css/elements.css') }}" rel="stylesheet">

             <form class="form-horizontal" method="post" action="{{ url('/evaltest/'.$data0->id) }}">
            {{ csrf_field() }}

             <input type="hidden" name="user_id" value="{{$data0->id}}">

            Recommendation:

            <input type="radio" id ="recommendation" name="recommendation" value="Yes"> Yes

            <input type="radio" id ="recommendation" name="recommendation" value="No"> No

                  <input id= "submit" type="submit" href="javascript: check_empty()" class="btn btn-primary" value="Save">

            </form>

//this will show a few info but no button
@include('test')

Click Button to Evaluate

    <button id="popup" onclick="div_show()">Popup</button>

//this will show even lesser info but button is shown
//@include('test')

test.blade.php (there are more information inside but I only put some as an example of how I got the information)

@foreach ($data as $object)
    Name: {{ $object->Name }}

    Alias: {{ $object->Alias }}

    Email: {{$object->Email}}

@endforeach

This is the screenshot I am facing right now:

This is the screenshot of test.blade.php which I want it to be together with evaltest.blade.php

As you can see in the test.blade.php, there is a scroll bar which contain other kind of information and it also contain many other information but evaltest.blade.php only show a few but when I view page source for evaltest.blade.php, it shows that all the data have already been loaded


问:
Angular 1.4.8 Route Params htaccess
im having a problem when trying to refresh my page in second level, when has set a parameter by routing angular like this:

localhost/ADMIN/page/1

where

localhost/BASE_FOLDER/ROUTE/ROUT_PARAM

So, i have this defined in my routing app:

```<code>app.config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) {
      $routeProvider.
        when('/home', {
          templateUrl: 'template/home.html',
          controller: 'homeController'
        })
        .when('/page', {
          templateUrl: 'template/page-list.html',
          controller: 'pageListController'
        })
        .when('/page/:id', {
          templateUrl: 'template/page-details.html',
          controller: 'pageDetailsController'
        })
        .when('/', {
          redirectTo: 'home'
        })
        .otherwise({
          redirectTo: '404'
        });
        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('');
    }]);
</code>```

So the problem of refresh only has an error when is in /page/:id for rewrite rules im sure, but i cant find the error, hope you can see it, thank you.

```<code>RewriteEngine on
RewriteBase /ADMIN/

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d

RewriteRule ^ - [L]

# Redirect urls without a trailing slash
RewriteRule ^(.*)/$ $1 [L,R=301]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</code>```

This is the error, but cant see it. The page display all wi

答:
The problema was setting the base tag in the index.html

```<code><html>
  <head>
    ....
    <base href="/ADMIN/" >
  </head>
  <body>
    ...
  </body>
</html>
</code>```

The position of the 'base' tag is so important, because it need be set at the first line of the head tag, like this:

```<code><html>
  <head>
    <base href="/ADMIN/" >
    ....
  </head>
  <body>
    ...
  </body>
</html>
</code>```

And solved! :)

Title: Angular 1.4.8 Route Params htaccess

Body:
im having a problem when trying to refresh my page in second level, when has set a parameter by routing angular like this:

localhost/ADMIN/page/1

where

localhost/BASE_FOLDER/ROUTE/ROUT_PARAM

So, i have this defined in my routing app:

app.config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) {
      $routeProvider.
        when('/home', {
          templateUrl: 'template/home.html',
          controller: 'homeController'
        })
        .when('/page', {
          templateUrl: 'template/page-list.html',
          controller: 'pageListController'
        })
        .when('/page/:id', {
          templateUrl: 'template/page-details.html',
          controller: 'pageDetailsController'
        })
        .when('/', {
          redirectTo: 'home'
        })
        .otherwise({
          redirectTo: '404'
        });
        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('');
    }]);

So the problem of refresh only has an error when is in /page/:id for rewrite rules im sure, but i cant find the error, hope you can see it, thank you.

RewriteEngine on
RewriteBase /ADMIN/

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d

RewriteRule ^ - [L]

# Redirect urls without a trailing slash
RewriteRule ^(.*)/$ $1 [L,R=301]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

This is the error, but cant see it. The page display all wi

Body:
The problema was setting the base tag in the index.html

<html>
  <head>
    ....
    <base href="/ADMIN/" >
  </head>
  <body>
    ...
  </body>
</html>

The position of the 'base' tag is so important, because it need be set at the first line of the head tag, like this:

<html>
  <head>
    <base href="/ADMIN/" >
    ....
  </head>
  <body>
    ...
  </body>
</html>

And solved! :)


问:
How to Transform using Saxon-api
I am using saxon 9.8. I want to write a transform function in C# as below.So I have

```<code> `using Saxon.Api;
  private string Transform(Stream xmlStream, string transform)
    {

    }`
</code>```

Please help me fill this function

答:
I think you should at least try to write your code on your own and when you are stuck then look for possible answers on the internet. And only when you couldn't solve our problem on this way than asked a specific question. I am not going to write your whole code for you. But i can share here how i am using the Saxon API for XSLT transformation:

```<code>    public static String TransfromXMLWithXSLT2(String i_xmlData, String i_xsltCode)
    {
        Processor xsltProcessor = new Processor();
        DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder();
        documentBuilder.BaseUri = new Uri("file://");
        XdmNode xdmNode = documentBuilder.Build(new StringReader(i_xmlData));

        XsltCompiler xsltCompiler = xsltProcessor.NewXsltCompiler();
        XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(i_xsltCode));
        XsltTransformer xsltTransformer = xsltExecutable.Load();
        xsltTransformer.InitialContextNode = xdmNode;

        using (StringWriter stringWriter = new StringWriter()) {
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(stringWriter);
            xsltTransformer.Run(serializer);
            return stringWriter.ToString();
        }
    }
</code>```

I am using a switch in my transformation class to support XSLT1.0 too. For XSLT1.0 I prefer the .Net functionality, just for your info it looks like this in my code:

```<code>    public static String TransfromXMLWithXSLT1(String i_xmlData, String i_xsltCode)
    {
        XslCompiledTransform xslt = new XslCompiledTransform();

        using (StringReader xsltStringReader = new StringReader(i_xsltCode)) {
            using (XmlReader xsltXmlReader = XmlReader.Create(xsltStringReader)) {
                xslt.Load(xsltXmlReader);
                using (StringReader tableStringReader = new StringReader(i_xmlData)) {
                    using (XmlReader tableXmlReader = XmlReader.Create(tableStringReader)) {
                        using (StringWriter stringWriter = new StringWriter()) {
                            xslt.Transform(tableXmlReader, new XsltArgumentList(), stringWriter);
                            return stringWriter.ToString();
                        }
                    }
                }
            }
        }
    }
</code>```

So if you need Streams/Readers and not Strings simply change the code in the way it is needed!

Title: How to Transform using Saxon-api

Body:
I am using saxon 9.8. I want to write a transform function in C# as below.So I have

 `using Saxon.Api;
  private string Transform(Stream xmlStream, string transform)
    {

    }`

Please help me fill this function

Body:
I think you should at least try to write your code on your own and when you are stuck then look for possible answers on the internet. And only when you couldn't solve our problem on this way than asked a specific question. I am not going to write your whole code for you. But i can share here how i am using the Saxon API for XSLT transformation:

    public static String TransfromXMLWithXSLT2(String i_xmlData, String i_xsltCode)
    {
        Processor xsltProcessor = new Processor();
        DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder();
        documentBuilder.BaseUri = new Uri("file://");
        XdmNode xdmNode = documentBuilder.Build(new StringReader(i_xmlData));

        XsltCompiler xsltCompiler = xsltProcessor.NewXsltCompiler();
        XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(i_xsltCode));
        XsltTransformer xsltTransformer = xsltExecutable.Load();
        xsltTransformer.InitialContextNode = xdmNode;

        using (StringWriter stringWriter = new StringWriter()) {
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(stringWriter);
            xsltTransformer.Run(serializer);
            return stringWriter.ToString();
        }
    }

I am using a switch in my transformation class to support XSLT1.0 too. For XSLT1.0 I prefer the .Net functionality, just for your info it looks like this in my code:

    public static String TransfromXMLWithXSLT1(String i_xmlData, String i_xsltCode)
    {
        XslCompiledTransform xslt = new XslCompiledTransform();

        using (StringReader xsltStringReader = new StringReader(i_xsltCode)) {
            using (XmlReader xsltXmlReader = XmlReader.Create(xsltStringReader)) {
                xslt.Load(xsltXmlReader);
                using (StringReader tableStringReader = new StringReader(i_xmlData)) {
                    using (XmlReader tableXmlReader = XmlReader.Create(tableStringReader)) {
                        using (StringWriter stringWriter = new StringWriter()) {
                            xslt.Transform(tableXmlReader, new XsltArgumentList(), stringWriter);
                            return stringWriter.ToString();
                        }
                    }
                }
            }
        }
    }

So if you need Streams/Readers and not Strings simply change the code in the way it is needed!


问:
PHP get array from string
I have an array in string given below.

```<code>$string="
"Status":true,
"ReVerifiedCount":1,
"ProfilePrefix":"INVTRK"
";
</code>```

How I can get array from this string same as it exists in string.

答:
First your String looks like a json string.

```<code>$string='{
"Status":true,
"ReVerifiedCount":1,
"ProfilePrefix":"INVTRK"
}';
</code>```

This is the correct form.

To parse it use json_decode from PHP

```<code>$parsedArray = json_decode($string, true);
</code>```

Here is a link to the doc : http://php.net/manual/en/function.json-decode.php

Title: PHP get array from string

Body:
I have an array in string given below.

$string="
"Status":true,
"ReVerifiedCount":1,
"ProfilePrefix":"INVTRK"
";

How I can get array from this string same as it exists in string.

Body:
First your String looks like a json string.

$string='{
"Status":true,
"ReVerifiedCount":1,
"ProfilePrefix":"INVTRK"
}';

This is the correct form.

To parse it use json_decode from PHP

$parsedArray = json_decode($string, true);

Here is a link to the doc : http://php.net/manual/en/function.json-decode.php


问:
Enable global warnings
I have to optimize an intranet written in Perl (about 3000 files). The first thing I want to do is enable warnings "-w" or "use warnings;" so I can get rid of all those errors, then try to implement "use strict;".

Is there a way of telling Perl to use warnings all the time (like the settings in php.ini for PHP), without the need to modify each script to add "-w" to it's first line?

I even thought to make an alias for /usr/bin/perl, or move it to another name and make a simple script instead of it just to add the -w flag (like a proxy).

How would you debug it?

答:
Retrofitting warnings and strict is hard.  I don't recommend a Big Bang approach, setting warnings (let alone strictures) on everything.  You will be inundated with warnings to the point of uselessness.

You start by enabling warnings on the modules used by the scripts (there are some, aren't there?), rather than applying warnings to everything.  Get the core clean, then get to work on the periphery, one unit at a time.  So, in fact, I'd recommend having a simple (Perl) script that simply finds a line that does not start with a hash and adds use warnings; (and maybe use strict; too, since you're going to be dealing with one script at a time), so you can do the renovations one script at a time.

In other words, you will probably be best off actually editing each file as you're about to renovate it.

I'd only use the blanket option to make a simple assessment of the scope of the problem: is it a complete and utter disaster, or merely a few peccadilloes in a few files.  Sadly, if the code was developed without warnings and strict, it is more likely to be 'disaster' than 'minimal'.

You may find that your predecessors were prone to copy and paste and some erroneous idioms crop up repeatedly in copied code.  Write a Perl script that fixes each one.  I have a bunch of fix* scripts in my personal bin directory that deal with various changes - either fixing issues created by recalcitrant (or, more usually, simply long departed) colleagues or to accommodate my own changing standards.

Title: Enable global warnings

ContentLicense: CC BY-SA 2.5


问:
PropertyChanged isn't working as expected
I'm currently trying myself on creating a WPF project with MVVM using Fody Property changed.

```<code><Window x:Class="TestMVVM.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestMVVM"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525"
    DataContext="{x:Static local:MainWindowViewModel.Instance}"
    x:Name="WindowElement">

<StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Text, Mode=TwoWay}" />
    <Button Content="Browse" Command="{Binding WSDLBrowseClick}"/>
</StackPanel>
</code>```

```<code>public static class Model
{
    public static string text { get; set; }
}

public class MainWindowViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };

    public static MainWindowViewModel Instance => new MainWindowViewModel();

    public string Text { get; set; }
    /*
    {
        get { return Model.text; }
        set
        {
            if (value == Text)
                return;

            Model.text = value;

            PropertyChanged(this, new PropertyChangedEventArgs("Text"));
        }
    }*/

    public ICommand WSDLBrowseClick { get; set; }

    public MainWindowViewModel()
    {
        WSDLBrowseClick = new RelayCommand(BrowseWSDL);
    }

    private void BrowseWSDL()
    {
        Text = "Test";
    }
}
</code>```

Basically I want the TextBlock to show the "Test"-Text when I click the button. The Click-Command gets executed but the TextBlock's text doesn't change. I want to use the property Text as a local memory that keeps the textblock up to date so I can later send the value to model.text and use it there. But it only works if I use the code that I have currently commented out. Isn't fody weaver supposed to do the same thing for me (just that he creates another private variable instead of using model.text)?

答: I managed to make it work by adding <PropertyChanged/> to my FodyWeavers.xml

Body:
I'm currently trying myself on creating a WPF project with MVVM using Fody Property changed.

<Window x:Class="TestMVVM.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestMVVM"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525"
    DataContext="{x:Static local:MainWindowViewModel.Instance}"
    x:Name="WindowElement">

<StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Text, Mode=TwoWay}" />
    <Button Content="Browse" Command="{Binding WSDLBrowseClick}"/>
</StackPanel>

public static class Model
{
    public static string text { get; set; }
}

public class MainWindowViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };

    public static MainWindowViewModel Instance => new MainWindowViewModel();

    public string Text { get; set; }
    /*
    {
        get { return Model.text; }
        set
        {
            if (value == Text)
                return;

            Model.text = value;

            PropertyChanged(this, new PropertyChangedEventArgs("Text"));
        }
    }*/

    public ICommand WSDLBrowseClick { get; set; }

    public MainWindowViewModel()
    {
        WSDLBrowseClick = new RelayCommand(BrowseWSDL);
    }

    private void BrowseWSDL()
    {
        Text = "Test";
    }
}

Basically I want the TextBlock to show the "Test"-Text when I click the button. The Click-Command gets executed but the TextBlock's text doesn't change. I want to use the property Text as a local memory that keeps the textblock up to date so I can later send the value to model.text and use it there. But it only works if I use the code that I have currently commented out. Isn't fody weaver supposed to do the same thing for me (just that he creates another private variable instead of using model.text)?


问:
Confused on creating C# discord bot
About a week ago I was planning on making a discord bot with C#. I do know the language decently enough to program simple things in windows forms or console apps. However, when I tried to create a discord bot using the NuGet packet manager I stumbled upon a problem: The compiler did not seem to recognize the

```<code>using Discord;
</code>```

This seemed weird to me because I looked at approximately 6 different tutorials on how to make the bot. At this point I gave up because I can not debug code or whatever: I can't even start to code.

答:
The solution to this has been found by the OP while writing the question. Turning this into a Community wiki answer per this meta post.

All tutorials create another class. Simply don't add your Discord.NET to that, first click on your actual main class.

Title: Confused on creating C# discord bot

Body:
About a week ago I was planning on making a discord bot with C#. I do know the language decently enough to program simple things in windows forms or console apps. However, when I tried to create a discord bot using the NuGet packet manager I stumbled upon a problem: The compiler did not seem to recognize the

using Discord;

This seemed weird to me because I looked at approximately 6 different tutorials on how to make the bot. At this point I gave up because I can not debug code or whatever: I can't even start to code.


问:
Promise fulfilled inspite of rejection
I am using bluebird settle method to check results for promises regardless of any rejections. In the secondMethod  I have rejected the promise still I get    isFulfilled() true.

```<code>var Promise = require('bluebird');

Promise.settle([firstMethod, secondMethod]).then(function(results){
    console.log(results[0].isFulfilled());
    console.log(results[1].isFulfilled());
   // console.log(results[1].reason());
}).catch(function(error){
    console.log(error);
});

    var firstMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         resolve({data: '123'});
      }, 2000);
   });
   return promise;
};

var secondMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         reject((new Error('fail')));
      }, 2000);
   });
   return promise;
};
</code>```

答:
I debugged your code and the code within your functions isn't being called. You need to actually call the functions :)</p>

```<code>Promise.settle([firstMethod(), secondMethod()]).then(function (results) {
    console.log(results[0].isFulfilled()); // prints "true"
    console.log(results[1].isFulfilled()); // prints "false"
    console.log(results[1].reason()); // prints "fail"
}).catch(function (error) {
    console.log(error);
});
</code>```

Title: Promise fulfilled inspite of rejection

Body:
I am using bluebird settle method to check results for promises regardless of any rejections. In the secondMethod  I have rejected the promise still I get    isFulfilled() true.

var Promise = require('bluebird');

Promise.settle([firstMethod, secondMethod]).then(function(results){
    console.log(results[0].isFulfilled());
    console.log(results[1].isFulfilled());
   // console.log(results[1].reason());
}).catch(function(error){
    console.log(error);
});

    var firstMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         resolve({data: '123'});
      }, 2000);
   });
   return promise;
};

var secondMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         reject((new Error('fail')));
      }, 2000);
   });
   return promise;
};

Body:
I debugged your code and the code within your functions isn't being called. You need to actually call the functions :)

Promise.settle([firstMethod(), secondMethod()]).then(function (results) {
    console.log(results[0].isFulfilled()); // prints "true"
    console.log(results[1].isFulfilled()); // prints "false"
    console.log(results[1].reason()); // prints "fail"
}).catch(function (error) {
    console.log(error);
});


问:
Taking sum From a table and trying to update that rows in another
here is everything i tried yet !

```<code>UPDATE DailyBooking
SET RecievedAmount =
(
    SELECT DailyBooking.ID,
        (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
         WHERE RecipientDetails.DBID = DailyBooking.ID)
    FROM DailyBooking
    INNER JOIN RecipientDetails
        ON RecipientDetails.DBID = DailyBooking.ID
 )
</code>```

this query is throwing error

Only one expression can be specified in the select list when the
  subquery is not introduced with EXISTS.

and when i try that with where clause like :

```<code> UPDATE DailyBooking SET RecievedAmount=(
    SELECT DailyBooking.ID,
    (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
    WHERE RecipientDetails.DBID = DailyBooking.ID) FROM DailyBooking INNER JOIN RecipientDetails ON
    RecipientDetails.DBID =DailyBooking.ID
     ) where DailyBooking.ID = RecipientDetails.DBID
</code>```

it is throwing error like :

Msg 4104, Level 16, State 1, Line 6 The multi-part identifier
  "RecipientDetails.DBID" could not be bound.

Tables !
1 Table Providing Sum :
RecipientDetails

Table having RecievedAmount Column:

DailyBooking

Thanks in Advance..

答:
You can't have the inner SQL return more than 1 value, since it's result is what the SET recieves.

Try this (will not work in all DBs, but you didn't specify which one you use):

```<code>UPDATE DailyBooking d
SET d.RecievedAmount =
(
   SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
   WHERE RecipientDetails.DBID = d.ID
)
</code>```

Body:
here is everything i tried yet !

UPDATE DailyBooking
SET RecievedAmount =
(
    SELECT DailyBooking.ID,
        (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
         WHERE RecipientDetails.DBID = DailyBooking.ID)
    FROM DailyBooking
    INNER JOIN RecipientDetails
        ON RecipientDetails.DBID = DailyBooking.ID
 )

this query is throwing error

Only one expression can be specified in the select list when the
  subquery is not introduced with EXISTS.

and when i try that with where clause like :

 UPDATE DailyBooking SET RecievedAmount=(
    SELECT DailyBooking.ID,
    (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
    WHERE RecipientDetails.DBID = DailyBooking.ID) FROM DailyBooking INNER JOIN RecipientDetails ON
    RecipientDetails.DBID =DailyBooking.ID
     ) where DailyBooking.ID = RecipientDetails.DBID

it is throwing error like :

Msg 4104, Level 16, State 1, Line 6 The multi-part identifier
  "RecipientDetails.DBID" could not be bound.

Tables !
1 Table Providing Sum :
RecipientDetails

Table having RecievedAmount Column:

DailyBooking

Thanks in Advance..

Body:
You can't have the inner SQL return more than 1 value, since it's result is what the SET recieves.

Try this (will not work in all DBs, but you didn't specify which one you use):

UPDATE DailyBooking d
SET d.RecievedAmount =
(
   SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
   WHERE RecipientDetails.DBID = d.ID
)


答:
One option would be to move your aggregation query into a CTE and then join update with it:

```<code>WITH cte AS (
    SELECT DBID, SUM(Amount) AS RecievedAmount
    FROM RecipientDetails
    GROUP BY DBID
)
UPDATE db
SET RecievedAmount = t.RecievedAmount
FROM DailyBooking db
INNER JOIN cte t
    ON db.ID = t.DBID;
</code>```

This should perform better than updating via a correlated subquery to compute the sum.

Title: Taking sum From a table and trying to update that rows in another

Body:
One option would be to move your aggregation query into a CTE and then join update with it:

WITH cte AS (
    SELECT DBID, SUM(Amount) AS RecievedAmount
    FROM RecipientDetails
    GROUP BY DBID
)
UPDATE db
SET RecievedAmount = t.RecievedAmount
FROM DailyBooking db
INNER JOIN cte t
    ON db.ID = t.DBID;

This should perform better than updating via a correlated subquery to compute the sum.


问:
Define Date format, regex match, and check validity - Peer Review
I'm writing a input validation method for codeigniter to check date format.  I'm actually just doing it in a test script to get the functionality nailed down.  I've got something that works but I'd just like see if I'm approaching this the best (or worst) way.

Really specifically I'm looking at the second half, I've commented to point out what I mean.

```<code><?

$input = $_POST['input'];   //text input of intended format
$date  = $_POST['date'];    //text input of date in matching format
                            //examples: y-m-d, Y.M.D, m/D/Y  (Case has no affect)

//I'm setting up a regex string based on given format
$pattern = preg_replace('/[yY]/','([0-9]{4})',$input);
$pattern = preg_replace('/[mM]/','([0-9]{1,2})',$pattern);
$pattern = preg_replace('/[dD]/','([0-9]{1,2})',$pattern);

//escaping slashes (if used as date delimiter)
$pattern = str_replace('/','\/',$pattern);

echo "Format  : " . $input . "<br />";
echo "Date    : " . $date . "<br/>";
echo "============" . "<br />";
echo "<br/>";

//if given date matches given format
if(preg_match('/^'.$pattern.'$/',$date,$matches)) {
    echo 'YAY A MATCH! <br/>';

    //From here down seems like it could be improved, seems a bit brute force
    //All of this below, is trying to get the order of the format so I can feed the proper values
    //to the checkdate() function to check date validity.

    preg_match('/[yY]/', $input, $match_year,PREG_OFFSET_CAPTURE);
    preg_match('/[mM]/', $input, $match_month,PREG_OFFSET_CAPTURE);
    preg_match('/[dD]/', $input, $match_day,PREG_OFFSET_CAPTURE);

    if ($match_year[0][1] < $match_month[0][1] && $match_year[0][1] < $match_day[0][1]) {
        $year = $matches[1];
        array_splice($matches,1,1);
    }
    else if ($match_year[0][1] > $match_month[0][1] && $match_year[0][1] > $match_day[0][1]) {
        $year = $matches[3];
        array_splice($matches,3,1);
    }
    else {
        $year = $matches[2];
        array_splice($matches,2,1);
    }

    if ($match_month[0][1] < $match_day[0][1]) {
        $month = $matches[1];
        $day   = $matches[2];
    }
    else {
        $month = $matches[2];
        $day   = $matches[1];
    }

    echo "<br/>";
    echo "<br/>";
    echo $month . ' / ' . $day . ' / ' . $year . "<br/>";

    if (checkdate($month,$day,$year)) {
        echo "This is a valid date.";
    }
    else {
        echo "This is not a valid date";
    }
}
else {
    echo "Given date does not match given format";
}
</code>```

答:
Why not just do it all in one regex using named subpatterns?

```<code>$search = array(
    '/[yY]/',
    '/[mM]/',
    '/[dD]/',
);
$replace = array(
    '(?P<year>[0-9]{4})',
    '(?P<month>[0-9]{1,2})',
    '(?P<day>[0-9]{1,2})',
);
$pattern = preg_replace($search, $replace, $input);
</code>```

Then, just run it against the input:

```<code>if (preg_match('/' . $pattern . '/', $date, $match)) {
    $year = $match['year'];
    $month = $match['month'];
    $day = $match['day'];
} else {
    echo "Date not in proper format";
}
</code>```

But in general depending on your needs I'd just use strtotime or date_parse_from_format...

Body:
I'm writing a input validation method for codeigniter to check date format.  I'm actually just doing it in a test script to get the functionality nailed down.  I've got something that works but I'd just like see if I'm approaching this the best (or worst) way.

Really specifically I'm looking at the second half, I've commented to point out what I mean.

<?

$input = $_POST['input'];   //text input of intended format
$date  = $_POST['date'];    //text input of date in matching format
                            //examples: y-m-d, Y.M.D, m/D/Y  (Case has no affect)

//I'm setting up a regex string based on given format
$pattern = preg_replace('/[yY]/','([0-9]{4})',$input);
$pattern = preg_replace('/[mM]/','([0-9]{1,2})',$pattern);
$pattern = preg_replace('/[dD]/','([0-9]{1,2})',$pattern);

//escaping slashes (if used as date delimiter)
$pattern = str_replace('/','\/',$pattern);

echo "Format  : " . $input . "
";
echo "Date    : " . $date . "
";
echo "============" . "
";
echo "
";

//if given date matches given format
if(preg_match('/^'.$pattern.'$/',$date,$matches)) {
    echo 'YAY A MATCH!
';

    //From here down seems like it could be improved, seems a bit brute force
    //All of this below, is trying to get the order of the format so I can feed the proper values
    //to the checkdate() function to check date validity.

    preg_match('/[yY]/', $input, $match_year,PREG_OFFSET_CAPTURE);
    preg_match('/[mM]/', $input, $match_month,PREG_OFFSET_CAPTURE);
    preg_match('/[dD]/', $input, $match_day,PREG_OFFSET_CAPTURE);

    if ($match_year[0][1] < $match_month[0][1] && $match_year[0][1] < $match_day[0][1]) {
        $year = $matches[1];
        array_splice($matches,1,1);
    }
    else if ($match_year[0][1] > $match_month[0][1] && $match_year[0][1] > $match_day[0][1]) {
        $year = $matches[3];
        array_splice($matches,3,1);
    }
    else {
        $year = $matches[2];
        array_splice($matches,2,1);
    }

    if ($match_month[0][1] < $match_day[0][1]) {
        $month = $matches[1];
        $day   = $matches[2];
    }
    else {
        $month = $matches[2];
        $day   = $matches[1];
    }

    echo "
";
    echo "
";
    echo $month . ' / ' . $day . ' / ' . $year . "
";

    if (checkdate($month,$day,$year)) {
        echo "This is a valid date.";
    }
    else {
        echo "This is not a valid date";
    }
}
else {
    echo "Given date does not match given format";
}

Body:
Why not just do it all in one regex using named subpatterns?

$search = array(
    '/[yY]/',
    '/[mM]/',
    '/[dD]/',
);
$replace = array(
    '(?P<year>[0-9]{4})',
    '(?P<month>[0-9]{1,2})',
    '(?P<day>[0-9]{1,2})',
);
$pattern = preg_replace($search, $replace, $input);

Then, just run it against the input:

if (preg_match('/' . $pattern . '/', $date, $match)) {
    $year = $match['year'];
    $month = $match['month'];
    $day = $match['day'];
} else {
    echo "Date not in proper format";
}

But in general depending on your needs I'd just use strtotime or date_parse_from_format...


问:
Using both AND, OR in If condition Javascript
Similar questions haven't justified my actual question.
I have a If condition where if it satisfies 2 conditions it should set value as A else B. Below is the code block describing my question

```<code>if(($form[0].lang.value==SPN||PTB||GRM) && ("1" == "<awi:script script='IsTranslationON'/>"))
    {
    $form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT_Translation";
     }
    else
      {$form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT";}
 //Submit form
      submit=false;
      if(submit){$form[0].submit()}else{alert($form[0].$rtag.value)}
</code>```

Issue is - evrytime it gets deiplayed only statement from If condition. It is not checking value with $lang.value
Does any of the mates help me checking my if condition please.
EDIT- The value I am getting in alert box is "Test_IND_GENERAL_SUPPORT_Translation".

答:
This $form[0].lang.value==SPN||PTB||GRM is incorrect. You need to write a new condition check for each of these expected values. EG

```<code>if($form[0].lang.value==SPN || $form[0].lang.value== PTB ... etc )
</code>```

Body:
Similar questions haven't justified my actual question.
I have a If condition where if it satisfies 2 conditions it should set value as A else B. Below is the code block describing my question

if(($form[0].lang.value==SPN||PTB||GRM) && ("1" == "<awi:script script='IsTranslationON'/>"))
    {
    $form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT_Translation";
     }
    else
      {$form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT";}
 //Submit form
      submit=false;
      if(submit){$form[0].submit()}else{alert($form[0].$rtag.value)}

Issue is - evrytime it gets deiplayed only statement from If condition. It is not checking value with $lang.value
Does any of the mates help me checking my if condition please.
EDIT- The value I am getting in alert box is "Test_IND_GENERAL_SUPPORT_Translation".

Body:
This $form[0].lang.value==SPN||PTB||GRM is incorrect. You need to write a new condition check for each of these expected values. EG

if($form[0].lang.value==SPN || $form[0].lang.value== PTB ... etc )


问:
Returning value after several Runnable finish
Currently I have a code as follow :

```<code>public String getValue()
{
   StringBuilder builder = new StringBuilder();
   // 1st step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString1);
   // 2nd step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString2);
   // 3rd step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString3);

   return builder.toString();
}
</code>```

I've read about Runnable object that can be used to split process into several thread, which going change my code into something like this :

```<code>public String getValue()
{
     Thread firstTread = new Thread(new Process1());
     firstTread.start();
     Thread secondTread = new Thread(new Process1());
     secondTread.start();
     Thread thirdTread = new Thread(new Process1());
     thirdTread.start();

     // here i got confuse how to determine whether all thread allready finished
     // before returning builder.toString();
}
//this is internal class
class Process1 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

class Process2 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

class Process3 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}
</code>```

How can I achieve that my goal to split the process into several thread?

答:
You use Callable which pretty much is a Runnable returning a value. And you use an ExecutorService instead of creating Thread objects yourself.

```<code>public String getValue()
{
    ExecutorService threaded = Executors.newFixedThreadPool(NUM_THREADS);
    List<CompletableFuture> results = threaded.invokeAll(
        Arrays.asList(this::process1, this::process2, this::process3);
    results.stream()
        .map(Future::get)  // collects the result from each thread
        .collect(Collectors.joining());
}
private String process1() { return "1"; }
private String process2() { return "2"; }
private String process3() { return "3"; }
</code>```

EDIT:
Note that the output will not be "in different order" because invokeAll returns "A list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list".

Body:
Currently I have a code as follow :

public String getValue()
{
   StringBuilder builder = new StringBuilder();
   // 1st step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString1);
   // 2nd step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString2);
   // 3rd step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString3);

   return builder.toString();
}

I've read about Runnable object that can be used to split process into several thread, which going change my code into something like this :

public String getValue()
{
     Thread firstTread = new Thread(new Process1());
     firstTread.start();
     Thread secondTread = new Thread(new Process1());
     secondTread.start();
     Thread thirdTread = new Thread(new Process1());
     thirdTread.start();

     // here i got confuse how to determine whether all thread allready finished
     // before returning builder.toString();
}
//this is internal class
class Process1 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

class Process2 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

class Process3 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

How can I achieve that my goal to split the process into several thread?

Body:
You use Callable which pretty much is a Runnable returning a value. And you use an ExecutorService instead of creating Thread objects yourself.

public String getValue()
{
    ExecutorService threaded = Executors.newFixedThreadPool(NUM_THREADS);
    List<CompletableFuture> results = threaded.invokeAll(
        Arrays.asList(this::process1, this::process2, this::process3);
    results.stream()
        .map(Future::get)  // collects the result from each thread
        .collect(Collectors.joining());
}
private String process1() { return "1"; }
private String process2() { return "2"; }
private String process3() { return "3"; }

EDIT:
Note that the output will not be "in different order" because invokeAll returns "A list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list".


问:
What is $ dollar sign in hyperledger composer?
In query language _$ sign is used frequently, what does this mean and also every class keyword has a dollar prefix. What is the significance/meaning of $ and _$ sign.  </p>

答: The $ prefix is used by Composer to identify the type of an entity serialized to JSON. The _$ prefix is used in the query language to create parameterized queries.


问:
Java Streams - forEach with pre-Action and post-Action
When using Stream.forEach(), I was thinking if it is not possible to add a pre-action and post-action to be executed when the stream is not empty. For example, when printing a List, one could prepend something or write something else when the stream is empty.

Now I came up with something like

```<code>private static <T> void forEach(Stream<T> stream, Consumer<? super T> action,
    Runnable preAction, Runnable postAction, Runnable ifEmpty) {
    AtomicBoolean hasElements = new AtomicBoolean(false);
    Consumer<T> preActionConsumer = x -> {
        if (hasElements.compareAndSet(false, true)) {
            preAction.run();
        }
    };
    stream.forEach(preActionConsumer.andThen(action));
    if (hasElements.get()) {
        postAction.run();
    } else {
        ifEmpty.run();
    }
}
</code>```

For sequential streams, this should work, should it not?
Is this method correct, is it as "good idea" have such a method or are there any caveats?

This does not work for parallel streams, since the preAction might be slower than another thread executing the action, but implementing it correctly without resorting to synchronized or other concurrency utils which defeat the purpose of parallel streams will probably be not easy...

edit: adding use-case. Reading searching integers from a file using a regex and writing them to another file. Using this approach, I don't have to create a String in memory and after that write it to some file. (Obviously, for my real task, I am using more complicated regexes.)

```<code>public static void main(String[] args) throws IOException {
    Stream<String> lines = Files.lines(Paths.get("foo.txt"));

    Pattern findInts = Pattern.compile("(\\d+)");
    Path barFile = Paths.get("bar.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(barFile , StandardOpenOption.CREATE_NEW)) {
        lines.flatMap(x -> findInts.matcher(x).results())
                .forEach(x-> convertCheckedIOException(() ->  {
                            writer.write(x.group(1));
                            writer.newLine();
                        })
                );
    }
}

public static void convertCheckedIOException(Run r) {
    try {
        r.run();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

interface Run {
    void run() throws IOException;
}
</code>```

答:
I like the idea of having a util like this. At first I thought using a second flag that is set/unset by the preaction and halts the action might be enough. But what makes it more complicated is the fact that preAction is put in front of every action call, not just the first one.

I came up with a synchronized solution that enforces the order pre, actions, post/empty. One caveat is that the first batch of parallel threads will have to wait for the first of them to finish as they will run into synchronized:

```<code>private static <T> void forEach(Stream<T> stream, Consumer<? super T> action, Runnable preAction, Runnable postAction, Runnable ifEmpty)
{
    AtomicBoolean hasElements = new AtomicBoolean(false);

    stream.forEach(new Consumer<T>()
    {
        private Consumer<? super T> delegate = new Consumer<T>()
        {
            private Consumer<? super T> delegate2 = new Consumer<T>()
            {
                @Override
                public void accept(T x)
                {
                    System.out.println("check");
                    hasElements.set(true);
                    preAction.run();
                    action.accept(x);
                    delegate2 = action; // rest of first batch won't run preAction anymore
                    delegate = action; // next batches won't even synchronize anymore
                }
            };

            @Override
            public void accept(T x)
            {
                synchronized (this)
                {
                    delegate2.accept(x);
                }
            }
        };

        @Override
        public void accept(T x)
        {
            delegate.accept(x);
        }
    });

    if (hasElements.get()) { postAction.run(); } else { ifEmpty.run(); }
}

public static void main(String[] args)
{
    Stream<Integer> s = Stream.generate(() -> 1).limit(1000).parallel();
    forEach(s, i -> System.out.println(Thread.currentThread().getId()), () -> System.out.println("pre"),
            () -> System.out.println("post"), () -> System.out.println("empty"));
}

Output:
check
pre
...
many thread IDs
...
post
</code>```

Body:
When using Stream.forEach(), I was thinking if it is not possible to add a pre-action and post-action to be executed when the stream is not empty. For example, when printing a List, one could prepend something or write something else when the stream is empty.

Now I came up with something like

private static <T> void forEach(Stream<T> stream, Consumer<? super T> action,
    Runnable preAction, Runnable postAction, Runnable ifEmpty) {
    AtomicBoolean hasElements = new AtomicBoolean(false);
    Consumer<T> preActionConsumer = x -> {
        if (hasElements.compareAndSet(false, true)) {
            preAction.run();
        }
    };
    stream.forEach(preActionConsumer.andThen(action));
    if (hasElements.get()) {
        postAction.run();
    } else {
        ifEmpty.run();
    }
}

For sequential streams, this should work, should it not?
Is this method correct, is it as "good idea" have such a method or are there any caveats?

This does not work for parallel streams, since the preAction might be slower than another thread executing the action, but implementing it correctly without resorting to synchronized or other concurrency utils which defeat the purpose of parallel streams will probably be not easy...

edit: adding use-case. Reading searching integers from a file using a regex and writing them to another file. Using this approach, I don't have to create a String in memory and after that write it to some file. (Obviously, for my real task, I am using more complicated regexes.)

public static void main(String[] args) throws IOException {
    Stream<String> lines = Files.lines(Paths.get("foo.txt"));

    Pattern findInts = Pattern.compile("(\\d+)");
    Path barFile = Paths.get("bar.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(barFile , StandardOpenOption.CREATE_NEW)) {
        lines.flatMap(x -> findInts.matcher(x).results())
                .forEach(x-> convertCheckedIOException(() ->  {
                            writer.write(x.group(1));
                            writer.newLine();
                        })
                );
    }
}

public static void convertCheckedIOException(Run r) {
    try {
        r.run();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

interface Run {
    void run() throws IOException;
}

Body:
I like the idea of having a util like this. At first I thought using a second flag that is set/unset by the preaction and halts the action might be enough. But what makes it more complicated is the fact that preAction is put in front of every action call, not just the first one.

I came up with a synchronized solution that enforces the order pre, actions, post/empty. One caveat is that the first batch of parallel threads will have to wait for the first of them to finish as they will run into synchronized:

private static <T> void forEach(Stream<T> stream, Consumer<? super T> action, Runnable preAction, Runnable postAction, Runnable ifEmpty)
{
    AtomicBoolean hasElements = new AtomicBoolean(false);

    stream.forEach(new Consumer<T>()
    {
        private Consumer<? super T> delegate = new Consumer<T>()
        {
            private Consumer<? super T> delegate2 = new Consumer<T>()
            {
                @Override
                public void accept(T x)
                {
                    System.out.println("check");
                    hasElements.set(true);
                    preAction.run();
                    action.accept(x);
                    delegate2 = action; // rest of first batch won't run preAction anymore
                    delegate = action; // next batches won't even synchronize anymore
                }
            };

            @Override
            public void accept(T x)
            {
                synchronized (this)
                {
                    delegate2.accept(x);
                }
            }
        };

        @Override
        public void accept(T x)
        {
            delegate.accept(x);
        }
    });

    if (hasElements.get()) { postAction.run(); } else { ifEmpty.run(); }
}

public static void main(String[] args)
{
    Stream<Integer> s = Stream.generate(() -> 1).limit(1000).parallel();
    forEach(s, i -> System.out.println(Thread.currentThread().getId()), () -> System.out.println("pre"),
            () -> System.out.println("post"), () -> System.out.println("empty"));
}

Output:
check
pre
...
many thread IDs
...
post