问:
Conversion to_datetime error, unrecognized value type
I have a flights.csv Database of flights taking off and landing on a particular airport and times associated with each flight step, i.e. Departure, Wheels off the ground, Wheels on the ground, Arrival, Actual Arrival and Departure, etc.

Now I want to convert the times given in the database in the form of floats in 24hr format
For eg: 13:45 is 1345.0
00:02 is 0002.0

Two of these columns (Scheduled_departure and Scheduled arrival) are in integers, so it's very easy for me to convert them into time by:

flights['SCHEDULED_DEPARTURE'] = flights['SCHEDULED_DEPARTURE'].apply(lambda x: '{0:0>4}'.format(x))

(To add zeroes before the time number)

flights['SCHEDULED_DEPARTURE'] = pd.to_datetime(flights['SCHEDULED_DEPARTURE'],format= '%H%M').dt.time

(For actual conversion`

But since the other columns are in floats, I cannot directly use astype() since it creates an error for the decimal.

So I tried to bypass my way by:

pd.to_numeric(flights.DEPARTURE_TIME, downcast = 'integer')

(To remove the decimals)

flights.DEPARTURE_TIME = flights.DEPARTURE_TIME.astype(dtype='int32')

(For redundancy for the next step)

flights['DEPARTURE_TIME'] = flights['DEPARTURE_TIME'].apply(lambda x: '{0:0>4}'.format(x))

(To add zeroes before the number)

flights['DEPARTURE_TIME'] = pd.to_datetime(flights['DEPARTURE_TIME'],format= '%H%M').dt.time

(For actual time conversion)

But after this step, it outputs an error:

```<code>    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    ~\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in _convert_listlike_datetimes(arg, box, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
        290             try:
    --> 291                 values, tz = conversion.datetime_to_datetime64(arg)
        292                 return DatetimeIndex._simple_new(values, name=name, tz=tz)

    pandas/_libs/tslibs/conversion.pyx in
    pandas._libs.tslibs.conversion.datetime_to_datetime64()

    TypeError: Unrecognized value type: <class 'str'>

    During handling of the above exception, another exception occurred:

    ValueError                                Traceback (most recent call last)
    <ipython-input-23-a3defb9ecd52> in <module>
    ----> 1 flights['DEPARTURE_TIME'] =
    pd.to_datetime(flights['DEPARTURE_TIME'],format= '%H%M').dt.time

    ~\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in
    to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact,
    unit, infer_datetime_format, origin, cache)
     590         else:
     591             from pandas import Series
 --> 592             values = convert_listlike(arg._values, True, format)
     593             result = Series(values, index=arg.index, name=arg.name)
     594     elif isinstance(arg, (ABCDataFrame, compat.MutableMapping)):

    ~\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in
    _convert_listlike_datetimes(arg, box, format, name, tz, unit, errors,
    infer_datetime_format, dayfirst, yearfirst, exact)
         292                 return DatetimeIndex._simple_new(values, name=name, tz=tz)
         293             except (ValueError, TypeError):
     --> 294                 raise e
         295
         296     if result is None:

    ~\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in
    _convert_listlike_datetimes(arg, box, format, name, tz, unit, errors,
    infer_datetime_format, dayfirst, yearfirst, exact)
        259                 try:
        260                     result, timezones = array_strptime(
    --> 261                         arg, format, exact=exact, errors=errors)
        262                     if '%Z' in format or '%z' in format:
        263                         return _return_parsed_timezone_results(

     pandas/_libs/tslibs/strptime.pyx in
     pandas._libs.tslibs.strptime.array_strptime()

     ValueError: unconverted data remains: 0
</code>```

Help me convert those float numbers to time.

I cannot convert the integer directly as the datetime needs a proper format, that is including the zeroes.

The expected version of DEPARTURE_TIME looks like this:

0    08:00:00
1    08:30:00
2    19:10:00
3    15:15:00
4    14:27:00
Name: SCHEDULED_DEPARTURE, dtype: object

答:
Instead of a "true" input file, I used the following string:

```<code>data="""xx,DEPARTURE_TIME
f1,0800.0
f2,0830.0
f3,1910.0
f4,1515.0
f5,1427.0"""
</code>```

so the input is limited to DEPARTURE_TIME and xx representing other columns.

As the conversion function I defined:

```<code>def cnv(src):
    return f'{src[0:2]}:{src[2:4]}:00'
</code>```

It will be used to convert DEPARTURE_TIME column.

The src parameter is a string - a part of input row concerning the
respective column. The returned value is: first 2 chars, next 2 chars
and 00, with : between them.

And to read the source CSV I used:

```<code>df = pd.read_csv(pd.compat.StringIO(data),\
    converters={'DEPARTURE_TIME': cnv})
</code>```

In your program, read from your input file (instead of StringIO).

For now DEPARTURE_TIME column is of string type.

But if for any reason you want to have this column as time,
you can do another conversion:

```<code>df.DEPARTURE_TIME = pd.to_datetime(
    df.DEPARTURE_TIME, format= '%H:%M:%S' ).dt.time
</code>```

When you print(df), both before and after the above instruction
you will get just the same output:

```<code>   xx DEPARTURE_TIME
0  f1       08:00:00
1  f2       08:30:00
2  f3       19:10:00
3  f4       15:15:00
4  f5       14:27:00
</code>```

But if you run type(df.iloc[0,1]), you will see that after conversion the type
is datetime.time (before it was str).

On the other hand, if you run df.info() you will see that both before and after
the last conversion the type of DEPARTURE_TIME column is object.

The same approach you can use to other input columns formatted as floats.

Body:
I have a flights.csv Database of flights taking off and landing on a particular airport and times associated with each flight step, i.e. Departure, Wheels off the ground, Wheels on the ground, Arrival, Actual Arrival and Departure, etc.

Now I want to convert the times given in the database in the form of floats in 24hr format
For eg: 13:45 is 1345.0
00:02 is 0002.0

Two of these columns (Scheduled_departure and Scheduled arrival) are in integers, so it's very easy for me to convert them into time by:

flights['SCHEDULED_DEPARTURE'] = flights['SCHEDULED_DEPARTURE'].apply(lambda x: '{0:0>4}'.format(x))

(To add zeroes before the time number)

flights['SCHEDULED_DEPARTURE'] = pd.to_datetime(flights['SCHEDULED_DEPARTURE'],format= '%H%M').dt.time

(For actual conversion`

But since the other columns are in floats, I cannot directly use astype() since it creates an error for the decimal.

So I tried to bypass my way by:

pd.to_numeric(flights.DEPARTURE_TIME, downcast = 'integer')

(To remove the decimals)

flights.DEPARTURE_TIME = flights.DEPARTURE_TIME.astype(dtype='int32')

(For redundancy for the next step)

flights['DEPARTURE_TIME'] = flights['DEPARTURE_TIME'].apply(lambda x: '{0:0>4}'.format(x))

(To add zeroes before the number)

flights['DEPARTURE_TIME'] = pd.to_datetime(flights['DEPARTURE_TIME'],format= '%H%M').dt.time

(For actual time conversion)

But after this step, it outputs an error:

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    ~\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in _convert_listlike_datetimes(arg, box, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
        290             try:
    --> 291                 values, tz = conversion.datetime_to_datetime64(arg)
        292                 return DatetimeIndex._simple_new(values, name=name, tz=tz)

    pandas/_libs/tslibs/conversion.pyx in
    pandas._libs.tslibs.conversion.datetime_to_datetime64()

    TypeError: Unrecognized value type: <class 'str'>

    During handling of the above exception, another exception occurred:

    ValueError                                Traceback (most recent call last)
    <ipython-input-23-a3defb9ecd52> in <module>
    ----> 1 flights['DEPARTURE_TIME'] =
    pd.to_datetime(flights['DEPARTURE_TIME'],format= '%H%M').dt.time

    ~\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in
    to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact,
    unit, infer_datetime_format, origin, cache)
     590         else:
     591             from pandas import Series
 --> 592             values = convert_listlike(arg._values, True, format)
     593             result = Series(values, index=arg.index, name=arg.name)
     594     elif isinstance(arg, (ABCDataFrame, compat.MutableMapping)):

    ~\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in
    _convert_listlike_datetimes(arg, box, format, name, tz, unit, errors,
    infer_datetime_format, dayfirst, yearfirst, exact)
         292                 return DatetimeIndex._simple_new(values, name=name, tz=tz)
         293             except (ValueError, TypeError):
     --> 294                 raise e
         295
         296     if result is None:

    ~\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in
    _convert_listlike_datetimes(arg, box, format, name, tz, unit, errors,
    infer_datetime_format, dayfirst, yearfirst, exact)
        259                 try:
        260                     result, timezones = array_strptime(
    --> 261                         arg, format, exact=exact, errors=errors)
        262                     if '%Z' in format or '%z' in format:
        263                         return _return_parsed_timezone_results(

     pandas/_libs/tslibs/strptime.pyx in
     pandas._libs.tslibs.strptime.array_strptime()

     ValueError: unconverted data remains: 0

Help me convert those float numbers to time.

I cannot convert the integer directly as the datetime needs a proper format, that is including the zeroes.

The expected version of DEPARTURE_TIME looks like this:

0    08:00:00
1    08:30:00
2    19:10:00
3    15:15:00
4    14:27:00
Name: SCHEDULED_DEPARTURE, dtype: object

Body:
Instead of a "true" input file, I used the following string:

data="""xx,DEPARTURE_TIME
f1,0800.0
f2,0830.0
f3,1910.0
f4,1515.0
f5,1427.0"""

so the input is limited to DEPARTURE_TIME and xx representing other columns.

As the conversion function I defined:

def cnv(src):
    return f'{src[0:2]}:{src[2:4]}:00'

It will be used to convert DEPARTURE_TIME column.

The src parameter is a string - a part of input row concerning the
respective column. The returned value is: first 2 chars, next 2 chars
and 00, with : between them.

And to read the source CSV I used:

df = pd.read_csv(pd.compat.StringIO(data),\
    converters={'DEPARTURE_TIME': cnv})

In your program, read from your input file (instead of StringIO).

For now DEPARTURE_TIME column is of string type.

But if for any reason you want to have this column as time,
you can do another conversion:

df.DEPARTURE_TIME = pd.to_datetime(
    df.DEPARTURE_TIME, format= '%H:%M:%S' ).dt.time

When you print(df), both before and after the above instruction
you will get just the same output:

   xx DEPARTURE_TIME
0  f1       08:00:00
1  f2       08:30:00
2  f3       19:10:00
3  f4       15:15:00
4  f5       14:27:00

But if you run type(df.iloc[0,1]), you will see that after conversion the type
is datetime.time (before it was str).

On the other hand, if you run df.info() you will see that both before and after
the last conversion the type of DEPARTURE_TIME column is object.

The same approach you can use to other input columns formatted as floats.


来源: stackexchange

问:
How can I open a website in my web browser using Python?
I want to open a website in my local computer's web browser (Chrome or Internet Explorer) using Python.

```<code>open("http://google.co.kr") # something like this
</code>```

Is there a module that can do this for me?

答:
If you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:</p>

```<code>from threading import Timer
from time import sleep

import subprocess
import platform

# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser
# Hint 2: fullscreen will only work if chrome is not already running

platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}

browser = None
def open_browser():
    global browser

    platform_name = platform.system()

    if platform_name in  platform_browser:
        browser = subprocess.Popen(platform_browser[platform_name])
    else:
        print(":-(")

Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch

sleep(20) # start e.g. your python web server here instead

browser.kill()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to open a website in my local computer's web browser (Chrome or Internet Explorer) using Python.

open("http://google.co.kr") # something like this

Is there a module that can do this for me?

Body:
If you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:

from threading import Timer
from time import sleep

import subprocess
import platform

# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser
# Hint 2: fullscreen will only work if chrome is not already running

platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}

browser = None
def open_browser():
    global browser

    platform_name = platform.system()

    if platform_name in  platform_browser:
        browser = subprocess.Popen(platform_browser[platform_name])
    else:
        print(":-(")

Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch

sleep(20) # start e.g. your python web server here instead

browser.kill()

ContentLicense: CC BY-SA 4.0


问:
Doing context:component-scan programatic way?
I'm mixed using AnnotationConfigApplicationContext and ClasspathXmlApplicationContext currently, and make AnnotationConfigApplicationContext as the parent context. But I found that beans defined in AnnotationConfigApplicationContext doesn't cope well with beans defined in ClasspathXmlApplicationContext. So I'd like to drop ClasspathXmlApplicationContext anyway, and make my application use AnnotationConfigApplicationContext only.

The problem is, I don't know how to replace <context:component-scan> totally. I can easily do a package scan using AnnotationConfigApplicationContext.scan(...), but there seems no way to add include/exclude pattern in AnnotationConfigApplicationContext.

Any idea?

答:
It doesn't look like the class AnnotationConfigApplicationContext provides exclusion/inclusion filters out-of-the-box. Internally the class uses an instance of ClassPathBeanDefinitionScanner to scan for annotations which provides the methods addExcludeFilter and addIncludeFilter. Unfortunately, the field is private and doesn't have a getter method so you can't just write an implementation that extends AnnotationConfigApplicationContext and add include and exclude methods. Instead you'll probably have to copy the code from AnnotationConfigApplicationContext and add the missing methods:

```<code>public void addExcludeFilter(TypeFilter excludeFilter)
{
    this.scanner.addExcludeFilter(excludeFilter);
}

public void addIncludeFilter(TypeFilter includeFilter)
{
    this.scanner.addIncludeFilter(includeFilter);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It doesn't look like the class AnnotationConfigApplicationContext provides exclusion/inclusion filters out-of-the-box. Internally the class uses an instance of ClassPathBeanDefinitionScanner to scan for annotations which provides the methods addExcludeFilter and addIncludeFilter. Unfortunately, the field is private and doesn't have a getter method so you can't just write an implementation that extends AnnotationConfigApplicationContext and add include and exclude methods. Instead you'll probably have to copy the code from AnnotationConfigApplicationContext and add the missing methods:

public void addExcludeFilter(TypeFilter excludeFilter)
{
    this.scanner.addExcludeFilter(excludeFilter);
}

public void addIncludeFilter(TypeFilter includeFilter)
{
    this.scanner.addIncludeFilter(includeFilter);
}


问:
What are the best practices to returns models(DTO) from a method?
While I was going through Nop Commerce Source Code,they have created Factories which converts Domain model in to View models.

But I see some methods of Factories returns IList,some returns IEnumerable So I got bit confused why this inconsistency and Why not return IEnumerable.

In the older versions of Nop Commerce,I have seen that they always use to return IEnumerable<Model> but now in the latest versions most of the view models are returned in IList.I know with IList its good to work with abstraction instead of concrete type(List) but then IEnumerable is much better because everything derives from it.

Now this makes me wonder so as to what data structure to consider while returning model from a method?

Is it always have to be IEnumerable because everything derives from this interface and most importantly always works with abstraction?

Code :

```<code>public partial interface ICountryModelFactory
{
    IList<StateProvinceModel> GetStatesByCountryId(string countryId, bool addSelectStateItem);
}

public partial interface IBlogModelFactory
{
   List<BlogPostYearModel> PrepareBlogPostYearModel(); // Now why Concrete List here?
}

public partial interface IProductModelFactory
{
  IEnumerable<ProductOverviewModel> PrepareProductOverviewModels(IEnumerable<Product> products,
            bool preparePriceModel = true, bool preparePictureModel = true,
            int? productThumbPictureSize = null, bool prepareSpecificationAttributes = false,
            bool forceRedirectionAfterAddingToCart = false);

  IList<ProductSpecificationModel> PrepareProductSpecificationModel(Product product);
}
</code>```

I am bit confused here so as to what is the best practices while converting domain model to view model and what data structure is the best to use when returning view model?

Is it always better to return IEnumerable<MyModel> from a method like below :

```<code>public IEnumerable<MyModel> ReturnMyModel(Product product){ }
</code>```

Note : This is not a question asking difference between IEnumerable vs IList

Nop Commerce Version = 4.20

答:
IEnumerable is much better because everything derives from it.

I don't think that it is the way to think about it. It is neither better nor worse. It is different and serves a different purpose.

IEnumerable

Some resultsets are infinite (or just too big to practically fit into memory). In such cases, yielding the records one by one means that they can be processed without ever having to realise the entire set in memory.

Some resultsets are held in something that is not actually a list. Maybe it is a queue or a dictionary key or a hashset or something else. Returning as IEnumerable means that the method doesn't need to create a new list object, fill it up with data just to return the client which may never have intended on doing any more than a foreach over it.

Sometimes you may have the data in a list, but don't want the caller to be modifying that list. If the data is immutable, you can just return your list as an IEnumerable and know they cannot add/remove from your source list

IList

Sometimes the method required you to build the list, so why not give the caller the capability to (efficiently) get the count, access an object by index, add, remove or sort elements without cloning it to yet another a new object

I prefer to think of it in terms of returning the most useful thing that you can provide to the caller. If I return you an IList, you can assign it to an IEnumerable variable, or use it as the value to an IEnumerable parameter of a subsequent method.

So if I have the data in a List<T> already, and I am happy for you to mutate that list, then I will return it as an IList<T>. But if I have the data in a Queue<T>, I am not going to go out of my way to do a .ToList() call and return you an IList of it. If you want a List, you can do that yourself, but if you were just iterating it then my .ToList() "helpful" call just wasted a whole bunch of clock cycles and RAM.

Body:
While I was going through Nop Commerce Source Code,they have created Factories which converts Domain model in to View models.

But I see some methods of Factories returns IList,some returns IEnumerable So I got bit confused why this inconsistency and Why not return IEnumerable.

In the older versions of Nop Commerce,I have seen that they always use to return IEnumerable<Model> but now in the latest versions most of the view models are returned in IList.I know with IList its good to work with abstraction instead of concrete type(List) but then IEnumerable is much better because everything derives from it.

Now this makes me wonder so as to what data structure to consider while returning model from a method?

Is it always have to be IEnumerable because everything derives from this interface and most importantly always works with abstraction?

Code :

public partial interface ICountryModelFactory
{
    IList<StateProvinceModel> GetStatesByCountryId(string countryId, bool addSelectStateItem);
}

public partial interface IBlogModelFactory
{
   List<BlogPostYearModel> PrepareBlogPostYearModel(); // Now why Concrete List here?
}

public partial interface IProductModelFactory
{
  IEnumerable<ProductOverviewModel> PrepareProductOverviewModels(IEnumerable<Product> products,
            bool preparePriceModel = true, bool preparePictureModel = true,
            int? productThumbPictureSize = null, bool prepareSpecificationAttributes = false,
            bool forceRedirectionAfterAddingToCart = false);

  IList<ProductSpecificationModel> PrepareProductSpecificationModel(Product product);
}

I am bit confused here so as to what is the best practices while converting domain model to view model and what data structure is the best to use when returning view model?

Is it always better to return IEnumerable<MyModel> from a method like below :

public IEnumerable<MyModel> ReturnMyModel(Product product){ }

Note : This is not a question asking difference between IEnumerable vs IList

Nop Commerce Version = 4.20


问:
In SQL, why do we need a primary key if we can use NOT NULL and UNIQUE constraints in place of a primary key?
A primary key in SQL is a combination of both NOT NULL and UNIQUE constraints, with the only difference that only one primary key constraint can exist within a table.

Why can't we only manage with the NOT NULL and UNIQUE constraints? Even they both do the same thing.

答:
You pointed a differences between a primary key and unique constraints, but this is not the only differences between them.

The key differences between a primary key and a unique key is - a clustered index is automatically created when a primary key is defined whereas a unique key generates the non-clustered index. You can do some Google search to get an idea on a clustered and non-clustered index.

Another differences is - a primary key is a unique field on a table, but it is special in the sense that the table considers that row as its key. This means that other tables can use this field to create foreign key relationships to themselves. A unique constraint simply means that a particular field must be unique.


问:
elasticdump import index setting not working
I am able to export index setting using below command

```<code>elasticdump --input=http://localhost:9200/tempIndex --output=/Users/Desktop/indexFile --type=settings
</code>```

but when i tried to import the same setting it is not updating the index setting

The command i used for import is :

```<code>elasticdump --input=/Users/Desktop/indexFile --output=http://localhost:9200/tempIndex --type=settings
</code>```

output of command :

```<code> 07:06:33 GMT | starting dump
 07:06:33 GMT | got 1 objects from source file (offset: 0)
 07:06:34 GMT | sent 1 objects to destination elasticsearch, wrote 0
 07:06:34 GMT | got 0 objects from source file (offset: 1)
 07:06:34 GMT | Total Writes: 0
 07:06:34 GMT | dump complete
</code>```

Below is the settings of my index exported using elasticdump settings option

```<code>{
    "tempIndex":{
        "settings":{
            "index":{
                "mapping":{
                    "nested_fields":{
                        "limit":"2000"
                    },
                    "total_fields":{
                        "limit":"2000"
                    }
                },
                "analysis":{
                    "normalizer":{
                        "lowercase_normalizer":{
                            "filter":[
                                "lowercase"
                            ],
                            "type":"custom",
                            "char_filter":[

                            ]
                        }
                    }
                },
                "number_of_shards":"5",
                "number_of_replicas":"1"
            }
        }
    }
}
</code>```

答:
I believe that elasticdump is hiding an error from elasticsearch here. If the index tempIndex already exists, then you cannot update the number_of_shards and analysis settings. These settings are not dynamic. Try running :

```<code>POST /tempIndex/_settings
{
    "tempIndex":{
        "settings":{
            "index":{
                "mapping":{
                    "nested_fields":{
                        "limit":"2000"
                    },
                    "total_fields":{
                        "limit":"2000"
                    }
                },
                "analysis":{
                    "normalizer":{
                        "lowercase_normalizer":{
                            "filter":[
                                "lowercase"
                            ],
                            "type":"custom",
                            "char_filter":[

                            ]
                        }
                    }
                },
                "number_of_shards":"5",
                "number_of_replicas":"1"
            }
        }
    }
}
</code>```

You are likely to get an error from elasticsearch. Since the request is invalid, no settings will be updated.

You can either remove the index tempIndex if that is possible or remove the settings that are not dynamic from indexFile.

Body:
I am able to export index setting using below command

elasticdump --input=http://localhost:9200/tempIndex --output=/Users/Desktop/indexFile --type=settings

but when i tried to import the same setting it is not updating the index setting

The command i used for import is :

elasticdump --input=/Users/Desktop/indexFile --output=http://localhost:9200/tempIndex --type=settings

output of command :

 07:06:33 GMT | starting dump
 07:06:33 GMT | got 1 objects from source file (offset: 0)
 07:06:34 GMT | sent 1 objects to destination elasticsearch, wrote 0
 07:06:34 GMT | got 0 objects from source file (offset: 1)
 07:06:34 GMT | Total Writes: 0
 07:06:34 GMT | dump complete

Below is the settings of my index exported using elasticdump settings option

{
    "tempIndex":{
        "settings":{
            "index":{
                "mapping":{
                    "nested_fields":{
                        "limit":"2000"
                    },
                    "total_fields":{
                        "limit":"2000"
                    }
                },
                "analysis":{
                    "normalizer":{
                        "lowercase_normalizer":{
                            "filter":[
                                "lowercase"
                            ],
                            "type":"custom",
                            "char_filter":[

                            ]
                        }
                    }
                },
                "number_of_shards":"5",
                "number_of_replicas":"1"
            }
        }
    }
}

Body:
I believe that elasticdump is hiding an error from elasticsearch here. If the index tempIndex already exists, then you cannot update the number_of_shards and analysis settings. These settings are not dynamic. Try running :

POST /tempIndex/_settings
{
    "tempIndex":{
        "settings":{
            "index":{
                "mapping":{
                    "nested_fields":{
                        "limit":"2000"
                    },
                    "total_fields":{
                        "limit":"2000"
                    }
                },
                "analysis":{
                    "normalizer":{
                        "lowercase_normalizer":{
                            "filter":[
                                "lowercase"
                            ],
                            "type":"custom",
                            "char_filter":[

                            ]
                        }
                    }
                },
                "number_of_shards":"5",
                "number_of_replicas":"1"
            }
        }
    }
}

You are likely to get an error from elasticsearch. Since the request is invalid, no settings will be updated.

You can either remove the index tempIndex if that is possible or remove the settings that are not dynamic from indexFile.


问:
How to restart jenkins running on the windows machine
Am running jenkins on my windows 10 machine through jenkins.war by running the below command from cmd

java -jar jenkins.war --httpPost=8047

when i try to restart jenkins through UI, am not able to do it getting the exception "Jenkins cannot restart itself as currently configured."

This is the commands i have tried so far by restarting.

http://localhost:8090/restart and i tried with one more url as well

http://localhost:8090/safeRestart

Kindly advise if am missing anything here.

答:
Please change your port URL. You have started jenkins on 8047 and you are using port 8090.

You can use http://localhost:8047/restart


问:
Django: Get first Choice Value from tuple

Models.py

```<code>class Person(models.Model):
    name = models.CharField(max_length=200)
    CATEGORY_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES)
    to_be_listed = models.BooleanField(default=True)
</code>```

views.py

```<code>def index(request,get_gender):
    all_details = {
        'list': Person.objects.filter(gender=get_gender).order_by('-id'),
    }

    return render(request,'index/person.html',context=all_details)
</code>```

On index, I'm getting M or F as a get_gender parameter but when I get it from a model I'm getting second value from the tuple (male or female) but I need to get first value(m or f).

How to get m or f from the tuple?

答:
In your template html:

From your person object:

To get 'M' or 'F':

```<code>{{person.gender}}
</code>```

and to get 'Male' or 'Female':

```<code>{{person.get_gender_display}}
</code>```

Body:
Models.py

class Person(models.Model):
    name = models.CharField(max_length=200)
    CATEGORY_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES)
    to_be_listed = models.BooleanField(default=True)

views.py

def index(request,get_gender):
    all_details = {
        'list': Person.objects.filter(gender=get_gender).order_by('-id'),
    }

    return render(request,'index/person.html',context=all_details)

On index, I'm getting M or F as a get_gender parameter but when I get it from a model I'm getting second value from the tuple (male or female) but I need to get first value(m or f).

How to get m or f from the tuple?

Body:
In your template html:

From your person object:

To get 'M' or 'F':

{{person.gender}}

and to get 'Male' or 'Female':

{{person.get_gender_display}}


问:
Conversion of datetime to varchar not working when passing through variables
I came across this weird problem where I need to convert datetime to varchar.

I ran these 2 queries:

```<code>declare @d datetime
set @d ='31/12/2019 16:12:25.317'

select @d

select convert(varchar(50), '31/12/2019 16:12:25.317', 101)
</code>```

The first query throws an error:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

The second query works fine.

答:
The failure is happening at the first step, because @d is declared as a datetime rather than a string (unless your internationalization settings allow it).  I think you intend:

```<code>declare @d varchar(255)
set @d = '31/12/2019 16:12:25.317';

select convert(date, @d, 103)
</code>```

In general, when setting datetime constants, you should use:

```<code>declare @d datetime;
set @d = '2019-12-31T16:12:25.317';
</code>```

This is SQL Server's location-independent method of defining a date/time.  Caveat:  Although this is the correct method, I routinely leave out the T to be compatible with other databases (and it still works always or almost always).

Body:
I came across this weird problem where I need to convert datetime to varchar.

I ran these 2 queries:

declare @d datetime
set @d ='31/12/2019 16:12:25.317'

select @d

select convert(varchar(50), '31/12/2019 16:12:25.317', 101)

The first query throws an error:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

The second query works fine.

Body:
The failure is happening at the first step, because @d is declared as a datetime rather than a string (unless your internationalization settings allow it).  I think you intend:

declare @d varchar(255)
set @d = '31/12/2019 16:12:25.317';

select convert(date, @d, 103)

In general, when setting datetime constants, you should use:

declare @d datetime;
set @d = '2019-12-31T16:12:25.317';

This is SQL Server's location-independent method of defining a date/time.  Caveat:  Although this is the correct method, I routinely leave out the T to be compatible with other databases (and it still works always or almost always).


问:
Rails 5.2.3 / Heroku - Why is it not possible to run postgres in production mode with squlite3 in development mode?
I'm using Rails 5.2.3 and I'm getting an application error when I try to view my production app on Heroku pipeline & the following errors when:

I run heroku logs I get: heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"

I run heroku run rails console I get: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. (LoadError)

I run heroku run rails db:migrate I get: LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

I want to use sqlite3 for development and postgres for production, so why do I need to make the sqlite3 gemfile available in production mode?

Here's my gemfile:

```<code>group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end
</code>```

Here's my database.yml:

```<code>default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
</code>```

答:
Your production setting in database.yml is inheriting the development settings - you want to change it to

```<code>production:
  adapter: postgresql
  url: <%= ENV['DATABASE_URL'] %>
</code>```

The url: <%= ENV['DATABASE_URL'] %> is applicable if you're using Heroku. If not you can consider the credential specification format here.

Body:
I'm using Rails 5.2.3 and I'm getting an application error when I try to view my production app on Heroku pipeline & the following errors when:

I run heroku logs I get: heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"

I run heroku run rails console I get: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. (LoadError)

I run heroku run rails db:migrate I get: LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

I want to use sqlite3 for development and postgres for production, so why do I need to make the sqlite3 gemfile available in production mode?

Here's my gemfile:

group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end

Here's my database.yml:

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

Body:
Your production setting in database.yml is inheriting the development settings - you want to change it to

production:
  adapter: postgresql
  url: <%= ENV['DATABASE_URL'] %>

The url: <%= ENV['DATABASE_URL'] %> is applicable if you're using Heroku. If not you can consider the credential specification format here.


问:
What is the JavaScript version of sleep()?
Is there a better way to engineer a sleep in JavaScript than the following pausecomp function (taken from here)?

```<code>function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}
</code>```

This is not a duplicate of Sleep in JavaScript - delay between actions; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

答:
2019 Update using Atomics.wait

It should work in Node.js 9.3 or higher.

I needed a pretty accurate timer in Node.js and it works great for that.

However, it seems like there is extremely limited support in browsers.

let ms = 10000;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);```
</div>
</div>
</p>
<p>Ran a few 10 second timer benchmarks.</p>
<p>With setTimeout I get a error of up to 7000 microseconds (7 ms).</p>
<p>With Atomics, my error seems to stay under 600 microseconds (0.6 ms)</p>
<p><strong>2020 Update: In Summary</strong></p>
<pre class="lang-js prettyprint-override"><code>function sleep(millis){ // Need help of a server-side page
  let netMillis = Math.max(millis-5, 0); // Assuming 5 ms overhead
  let xhr = new XMLHttpRequest();
  xhr.open('GET', '/sleep.jsp?millis=' + netMillis + '&rand=' + Math.random(), false);
  try{
    xhr.send();
  }catch(e){
  }
}

function sleepAsync(millis){ // Use only in async function
  let netMillis = Math.max(millis-1, 0); // Assuming 1 ms overhead
  return new Promise((resolve) => {
    setTimeout(resolve, netMillis);
  });
}
function sleepSync(millis){ // Use only in worker thread, currently Chrome-only
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);
}

function sleepTest(){
  console.time('sleep');
  sleep(1000);
  console.timeEnd('sleep');
}

async function sleepAsyncTest(){
  console.time('sleepAsync');
  await sleepAsync(1000);
  console.timeEnd('sleepAsync');
}

function sleepSyncTest(){
  let source = `${sleepSync.toString()}
    console.time('sleepSync');
    sleepSync(1000);
    console.timeEnd('sleepSync');`;
  let src = 'data:text/javascript,' + encodeURIComponent(source);
  console.log(src);
  var worker = new Worker(src);
}
</code>```

of which the server-side page, e.g. sleep.jsp, looks like:

<%
try{
  Thread.sleep(Long.parseLong(request.getParameter("millis")));
}catch(InterruptedException e){}
%>
```

Body:
Is there a better way to engineer a sleep in JavaScript than the following pausecomp function (taken from here)?

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}

This is not a duplicate of Sleep in JavaScript - delay between actions; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

Body:
2019 Update using Atomics.wait

It should work in Node.js 9.3 or higher.

I needed a pretty accurate timer in Node.js and it works great for that.

However, it seems like there is extremely limited support in browsers.

let ms = 10000;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);

Ran a few 10 second timer benchmarks.

With setTimeout I get a error of up to 7000 microseconds (7 ms).

With Atomics, my error seems to stay under 600 microseconds (0.6 ms)

2020 Update: In Summary

function sleep(millis){ // Need help of a server-side page
  let netMillis = Math.max(millis-5, 0); // Assuming 5 ms overhead
  let xhr = new XMLHttpRequest();
  xhr.open('GET', '/sleep.jsp?millis=' + netMillis + '&rand=' + Math.random(), false);
  try{
    xhr.send();
  }catch(e){
  }
}

function sleepAsync(millis){ // Use only in async function
  let netMillis = Math.max(millis-1, 0); // Assuming 1 ms overhead
  return new Promise((resolve) => {
    setTimeout(resolve, netMillis);
  });
}
function sleepSync(millis){ // Use only in worker thread, currently Chrome-only
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);
}

function sleepTest(){
  console.time('sleep');
  sleep(1000);
  console.timeEnd('sleep');
}

async function sleepAsyncTest(){
  console.time('sleepAsync');
  await sleepAsync(1000);
  console.timeEnd('sleepAsync');
}

function sleepSyncTest(){
  let source = `${sleepSync.toString()}
    console.time('sleepSync');
    sleepSync(1000);
    console.timeEnd('sleepSync');`;
  let src = 'data:text/javascript,' + encodeURIComponent(source);
  console.log(src);
  var worker = new Worker(src);
}

of which the server-side page, e.g. sleep.jsp, looks like:

<%
try{
  Thread.sleep(Long.parseLong(request.getParameter("millis")));
}catch(InterruptedException e){}
%>


问:
Container borderRadius vs ClipRRect borderRadius
Both Container and ClipRRect has borderRadius property, but sometimes Container fail to work. Here is the example.

Not working

```<code>Container(
  decoration: BoxDecoration(borderRadius: BorderRadius.circular(100)),
  child: RaisedButton(onPressed: null),
),
</code>```

Working

```<code>ClipRRect(
  borderRadius: BorderRadius.circular(100),
  child: RaisedButton(onPressed: null),
),
</code>```

I want to know why Container fails sometimes and where else it can fail?

答:
ClipRRect inserts a render object that modifies the render tree of the widgets in its subtree.

Subtree of ClipRRect will be affected and the corners will be clipped.

Hit tests for the widget itself as well as for its children will be performed with the clip path respected. Meaning that gesture recognizers (/ buttons) within the widget will not receive taps outside of the clipped area.

ClipRRect is relatively expensive, but is suitable to clip an image or other complex graphic elements that do not provide rounded corners setting on their own.

Container on the other hand, when used with BoxDecoration and borderRadius / shape set, simply draws a box with rounded corners on its background.

Subtree of such Container will not be affected by the background decoration of their parent widget.

Hit tests for the Container will be performed with borderRadius respected, providing "truly rounded" UI-wise tap experience for the container itself. However, children gesture recognizers are not exposed to the decoration settings - hence, gestures will be received as usual even beyond the "clipped" area.

Decorated container with shape or borderRadius set is preferable as it is relatively less expensive to draw and maintain, given that the clipping mask for the subtree is not needed.

In the end, I do have to note that neither way described here is the best way in your case.

To create a RaisedButton with rounded corners use RoundedRectangleBorder for the shape property of your button.

e.g.

RaisedButton(
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(100))
  // ...,
)
```

Body:
Both Container and ClipRRect has borderRadius property, but sometimes Container fail to work. Here is the example.

Not working

Container(
  decoration: BoxDecoration(borderRadius: BorderRadius.circular(100)),
  child: RaisedButton(onPressed: null),
),

Working

ClipRRect(
  borderRadius: BorderRadius.circular(100),
  child: RaisedButton(onPressed: null),
),

I want to know why Container fails sometimes and where else it can fail?


问:
Where to put navigation-related code in angular app?
Currently I have in my AuthGuard constructor a subsription to redux state change below. It will just redirect to original page requested after login. This is not correct place but i don't know where it should be:

auth.guard.ts:

```<code>this.subscription = this.ngRedux.select<ILoginState>('login')
  .subscribe(newState => {
    if (newState.isLoggedIn) {
        let redirectUrl : string = ngRedux.getState().window.windowData.redirectUrl;
        if (!redirectUrl) {
          redirectUrl = '/map/' + this.tabService.sessionId;
        }
        this.router.navigate([redirectUrl]);
      }
  });
</code>```

I have also other navigation related stuff like below. This is currently in a service that is supposed to manage different browser windows and state syncing across them:

```<code>/* track url changes and change redux state */
this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    this.ngRedux.dispatch(this.windowActions.setOutletActiveRoute(event.urlAfterRedirects));
  }
});
</code>```

Both could be in new navigation-service.ts in core or in app.component.ts. I read an article about not subscribing in angular service so maybe not service. Also putting everything in app.component sounds bad idea. I would like to put all navigation related stuff to it's own place to separate concerns. What would be recommended way?

答:
Create a app.navigator.ts file and put your navigation logic there, this is not a service or component just a ts file.

app.navigator.ts

```<code>......

/* track url changes and change redux state */
this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    this.ngRedux.dispatch(this.windowActions.setOutletActiveRoute(event.urlAfterRedirects));
  }
});

......
</code>```

Body:
Currently I have in my AuthGuard constructor a subsription to redux state change below. It will just redirect to original page requested after login. This is not correct place but i don't know where it should be:

auth.guard.ts:

this.subscription = this.ngRedux.select<ILoginState>('login')
  .subscribe(newState => {
    if (newState.isLoggedIn) {
        let redirectUrl : string = ngRedux.getState().window.windowData.redirectUrl;
        if (!redirectUrl) {
          redirectUrl = '/map/' + this.tabService.sessionId;
        }
        this.router.navigate([redirectUrl]);
      }
  });

I have also other navigation related stuff like below. This is currently in a service that is supposed to manage different browser windows and state syncing across them:

/* track url changes and change redux state */
this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    this.ngRedux.dispatch(this.windowActions.setOutletActiveRoute(event.urlAfterRedirects));
  }
});

Both could be in new navigation-service.ts in core or in app.component.ts. I read an article about not subscribing in angular service so maybe not service. Also putting everything in app.component sounds bad idea. I would like to put all navigation related stuff to it's own place to separate concerns. What would be recommended way?

Body:
Create a app.navigator.ts file and put your navigation logic there, this is not a service or component just a ts file.

app.navigator.ts

......

/* track url changes and change redux state */
this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    this.ngRedux.dispatch(this.windowActions.setOutletActiveRoute(event.urlAfterRedirects));
  }
});

......


问:
UITableView Cell should not scroll horizontally swift iOS
I have a table view which has card kind of cells as shown in picture.
I have set the content Inset so that I can get the cells with 20px spacing in left,right and top.

    tableVw.contentInset = UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20)

Its displaying as I expected but the problem is, cells can be moved in all direction. But when I move it to right/top, it automatically comes back to original position. But when I move to left it just goes inside and don't scroll back to original position as shown in picture.

I don't want the cells to move at all or I want the cells to come back to centre if its dragged anywhere also. Please help!

答: Dont provide uiedgeinsets to tableview instead add a view in uitableview cell that cover up the whole cell and add another uiview inside that view and give constraint from top bottom leading trailing equals to 8 or whatever you want then the cell wont move anyways and u tableview cells will look like it has edgeinsets.</p>


问:
How do I merge rows while also moving columns to the merged row?
Hello everyone and thanks for reading my question.

I have the following in R:

```<code>**type, status, count**
human, living, 36
human, living, 57
human, dead, 43
mouse, living, 4
mouse, dead 8
</code>```

What I want to do is merge the rows based on 'type' (so 'type' would be exclusive) and then move the contents of 'status' and 'count' to the merged row and add some symbols as shown below:

```<code>**type, status, count**
human, living = "36, 57", dead = "43"
mouse, living = "4", dead = "8"
</code>```

I did manage to merge the rows in R (sort of) but I cannot figure out how to move the status and count to the merged row and lay them out as shown.

I don't have to use R but I thought R was the most suitable way of doing this but I could use anything to get the job done.  Any help would be greatly appreciated.

Many thanks.

Edit: This is the final solution which worked great (thanks loads to gersht):

```<code>rm(list=ls());

library(tidyr)
library(dplyr)

df <- read.table("D:/test.csv", header = TRUE, sep=",")

df <- df %>%
    group_by(type, status) %>%
    mutate(count = paste(count, collapse = ", ")) %>%
    ungroup() %>%
    distinct() %>%
    spread(status, count) %>%
    mutate(dead = paste("dead = ", dead),
           living = paste("living = ", living))

write.table(df, col.names = FALSE)
</code>```

答:
This will return a dataframe with correct values, more or less. You can change column order and column names as needed:

library(tidyr)
library(dplyr)

df %>%
    group_by(type, status) %>%
    mutate(count = paste(count, collapse = ", ")) %>%
    ungroup() %>%
    distinct() %>%
    spread(status, count) %>%
    mutate(dead = paste("dead = ", dead),
           living = paste("living = ", living))

#### OUTPUT ####

# A tibble: 2 x 3
  type  dead       living
  <chr> <chr>      <chr>
1 human dead =  43 living =  36, 57
2 mouse dead =  8  living =  4
```

<p>I've simply grouped by <code>type</code> and <code>status</code> so I can then collapse the values of <code>count</code> into a single string using <code>mutate()</code>. I use <code>ungroup()</code> as good practice, but it isn't strictly necessary.</p>

<p>This creates some duplicates, which I remove with <code>distinct()</code>. I then use the <code>spread()</code> function to move <code>living</code> and <code>dead</code> to their own columns, and then I use <code>mutate</code> again to add strings <code>"living = "</code> and <code>"dead = "</code> to their respective columns.</p>

<h2>data</h2>

<pre class="lang-r prettyprint-override"><code>structure(list(type = c("human", "human", "human", "mouse", "mouse"
), status = c("living", "living", "dead", "living", "dead"),
    count = c(36, 57, 43, 4, 8)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

Body:
Hello everyone and thanks for reading my question.

I have the following in R:

**type, status, count**
human, living, 36
human, living, 57
human, dead, 43
mouse, living, 4
mouse, dead 8

What I want to do is merge the rows based on 'type' (so 'type' would be exclusive) and then move the contents of 'status' and 'count' to the merged row and add some symbols as shown below:

**type, status, count**
human, living = "36, 57", dead = "43"
mouse, living = "4", dead = "8"

I did manage to merge the rows in R (sort of) but I cannot figure out how to move the status and count to the merged row and lay them out as shown.

I don't have to use R but I thought R was the most suitable way of doing this but I could use anything to get the job done.  Any help would be greatly appreciated.

Many thanks.

Edit: This is the final solution which worked great (thanks loads to gersht):

rm(list=ls());

library(tidyr)
library(dplyr)

df <- read.table("D:/test.csv", header = TRUE, sep=",")

df <- df %>%
    group_by(type, status) %>%
    mutate(count = paste(count, collapse = ", ")) %>%
    ungroup() %>%
    distinct() %>%
    spread(status, count) %>%
    mutate(dead = paste("dead = ", dead),
           living = paste("living = ", living))

write.table(df, col.names = FALSE)

Body:
This will return a dataframe with correct values, more or less. You can change column order and column names as needed:

library(tidyr)
library(dplyr)

df %>%
    group_by(type, status) %>%
    mutate(count = paste(count, collapse = ", ")) %>%
    ungroup() %>%
    distinct() %>%
    spread(status, count) %>%
    mutate(dead = paste("dead = ", dead),
           living = paste("living = ", living))

#### OUTPUT ####

# A tibble: 2 x 3
  type  dead       living
  <chr> <chr>      <chr>
1 human dead =  43 living =  36, 57
2 mouse dead =  8  living =  4

I've simply grouped by type and status so I can then collapse the values of count into a single string using mutate(). I use ungroup() as good practice, but it isn't strictly necessary.

This creates some duplicates, which I remove with distinct(). I then use the spread() function to move living and dead to their own columns, and then I use mutate again to add strings "living = " and "dead = " to their respective columns.

data

structure(list(type = c("human", "human", "human", "mouse", "mouse"
), status = c("living", "living", "dead", "living", "dead"),
    count = c(36, 57, 43, 4, 8)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))


问:
Get the first row value of textarea

<form>
  <textarea id="tawktouser" rows="4" class="form-control"></textarea>
  <button type="button" id="add" class="btn green">Add</button>
</form>
```

I can't get the value of textarea in row manner - for example first row is name 2nd email 3rd is phone number - like this
Name : name
Email : abc@gmail.com
Phone : 11111

答:
Try

```<code>  var tawktouser = $("#tawktouser").val().split('\n');
  alert(tawktouser[0])
</code>```

<form>
  <textarea id="tawktouser" rows="4" class="form-control">
name
abc@gmail.com
11111
  </textarea>
  <button type="button" id="add" class="btn green">Add</button>
</form>
```

Title: Get the first row value of textarea

Body:
<form>
  <textarea id="tawktouser" rows="4" class="form-control"></textarea>
  <button type="button" id="add" class="btn green">Add</button>
</form>

I can't get the value of textarea in row manner - for example first row is name 2nd email 3rd is phone number - like this
Name : name
Email : abc@gmail.com
Phone : 11111

Body:
Try

  var tawktouser = $("#tawktouser").val().split('\n');
  alert(tawktouser[0])

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <textarea id="tawktouser" rows="4" class="form-control">
name
abc@gmail.com
11111
  </textarea>
  <button type="button" id="add" class="btn green">Add</button>
</form>
<script>
  $(document).ready(function() {
    $("#add").click(function() {
      var tawktouser = $("#tawktouser").val().split('\n');
      alert(tawktouser[0])
    });
  });
</script>


问:
What does a vertical bar mean in a SQL function call?
I'm learning SQL, and a lot of the examples have | (vertical bar) in function parameters.  What does it represent?  Like this:

```<code>TRUNC(column|expression, decimal places)
</code>```

between column and expression.

答:
A typical method of defining or explaining a grammar is with Backus-Naur Form (BNF) or some variation that is usually much less formal.  In BNF, definitions that can have one of two or more choices often show the valid choices separated by a vertical bar.  The example you show says that a couple of valid uses of TRUNC are:

```<code>TRUNC( somecolumn, 5 )
TRUNC( colA * colB, 8 )
</code>```

Body:
I'm learning SQL, and a lot of the examples have | (vertical bar) in function parameters.  What does it represent?  Like this:

TRUNC(column|expression, decimal places)

between column and expression.

Body:
A typical method of defining or explaining a grammar is with Backus-Naur Form (BNF) or some variation that is usually much less formal.  In BNF, definitions that can have one of two or more choices often show the valid choices separated by a vertical bar.  The example you show says that a couple of valid uses of TRUNC are:

TRUNC( somecolumn, 5 )
TRUNC( colA * colB, 8 )


问:
How to move an overflow'ed element with mouse position in jquery
How can I move an overflowed element with mouse position?
I have a div element 500px width.
I have also another div element inside that 500px div and it's width is 700px.
now I want this second div change position with mouse movement.

When mouse position in the left side in the main div element then the second div element should be shown in left.

When mouse position in the center in the main div element then the second div element should be shown in the center.

When mouse position in the right side in the main div element then the second div element should be shown in right.

See this photo:

.main-wrap {
 height: 200px;
 width: 300px;
 background-color: red;
 overflow: hidden;
 position: relative;
}

.element {
 position: absolute;
 left: 0;
 top: 25px;
 height: 150px;
 width: 700px;
 background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-wrap">
    <div class="element"></div>
</div></code>```

答:
If I understand correctly what you would like to do, you could create a mousemove function that moves the red element in the opposite direction of your cursor.

Here's a fiddle: http://jsfiddle.net/collederfomento/y53o6z7f/18/
First you retrieve the width of the document:

```<code>var vW = $(window).width();
</code>```

Then you create the mousemove function:

```<code>$(document).on("mousemove", function() {
   let mW = ((((event.pageX)*100)/vW).toFixed(3))-50;
   $("#red").css('transform', 'translateX(' +(-mW/2)+ '%)');
});
</code>```

The first line of the function retrieves the X position of the cursor, from a scale of -50 (the left side of the screen) to 50 (the right side) and stores it as a variable called mW.

The second line takes the mW variable and moves the red element in the opposite direction by half the amount (you can change that, of course).

Body:
If I understand correctly what you would like to do, you could create a mousemove function that moves the red element in the opposite direction of your cursor.

Here's a fiddle: http://jsfiddle.net/collederfomento/y53o6z7f/18/
First you retrieve the width of the document:

var vW = $(window).width();

Then you create the mousemove function:

$(document).on("mousemove", function() {
   let mW = ((((event.pageX)*100)/vW).toFixed(3))-50;
   $("#red").css('transform', 'translateX(' +(-mW/2)+ '%)');
});

The first line of the function retrieves the X position of the cursor, from a scale of -50 (the left side of the screen) to 50 (the right side) and stores it as a variable called mW.

The second line takes the mW variable and moves the red element in the opposite direction by half the amount (you can change that, of course).


问:
How do I re-render a component manually?
I'm a newcomer to Angular2, I'm used to the Angular 1 digest cycle, meaning if I update the scope of a view I can manually trigger a digest by calling $scope.$digest(). However, I'm not sure how to do this in Angular2, esp given that the new framework doesn't have the implicit data binding that the old version had.

Here's my problem. I have a route that loads a component when a url with a parameter is hit:

```<code>// Router
export const AppRoutes : RouterConfig = [
    {
    path: 'my/:arg/view',
    component: MyComponent
    }
]
</code>```

Then I have this component:

```<code>// Component
export class MyComponent {
    constructor(private route : ActivatedRoute,
      private r : Router) {
    let id = parseInt(this.route.params['value'].id);
    console.log(id);
    // do stuff with id
    }

    reloadWithNewId(id:number) {
        this.r.navigateByUrl('my/' + id + '/view');
    }
}
</code>```

Lets say I navigate to url /my/1/view. It will call the constructor and the number 1 is logged. However, if I call reloadWithNewId with a new id, reloadWithNewIf(2), the constructor is not called again. How do I manually reload the component?

答:
I think the changeDetectorRef is the proper tool for this job:

HTML

```<code><my-component *ngIf="!reloading"
              (loadNext)="onLoadNext()">
</my-component>
</code>```

TS

```<code>  constructor(
    private cdr: ChangeDetectorRef
  ) { }

  onLoadNext() {
      this.reloading = true;
      this.cdr.detectChanges();
      this.reloading = false;
      this.cdr.detectChanges();
  }
</code>```

Why would you want this, instead of "updating the model and the view updates itself", as in the answer that Günther provided? This way you're sure the component gets reinitialized and there aren't some left over values from before. That's why I find it cleaner to do it like this.

Example: https://stackblitz.com/edit/commatrainer-v1

Body:
I'm a newcomer to Angular2, I'm used to the Angular 1 digest cycle, meaning if I update the scope of a view I can manually trigger a digest by calling $scope.$digest(). However, I'm not sure how to do this in Angular2, esp given that the new framework doesn't have the implicit data binding that the old version had.

Here's my problem. I have a route that loads a component when a url with a parameter is hit:

// Router
export const AppRoutes : RouterConfig = [
    {
    path: 'my/:arg/view',
    component: MyComponent
    }
]

Then I have this component:

// Component
export class MyComponent {
    constructor(private route : ActivatedRoute,
      private r : Router) {
    let id = parseInt(this.route.params['value'].id);
    console.log(id);
    // do stuff with id
    }

    reloadWithNewId(id:number) {
        this.r.navigateByUrl('my/' + id + '/view');
    }
}

Lets say I navigate to url /my/1/view. It will call the constructor and the number 1 is logged. However, if I call reloadWithNewId with a new id, reloadWithNewIf(2), the constructor is not called again. How do I manually reload the component?

Body:
I think the changeDetectorRef is the proper tool for this job:

HTML

<my-component *ngIf="!reloading"
              (loadNext)="onLoadNext()">
</my-component>

TS

  constructor(
    private cdr: ChangeDetectorRef
  ) { }

  onLoadNext() {
      this.reloading = true;
      this.cdr.detectChanges();
      this.reloading = false;
      this.cdr.detectChanges();
  }

Why would you want this, instead of "updating the model and the view updates itself", as in the answer that Günther provided? This way you're sure the component gets reinitialized and there aren't some left over values from before. That's why I find it cleaner to do it like this.

Example: https://stackblitz.com/edit/commatrainer-v1


问:
How to use onActivityResult twice in one Activity
error:method onActivityResult(int,int, Intent) is already defined in class scan.

So I'm trying to build an app where u snap a photo and than the app detects text on the photo. Sadly I use the method onActivityResult twice.
Since I'm new to coding and in general a bit stupid, I don't know how to solve this.

adding the number 1 behind the ints where I first used them, but well that didn't do it

```<code>private void camera(){
    Intent intent2 = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent2, 0);
}
@Override
protected void onActivityResult (int requestCode1, int resultCode1 , Intent data1) {
    super.onActivityResult(requestCode1,resultCode1,data1);
    if (resultCode1==RESULT_OK){
        Bitmap btp = (Bitmap) data1.getExtras().get("data");
        imageView.setImageBitmap(btp);
    }
}

public void detect (View v){
    if (bitmap == null){
        Toast.makeText(getApplicationContext(),"Bitmap is null",Toast.LENGTH_SHORT).show();
    }
    else {
        FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
        FirebaseVisionTextRecognizer firebaseVisionTextRecognizer = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
        firebaseVisionTextRecognizer.processImage(firebaseVisionImage)
                .addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
                    @Override
                    public void onSuccess(FirebaseVisionText firebaseVisionText) {
                        process_text(firebaseVisionText);
                    }
                });

    }

}

private void process_text(FirebaseVisionText firebaseVisionText) {
    List<FirebaseVisionText.TextBlock> blocks = firebaseVisionText.getTextBlocks();
    if (blocks.size() == 0){
        Toast.makeText(getApplicationContext(),"no text detected",Toast.LENGTH_LONG).show();
    }
    else {
        for (FirebaseVisionText.TextBlock block:firebaseVisionText.getTextBlocks()){
            String text = block.getText();
            textView.setText(text);
        }
    }
}

public void pick_image(View v){
    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(i,1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1 && resultCode == RESULT_OK)
    {
        Uri uri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
            imageView.setImageBitmap(bitmap);
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
</code>```

error: method onActivityResult(int,int,Intent) is already defined in class scan

答:
Define request code inside your class

static final int REQUEST_PHOTO_1 = 1;
static final int REQUEST_PHOTO_2 = 2;

Then while calling use

```<code>startActivityForResult(intent1, REQUEST_PHOTO_1);
startActivityForResult(intent2, REQUEST_PHOTO_2);
</code>```

Now, in onActivityResult you can do something like this.

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_PHOTO_1 && resultCode == RESULT_OK)
{
    ....
}
else if(requestCode == REQUEST_PHOTO_2 && resultCode == RESULT_OK)
{
    ....
}
else if (resultCode==RESULT_OK){
    Bitmap btp = (Bitmap) data.getExtras().get("data");
    imageView.setImageBitmap(btp);
}
}
</code>```

Body:
error:method onActivityResult(int,int, Intent) is already defined in class scan.

So I'm trying to build an app where u snap a photo and than the app detects text on the photo. Sadly I use the method onActivityResult twice.
Since I'm new to coding and in general a bit stupid, I don't know how to solve this.

adding the number 1 behind the ints where I first used them, but well that didn't do it

private void camera(){
    Intent intent2 = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent2, 0);
}
@Override
protected void onActivityResult (int requestCode1, int resultCode1 , Intent data1) {
    super.onActivityResult(requestCode1,resultCode1,data1);
    if (resultCode1==RESULT_OK){
        Bitmap btp = (Bitmap) data1.getExtras().get("data");
        imageView.setImageBitmap(btp);
    }
}

public void detect (View v){
    if (bitmap == null){
        Toast.makeText(getApplicationContext(),"Bitmap is null",Toast.LENGTH_SHORT).show();
    }
    else {
        FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
        FirebaseVisionTextRecognizer firebaseVisionTextRecognizer = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
        firebaseVisionTextRecognizer.processImage(firebaseVisionImage)
                .addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
                    @Override
                    public void onSuccess(FirebaseVisionText firebaseVisionText) {
                        process_text(firebaseVisionText);
                    }
                });

    }

}

private void process_text(FirebaseVisionText firebaseVisionText) {
    List<FirebaseVisionText.TextBlock> blocks = firebaseVisionText.getTextBlocks();
    if (blocks.size() == 0){
        Toast.makeText(getApplicationContext(),"no text detected",Toast.LENGTH_LONG).show();
    }
    else {
        for (FirebaseVisionText.TextBlock block:firebaseVisionText.getTextBlocks()){
            String text = block.getText();
            textView.setText(text);
        }
    }
}

public void pick_image(View v){
    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(i,1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1 && resultCode == RESULT_OK)
    {
        Uri uri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
            imageView.setImageBitmap(bitmap);
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}

error: method onActivityResult(int,int,Intent) is already defined in class scan

Body:
Define request code inside your class

static final int REQUEST_PHOTO_1 = 1;
static final int REQUEST_PHOTO_2 = 2;

Then while calling use

startActivityForResult(intent1, REQUEST_PHOTO_1);
startActivityForResult(intent2, REQUEST_PHOTO_2);

Now, in onActivityResult you can do something like this.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_PHOTO_1 && resultCode == RESULT_OK)
{
    ....
}
else if(requestCode == REQUEST_PHOTO_2 && resultCode == RESULT_OK)
{
    ....
}
else if (resultCode==RESULT_OK){
    Bitmap btp = (Bitmap) data.getExtras().get("data");
    imageView.setImageBitmap(btp);
}
}


问:
How does Wikipedia make its search field?
I would like to know how Wikipedia does its search field.  What I mean by this is two things:  Its gradient and its button.

How does it make a gradient in the field?  This can be easily done with CSS cross browser at this point, but when you do the IE CSS code, it aliases the text.  Wikipedia has a gradient background, but the text is still anti-aliased!  How do they do that?

Also, how did they put a clickable search button INSIDE the text field?

Thanks.

答:
You could just look at the code. The search box as it appears is only a div element with a border. This div itself has the gradient set via CSS (background-image). As you can see the button element is also not inside the text field. </p>

```<code><div id="simpleSearch">
    <input id="searchInput" name="search" type="text"  title="Search Wikipedia [f]" accesskey="f"  value="" />
    <button id="searchButton" type='submit' name='button'  title=""><img src="[x]" alt="Filltext" /></button>
</div>
</code>```

Body:
You could just look at the code. The search box as it appears is only a div element with a border. This div itself has the gradient set via CSS (background-image). As you can see the button element is also not inside the text field.

<div id="simpleSearch">
    <input id="searchInput" name="search" type="text"  title="Search Wikipedia [f]" accesskey="f"  value="" />
    <button id="searchButton" type='submit' name='button'  title=""><img src="[x]" alt="Filltext" /></button>
</div>


问:
How do i enable developer mode in google chrome (in mac)
How do i enable the developer mode in google chrome browser (mac)

I cannot find answer

Code is not applicable

Output is also not applicable

答:
Open Chrome Browser

Click on : button

Select Settings

Click Extensions

Toggle the Developer Mode option


答:
Have a look at the documentation and the reference.

The second parameter of startActivityForResult(Intent intent, int requestCode) is a request code, that will be passed as the first parameter of onActivityResult(int requestCode, int resultCode, Intent data).

Example:

private void camera(){
    Intent intent2 = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent2, 0);
}

public void pick_image(View v){
    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(i, 1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK)
    {
        switch(requestCode){
            case 0: // handle camera
                Bitmap btp = (Bitmap) data1.getExtras().get("data");
                imageView.setImageBitmap(btp);
            break;
            case 1: // handle pick_image
               Uri uri = data.getData();
               try {
                   bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                   imageView.setImageBitmap(bitmap);
               } catch (IOException e){
                   e.printStackTrace();
               }
            break;
        }
    }
}
```

As the documentation shows, you should refactor the request codes into class constants for better readability and easier understanding.

Title: How to use onActivityResult twice in one Activity

Body:
Have a look at the documentation and the reference.

The second parameter of startActivityForResult(Intent intent, int requestCode) is a request code, that will be passed as the first parameter of onActivityResult(int requestCode, int resultCode, Intent data).

Example:

private void camera(){
    Intent intent2 = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent2, 0);
}

public void pick_image(View v){
    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(i, 1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK)
    {
        switch(requestCode){
            case 0: // handle camera
                Bitmap btp = (Bitmap) data1.getExtras().get("data");
                imageView.setImageBitmap(btp);
            break;
            case 1: // handle pick_image
               Uri uri = data.getData();
               try {
                   bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                   imageView.setImageBitmap(bitmap);
               } catch (IOException e){
                   e.printStackTrace();
               }
            break;
        }
    }
}

As the documentation shows, you should refactor the request codes into class constants for better readability and easier understanding.


问:
Count Instances of Class
I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.

Say for example I have class Foo.  I want to be able to, in the same process, get a current count of all instance of Foo.

However I cannot modify Foo, so a static int with counting is out.  Also I cannot just add all instances I make to some static list and count that.  I want to be able to just say:

```<code>System.GC.numberOf< Foo >()
</code>```

or something.

I was looking through the garbage collectors but I could not find any relevant methods.

答:
If you can't modify the class directly (perhaps because it is a built-in class?), could you create a wrapper, or a subclass that inherits the original?

```<code>public class subFoo extends foo
{
    protected static int count = 0;

    public subFoo()
    {
        count++;
        super();
    }

    protected void finalize() throws Throwable
    {
        count--;
        super.finalize();
    }

    public static int getInstanceCount()
    {
        return count;
    }
}
</code>```

This example is Java and may have some syntax issues 'cause I'm a little rusty.

Of course, you'd have to be sure to redeclare all your foo as subFoo throughout the rest of your code.

Title: Count Instances of Class

Body:
I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.

Say for example I have class Foo.  I want to be able to, in the same process, get a current count of all instance of Foo.

However I cannot modify Foo, so a static int with counting is out.  Also I cannot just add all instances I make to some static list and count that.  I want to be able to just say:

System.GC.numberOf< Foo >()

or something.

I was looking through the garbage collectors but I could not find any relevant methods.

Body:
If you can't modify the class directly (perhaps because it is a built-in class?), could you create a wrapper, or a subclass that inherits the original?

public class subFoo extends foo
{
    protected static int count = 0;

    public subFoo()
    {
        count++;
        super();
    }

    protected void finalize() throws Throwable
    {
        count--;
        super.finalize();
    }

    public static int getInstanceCount()
    {
        return count;
    }
}

This example is Java and may have some syntax issues 'cause I'm a little rusty.

Of course, you'd have to be sure to redeclare all your foo as subFoo throughout the rest of your code.


问:
How to add missing dates and populate values inside groups with 'data.table'
Let see the following example in dplyr style.

```<code># 1. Data set
df <- data.table(
  g1 = c(1, 1, 2, 1, 2, 2, 1),
  g2 = c(2, 1, 3, 3, 1, 1, 2),
  status = c(1, 0, 1, 0, 0, 1, 1),
  date_obs = as.Date(c("2019-01-01", "2019-01-02", "2019-01-12", "2019-01-15",
           "2019-01-20", "2019-01-24", "2019-01-30")))

# 2. Arrange data
df <- df %>%
  arrange(g1, g2, date_obs)

# 3. Populate missing 'date_obs' and 'status' values
df_filled <- df %>%
  group_by(g1, g2) %>%
  complete(date_obs = seq.Date(min(date_obs), max(date_obs), by = "day")) %>%
  fill(status) %>%
  arrange(g1, g2, date_obs) %>%
  ungroup()
</code>```

How can I make the same operations by using data.table R syntax?

Thanks!

Body:
Let see the following example in dplyr style.

# 1. Data set
df <- data.table(
  g1 = c(1, 1, 2, 1, 2, 2, 1),
  g2 = c(2, 1, 3, 3, 1, 1, 2),
  status = c(1, 0, 1, 0, 0, 1, 1),
  date_obs = as.Date(c("2019-01-01", "2019-01-02", "2019-01-12", "2019-01-15",
           "2019-01-20", "2019-01-24", "2019-01-30")))

# 2. Arrange data
df <- df %>%
  arrange(g1, g2, date_obs)

# 3. Populate missing 'date_obs' and 'status' values
df_filled <- df %>%
  group_by(g1, g2) %>%
  complete(date_obs = seq.Date(min(date_obs), max(date_obs), by = "day")) %>%
  fill(status) %>%
  arrange(g1, g2, date_obs) %>%
  ungroup()

How can I make the same operations by using data.table R syntax?

Thanks!

Body:
Another option using a rolling join.

setkey(DT, g1, g2, date_obs)

out <- DT[DT[, .(date_obs = seq(first(date_obs),
                                last(date_obs),
                                by = "day")), by=.(g1, g2)],
          on=.(g1, g2, date_obs),
          roll = TRUE]
out
#    g1 g2 status   date_obs
# 1:  1  1      0 2019-01-02
# 2:  1  2      1 2019-01-01
# 3:  1  2      1 2019-01-02
# 4:  1  2      1 2019-01-03
# 5:  1  2      1 2019-01-04
# 6:  1  2      1 2019-01-05
# 7:  1  2      1 2019-01-06
# 8:  1  2      1 2019-01-07
# 9:  1  2      1 2019-01-08
#10:  1  2      1 2019-01-09
#11:  1  2      1 2019-01-10
#12:  1  2      1 2019-01-11
#13:  1  2      1 2019-01-12
#14:  1  2      1 2019-01-13
#15:  1  2      1 2019-01-14
#16:  1  2      1 2019-01-15
#17:  1  2      1 2019-01-16
#18:  1  2      1 2019-01-17
#19:  1  2      1 2019-01-18
#20:  1  2      1 2019-01-19
#21:  1  2      1 2019-01-20
#22:  1  2      1 2019-01-21
#23:  1  2      1 2019-01-22
#24:  1  2      1 2019-01-23
#25:  1  2      1 2019-01-24
#26:  1  2      1 2019-01-25
#27:  1  2      1 2019-01-26
#28:  1  2      1 2019-01-27
#29:  1  2      1 2019-01-28
#30:  1  2      1 2019-01-29
#31:  1  2      1 2019-01-30
#32:  1  3      0 2019-01-15
#33:  2  1      0 2019-01-20
#34:  2  1      0 2019-01-21
#35:  2  1      0 2019-01-22
#36:  2  1      0 2019-01-23
#37:  2  1      1 2019-01-24
#38:  2  3      1 2019-01-12
#    g1 g2 status   date_obs

data

DT <- data.table(
  g1 = c(1, 1, 2, 1, 2, 2, 1),
  g2 = c(2, 1, 3, 3, 1, 1, 2),
  status = c(1, 0, 1, 0, 0, 1, 1),
  date_obs = as.Date(c("2019-01-01", "2019-01-02", "2019-01-12", "2019-01-15",
                       "2019-01-20", "2019-01-24", "2019-01-30")))


问:
Move rects in canvas at the same time
I have created multiple rectangles in the Canvas element. The primary goal is to move all of them in the direction of the touch or mouse move event. Maybe the answer is in front of me, but right now I am blind :(

Here is the example code on plunker

Code:

```<code>var context = {
  collection: [],
  canvas: document.getElementById('canvas'),
  ctx: canvas.getContext('2d'),
  isMoving: false
};

for (let f = 0; f < 3; f++) {
    var item = {
        x: (Math.random() * 200),
        y: (Math.random() * 100),
        w: 50,
        h: 50
    };

    context.collection.push(item);
}

drawAll(context);
</code>```

Touch event handler:

```<code>context.canvas.addEventListener("mousedown", function (e) { onTouchHandler(e, context) }, false)
context.canvas.addEventListener("mousemove", function (e) { onTouchHandler(e, context) }, false);
context.canvas.addEventListener("mouseup", function (e) { onTouchHandler(e, context) }, false);

function onTouchHandler(e, context) {
    var touch = getTouchCoordinates(e.pageX, e.pageY, context.canvas);

    switch (e.type) {
        case 'mousedown':
            context.isMoving = true;
            break;
        case 'mousemove':
            if(context.isMoving === true){
                console.log(touch);

                //TODO: move all objects by the cursor...
                for (let f = 0; f < context.collection.length; f++) {
                    var item = context.collection[f];
                }

                //drawAll(context);
            }
            break;
        case 'mouseup':
            context.isMoving = false;
            break;
        default:
            break;
    }
}
</code>```

Draw rectangles:

```<code>function drawAll(context){
  var canvas = context.canvas,
      ctx = context.ctx,
      shapes = context.collection;

  clearAll(ctx, canvas);

  for (let x = 0; x < shapes.length; x++) {
      var element = shapes[x];
      ctx.rect(element.x, element.y, element.w, element.h);
      ctx.stroke();
  }

}
</code>```

Clear rects:

```<code>function clearAll(ctx, canvas){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}
</code>```

Get touch x,y:

```<code>function getTouchCoordinates(pageX, pageY, canvas) {
    var element = canvas,
        offsetX = 0,
        offsetY = 0,
        currentX,
        currentY;

    if (element.offsetParent != undefined) {
        do {
            offsetX += element.offsetLeft;
            offsetY += element.offsetTop;
        } while ((element = element.offsetParent))
    }

    currentX = pageX - offsetX;
    currentY = pageY - offsetY;

    return {
        x: currentX,
        y: currentY
    }
}
</code>```

答:
I've simplified your code a bit just to show how you could move the rectangles. I'm not checking for mouse press or release.

```<code>var context = {
  collection: [],
  canvas: document.getElementById('canvas'),
  ctx: canvas.getContext('2d'),
  isMoving: false
};

// rectangle positions
for (let f = 0; f < 3; f++) {
    var item = {
        x: (Math.random() * 200),
        y: (Math.random() * 100),
        w: 50,
        h: 50
    };

    context.collection.push(item);
}

// listen
context.canvas.addEventListener("mousemove",  (e) => onMoveHandler(e));

// Draw
drawAll();

function onMoveHandler(e) {
    //console.log(e.clientX, e.clientY)

    for (let f = 0; f < context.collection.length; f++) {
        var item = context.collection[f];

        var xdifference = item.x - e.pageX
        item.x = (xdifference < 0) ? item.x + 1 : item.x -1

        var ydifference = item.y - e.pageY
        item.y = (ydifference < 0) ? item.y + 1 : item.y -1
    }
    drawAll()
}

function drawAll(){

  // clear all
  clearAll();

  for (let x = 0; x < context.collection.length; x++) {
      var element = context.collection[x];
      context.ctx.rect(element.x, element.y, element.w, element.h);
      context.ctx.stroke();
  }

}

function clearAll(){
  context.ctx.clearRect(0, 0, context.canvas.width, context.canvas.height);
}
</code>```

If you want a more "natural" looking movement towards the mouse, you can calculate the x and y difference using the Pythagorean theorem:

```<code>var xdifference = e.pageX - item.x
var ydifference = e.pageY - item.y

let distance = Math.sqrt(xdifference * xdifference + ydifference * ydifference)
item.x += (xdifference / distance)
item.y += (ydifference / distance)
</code>```

In the plunker example it's not 100% accurate because the x,y offset of the element on the page isn't used in the calculation :)

Title: Move rects in canvas at the same time

Body:
I have created multiple rectangles in the Canvas element. The primary goal is to move all of them in the direction of the touch or mouse move event. Maybe the answer is in front of me, but right now I am blind :(

Here is the example code on plunker

Code:

var context = {
  collection: [],
  canvas: document.getElementById('canvas'),
  ctx: canvas.getContext('2d'),
  isMoving: false
};

for (let f = 0; f < 3; f++) {
    var item = {
        x: (Math.random() * 200),
        y: (Math.random() * 100),
        w: 50,
        h: 50
    };

    context.collection.push(item);
}

drawAll(context);

Touch event handler:

context.canvas.addEventListener("mousedown", function (e) { onTouchHandler(e, context) }, false)
context.canvas.addEventListener("mousemove", function (e) { onTouchHandler(e, context) }, false);
context.canvas.addEventListener("mouseup", function (e) { onTouchHandler(e, context) }, false);

function onTouchHandler(e, context) {
    var touch = getTouchCoordinates(e.pageX, e.pageY, context.canvas);

    switch (e.type) {
        case 'mousedown':
            context.isMoving = true;
            break;
        case 'mousemove':
            if(context.isMoving === true){
                console.log(touch);

                //TODO: move all objects by the cursor...
                for (let f = 0; f < context.collection.length; f++) {
                    var item = context.collection[f];
                }

                //drawAll(context);
            }
            break;
        case 'mouseup':
            context.isMoving = false;
            break;
        default:
            break;
    }
}

Draw rectangles:

function drawAll(context){
  var canvas = context.canvas,
      ctx = context.ctx,
      shapes = context.collection;

  clearAll(ctx, canvas);

  for (let x = 0; x < shapes.length; x++) {
      var element = shapes[x];
      ctx.rect(element.x, element.y, element.w, element.h);
      ctx.stroke();
  }

}

Clear rects:

function clearAll(ctx, canvas){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

Get touch x,y:

function getTouchCoordinates(pageX, pageY, canvas) {
    var element = canvas,
        offsetX = 0,
        offsetY = 0,
        currentX,
        currentY;

    if (element.offsetParent != undefined) {
        do {
            offsetX += element.offsetLeft;
            offsetY += element.offsetTop;
        } while ((element = element.offsetParent))
    }

    currentX = pageX - offsetX;
    currentY = pageY - offsetY;

    return {
        x: currentX,
        y: currentY
    }
}

Body:
I've simplified your code a bit just to show how you could move the rectangles. I'm not checking for mouse press or release.

var context = {
  collection: [],
  canvas: document.getElementById('canvas'),
  ctx: canvas.getContext('2d'),
  isMoving: false
};

// rectangle positions
for (let f = 0; f < 3; f++) {
    var item = {
        x: (Math.random() * 200),
        y: (Math.random() * 100),
        w: 50,
        h: 50
    };

    context.collection.push(item);
}

// listen
context.canvas.addEventListener("mousemove",  (e) => onMoveHandler(e));

// Draw
drawAll();

function onMoveHandler(e) {
    //console.log(e.clientX, e.clientY)

    for (let f = 0; f < context.collection.length; f++) {
        var item = context.collection[f];

        var xdifference = item.x - e.pageX
        item.x = (xdifference < 0) ? item.x + 1 : item.x -1

        var ydifference = item.y - e.pageY
        item.y = (ydifference < 0) ? item.y + 1 : item.y -1
    }
    drawAll()
}

function drawAll(){

  // clear all
  clearAll();

  for (let x = 0; x < context.collection.length; x++) {
      var element = context.collection[x];
      context.ctx.rect(element.x, element.y, element.w, element.h);
      context.ctx.stroke();
  }

}

function clearAll(){
  context.ctx.clearRect(0, 0, context.canvas.width, context.canvas.height);
}

If you want a more "natural" looking movement towards the mouse, you can calculate the x and y difference using the Pythagorean theorem:

var xdifference = e.pageX - item.x
var ydifference = e.pageY - item.y

let distance = Math.sqrt(xdifference * xdifference + ydifference * ydifference)
item.x += (xdifference / distance)
item.y += (ydifference / distance)

In the plunker example it's not 100% accurate because the x,y offset of the element on the page isn't used in the calculation :)