问:
Pandas convert dataframe to array of tuples
I have manipulated some data using pandas and now I want to carry out a batch save back to the database. This requires me to convert the dataframe into an array of tuples, with each tuple corresponding to a "row" of the dataframe.

My DataFrame looks something like:

```<code>In [182]: data_set
Out[182]:
  index data_date   data_1  data_2
0  14303 2012-02-17  24.75   25.03
1  12009 2012-02-16  25.00   25.07
2  11830 2012-02-15  24.99   25.15
3  6274  2012-02-14  24.68   25.05
4  2302  2012-02-13  24.62   24.77
5  14085 2012-02-10  24.38   24.61
</code>```

I want to convert it to an array of tuples like:

```<code>[(datetime.date(2012,2,17),24.75,25.03),
(datetime.date(2012,2,16),25.00,25.07),
...etc. ]
</code>```

Any suggestion on how I can efficiently do this?

答:
Motivation

Many data sets are large enough that we need to concern ourselves with speed/efficiency.  So I offer this solution in that spirit.  It happens to also be succinct.

For the sake of comparison, let's drop the index column

```<code>df = data_set.drop('index', 1)
</code>```

Solution

I'll propose the use of zip and map

```<code>list(zip(*map(df.get, df)))

[('2012-02-17', 24.75, 25.03),
 ('2012-02-16', 25.0, 25.07),
 ('2012-02-15', 24.99, 25.15),
 ('2012-02-14', 24.68, 25.05),
 ('2012-02-13', 24.62, 24.77),
 ('2012-02-10', 24.38, 24.61)]
</code>```

It happens to also be flexible if we wanted to deal with a specific subset of columns.  We'll assume the columns we've already displayed are the subset we want.

```<code>list(zip(*map(df.get, ['data_date', 'data_1', 'data_2'])))

[('2012-02-17', 24.75, 25.03),
 ('2012-02-16', 25.0, 25.07),
 ('2012-02-15', 24.99, 25.15),
 ('2012-02-14', 24.68, 25.05),
 ('2012-02-13', 24.62, 24.77),
 ('2012-02-10', 24.38, 24.61)]
</code>```

What is Quicker?

Turn's out records is quickest followed by asymptotically converging zipmap and iter_tuples

I'll use a library simple_benchmarks that I got from this post

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

import pandas as pd
import numpy as np

def tuple_comp(df): return [tuple(x) for x in df.to_numpy()]
def iter_namedtuples(df): return list(df.itertuples(index=False))
def iter_tuples(df): return list(df.itertuples(index=False, name=None))
def records(df): return df.to_records(index=False).tolist()
def zipmap(df): return list(zip(*map(df.get, df)))

funcs = [tuple_comp, iter_namedtuples, iter_tuples, records, zipmap]
for func in funcs:
    b.add_function()(func)

def creator(n):
    return pd.DataFrame({"A": random.randint(n, size=n), "B": random.randint(n, size=n)})

@b.add_arguments('Rows in DataFrame')
def argument_provider():
    for n in (10 ** (np.arange(4, 11) / 2)).astype(int):
        yield n, creator(n)

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

Check the results

```<code>r.to_pandas_dataframe().pipe(lambda d: d.div(d.min(1), 0))

        tuple_comp  iter_namedtuples  iter_tuples   records    zipmap
100       2.905662          6.626308     3.450741  1.469471  1.000000
316       4.612692          4.814433     2.375874  1.096352  1.000000
1000      6.513121          4.106426     1.958293  1.000000  1.316303
3162      8.446138          4.082161     1.808339  1.000000  1.533605
10000     8.424483          3.621461     1.651831  1.000000  1.558592
31622     7.813803          3.386592     1.586483  1.000000  1.515478
100000    7.050572          3.162426     1.499977  1.000000  1.480131
</code>```

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

Body:
I have manipulated some data using pandas and now I want to carry out a batch save back to the database. This requires me to convert the dataframe into an array of tuples, with each tuple corresponding to a "row" of the dataframe.

My DataFrame looks something like:

In [182]: data_set
Out[182]:
  index data_date   data_1  data_2
0  14303 2012-02-17  24.75   25.03
1  12009 2012-02-16  25.00   25.07
2  11830 2012-02-15  24.99   25.15
3  6274  2012-02-14  24.68   25.05
4  2302  2012-02-13  24.62   24.77
5  14085 2012-02-10  24.38   24.61

I want to convert it to an array of tuples like:

[(datetime.date(2012,2,17),24.75,25.03),
(datetime.date(2012,2,16),25.00,25.07),
...etc. ]

Any suggestion on how I can efficiently do this?

Body:
Motivation

Many data sets are large enough that we need to concern ourselves with speed/efficiency.  So I offer this solution in that spirit.  It happens to also be succinct.

For the sake of comparison, let's drop the index column

df = data_set.drop('index', 1)

Solution

I'll propose the use of zip and map

list(zip(*map(df.get, df)))

[('2012-02-17', 24.75, 25.03),
 ('2012-02-16', 25.0, 25.07),
 ('2012-02-15', 24.99, 25.15),
 ('2012-02-14', 24.68, 25.05),
 ('2012-02-13', 24.62, 24.77),
 ('2012-02-10', 24.38, 24.61)]

It happens to also be flexible if we wanted to deal with a specific subset of columns.  We'll assume the columns we've already displayed are the subset we want.

list(zip(*map(df.get, ['data_date', 'data_1', 'data_2'])))

[('2012-02-17', 24.75, 25.03),
 ('2012-02-16', 25.0, 25.07),
 ('2012-02-15', 24.99, 25.15),
 ('2012-02-14', 24.68, 25.05),
 ('2012-02-13', 24.62, 24.77),
 ('2012-02-10', 24.38, 24.61)]

What is Quicker?

Turn's out records is quickest followed by asymptotically converging zipmap and iter_tuples

I'll use a library simple_benchmarks that I got from this post

from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()

import pandas as pd
import numpy as np

def tuple_comp(df): return [tuple(x) for x in df.to_numpy()]
def iter_namedtuples(df): return list(df.itertuples(index=False))
def iter_tuples(df): return list(df.itertuples(index=False, name=None))
def records(df): return df.to_records(index=False).tolist()
def zipmap(df): return list(zip(*map(df.get, df)))

funcs = [tuple_comp, iter_namedtuples, iter_tuples, records, zipmap]
for func in funcs:
    b.add_function()(func)

def creator(n):
    return pd.DataFrame({"A": random.randint(n, size=n), "B": random.randint(n, size=n)})

@b.add_arguments('Rows in DataFrame')
def argument_provider():
    for n in (10 ** (np.arange(4, 11) / 2)).astype(int):
        yield n, creator(n)

r = b.run()

Check the results

r.to_pandas_dataframe().pipe(lambda d: d.div(d.min(1), 0))

        tuple_comp  iter_namedtuples  iter_tuples   records    zipmap
100       2.905662          6.626308     3.450741  1.469471  1.000000
316       4.612692          4.814433     2.375874  1.096352  1.000000
1000      6.513121          4.106426     1.958293  1.000000  1.316303
3162      8.446138          4.082161     1.808339  1.000000  1.533605
10000     8.424483          3.621461     1.651831  1.000000  1.558592
31622     7.813803          3.386592     1.586483  1.000000  1.515478
100000    7.050572          3.162426     1.499977  1.000000  1.480131

r.plot()


来源: stackexchange

问:
How to/best practice on how to differentiate between serialised objects stored within JSON format?
Suppose that I serialise two different objects and save them to a directory.

Problem: Upon application start up, parsing the JSON files are not a problem - since GSON is employed, I can write my own serialisers and  deserialisers for both of the JSON files for their respective objects to be constructed.

But the problem is, how can I differentiate between the numerous JSON files in terms of what they store within them, so I can apply the correct deserialiser to it.

Thank you, best.

答: I think that the best way is parse JSON to a HashMap<String, Object> with multiple level. GSON will parse your JSON to HashMap with key is object name and value is an object (This object will belong to 3 type: HashMap for a object in JSON, List for an array in JSON and String for a string in JSON). To using this HashMap you need to iterate through the HashMap using a recursive method.

ContentLicense: CC BY-SA 3.0


问:
How do I get the count of rows using Bookshelf?
How can I get the number of rows (without any filter)?

I've tried this User.fetch().count() and User.count(), but I get these errors respectively:

```<code>TypeError: User.fetch is not a function

AssertionError: expected { Object (_bitField, _fulfillmentHandler0, ...) } to equal 0
</code>```

Here's my model:

```<code>let bookshelf = require('../config/database');

require('./role');

var User = bookshelf.Model.extend({
    tableName: 'users',
    role: function() {
        return this.hasOne(Role);
    }
});

module.exports = bookshelf.model('User', User);
</code>```

答:
try this:

```<code>const knex = require("knex")(require("./knexfile").development);
const Bookshelf = require("bookshelf")(knex);

const User = Bookshelf.Model.extend({
  tableName: "user",
  idAttribute: "userid"
});

knex.migrate.latest().then(_ => {

  User.forge().count().then(ret => {
    console.log(ret);
    process.exit(0);
  });

});
</code>```

the output should be:

```<code>[sombriks@sephiroth sample-knex-bookshelf]$ node index.js
Knex:warning - sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs
.org/#Builder-insert).
3
[sombriks@sephiroth sample-knex-bookshelf]$
</code>```

please take a look at this repo if you want a more detailed info.

Body:
How can I get the number of rows (without any filter)?

I've tried this User.fetch().count() and User.count(), but I get these errors respectively:

TypeError: User.fetch is not a function

AssertionError: expected { Object (_bitField, _fulfillmentHandler0, ...) } to equal 0

Here's my model:

let bookshelf = require('../config/database');

require('./role');

var User = bookshelf.Model.extend({
    tableName: 'users',
    role: function() {
        return this.hasOne(Role);
    }
});

module.exports = bookshelf.model('User', User);

Body:
try this:

const knex = require("knex")(require("./knexfile").development);
const Bookshelf = require("bookshelf")(knex);

const User = Bookshelf.Model.extend({
  tableName: "user",
  idAttribute: "userid"
});

knex.migrate.latest().then(_ => {

  User.forge().count().then(ret => {
    console.log(ret);
    process.exit(0);
  });

});

the output should be:

[sombriks@sephiroth sample-knex-bookshelf]$ node index.js
Knex:warning - sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs
.org/#Builder-insert).
3
[sombriks@sephiroth sample-knex-bookshelf]$

please take a look at this repo if you want a more detailed info.


问:
Can't run django app with rest api on Heroku
I Just created an account on "Heroku.com" and followed the steps in the guide to create a new python project. I cloned the files locally and added a new app to the project and I created a rest api. I added 'rest_framework' to my "settings.py" and I was able to run the project locally. When I tried to push the changes back to heroku, it fails and i get this message:

```<code>Counting objects: 6, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 632 bytes | 0 bytes/s, done.
Total 6 (delta 5), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing requirements with pip
remote:
remote: Package django found!
remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 10, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/core/management/__init__.py", line 353, in
execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/core/management/__init__.py", line 327, in execute
remote:            django.setup()
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/__init__.py", line 18, in setup
remote:            apps.populate(settings.INSTALLED_APPS)
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/apps/registry.py", line 85, in populate
remote:            app_config = AppConfig.create(entry)
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/apps/config.py", line 90, in create
remote:            module = import_module(entry)
remote:          File
"/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in
import_module
remote:            return _bootstrap._gcd_import(name[level:], package,
level)
remote:          File "<frozen importlib._bootstrap>", line 978, in
_gcd_import
remote:          File "<frozen importlib._bootstrap>", line 961, in
_find_and_load
remote:          File "<frozen importlib._bootstrap>", line 948, in
_find_and_load_unlocked
remote:        ModuleNotFoundError: No module named 'rest_framework'
remote:
remote:  !     Error while running '$ python manage.py collectstatic --
noinput'.
remote:        See traceback above for details.
remote:
remote:        You may need to update application code to resolve this
error.
remote:        Or, you can disable collectstatic for this application:
remote:
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1
remote:
remote:        https://devcenter.heroku.com/articles/django-assets
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to xplearner.
remote:
To https://git.heroku.com/xplearner.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/xplearner.git'
</code>```

When I remove 'rest_framework' from my 'settings.py' I can successfully push my changes to "Heroku" but I can no more run the app locally since it won't find restframework in my settings and in the same case, I get this error when i try to launch the project online on Heroku:

```<code>ModuleNotFoundError at /admin/
No module named 'rest_framework'
</code>```

Please can someone suggest a solution to this problem? What am I not doing right?

答: Maybe this is a python2/python3 problem. You can change rest_framework with djangorestframeworkIf you use python3 with this package locally, can you spesify a little more information about requirements and heroku confs.

Body:
I Just created an account on "Heroku.com" and followed the steps in the guide to create a new python project. I cloned the files locally and added a new app to the project and I created a rest api. I added 'rest_framework' to my "settings.py" and I was able to run the project locally. When I tried to push the changes back to heroku, it fails and i get this message:

Counting objects: 6, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 632 bytes | 0 bytes/s, done.
Total 6 (delta 5), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing requirements with pip
remote:
remote: Package django found!
remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 10, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/core/management/__init__.py", line 353, in
execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/core/management/__init__.py", line 327, in execute
remote:            django.setup()
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/__init__.py", line 18, in setup
remote:            apps.populate(settings.INSTALLED_APPS)
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/apps/registry.py", line 85, in populate
remote:            app_config = AppConfig.create(entry)
remote:          File "/app/.heroku/python/lib/python3.6/site-
packages/django/apps/config.py", line 90, in create
remote:            module = import_module(entry)
remote:          File
"/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in
import_module
remote:            return _bootstrap._gcd_import(name[level:], package,
level)
remote:          File "<frozen importlib._bootstrap>", line 978, in
_gcd_import
remote:          File "<frozen importlib._bootstrap>", line 961, in
_find_and_load
remote:          File "<frozen importlib._bootstrap>", line 948, in
_find_and_load_unlocked
remote:        ModuleNotFoundError: No module named 'rest_framework'
remote:
remote:  !     Error while running '$ python manage.py collectstatic --
noinput'.
remote:        See traceback above for details.
remote:
remote:        You may need to update application code to resolve this
error.
remote:        Or, you can disable collectstatic for this application:
remote:
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1
remote:
remote:        https://devcenter.heroku.com/articles/django-assets
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to xplearner.
remote:
To https://git.heroku.com/xplearner.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/xplearner.git'

When I remove 'rest_framework' from my 'settings.py' I can successfully push my changes to "Heroku" but I can no more run the app locally since it won't find restframework in my settings and in the same case, I get this error when i try to launch the project online on Heroku:

ModuleNotFoundError at /admin/
No module named 'rest_framework'

Please can someone suggest a solution to this problem? What am I not doing right?


问:
Narrowing conversions in C++0x. Is it just me, or does this sound like a breaking change?
C++0x is going to make the following code and similar code ill-formed, because it requires a so-called narrowing conversion of a double to a int.

```<code>int a[] = { 1.0 };
</code>```

I'm wondering whether this kind of initialization is used much in real world code. How many code will be broken by this change? Is it much effort to fix this in your code, if your code is affected at all?

For reference, see 8.5.4/6 of n3225

A narrowing conversion is an implicit conversion

from a floating-point type to an integer type, or

from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or

from an integer type or unscoped enumeration type to a ﬂoating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type, or

from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.

答:
I wouldn't be all that surprised if somebody gets caught out by something like:

```<code>float ra[] = {0, CHAR_MAX, SHORT_MAX, INT_MAX, LONG_MAX};
</code>```

(on my implementation, the last two don't produce the same result when converted back to int/long, hence are narrowing)

I don't remember ever writing this, though. It's only useful if an approximation to the limits is useful for something.

This seems at least vaguely plausible too:

```<code>void some_function(int val1, int val2) {
    float asfloat[] = {val1, val2};    // not in C++0x
    double asdouble[] = {val1, val2};  // not in C++0x
    int asint[] = {val1, val2};        // OK
    // now do something with the arrays
}
</code>```

but it isn't entirely convincing, because if I know I have exactly two values, why put them in arrays rather than just float floatval1 = val1, floatval1 = val2;? What's the motivation, though, why that should compile (and work, provided the loss of precision is within acceptable accuracy for the program), while float asfloat[] = {val1, val2}; shouldn't? Either way I'm initializing two floats from two ints, it's just that in one case the two floats happen to be members of an aggregate.

That seems particularly harsh in cases where a non-constant expression results in a narrowing conversion even though (on a particular implementation), all values of the source type are representable in the destination type and convertible back to their original values:

```<code>char i = something();
static_assert(CHAR_BIT == 8);
double ra[] = {i}; // how is this worse than using a constant value?
</code>```

Assuming there's no bug, presumably the fix is always to make the conversion explicit. Unless you're doing something odd with macros, I think an array initializer only appears close to the type of the array, or at least to something representing the type, which could be dependent on a template parameter. So a cast should be easy, if verbose.

ContentLicense: CC BY-SA 2.5

Body:
C++0x is going to make the following code and similar code ill-formed, because it requires a so-called narrowing conversion of a double to a int.

int a[] = { 1.0 };

I'm wondering whether this kind of initialization is used much in real world code. How many code will be broken by this change? Is it much effort to fix this in your code, if your code is affected at all?

For reference, see 8.5.4/6 of n3225

A narrowing conversion is an implicit conversion

from a floating-point type to an integer type, or

from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or

from an integer type or unscoped enumeration type to a ﬂoating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type, or

from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.

Body:
I wouldn't be all that surprised if somebody gets caught out by something like:

float ra[] = {0, CHAR_MAX, SHORT_MAX, INT_MAX, LONG_MAX};

(on my implementation, the last two don't produce the same result when converted back to int/long, hence are narrowing)

I don't remember ever writing this, though. It's only useful if an approximation to the limits is useful for something.

This seems at least vaguely plausible too:

void some_function(int val1, int val2) {
    float asfloat[] = {val1, val2};    // not in C++0x
    double asdouble[] = {val1, val2};  // not in C++0x
    int asint[] = {val1, val2};        // OK
    // now do something with the arrays
}

but it isn't entirely convincing, because if I know I have exactly two values, why put them in arrays rather than just float floatval1 = val1, floatval1 = val2;? What's the motivation, though, why that should compile (and work, provided the loss of precision is within acceptable accuracy for the program), while float asfloat[] = {val1, val2}; shouldn't? Either way I'm initializing two floats from two ints, it's just that in one case the two floats happen to be members of an aggregate.

That seems particularly harsh in cases where a non-constant expression results in a narrowing conversion even though (on a particular implementation), all values of the source type are representable in the destination type and convertible back to their original values:

char i = something();
static_assert(CHAR_BIT == 8);
double ra[] = {i}; // how is this worse than using a constant value?

Assuming there's no bug, presumably the fix is always to make the conversion explicit. Unless you're doing something odd with macros, I think an array initializer only appears close to the type of the array, or at least to something representing the type, which could be dependent on a template parameter. So a cast should be easy, if verbose.


问:
How to display data present in datatable variable dt in gridview form in c#?
I've created a datatable with 3 columns and would like to represent this data present in datatable object dt in the form of a gridview in c#</p>

```<code>DataTable dt = new DataTable();
dt.Columns.Add("Customer", typeof(string));
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("City", typeof(string));
DataRow dr = dt.NewRow();
dr["customer"]="xyz";
dr["id"]= 1;
dr["city"]="berlin";
dt.Rows.Add(dr);
</code>```

答:
Define gridview markup in aspx page.

Below gridview has two columns of id and name.

```<code><asp:GridView ID="GridView1" runat="server" >
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                    <asp:Label ID="lblID" Text='<%# Eval("CustomerID") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                    <asp:Label ID="lblName" Text='<%# Eval("CustomerName") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
</asp:GridView>
</code>```

in codebehind

```<code>if (!Page.IsPostBack)
{
    DataTable dt = new DataTable();
    //populate dt here
    GridView1.DataSource = dt; ---> //Gets or sets the object from which the data-bound control retrieves its list.
    GridView1.DataBind();    ---> //Bind the DataSource to the GridView control
}
</code>```

Body:
I've created a datatable with 3 columns and would like to represent this data present in datatable object dt in the form of a gridview in c#

DataTable dt = new DataTable();
dt.Columns.Add("Customer", typeof(string));
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("City", typeof(string));
DataRow dr = dt.NewRow();
dr["customer"]="xyz";
dr["id"]= 1;
dr["city"]="berlin";
dt.Rows.Add(dr);

Body:
Define gridview markup in aspx page.

Below gridview has two columns of id and name.

<asp:GridView ID="GridView1" runat="server" >
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                    <asp:Label ID="lblID" Text='<%# Eval("CustomerID") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                    <asp:Label ID="lblName" Text='<%# Eval("CustomerName") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
</asp:GridView>

in codebehind

if (!Page.IsPostBack)
{
    DataTable dt = new DataTable();
    //populate dt here
    GridView1.DataSource = dt; ---> //Gets or sets the object from which the data-bound control retrieves its list.
    GridView1.DataBind();    ---> //Bind the DataSource to the GridView control
}


问:
VB.NET - Delete excess white spaces between words in a sentence
I'm a programing student, so I've started with vb.net as my first language and I need some help.

I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.

I made a part of the code but it doesn't work, Thanks.
enter image description here

答:
There is a very simple answer to this question, there is a string method that allows you to remove those "White Spaces" within a string.

```<code>Dim text_with_white_spaces as string = "Hey There!"
Dim text_without_white_spaces as string = text_with_white_spaces.Replace(" ", "")
'text_without_white_spaces should be equal to "HeyThere!"
</code>```

Hope it helped!

Body:
There is a very simple answer to this question, there is a string method that allows you to remove those "White Spaces" within a string.

Dim text_with_white_spaces as string = "Hey There!"
Dim text_without_white_spaces as string = text_with_white_spaces.Replace(" ", "")
'text_without_white_spaces should be equal to "HeyThere!"

Hope it helped!


问:
Atlassian Bamboo installation failing to start
I've installed Bamboo on my machine and I'm trying to run it. Every time I call bin\start-bamboo.bat from the command line it fails to start and I can't figure out why. Here's is what I have in my cataline.log:

23-May-2017 17:34:41.938 WARNING [main]
  org.apache.tomcat.util.digester.SetPropertiesRule.begin
  [SetPropertiesRule]{Server/Service/Engine/Valve} Setting property
  'resolveHosts' to 'false' did not find a matching property.
  23-May-2017 17:34:41.943 INFO [main]
  org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR
  based Apache Tomcat Native library which allows optimal performance in
  production environments was not found on the java.library.path:
  C:\Program Files
  (x86)\Java\jdk1.7.0_55\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
  Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft
  SQL Server\130\Tools\Binn\;C:\Program Files (x86)\Windows
  Kits\10\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL
  Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files
  (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft
  SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\120\Tools\Binn\ManagementStudio\;C:\Program Files
  (x86)\Microsoft SQL
  Server\120\DTS\Binn\;C:\Users\matth.dnx\bin;C:\Program
  Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\Microsoft Emulator
  Manager\1.0\;C:\Program Files (x86)\nodejs\;C:\Program
  Files\Microsoft\Web Platform Installer\;C:\Program
  Files\TortoiseGit\bin;C:\Program Files\Git\cmd;C:\Program
  Files\Intel\WiFi\bin\;C:\Program Files\Common
  Files\Intel\WirelessCommon\;C:\Program Files
  (x86)\Skype\Phone\;C:\Program Files\Intel\WiFi\bin\;C:\Program
  Files\Common
  Files\Intel\WirelessCommon\;C:\Users\matth\AppData\Roaming\npm;C:\Program
  Files
  (x86)\MSBuild\12.0\Bin;C:\Users\matth\Downloads\mysql-connector-java-5.1.42.tar\mysql-connector-java-5.1.42;.
  23-May-2017 17:34:41.989 INFO [main]
  org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler
  ["http-nio-8085"] 23-May-2017 17:34:42.003 INFO [main]
  org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a
  shared selector for servlet write/read 23-May-2017 17:34:42.005 INFO
  [main] org.apache.catalina.startup.Catalina.load Initialization
  processed in 299 ms 23-May-2017 17:34:42.014 INFO [main]
  org.apache.catalina.core.StandardService.startInternal Starting
  service Catalina 23-May-2017 17:34:42.014 INFO [main]
  org.apache.catalina.core.StandardEngine.startInternal Starting Servlet
  Engine: Apache Tomcat/8.0.36 23-May-2017 17:34:53.384 INFO
  [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars
  At least one JAR was scanned for TLDs yet contained no TLDs. Enable
  debug logging for this logger for a complete list of JARs that were
  scanned but no TLDs were found in them. Skipping unneeded JARs during
  scanning can improve startup time and JSP compilation time.
  23-May-2017 17:34:53.404 SEVERE [localhost-startStop-1]
  org.apache.catalina.core.StandardContext.startInternal One or more
  listeners failed to start. Full details will be found in the
  appropriate container log file 23-May-2017 17:34:53.585 INFO
  [localhost-startStop-1]
  org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom
  Creation of SecureRandom instance for session ID generation using
  [SHA1PRNG] took [179] milliseconds. 23-May-2017 17:34:53.585 SEVERE
  [localhost-startStop-1]
  org.apache.catalina.core.StandardContext.startInternal Context []
  startup failed due to previous errors 23-May-2017 17:34:53.643 INFO
  [main] org.apache.coyote.AbstractProtocol.start Starting
  ProtocolHandler ["http-nio-8085"] 23-May-2017 17:34:53.649 INFO [main]
  org.apache.catalina.startup.Catalina.start Server startup in 11644 ms

And here's what I have in my localhost log:

23-May-2017 17:34:53.401 INFO [localhost-startStop-1]
  org.apache.catalina.core.ApplicationContext.log No Spring
  WebApplicationInitializer types detected on classpath 23-May-2017
  17:34:53.402 SEVERE [localhost-startStop-1]
  org.apache.catalina.core.StandardContext.listenerStart Error
  configuring application listener of class
  com.atlassian.bamboo.setup.BootstrapLoaderListener
  java.lang.UnsupportedClassVersionError:
  com/atlassian/bamboo/setup/BootstrapLoaderListener : Unsupported
  major.minor version 52.0 (unable to load class
  com.atlassian.bamboo.setup.BootstrapLoaderListener) at
  org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2544)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:858)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1301)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
  at
  org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
  at
  org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
  at
  org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
  at
  org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4764)
  at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
  at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
  at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
  at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
  at java.util.concurrent.FutureTask.run(FutureTask.java:262) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  at java.lang.Thread.run(Thread.java:745)

23-May-2017 17:34:53.403 SEVERE [localhost-startStop-1]
  org.apache.catalina.core.StandardContext.listenerStart Error
  configuring application listener of class
  com.atlassian.bamboo.ww2.actions.setup.BambooContextLoaderListener
  java.lang.UnsupportedClassVersionError:
  com/atlassian/bamboo/ww2/actions/setup/BambooContextLoaderListener :
  Unsupported major.minor version 52.0 (unable to load class
  com.atlassian.bamboo.ww2.actions.setup.BambooContextLoaderListener) at
  org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2544)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:858)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1301)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
  at
  org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
  at
  org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
  at
  org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
  at
  org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4764)
  at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
  at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
  at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
  at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
  at java.util.concurrent.FutureTask.run(FutureTask.java:262) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  at java.lang.Thread.run(Thread.java:745)

23-May-2017 17:34:53.404 SEVERE [localhost-startStop-1]
  org.apache.catalina.core.StandardContext.listenerStart Error
  configuring application listener of class
  com.atlassian.bamboo.upgrade.UpgradeLauncher
  java.lang.UnsupportedClassVersionError:
  com/atlassian/bamboo/upgrade/UpgradeLauncher : Unsupported major.minor
  version 52.0 (unable to load class
  com.atlassian.bamboo.upgrade.UpgradeLauncher) at
  org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2544)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:858)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1301)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
  at
  org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
  at
  org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
  at
  org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
  at
  org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4764)
  at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
  at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
  at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
  at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
  at java.util.concurrent.FutureTask.run(FutureTask.java:262) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  at java.lang.Thread.run(Thread.java:745)

23-May-2017 17:34:53.404 SEVERE [localhost-startStop-1]
  org.apache.catalina.core.StandardContext.listenerStart Error
  configuring application listener of class
  com.atlassian.bamboo.session.SeraphHttpSessionDestroyedListener
  java.lang.UnsupportedClassVersionError:
  com/atlassian/bamboo/session/SeraphHttpSessionDestroyedListener :
  Unsupported major.minor version 52.0 (unable to load class
  com.atlassian.bamboo.session.SeraphHttpSessionDestroyedListener) at
  org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2544)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:858)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1301)
  at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
  at
  org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
  at
  org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
  at
  org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
  at
  org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4764)
  at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
  at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
  at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
  at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
  at java.util.concurrent.FutureTask.run(FutureTask.java:262) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  at java.lang.Thread.run(Thread.java:745)

23-May-2017 17:34:53.404 SEVERE [localhost-startStop-1]
  org.apache.catalina.core.StandardContext.listenerStart Skipped
  installing application listeners due to previous error(s)

If anyone could help that'd be most appreciated.

Thanks,

Matt

答:
The hint is within the stack trace:

Unsupported major.minor version 52.0

Check the Java versions - 52.0 is Java 8: https://en.wikipedia.org/wiki/Java_class_file#General_layout

Latest versions of Bamboo require JDK 1.8 (Java 8)
https://confluence.atlassian.com/bamboo/supported-platforms-289276764.html

But Bamboo is starting with Java 7:

...C:\Program Files (x86)\Java\jdk1.7.0_55\bin...

So you need to upgrade your current JDK, or install another JDK and point it to that.


问:
Docker file to run Python with Pandas
I have created the following Dockerfile

```<code>FROM python
COPY . /home
CMD pip install pandas
CMD mkdir /home/report
CMD mkdir /home/data
CMD python /home/hello.py
</code>```

where hello.py is the simple Python script

```<code>name = input('What is your Name? ')
print('Nice to meet you', name)

from pandas import read_csv
mydf = read_csv('mycsv.csv')
print(mydf.head())
</code>```

I then build the Docker image with docker build -t myexample . and run it with docker run -it myexample bash so as to interact with it via the shell. The building goes fine and upon running it I presented with the shell prompt, but then:

No directories report or data have been created under /home.

The last command python /home/hello.py does not execute on its own. I have to type it myself to get the script to run.

Once I type python /home/hello.py, the first two lines that greet and prompt for my name are executed properly, but then an error says that pandas is unknown.

It is not until I install pandas manually that the whole script runs correctly.

So, in summary, it seems that none of the CMD statements were taken into account. What am I doing wrong?

答:
When you build an image use RUN to execute commands. Then, use CMD only once to declare the command that will start the container after the build (so there is only CMD):

Dockerfile:

```<code>FROM python
RUN pip install pandas
RUN mkdir /home/report
RUN mkdir /home/data

COPY . /home
WORKDIR /home
CMD python /home/hello.py
</code>```

mycsv.csv:

```<code>a,b,c
1,2,3
4,5,6
</code>```

Build with: docker build . -t pandas-test

Run:

```<code>▶ docker run -it pandas-test
What is your Name? Tfovid
Nice to meet you Tfovid
   a  b  c
0  1  2  3
1  4  5  6
</code>```

Title: Docker file to run Python with Pandas

Body:
I have created the following Dockerfile

FROM python
COPY . /home
CMD pip install pandas
CMD mkdir /home/report
CMD mkdir /home/data
CMD python /home/hello.py

where hello.py is the simple Python script

name = input('What is your Name? ')
print('Nice to meet you', name)

from pandas import read_csv
mydf = read_csv('mycsv.csv')
print(mydf.head())

I then build the Docker image with docker build -t myexample . and run it with docker run -it myexample bash so as to interact with it via the shell. The building goes fine and upon running it I presented with the shell prompt, but then:

No directories report or data have been created under /home.

The last command python /home/hello.py does not execute on its own. I have to type it myself to get the script to run.

Once I type python /home/hello.py, the first two lines that greet and prompt for my name are executed properly, but then an error says that pandas is unknown.

It is not until I install pandas manually that the whole script runs correctly.

So, in summary, it seems that none of the CMD statements were taken into account. What am I doing wrong?

Body:
When you build an image use RUN to execute commands. Then, use CMD only once to declare the command that will start the container after the build (so there is only CMD):

Dockerfile:

FROM python
RUN pip install pandas
RUN mkdir /home/report
RUN mkdir /home/data

COPY . /home
WORKDIR /home
CMD python /home/hello.py

mycsv.csv:

a,b,c
1,2,3
4,5,6

Build with: docker build . -t pandas-test

Run:

▶ docker run -it pandas-test
What is your Name? Tfovid
Nice to meet you Tfovid
   a  b  c
0  1  2  3
1  4  5  6


问:
Running an passed function and passport.authenticate
I want both the function that sets the JWT and the passport.authenticate to run but only the former is running.

Is there a way I can have both run?

```<code>router.post('/login', (req, res, next) => {

   const userEmail = req.body.username;

   User.getUserByEmail(userEmail, function(err, user) {

     const token = jwt.sign(user, config.secret, {
       expiresIn: 604800 // 1 week
     });
     new Cookies(req, res).set('access_tokenx', token, {
       httpOnly: true,
       secure: false
     });
     return res.send();
   });
 },
 passport.authenticate('local', {
   successRedirect: '/',
   failureRedirect: '/users/login',
   failureFlash: true
 }),
 function(req, res) {
   res.redirect('/');
 });
</code>```

答:
From the express docs:

If the current middleware function does not end the request-response
  cycle, it must call next() to pass control to the next middleware
  function.

Since you're trying to run two middleware functions and one "final" request processor, you should replace return res.send(); with next() in the function that sets the JWT.

Also keep in mind that if any errors arise you should call next(err). (You should never allow a request to go unhandled in a middleware function because the client will never receive a response).

Body:
I want both the function that sets the JWT and the passport.authenticate to run but only the former is running.

Is there a way I can have both run?

router.post('/login', (req, res, next) => {

   const userEmail = req.body.username;

   User.getUserByEmail(userEmail, function(err, user) {

     const token = jwt.sign(user, config.secret, {
       expiresIn: 604800 // 1 week
     });
     new Cookies(req, res).set('access_tokenx', token, {
       httpOnly: true,
       secure: false
     });
     return res.send();
   });
 },
 passport.authenticate('local', {
   successRedirect: '/',
   failureRedirect: '/users/login',
   failureFlash: true
 }),
 function(req, res) {
   res.redirect('/');
 });


问:
Javascript Canvas rotate image in circle axis
I need help, I have been trying to rotate my image which is a pointer. with my code below it rotates but it rotates not as I want.

Code:

```<code>  var c = document.getElementById("ctx");
    var ctx = c.getContext("2d");
    for (var d = 0; d < 360; d++) {
        setTimeout(function (d) {
            c.globalAlpha = 0.5;
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.save();
            ctx.translate(c.width / 2, c.height / 2);
            ctx.rotate(d * Math.PI / 180);
            ctx.drawImage(imageLoader.pointer, -imageLoader.pointer.width / 2, -imageLoader.pointer.height / 2);
            ctx.restore();
        }, 100 * d, d);
    }
</code>```

This code makes my image rotate weirdly I think it rotates on its own axis but I am not sure.

However I need a rotation something like this image.

I think this rotation is around a circle, i need something like this , can someone give me a hint or help me out?

I was trying to do it with a shape but its more difficult because i need to find the tangent and more geometric formulas to make it rotate like this.

I appreciate your time in advance, thanks.

答:
The function to draw a rotated image rotating around a point on the canvas and offset to its own center of rotation.

```<code>// x,y is the location on the canvas that the image will rotate around
// cx,cy is the coordinates on the image that is rotated around
// angle is the amount of rotation in radians
function  drawImage(image,x,y,cx,cy,angle){
    ctx.setTransform(1,0,0,1,x,y);  // set the rotation origin
    ctx.rotate(angle); // rotate
    ctx.drawImage(image,-cx,-cy); // draw image offset to put cx,cy at the point of rotation
    ctx.setTransform(1,0,0,1,0,0); // restore the transform
}
</code>```

So if your image is 50 by 100 pixels and you want the image to rotate about the point on it at 25, 80 (center near bottom) and that rotation point to be on the canvas at 200,200 then

```<code>drawImage(image,200,200,25,80,3); //rotate 3 radians
</code>```

To do so in an animation.

```<code>// assumes image has loaded and ctx is the context of the canvas.
requestAnimationFrame(mainLoop); // starts the animation
function mainLoop(time){ // time is passed by  requestAnimationFrame
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); // clear
    drawImage(image,200,200,25,80,(time / 5000) * Math.PI * 2); // rotate one every 5 seconds
    requestAnimationFrame(mainLoop);
}
</code>```

const image = new Image
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
const ctx = myCanvas.getContext("2d");

function  drawImage(image,x,y,cx,cy,angle){
    ctx.setTransform(1,0,0,1,x,y);  // set the rotation origin
    ctx.rotate(angle); // rotate
    ctx.drawImage(image,-cx,-cy); // draw image offset to put cx,cy at the point of rotation
    ctx.setTransform(1,0,0,1,0,0); // restore the transform
}

// assumes image has loaded and ctx is the context of the canvas.
requestAnimationFrame(mainLoop); // starts the animation
function mainLoop(time){ // time is passed by  requestAnimationFrame
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); // clear
    if(image.complete){
        drawImage(image,250,250,image.width / 2,image.height * 0.8,(time / 5000) * Math.PI * 2); // rotate one every 5 seconds
    }
    requestAnimationFrame(mainLoop);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
   border : 2px black solid;
}</code>```

<canvas id="myCanvas" width = 500 height = 500></canvas>```

Body:
I need help, I have been trying to rotate my image which is a pointer. with my code below it rotates but it rotates not as I want.

Code:

  var c = document.getElementById("ctx");
    var ctx = c.getContext("2d");
    for (var d = 0; d < 360; d++) {
        setTimeout(function (d) {
            c.globalAlpha = 0.5;
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.save();
            ctx.translate(c.width / 2, c.height / 2);
            ctx.rotate(d * Math.PI / 180);
            ctx.drawImage(imageLoader.pointer, -imageLoader.pointer.width / 2, -imageLoader.pointer.height / 2);
            ctx.restore();
        }, 100 * d, d);
    }

This code makes my image rotate weirdly I think it rotates on its own axis but I am not sure.

However I need a rotation something like this image.

I think this rotation is around a circle, i need something like this , can someone give me a hint or help me out?

I was trying to do it with a shape but its more difficult because i need to find the tangent and more geometric formulas to make it rotate like this.

I appreciate your time in advance, thanks.

Body:
The function to draw a rotated image rotating around a point on the canvas and offset to its own center of rotation.

// x,y is the location on the canvas that the image will rotate around
// cx,cy is the coordinates on the image that is rotated around
// angle is the amount of rotation in radians
function  drawImage(image,x,y,cx,cy,angle){
    ctx.setTransform(1,0,0,1,x,y);  // set the rotation origin
    ctx.rotate(angle); // rotate
    ctx.drawImage(image,-cx,-cy); // draw image offset to put cx,cy at the point of rotation
    ctx.setTransform(1,0,0,1,0,0); // restore the transform
}

So if your image is 50 by 100 pixels and you want the image to rotate about the point on it at 25, 80 (center near bottom) and that rotation point to be on the canvas at 200,200 then

drawImage(image,200,200,25,80,3); //rotate 3 radians

To do so in an animation.

// assumes image has loaded and ctx is the context of the canvas.
requestAnimationFrame(mainLoop); // starts the animation
function mainLoop(time){ // time is passed by  requestAnimationFrame
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); // clear
    drawImage(image,200,200,25,80,(time / 5000) * Math.PI * 2); // rotate one every 5 seconds
    requestAnimationFrame(mainLoop);
}

const image = new Image
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
const ctx = myCanvas.getContext("2d");

function  drawImage(image,x,y,cx,cy,angle){
    ctx.setTransform(1,0,0,1,x,y);  // set the rotation origin
    ctx.rotate(angle); // rotate
    ctx.drawImage(image,-cx,-cy); // draw image offset to put cx,cy at the point of rotation
    ctx.setTransform(1,0,0,1,0,0); // restore the transform
}

// assumes image has loaded and ctx is the context of the canvas.
requestAnimationFrame(mainLoop); // starts the animation
function mainLoop(time){ // time is passed by  requestAnimationFrame
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); // clear
    if(image.complete){
        drawImage(image,250,250,image.width / 2,image.height * 0.8,(time / 5000) * Math.PI * 2); // rotate one every 5 seconds
    }
    requestAnimationFrame(mainLoop);
}

canvas {
   border : 2px black solid;
}

<canvas id="myCanvas" width = 500 height = 500></canvas>


问:
A list of plotting functions in base R?
Each time I encounter a new plotting function in Base R (e.g., dotchart(), smoothScatter(). matplot()), I wish there was a list of plotting functions in Base R which I could refer to for various plotting cases.

Question:

I was wondering if any our colleagues might be aware of a list of plotting functions in Base R which I could refer to for various plotting cases?

答: I found this site R plot gallery that has a wide array of basic types.  Click on them to see the numerous variants and the function call for each.</p>

Title: A list of plotting functions in base R?


问:
Is 'cast' dangerous in user-submitted content in classic ASP?
The legacy web app I have inherited, which was custom-written for Oxfam New Zealand in classic ASP, runs a string replace on user-submitted inputs removing the string 'cast' presumably because of the cast function.

However this means that none of our participants can have a name or email address that contains that string. This is causing problems for someone with the surname Hardcastle.

This seems completely over the top security-wise - or at least there must be a way to ensure the user inputs are safe without changing the inputs of people with 'cast' in their name or email address.

The actual replace is done with:

```<code>strString = (Replace(strString, "cast", "", 1, -1, vbTextCompare))
</code>```

I'm considering just commenting that line out, would that be safe to do?

答:
I could change it to

```<code>strString = (Replace(strString, "cast(", "", 1, -1, vbTextCompare))
</code>```

that way, you still get the "safety" of escaping the SQL, but won't aggravate users with cast in their names

Body:
The legacy web app I have inherited, which was custom-written for Oxfam New Zealand in classic ASP, runs a string replace on user-submitted inputs removing the string 'cast' presumably because of the cast function.

However this means that none of our participants can have a name or email address that contains that string. This is causing problems for someone with the surname Hardcastle.

This seems completely over the top security-wise - or at least there must be a way to ensure the user inputs are safe without changing the inputs of people with 'cast' in their name or email address.

The actual replace is done with:

strString = (Replace(strString, "cast", "", 1, -1, vbTextCompare))

I'm considering just commenting that line out, would that be safe to do?

Body:
I could change it to

strString = (Replace(strString, "cast(", "", 1, -1, vbTextCompare))

that way, you still get the "safety" of escaping the SQL, but won't aggravate users with cast in their names


问:
Singleton is instantiated twice in Glassfish Server
My singleton is called Resources. It should only be instantiated once by this Singleton standard I used:

package site.kevindhu.models;

import site.kevindhu.entity.Player;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class Resources {
    public static Resources resources;
    public Map<String, Object> data;

    static {
        resources = new Resources();
    }

    private Resources() {
        data = new HashMap<>();
        data.put("players", new HashSet<Player>());
        data.put("newPlayers", new HashSet<Player>());
    }

    public static Resources getInstance() {
        return resources;
    }
}```
</div>
</div>
</p>

<p>However, it is not working correctly!</p>

<p>When I deploy a .ear to run my glassfish server, it goes into this block twice:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>static {
        resources = new Resources();
    }</code>```

As a result, the "singleton" actually creates two different Resources each time I run the server.

I know I do twice because I debug it calls two different Resources objects whenever I attempt to call Resources.resources.

Is this possibly because I am deploying a .ear file? How do the specifics of this double instantiation work?

答:
The best way to go is to let the compiler handle it for you:</p>

```<code>/** Singleton. */
public enum Resources {
  RESOURCES;

  private final Map<String, Team> teams = new HashMap<>();

  public boolean add(Team team) {
    return team != null
        && teams.put(team.getName(), team) == null;
  }

  public Team find(String name) {
    return name == null ? null : teams.get(name);
  }

  public Team find(Team team) {
    return team == null ? null : get(team.getName());
  }

  public Map<String, Team> getTeams() {
    return Collections.unmodifiableMap(teams);
  }

  // remove, iterators, etc.
}

public class TeamImpl implements Team {
  private final String name;
  private final Map<String, Player> roster = new HashMap<>();

  public TeamImpl(String name) {
    if (name == null) {
      throw new IllegalArgumentException("name must not be null");
    }
    this.name = name;
    assert this.name != null;
  }

  @Override
  public boolean equals(Object other) {
    // base comparison on team name
  }

  @Override
  public int hashCode() {
    assert this.name != null;
    return name.hashCode();
  }

  // methods from interface Team:

  @Override
  public String getName() {
    return name;
  }

  @Override
  public Set<Player> getRoster() {
    return Collections.unmodifiableSet(new HashSet<>(roster.values()));
  }

  @Override
  public boolean add(Player player) {
    return player != null
        && roster.put(player.getName(), player) == null;
  }

  @Override
  public Player find(String name) {
    return name == null ? null : roster.get(name);
  }

  // remove, iterators, etc.
}
</code>```

Body:
My singleton is called Resources. It should only be instantiated once by this Singleton standard I used:

package site.kevindhu.models;

import site.kevindhu.entity.Player;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class Resources {
    public static Resources resources;
    public Map<String, Object> data;

    static {
        resources = new Resources();
    }

    private Resources() {
        data = new HashMap<>();
        data.put("players", new HashSet<Player>());
        data.put("newPlayers", new HashSet<Player>());
    }

    public static Resources getInstance() {
        return resources;
    }
}

However, it is not working correctly!

When I deploy a .ear to run my glassfish server, it goes into this block twice:

static {
        resources = new Resources();
    }

As a result, the "singleton" actually creates two different Resources each time I run the server.

I know I do twice because I debug it calls two different Resources objects whenever I attempt to call Resources.resources.

Is this possibly because I am deploying a .ear file? How do the specifics of this double instantiation work?

Body:
The best way to go is to let the compiler handle it for you:

/** Singleton. */
public enum Resources {
  RESOURCES;

  private final Map<String, Team> teams = new HashMap<>();

  public boolean add(Team team) {
    return team != null
        && teams.put(team.getName(), team) == null;
  }

  public Team find(String name) {
    return name == null ? null : teams.get(name);
  }

  public Team find(Team team) {
    return team == null ? null : get(team.getName());
  }

  public Map<String, Team> getTeams() {
    return Collections.unmodifiableMap(teams);
  }

  // remove, iterators, etc.
}

public class TeamImpl implements Team {
  private final String name;
  private final Map<String, Player> roster = new HashMap<>();

  public TeamImpl(String name) {
    if (name == null) {
      throw new IllegalArgumentException("name must not be null");
    }
    this.name = name;
    assert this.name != null;
  }

  @Override
  public boolean equals(Object other) {
    // base comparison on team name
  }

  @Override
  public int hashCode() {
    assert this.name != null;
    return name.hashCode();
  }

  // methods from interface Team:

  @Override
  public String getName() {
    return name;
  }

  @Override
  public Set<Player> getRoster() {
    return Collections.unmodifiableSet(new HashSet<>(roster.values()));
  }

  @Override
  public boolean add(Player player) {
    return player != null
        && roster.put(player.getName(), player) == null;
  }

  @Override
  public Player find(String name) {
    return name == null ? null : roster.get(name);
  }

  // remove, iterators, etc.
}


问:
Trying to output ➜ on powershell prompt with cmder
I am using cmder console with powershell and creating a custom prompt.  So I creae a task that looks like this:

```<code>*PowerShell -ExecutionPolicy Bypass -NoLogo -NoExit -new_console:d:"%USERPROFILE%"
</code>```

Now inside Microsoft.PowerShell_profile.ps1 I create a prompt that looks like:

```<code>[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

function prompt
{
    Write-Host "➜"  -nonewline -foregroundcolor Magenta
}
</code>```

Now the prompt outputs:

```<code>âžœPS>
</code>```

So my ➜ is not outputting correct.  So I copy

```<code>âžœPS>function prompt { Write-Host "➜"  -nonewline -foregroundcolor Magenta }
</code>```

and paste it right into cmder prompt and now the prompt outputs

```<code>➜PS>
</code>```

as it should.  How can I get cmder to output UTF8 at the command prompt when putting it in Microsoft.PowerShell_profile.ps1?

答:
Based on @PetSerAl responses I did need to save the file as UTF8 with BOM.

I am also able to remove Console]::OutputEncoding = [System.Text.Encoding]::UTF8 from my Microsoft.PowerShell_profile.ps1.
  Now my Microsoft.PowerShell_profile.ps1 looks like:

```<code>function prompt
{
    Write-Host "➜"  -nonewline -foregroundcolor Magenta
}
</code>```

Body:
I am using cmder console with powershell and creating a custom prompt.  So I creae a task that looks like this:

*PowerShell -ExecutionPolicy Bypass -NoLogo -NoExit -new_console:d:"%USERPROFILE%"

Now inside Microsoft.PowerShell_profile.ps1 I create a prompt that looks like:

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

function prompt
{
    Write-Host "➜"  -nonewline -foregroundcolor Magenta
}

Now the prompt outputs:

âžœPS>

So my ➜ is not outputting correct.  So I copy

âžœPS>function prompt { Write-Host "➜"  -nonewline -foregroundcolor Magenta }

and paste it right into cmder prompt and now the prompt outputs

➜PS>

as it should.  How can I get cmder to output UTF8 at the command prompt when putting it in Microsoft.PowerShell_profile.ps1?

Body:
Based on @PetSerAl responses I did need to save the file as UTF8 with BOM.

I am also able to remove Console]::OutputEncoding = [System.Text.Encoding]::UTF8 from my Microsoft.PowerShell_profile.ps1.
  Now my Microsoft.PowerShell_profile.ps1 looks like:

function prompt
{
    Write-Host "➜"  -nonewline -foregroundcolor Magenta
}


问:
How can I extract external referrers from an Apache access log with Perl?
I need some help getting a regex working to parse all referrers from an apache access log file which come from real links offsite and which are valid referrals from real people rather than bots or spiders. I'm working in Perl.

This bit of code almost works already [the access log is opened with the filehandle $fh]:

```<code>my $totalreferals = 0;
while ( my $line = <$fh> ) {
    if ($line !~ m!

        \[\d{2}/\w{3}/\d{4}(?::\d\d){3}.+?\]
        \s"GET\s\S+\sHTTP/\d.\d"
        \s\S+
        \s\S+
        \s("-"|"http://(www\.|)mywebsite\.com.*"

        !xi
        )
    {
          $totalreferals++;
    }

    $line =~ m!

        \[(\d{2}/\w{3}/\d{4})(?::\d\d){3}.+?\]
        \s"GET\s(\S+)\sHTTP/\d.\d"
        \s(\S+)
        \s\S+
        \s"http://w{1,3}\.google\.
        (?:[a-z]{2}|com?\.[a-z]{2}|com)\.?/
        [^\"]*q=([^\"&]+)[^\"]*"

    !xi or next;

    my ( $datestr, $path, $status, $query ) = ( $1, $2, $3, $4 );
    .
    .
    #do other stuff
    .
    .
}
</code>```

The above regex successfully eliminates all internal links recorded in the access_log plus records that don't have a referrer, but it gives a $totalreferals that is otherwise way too large.

Examples of log $line that are being counted by the 1st regex, but which I want excluded are:

```<code>61.247.221.45 - - [02/Jan/2009:20:51:41 -0600] "GET /oil-paintings/section.php/2451/0 HTTP/1.1" 200 85856 "-" "Yeti/1.0 (NHN Corp.; http://help.naver.com/robots/)"
</code>```

-- Appears to be a spider from Korea

```<code>93.84.41.131 - - [31/Dec/2008:02:36:54 -0600] "GET /paintings/artists/w/Waterhouse_John_William/oil-big/Waterhouse_Destiny.jpg HTTP/1.1" 200 19924 "http://smrus.web-box.ru/Schemes" "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5"
</code>```

-- Request is for an image embedded within another website (we allow this)

```<code>87.115.8.230 - - [31/Dec/2008:03:08:17 -0600] "GET /paintings/artists/recently-added/july2008/big/Crucifixion-of-St-Peter-xx-Guido-Reni.JPG HTTP/1.1" 200 37348 "http://images.google.co.uk/im........DN&frame=small" "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5"
</code>```

-- Request is from google images (could be viewing the image full-size, or spidering it)

```<code>216.145.5.42 - - [31/Dec/2008:02:21:49 -0600] "GET / HTTP/1.1" 200 53508 "http://whois.domaintools.com/mywebsite.com" "SurveyBot/2.3 (Whois Source)"
</code>```

-- Request is from a whois bot

答:
Manni's suggestion to eliminate POST and HEAD was indeed correct because I was looking for negative matches (therefore should not restrict to GET as when parsing for query strings). Likewise with the error in the dot before the host without a www, and also needing to eliminate "-" (no referrer)

Also, I eliminated all matches against image files which more often than not are not direct referrals from external sites but are embedded within those sites, or are being indexed by a search engine (Google Images mostly).

I also found many of the server's image files include spaces in the filenames, which was breaking the regex where a \S+ was used for filename, I've changed this to .+

Finally, since I didn't need to grep the date when eliminating records I could simplify the first part of the regex.

The result is much closer to the numbers I'm expecting. Although I have yet to find a good way to eliminate all requests from bots and spiders.

For those that are interested, the final code looks like this:

```<code>my $totalreferals = 0;
while ( my $line = <$fh> ) {
    if ($line !~ m!

        \[.+\]
        \s("\S+\s.+\sHTTP/\d.\d"
        \s\S+
        \s\S+
        \s("-"|"http://(www\.|)mywebsite\.com.*")|
        "\S+\s.+\.(jpg|jpeg|gif|png)\sHTTP/\d.\d"
        \s\S+
        \s\S+
        \s".*")
        !xi
        )
    {
      $totalreferals++;
    }

    $line =~ m!

        \[(\d{2}/\w{3}/\d{4})(?::\d\d){3}.+?\]
        \s"GET\s(\S+)\sHTTP/\d.\d"
        \s(\S+)
        \s\S+
        \s"http://w{1,3}\.google\.
        (?:[a-z]{2}|com?\.[a-z]{2}|com)\.?/
        [^\"]*q=([^\"&]+)[^\"]*"

    !xi or next;

    my ( $datestr, $path, $status, $query ) = ( $1, $2, $3, $4 );
    .
    .
    #do other stuff
    .
    .
}
</code>```

Edit: In the course of my research, it seems that the only really viable way to distinguish between automatic crawlers and real human visitors is with tracking cookies. I doubt there's a way to account for that with pure log analysis. If anyone knows of a way to do it by analyzing logs please let me know. For know I will just add a footnote to my log reports that indicate they include traffic from bots.

OwnerDisplayName: rwired

Body:
I need some help getting a regex working to parse all referrers from an apache access log file which come from real links offsite and which are valid referrals from real people rather than bots or spiders. I'm working in Perl.

This bit of code almost works already [the access log is opened with the filehandle $fh]:

my $totalreferals = 0;
while ( my $line = <$fh> ) {
    if ($line !~ m!

        \[\d{2}/\w{3}/\d{4}(?::\d\d){3}.+?\]
        \s"GET\s\S+\sHTTP/\d.\d"
        \s\S+
        \s\S+
        \s("-"|"http://(www\.|)mywebsite\.com.*"

        !xi
        )
    {
          $totalreferals++;
    }

    $line =~ m!

        \[(\d{2}/\w{3}/\d{4})(?::\d\d){3}.+?\]
        \s"GET\s(\S+)\sHTTP/\d.\d"
        \s(\S+)
        \s\S+
        \s"http://w{1,3}\.google\.
        (?:[a-z]{2}|com?\.[a-z]{2}|com)\.?/
        [^\"]*q=([^\"&]+)[^\"]*"

    !xi or next;

    my ( $datestr, $path, $status, $query ) = ( $1, $2, $3, $4 );
    .
    .
    #do other stuff
    .
    .
}

The above regex successfully eliminates all internal links recorded in the access_log plus records that don't have a referrer, but it gives a $totalreferals that is otherwise way too large.

Examples of log $line that are being counted by the 1st regex, but which I want excluded are:

61.247.221.45 - - [02/Jan/2009:20:51:41 -0600] "GET /oil-paintings/section.php/2451/0 HTTP/1.1" 200 85856 "-" "Yeti/1.0 (NHN Corp.; http://help.naver.com/robots/)"

-- Appears to be a spider from Korea

93.84.41.131 - - [31/Dec/2008:02:36:54 -0600] "GET /paintings/artists/w/Waterhouse_John_William/oil-big/Waterhouse_Destiny.jpg HTTP/1.1" 200 19924 "http://smrus.web-box.ru/Schemes" "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5"

-- Request is for an image embedded within another website (we allow this)

87.115.8.230 - - [31/Dec/2008:03:08:17 -0600] "GET /paintings/artists/recently-added/july2008/big/Crucifixion-of-St-Peter-xx-Guido-Reni.JPG HTTP/1.1" 200 37348 "http://images.google.co.uk/im........DN&frame=small" "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5"

-- Request is from google images (could be viewing the image full-size, or spidering it)

216.145.5.42 - - [31/Dec/2008:02:21:49 -0600] "GET / HTTP/1.1" 200 53508 "http://whois.domaintools.com/mywebsite.com" "SurveyBot/2.3 (Whois Source)"

-- Request is from a whois bot

LastEditorDisplayName: brian d foy

Body:
Manni's suggestion to eliminate POST and HEAD was indeed correct because I was looking for negative matches (therefore should not restrict to GET as when parsing for query strings). Likewise with the error in the dot before the host without a www, and also needing to eliminate "-" (no referrer)

Also, I eliminated all matches against image files which more often than not are not direct referrals from external sites but are embedded within those sites, or are being indexed by a search engine (Google Images mostly).

I also found many of the server's image files include spaces in the filenames, which was breaking the regex where a \S+ was used for filename, I've changed this to .+

Finally, since I didn't need to grep the date when eliminating records I could simplify the first part of the regex.

The result is much closer to the numbers I'm expecting. Although I have yet to find a good way to eliminate all requests from bots and spiders.

For those that are interested, the final code looks like this:

my $totalreferals = 0;
while ( my $line = <$fh> ) {
    if ($line !~ m!

        \[.+\]
        \s("\S+\s.+\sHTTP/\d.\d"
        \s\S+
        \s\S+
        \s("-"|"http://(www\.|)mywebsite\.com.*")|
        "\S+\s.+\.(jpg|jpeg|gif|png)\sHTTP/\d.\d"
        \s\S+
        \s\S+
        \s".*")
        !xi
        )
    {
      $totalreferals++;
    }

    $line =~ m!

        \[(\d{2}/\w{3}/\d{4})(?::\d\d){3}.+?\]
        \s"GET\s(\S+)\sHTTP/\d.\d"
        \s(\S+)
        \s\S+
        \s"http://w{1,3}\.google\.
        (?:[a-z]{2}|com?\.[a-z]{2}|com)\.?/
        [^\"]*q=([^\"&]+)[^\"]*"

    !xi or next;

    my ( $datestr, $path, $status, $query ) = ( $1, $2, $3, $4 );
    .
    .
    #do other stuff
    .
    .
}

Edit: In the course of my research, it seems that the only really viable way to distinguish between automatic crawlers and real human visitors is with tracking cookies. I doubt there's a way to account for that with pure log analysis. If anyone knows of a way to do it by analyzing logs please let me know. For know I will just add a footnote to my log reports that indicate they include traffic from bots.

LastEditorDisplayName: rwired


问:
React-Router v4 rendering wrong component but matching correctly
I've got a sidebar with two buttons, 'test' and 'about'. Test (rocket icon) is rendered at '/test', and About (home icon) is rendered at '/'.

They're both located at the root of the app and are nested within a  component.

When I start at '/' and click the Link to="/test" it always loads the 'About' component, and when I check the props for the componentDidMount of 'About', the match object contains match data for "/test".

Only when I refresh does it render the proper component, 'Test', again. Any idea why this is happening?

AppRoutes.js:

```<code>export class AppRoutes extends React.Component {

  render() {
    return (
      <div>
        <Switch>
          <Route
            exact path="/"
            render={(matchProps) => (
              <LazyLoad getComponent={() => import('pages/appPages/About')} {...matchProps} />
            )}
          />
          <Route
            path="/login"
            render={(matchProps) => (
              <LazyLoad getComponent={() => import('pages/appPages/Login')} {...matchProps} />
            )}
          />
          <Route
            path="/register"
            render={(matchProps) => (
              <LazyLoad getComponent={() => import('pages/appPages/Register')} {...matchProps} />
            )}
          />
          <Route
            path="/test"
            render={(matchProps) => (
              <LazyLoad getComponent={() => import('pages/appPages/Test')} {...matchProps} />
            )}
          />
...
</code>```

AboutPage.js && TestPage.js (duplicates except for component name):

```<code>import React from 'react';

import SidebarContainer from 'containers/SidebarContainer';
import SidebarPageLayout from 'styles/SidebarPageLayout';

export const About = (props) => {
  console.log('About Loading: ', props);
  return (
    <SidebarPageLayout>
      <SidebarContainer />
      <div>About</div>
    </SidebarPageLayout>
  );
}

export default About;
</code>```

SidebarContainer.js:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

import Sidebar from 'sidebar/Sidebar';
import HamburgerButton from 'sidebar/HamburgerButton';
import AboutButton from 'sidebar/AboutButton';
import ProfileButton from 'sidebar/ProfileButton';
import TestButton from 'sidebar/TestButton';

export class SidebarContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sidebarIsOpen: false,
      sidebarElements: [],
    };
  }

  componentDidMount() {
    if (!this.props.authenticated) {
      this.setState({
        sidebarElements: _.concat(this.state.sidebarElements, HamburgerButton, ProfileButton, AboutButton, TestButton),
      });
    }
  }

  toggleSidebarIsOpenState = () => {
    this.setState({ sidebarIsOpen: !this.state.sidebarIsOpen });
  }

  render() {
    const { authenticated, sidebarIsOpen, sidebarElements} = this.state;
    return (
      <div>
        <Sidebar
          authenticated={authenticated}
          sidebarIsOpen={sidebarIsOpen}
          sidebarElements={_.isEmpty(sidebarElements) ? undefined: sidebarElements}
          toggleSidebarIsOpenState={this.toggleSidebarIsOpenState}
        />
      </div>
    );
  }
}

SidebarContainer.propTypes = {
  authenticated: PropTypes.bool,
};

export default SidebarContainer;
</code>```

Sidebar.js:

```<code>import React from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types'

import SidebarStyles from '../styles/SidebarStyles';

export const Sidebar = (props) => {
  if (props && props.sidebarElements) {
    return (
      <SidebarStyles sidebarIsOpen={props.sidebarIsOpen}>
        {_.map(props.sidebarElements, (value, index) => {
          return React.createElement(
            value,
            {
              key: index,
              authenticated: props.authenticated,
              sidebarIsOpen: props.sidebarIsOpen,
              toggleSidebarIsOpenState: props.toggleSidebarIsOpenState,
            },
          );
        })}
      </SidebarStyles>
    );
  }
  return (
    <div></div>
  );
}

Sidebar.propTypes = {
  authenticated: PropTypes.bool,
  sidebarIsOpen: PropTypes.bool,
  sidebarElements: PropTypes.array,
  toggleSidebarIsOpenState: PropTypes.func,
};

export default Sidebar;
</code>```

TestButton.js:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-fontawesome';
import {
  Link
} from 'react-router-dom';

export const TestButton = (props) => {
  return (
    <Link to="/test">
      <Icon name='rocket' size='2x' />
    </Link>
  );
}

export default TestButton;
</code>```

AboutButton.js:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-fontawesome';
import {
  Link
} from 'react-router-dom';

export const AboutButton = (props) => {
  return (
    <Link to="/">
      <Icon name='home' size='2x' />
    </Link>
  );
}

export default AboutButton;
</code>```

No refresh, just constant clicking on the '/test' route from the '/' route:

after refresh:

Edit:

Root components:

Edit:

store.js:

```<code>import {
  createStore,
  applyMiddleware,
  compose,
} from 'redux';
import createSagaMiddleware from 'redux-saga';

import { rootReducer } from './rootReducers';
import { rootSaga } from './rootSagas';

// sagas
const sagaMiddleware = createSagaMiddleware();

// dev-tools
const composeEnhancers = typeof window === 'object' && (
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
  ) : compose
);

export function configureStore() {
  const middlewares = [
    sagaMiddleware,
  ];
  const store = createStore(
    rootReducer,
    {},
    composeEnhancers(applyMiddleware(...middlewares))
  );

  sagaMiddleware.run(rootSaga);
  return store;
}

export const store = configureStore();
</code>```

index.js (root):

```<code>import React from 'react';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';

import { store } from './store';
import AppContainer from 'containers/AppContainer';

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <AppContainer />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);
</code>```

AppContainer:

```<code>import React from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

import { logout, verifyToken } from './actions';
import { selectAuthenticated, selectAuthenticating } from './selectors';
import AppRoutes from 'routes/AppRoutes';

export class AppContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { loaded: false };
  }

  componentDidMount() {
    const token = localStorage.getItem('jwt');
    if (token) {
      this.props.verifyToken(token, () => this.setState({ loaded: true }));
    } else {
      this.setState({ loaded: true });
    }
  }

  render() {
    if (this.state.loaded) {
      return (
        <AppRoutes
          authenticated={this.props.authenticated}
          authenticating={this.props.authenticating}
          logout={this.props.logout}
        />
      );
    } else {
      return <div>Loading ...</div>
    }
  }
}

function mapStateToProps(state) {
  return {
    authenticated: selectAuthenticated(state),
    authenticating: selectAuthenticating(state),
  };
}

function mapDispatchToProps(dispatch) {
  return {
    verifyToken: (token = '', callback = false) => dispatch(verifyToken(token, callback)),
    logout: () => dispatch(logout()),
  };
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(AppContainer));
</code>```

Edit 2 for LazyLoad:

services/LazyLoad/index.js:

```<code>import React from 'react';

export class LazyLoad extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      AsyncModule: null,
    };
  }

  componentDidMount() {
    this.props.getComponent()  // getComponent={() => import('./someFile.js')}
      .then(module => module.default)
      .then(AsyncModule => this.setState({AsyncModule}))
  }

  render() {
    const { loader, ...childProps } = this.props;
    const { AsyncModule } = this.state;

    if (AsyncModule) {
      return <AsyncModule {...childProps} />;
    }

    if (loader) {
      const Loader = loader;
      return <Loader />;
    }

    return null;
  }
}

export default LazyLoad;
</code>```

答:
Your problem lies with LazyLoad component. For both "/" or "test" paths, what AppRoutes component ultimately renders is a LazyLoad component. Because Route and Switch just conditionally render their children. However, React can't differentiate "/" LazyLoad component and "/test" LazyLoad component. So the first time it renders LazyLoad component and invokes the componentDidMount. But when route changes, React consider it as a prop change of previously rendered LazyLoad component. So it just invokes componentWillReceiveProps of previous LazyLoad component with new props instead of unmounting previous one and mount a new one. That's why it continuously show About component until refresh the page.

To solve this problem, if the getComponent prop has changed, we have to load the new module with new getComponent inside the componentWillReceiveProps. So we can modify the LazyLoad as follows which have a common method to load module and invoke it from both componentDidMount and componentWillReceiveProps with correct props.

```<code>import React from 'react';

export class LazyLoad extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      AsyncModule: null,
    };
  }

  componentDidMount() {
    this.load(this.props);
  }

  load(props){
    this.setState({AsyncModule: null}
    props.getComponent()  // getComponent={() => import('./someFile.js')}
      .then(module => module.default)
      .then(AsyncModule => this.setState({AsyncModule}))
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.getComponent !== this.props.getComponent) {
      this.load(nextProps)
    }
  }

  render() {
    const { loader, ...childProps } = this.props;
    const { AsyncModule } = this.state;

    if (AsyncModule) {
      return <AsyncModule {...childProps} />;
    }

    if (loader) {
      const Loader = loader;
      return <Loader />;
    }

    return null;
  }
}

export default LazyLoad;
</code>```

Body:
I've got a sidebar with two buttons, 'test' and 'about'. Test (rocket icon) is rendered at '/test', and About (home icon) is rendered at '/'.

They're both located at the root of the app and are nested within a  component.

When I start at '/' and click the Link to="/test" it always loads the 'About' component, and when I check the props for the componentDidMount of 'About', the match object contains match data for "/test".

Only when I refresh does it render the proper component, 'Test', again. Any idea why this is happening?

AppRoutes.js:

export class AppRoutes extends React.Component {

  render() {
    return (

        <Switch>
          <Route
            exact path="/"
            render={(matchProps) => (
              <LazyLoad getComponent={() => import('pages/appPages/About')} {...matchProps} />
            )}
          />
          <Route
            path="/login"
            render={(matchProps) => (
              <LazyLoad getComponent={() => import('pages/appPages/Login')} {...matchProps} />
            )}
          />
          <Route
            path="/register"
            render={(matchProps) => (
              <LazyLoad getComponent={() => import('pages/appPages/Register')} {...matchProps} />
            )}
          />
          <Route
            path="/test"
            render={(matchProps) => (
              <LazyLoad getComponent={() => import('pages/appPages/Test')} {...matchProps} />
            )}
          />
...

AboutPage.js && TestPage.js (duplicates except for component name):

import React from 'react';

import SidebarContainer from 'containers/SidebarContainer';
import SidebarPageLayout from 'styles/SidebarPageLayout';

export const About = (props) => {
  console.log('About Loading: ', props);
  return (
    <SidebarPageLayout>
      <SidebarContainer />

About

    </SidebarPageLayout>
  );
}

export default About;

SidebarContainer.js:

import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

import Sidebar from 'sidebar/Sidebar';
import HamburgerButton from 'sidebar/HamburgerButton';
import AboutButton from 'sidebar/AboutButton';
import ProfileButton from 'sidebar/ProfileButton';
import TestButton from 'sidebar/TestButton';

export class SidebarContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sidebarIsOpen: false,
      sidebarElements: [],
    };
  }

  componentDidMount() {
    if (!this.props.authenticated) {
      this.setState({
        sidebarElements: _.concat(this.state.sidebarElements, HamburgerButton, ProfileButton, AboutButton, TestButton),
      });
    }
  }

  toggleSidebarIsOpenState = () => {
    this.setState({ sidebarIsOpen: !this.state.sidebarIsOpen });
  }

  render() {
    const { authenticated, sidebarIsOpen, sidebarElements} = this.state;
    return (

        <Sidebar
          authenticated={authenticated}
          sidebarIsOpen={sidebarIsOpen}
          sidebarElements={_.isEmpty(sidebarElements) ? undefined: sidebarElements}
          toggleSidebarIsOpenState={this.toggleSidebarIsOpenState}
        />

    );
  }
}

SidebarContainer.propTypes = {
  authenticated: PropTypes.bool,
};

export default SidebarContainer;

Sidebar.js:

import React from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types'

import SidebarStyles from '../styles/SidebarStyles';

export const Sidebar = (props) => {
  if (props && props.sidebarElements) {
    return (
      <SidebarStyles sidebarIsOpen={props.sidebarIsOpen}>
        {_.map(props.sidebarElements, (value, index) => {
          return React.createElement(
            value,
            {
              key: index,
              authenticated: props.authenticated,
              sidebarIsOpen: props.sidebarIsOpen,
              toggleSidebarIsOpenState: props.toggleSidebarIsOpenState,
            },
          );
        })}
      </SidebarStyles>
    );
  }
  return (

  );
}

Sidebar.propTypes = {
  authenticated: PropTypes.bool,
  sidebarIsOpen: PropTypes.bool,
  sidebarElements: PropTypes.array,
  toggleSidebarIsOpenState: PropTypes.func,
};

export default Sidebar;

TestButton.js:

import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-fontawesome';
import {
  Link
} from 'react-router-dom';

export const TestButton = (props) => {
  return (
    <Link to="/test">
      <Icon name='rocket' size='2x' />
    </Link>
  );
}

export default TestButton;

AboutButton.js:

import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-fontawesome';
import {
  Link
} from 'react-router-dom';

export const AboutButton = (props) => {
  return (
    <Link to="/">
      <Icon name='home' size='2x' />
    </Link>
  );
}

export default AboutButton;

No refresh, just constant clicking on the '/test' route from the '/' route:

after refresh:

Edit:

Root components:

Edit:

store.js:

import {
  createStore,
  applyMiddleware,
  compose,
} from 'redux';
import createSagaMiddleware from 'redux-saga';

import { rootReducer } from './rootReducers';
import { rootSaga } from './rootSagas';

// sagas
const sagaMiddleware = createSagaMiddleware();

// dev-tools
const composeEnhancers = typeof window === 'object' && (
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
  ) : compose
);

export function configureStore() {
  const middlewares = [
    sagaMiddleware,
  ];
  const store = createStore(
    rootReducer,
    {},
    composeEnhancers(applyMiddleware(...middlewares))
  );

  sagaMiddleware.run(rootSaga);
  return store;
}

export const store = configureStore();

index.js (root):

import React from 'react';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';

import { store } from './store';
import AppContainer from 'containers/AppContainer';

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <AppContainer />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

AppContainer:

import React from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

import { logout, verifyToken } from './actions';
import { selectAuthenticated, selectAuthenticating } from './selectors';
import AppRoutes from 'routes/AppRoutes';

export class AppContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { loaded: false };
  }

  componentDidMount() {
    const token = localStorage.getItem('jwt');
    if (token) {
      this.props.verifyToken(token, () => this.setState({ loaded: true }));
    } else {
      this.setState({ loaded: true });
    }
  }

  render() {
    if (this.state.loaded) {
      return (
        <AppRoutes
          authenticated={this.props.authenticated}
          authenticating={this.props.authenticating}
          logout={this.props.logout}
        />
      );
    } else {
      return
Loading ...

    }
  }
}

function mapStateToProps(state) {
  return {
    authenticated: selectAuthenticated(state),
    authenticating: selectAuthenticating(state),
  };
}

function mapDispatchToProps(dispatch) {
  return {
    verifyToken: (token = '', callback = false) => dispatch(verifyToken(token, callback)),
    logout: () => dispatch(logout()),
  };
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(AppContainer));

Edit 2 for LazyLoad:

services/LazyLoad/index.js:

import React from 'react';

export class LazyLoad extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      AsyncModule: null,
    };
  }

  componentDidMount() {
    this.props.getComponent()  // getComponent={() => import('./someFile.js')}
      .then(module => module.default)
      .then(AsyncModule => this.setState({AsyncModule}))
  }

  render() {
    const { loader, ...childProps } = this.props;
    const { AsyncModule } = this.state;

    if (AsyncModule) {
      return <AsyncModule {...childProps} />;
    }

    if (loader) {
      const Loader = loader;
      return <Loader />;
    }

    return null;
  }
}

export default LazyLoad;

Body:
Your problem lies with LazyLoad component. For both "/" or "test" paths, what AppRoutes component ultimately renders is a LazyLoad component. Because Route and Switch just conditionally render their children. However, React can't differentiate "/" LazyLoad component and "/test" LazyLoad component. So the first time it renders LazyLoad component and invokes the componentDidMount. But when route changes, React consider it as a prop change of previously rendered LazyLoad component. So it just invokes componentWillReceiveProps of previous LazyLoad component with new props instead of unmounting previous one and mount a new one. That's why it continuously show About component until refresh the page.

To solve this problem, if the getComponent prop has changed, we have to load the new module with new getComponent inside the componentWillReceiveProps. So we can modify the LazyLoad as follows which have a common method to load module and invoke it from both componentDidMount and componentWillReceiveProps with correct props.

import React from 'react';

export class LazyLoad extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      AsyncModule: null,
    };
  }

  componentDidMount() {
    this.load(this.props);
  }

  load(props){
    this.setState({AsyncModule: null}
    props.getComponent()  // getComponent={() => import('./someFile.js')}
      .then(module => module.default)
      .then(AsyncModule => this.setState({AsyncModule}))
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.getComponent !== this.props.getComponent) {
      this.load(nextProps)
    }
  }

  render() {
    const { loader, ...childProps } = this.props;
    const { AsyncModule } = this.state;

    if (AsyncModule) {
      return <AsyncModule {...childProps} />;
    }

    if (loader) {
      const Loader = loader;
      return <Loader />;
    }

    return null;
  }
}

export default LazyLoad;


问:
How to have a facebook messenger bot send you a youtube video embedded in messenger
I was wondering if it is possible to have a messenger bot send you a youtube video link and generate a playable video inside messenger the same way you can if you paste a link inside the messenger. Right now my bot can send a message with a youtube link but it just sends it as text it doesn't generate a video recognizing the title, description etc. Any help would be appreciated. </p>

答:
You can also send by OpenGraph. It will automatically display the video inside m.me chat window but in mobile iOS app, currently it redirects to youtube page:</p>

```<code>curl -X POST -H "Content-Type: application/json" -d '{
  "recipient":{
    "id":"USER_ID"
  },
  "message":{
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"open_graph",
        "elements":[
           {
            "url":"https://www.youtube.com/watch?v=y9A1MEbgLyA"
          }
        ]
      }
    }
  }
}' "https://graph.facebook.com/v2.6/me/messages?access_token=$TOKEN"
</code>```

Body:
You can also send by OpenGraph. It will automatically display the video inside m.me chat window but in mobile iOS app, currently it redirects to youtube page:

curl -X POST -H "Content-Type: application/json" -d '{
  "recipient":{
    "id":"USER_ID"
  },
  "message":{
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"open_graph",
        "elements":[
           {
            "url":"https://www.youtube.com/watch?v=y9A1MEbgLyA"
          }
        ]
      }
    }
  }
}' "https://graph.facebook.com/v2.6/me/messages?access_token=$TOKEN"


问:
Why SIGKILL is not handled by my signal handler and sometime leads to account logout
I wrote the following code with the following intention:
The child sends SIGKILL signal to the parent and then the parent will handle it using the handler. The handler just increment the counter.

```<code>int counter = 0;

void handler(int sig) {
  counter++;
  sleep(1); /* Do some work in the handler */
  return;
}

int main() {
  int i;

  //signal(SIGUSR2, handler);
  signal(SIGKILL, handler);

  if (fork() == 0) {  /* Child */
    for (i = 0; i < 5; i++) {
      //kill(getppid(), SIGUSR2);
      kill(getppid(), SIGKILL);
      printf("sent SIGKILL to parent %d\n", getppid());
    }
    exit(0);
  }

  wait(NULL);
  printf("counter=%d\n", counter);
  exit(0);
}
</code>```

However, the first kind of output I get is:

```<code>sent SIGKILL to parent 8371
sent SIGKILL to parent 8371
sent SIGKILL to parent 8371
sent SIGKILL to parent 8371
sent SIGKILL to parent 8371
Killed
</code>```

Apparently, the SIGKILL kills the parent process. Why does this happen since my handler does not kill the parent?

Another non-deterministic, but very high probability event (~50%) is that on my ubuntu 14.04 64-bit machine. If I execute this code, I will get automatically logout from the account. Why would this happen?

答:
Have your read the manual of signal() ?

First:

The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead. See Portability below.

Second:

The signals SIGKILL and SIGSTOP cannot be caught or ignored.

Body:
I wrote the following code with the following intention:
The child sends SIGKILL signal to the parent and then the parent will handle it using the handler. The handler just increment the counter.

int counter = 0;

void handler(int sig) {
  counter++;
  sleep(1); /* Do some work in the handler */
  return;
}

int main() {
  int i;

  //signal(SIGUSR2, handler);
  signal(SIGKILL, handler);

  if (fork() == 0) {  /* Child */
    for (i = 0; i < 5; i++) {
      //kill(getppid(), SIGUSR2);
      kill(getppid(), SIGKILL);
      printf("sent SIGKILL to parent %d\n", getppid());
    }
    exit(0);
  }

  wait(NULL);
  printf("counter=%d\n", counter);
  exit(0);
}

However, the first kind of output I get is:

sent SIGKILL to parent 8371
sent SIGKILL to parent 8371
sent SIGKILL to parent 8371
sent SIGKILL to parent 8371
sent SIGKILL to parent 8371
Killed

Apparently, the SIGKILL kills the parent process. Why does this happen since my handler does not kill the parent?

Another non-deterministic, but very high probability event (~50%) is that on my ubuntu 14.04 64-bit machine. If I execute this code, I will get automatically logout from the account. Why would this happen?