问:
Delete multiple indices in one Elasticsearch HTTP request (cURL)
I was using this curl command line to clean my indices:

```<code>curl -XDELETE http://example.com/my_index-*
</code>```

But, now, I want to delete my_index-.*[.][0-3][0-9]:

to delete only my_index-YYYY.MM.dd

to keep my_index-YYYY.MM.dd-*

The relevant Elasticsearch documentation I have found:

Delete index API does say nothing on regex.

Multiple indices says:

It also support wildcards, for example: test* or *test or te*t or *test*, and the ability to "add" (+) and "remove" (-), for example: +test*,-test3.

Date math support in index names says:

Almost all APIs that have an index parameter, support date math in the index parameter value.

  [...]

  date_format is the optional format in which the computed date should be rendered. Defaults to YYYY.MM.dd.

My Questions:

Is it possible to send a DELETE request method to Elasticsearch HTTP server to delete indices only formatted my_index-YYYY.MM.dd?

Or the inverse, to delete all my_index-* but keeping my_index-*-*?

For example, regex can sometimes be provided within the POST data:

```<code>curl -XPOST http://example.com/my_index-2017.07.14/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "suggest": {
        "song-suggest" : {
            "regex" : "n[ever|i]r",
            "completion" : {
                "field" : "suggest"
            }
        }
    }
}'
</code>```

答:
Short answer

Delete all indices my_index-* except indices my_index-*-*

```<code>curl -X DELETE http://es.example.com/my_index-*,-my_index-*-*
</code>```

No regex

Elasticsearch 5.x does not accept regex or filename patterns ?[a-z] to select multiple indices.

However, the multiple indices documentation allows + and - to include and exclude indices.

Script to prevent accidental deletion of indices my_index-*-*:

```<code>#!/bin/bash -xe
pattern="${1:-*}"
curl -X DELETE https://es.example.com/my_index-"$pattern",-my_index-*-*?pretty
</code>```

Explanation

The parameter index can contain a comma separated list of index patterns, for example my_index_1,my_index_2,my_index_3.

Index pattern is based on wildcards, for example my_index*.

To include and exclude indices, use + and - as index prefix, for example my_index_*,-my_index_2017*,+my_index_2017-01*,-my_index_2017-01-31.

Do not need to use + on first index

Described example

This DELETE request deletes all indices my_index_* before my_index_2017-01-31

```<code>index_list='my_index_*,-my_index_2017*,+my_index_2017-01*,-my_index_2017-01-31'
curl -X DELETE http://es.example.com/"$index_list"
</code>```

Delete all my_index_*

Except my_index_2017*

Delete my_index_2017-01*

Except my_index_2017-01-31

Body:
I was using this curl command line to clean my indices:

curl -XDELETE http://example.com/my_index-*

But, now, I want to delete my_index-.*[.][0-3][0-9]:

to delete only my_index-YYYY.MM.dd

to keep my_index-YYYY.MM.dd-*

The relevant Elasticsearch documentation I have found:

Delete index API does say nothing on regex.

Multiple indices says:

It also support wildcards, for example: test* or *test or te*t or *test*, and the ability to "add" (+) and "remove" (-), for example: +test*,-test3.

Date math support in index names says:

Almost all APIs that have an index parameter, support date math in the index parameter value.

  [...]

  date_format is the optional format in which the computed date should be rendered. Defaults to YYYY.MM.dd.

My Questions:

Is it possible to send a DELETE request method to Elasticsearch HTTP server to delete indices only formatted my_index-YYYY.MM.dd?

Or the inverse, to delete all my_index-* but keeping my_index-*-*?

For example, regex can sometimes be provided within the POST data:

curl -XPOST http://example.com/my_index-2017.07.14/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "suggest": {
        "song-suggest" : {
            "regex" : "n[ever|i]r",
            "completion" : {
                "field" : "suggest"
            }
        }
    }
}'

Body:
Short answer

Delete all indices my_index-* except indices my_index-*-*

curl -X DELETE http://es.example.com/my_index-*,-my_index-*-*

No regex

Elasticsearch 5.x does not accept regex or filename patterns ?[a-z] to select multiple indices.

However, the multiple indices documentation allows + and - to include and exclude indices.

Script to prevent accidental deletion of indices my_index-*-*:

#!/bin/bash -xe
pattern="${1:-*}"
curl -X DELETE https://es.example.com/my_index-"$pattern",-my_index-*-*?pretty

Explanation

The parameter index can contain a comma separated list of index patterns, for example my_index_1,my_index_2,my_index_3.

Index pattern is based on wildcards, for example my_index*.

To include and exclude indices, use + and - as index prefix, for example my_index_*,-my_index_2017*,+my_index_2017-01*,-my_index_2017-01-31.

Do not need to use + on first index

Described example

This DELETE request deletes all indices my_index_* before my_index_2017-01-31

index_list='my_index_*,-my_index_2017*,+my_index_2017-01*,-my_index_2017-01-31'
curl -X DELETE http://es.example.com/"$index_list"

Delete all my_index_*

Except my_index_2017*

Delete my_index_2017-01*

Except my_index_2017-01-31


来源: stackexchange

问:
informatica Datetime conversion to SQL server Timstamp
I have a requirement where I have to load Informatica SESSSTARTTIME(datetime) to SQL server timestamp. When I am trying to connect datetime to timestamp I am getting error incompatible data type.

Any suggestions how this can be achieved?

Thanks

答:
MS SQL Server timestamp datatype has nothing to do with time. It's an autogenerated number and you cannot load it.

https://msdn.microsoft.com/en-us/library/ms182776(v=SQL.90).aspx

quote:

"Is a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The timestamp data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type."

ContentLicense: CC BY-SA 3.0


问:
Selected Option to none value is not working
I am having a Select input field in html page.In a if block a condition should work.

```<code><select id='selectopt'>
  <option value="">Select<option>
  <option value="1">1<option>
</select>

<input type="text" id='text1'>

if($('#text1').val==='name'){
    $("#selectopt option[value='']").attr('selected', true);
}
else{
}
</code>```

when i put this condition inside if its working in chrome and IE but not working in firefox..

答:
Match the if condition with value $('#text1').val().trim()=== 'name'

And  html syntax was wrong </option> tag not closing

Try with prop() instead of attr()

if ($('#text1').val().trim()=== 'name') {
  $("#selectopt option:empty").prop('selected', true);
} else {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='selectopt'>
  <option value="">Select<option>
  <option value="1">1<option>
</select>

<input type="text" id='text1' value="name"></code>```

Body:
I am having a Select input field in html page.In a if block a condition should work.

<select id='selectopt'>
  <option value="">Select<option>
  <option value="1">1<option>
</select>

<input type="text" id='text1'>

if($('#text1').val==='name'){
    $("#selectopt option[value='']").attr('selected', true);
}
else{
}

when i put this condition inside if its working in chrome and IE but not working in firefox..

Body:
Match the if condition with value $('#text1').val().trim()=== 'name'

And  html syntax was wrong </option> tag not closing

Try with prop() instead of attr()

if ($('#text1').val().trim()=== 'name') {
  $("#selectopt option:empty").prop('selected', true);
} else {}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='selectopt'>
  <option value="">Select<option>
  <option value="1">1<option>
</select>

<input type="text" id='text1' value="name">


问:
AWS Elastic Beanstalk deployment 502 Gateway Error
I have a single Docker container deployment to AWS Elastic Beanstalk.

When I visit the site, it returns a 502 error, which makes me think the port inside the Docker container is not exposed.

These are my settings:

Dockerrun.aws.json:

```<code>{
"AWSEBDockerrunVersion": "1",
"Volumes": [
  {
    "ContainerDirectory": "/var/app",
    "HostDirectory": "/var/app"
  }
],
"Logging": "/var/eb_log",
"Ports": [
  {
    "containerPort": 80
  }
]
}
</code>```

Dockerfile

```<code>FROM ubuntu:16.04

# Install Python Setuptools
RUN rm -fR /var/lib/apt/lists/*
RUN apt-get update
RUN apt-get install -y software-properties-common
RUN add-apt-repository ppa:jonathonf/python-3.6
RUN apt-get update && apt-get install -y python3-pip
RUN apt-get install -y python3.6
RUN apt-get install -y python3-dev
RUN apt-get install -y libpq-dev
RUN apt-get install libffi-dev
RUN apt-get install -y git

# Add and install Python modules
ADD requirements.txt /src/requirements.txt
RUN cd /src; pip3 install -r requirements.txt

# Bundle app source
ADD . /src

# Expose
EXPOSE  80

# Run
CMD ["python3", "/src/app.py"]
</code>```

app.py

```<code>from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

# run the app.
if __name__ == "__main__":
    # Setting debug to True enables debug output. This line should be
    # removed before deploying a production app.
    app.debug = False
    app.run(port=80)
</code>```

I see this in my docker-ps.log:

```<code>CONTAINER ID        IMAGE               COMMAND                 CREATED
STATUS              PORTS               NAMES
ead221e6d2c6        2eb62af087be        "python3 /src/app.py"   34 minutes ago      Up 34 minutes       80/tcp              peaceful_lamport
</code>```

and:

```<code>/var/log/eb-docker/containers/eb-current-app/ead221e6d2c6-stdouterr.log
-------------------------------------
* Running on http://127.0.0.1:80/ (Press CTRL+C to quit)
</code>```

and this error:

```<code>2017/07/06 05:57:36 [error] 15972#0: *10 connect() failed (111: Connection refused) while connecting to upstream, client: 172.5.154.225, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.3:80/", host: "bot-platform.us-west-2.elasticbeanstalk.com"
</code>```

What am I doing wrong?

答:
After looking up your error code I think you could give the following solution a try. It seems that you have to edit the nginx config of elastic beanstalk. Thereto you add the file nginx.config to the directory .ebextionsions in elastic beanstalk. Put the following content into the file:

```<code>files:
  "/etc/nginx/conf.d/000_my_config.conf":
  content: |
    upstream nodejsserver {
      server 127.0.0.1:8081;
      keepalive 256;
    }

    server {
      listen 8080;

      location / {
        proxy_pass  http://nodejsserver;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      }

      location /myconfig {
        proxy_pass http://my_proxy_pass_host;
      }
    }
</code>```

Maybe you have to adjust it a little but this seems to be the proper way to solve your problem. If you google your error you will find a lot slightly different solutions on how to adjust nginx in order to resolve this problem.

Body:
I have a single Docker container deployment to AWS Elastic Beanstalk.

When I visit the site, it returns a 502 error, which makes me think the port inside the Docker container is not exposed.

These are my settings:

Dockerrun.aws.json:

{
"AWSEBDockerrunVersion": "1",
"Volumes": [
  {
    "ContainerDirectory": "/var/app",
    "HostDirectory": "/var/app"
  }
],
"Logging": "/var/eb_log",
"Ports": [
  {
    "containerPort": 80
  }
]
}

Dockerfile

FROM ubuntu:16.04

# Install Python Setuptools
RUN rm -fR /var/lib/apt/lists/*
RUN apt-get update
RUN apt-get install -y software-properties-common
RUN add-apt-repository ppa:jonathonf/python-3.6
RUN apt-get update && apt-get install -y python3-pip
RUN apt-get install -y python3.6
RUN apt-get install -y python3-dev
RUN apt-get install -y libpq-dev
RUN apt-get install libffi-dev
RUN apt-get install -y git

# Add and install Python modules
ADD requirements.txt /src/requirements.txt
RUN cd /src; pip3 install -r requirements.txt

# Bundle app source
ADD . /src

# Expose
EXPOSE  80

# Run
CMD ["python3", "/src/app.py"]

app.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

# run the app.
if __name__ == "__main__":
    # Setting debug to True enables debug output. This line should be
    # removed before deploying a production app.
    app.debug = False
    app.run(port=80)

I see this in my docker-ps.log:

CONTAINER ID        IMAGE               COMMAND                 CREATED
STATUS              PORTS               NAMES
ead221e6d2c6        2eb62af087be        "python3 /src/app.py"   34 minutes ago      Up 34 minutes       80/tcp              peaceful_lamport

and:

/var/log/eb-docker/containers/eb-current-app/ead221e6d2c6-stdouterr.log
-------------------------------------
* Running on http://127.0.0.1:80/ (Press CTRL+C to quit)

and this error:

2017/07/06 05:57:36 [error] 15972#0: *10 connect() failed (111: Connection refused) while connecting to upstream, client: 172.5.154.225, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.3:80/", host: "bot-platform.us-west-2.elasticbeanstalk.com"

What am I doing wrong?

Body:
After looking up your error code I think you could give the following solution a try. It seems that you have to edit the nginx config of elastic beanstalk. Thereto you add the file nginx.config to the directory .ebextionsions in elastic beanstalk. Put the following content into the file:

files:
  "/etc/nginx/conf.d/000_my_config.conf":
  content: |
    upstream nodejsserver {
      server 127.0.0.1:8081;
      keepalive 256;
    }

    server {
      listen 8080;

      location / {
        proxy_pass  http://nodejsserver;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      }

      location /myconfig {
        proxy_pass http://my_proxy_pass_host;
      }
    }

Maybe you have to adjust it a little but this seems to be the proper way to solve your problem. If you google your error you will find a lot slightly different solutions on how to adjust nginx in order to resolve this problem.


问:
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)
I am using Maven 3.0.5 and Spring Tool Source 3.2 with Maven plugin installed. When I try to do 'Run As---> Maven install', I am getting the following error:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Spring Social Twitter4J Sample 1.0.0
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for org.apache.maven.plugins:maven-compiler-plugin:jar:2.3.2 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[WARNING] The POM for org.apache.maven.plugins:maven-war-plugin:jar:2.1.1 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[WARNING] The POM for org.apache.maven.plugins:maven-install-plugin:jar:2.3.1 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ spring-social-twitter4j ---
[debug] execute contextualize
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 15 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ spring-social-twitter4j ---
[WARNING] The POM for org.apache.maven.plugins:maven-compiler-plugin:jar:2.3.2 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
Jun 21, 2013 2:14:32 AM org.sonatype.guice.bean.reflect.Logs$JULSink warn
WARNING: Error injecting: org.apache.maven.plugin.CompilerMojo
**java.lang.NoClassDefFoundError: org/codehaus/plexus/compiler/CompilerException**
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
    at java.lang.Class.getDeclaredConstructors(Unknown Source)
    at com.google.inject.spi.InjectionPoint.forConstructorOf(InjectionPoint.java:245)
    at com.google.inject.internal.ConstructorBindingImpl.create(ConstructorBindingImpl.java:98)
    at com.google.inject.internal.InjectorImpl.createUninitializedBinding(InjectorImpl.java:629)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:831)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:758)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:255)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:204)
    at com.google.inject.internal.InjectorImpl.getProviderOrThrow(InjectorImpl.java:954)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:987)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:950)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1000)
    at org.sonatype.guice.bean.reflect.AbstractDeferredClass.get(AbstractDeferredClass.java:45)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:84)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:52)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:100)
    at org.sonatype.guice.plexus.lifecycles.PlexusLifecycleManager.onProvision(PlexusLifecycleManager.java:138)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:108)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:55)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:45)
    at com.google.inject.internal.InjectorImpl$3$1.call(InjectorImpl.java:965)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1011)
    at com.google.inject.internal.InjectorImpl$3.get(InjectorImpl.java:961)
    at com.google.inject.Scopes$1$1.get(Scopes.java:59)
    at org.sonatype.guice.bean.locators.LazyBeanEntry.getValue(LazyBeanEntry.java:83)
    at org.sonatype.guice.plexus.locators.LazyPlexusBean.getValue(LazyPlexusBean.java:49)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:253)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:245)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:455)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:92)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: java.lang.ClassNotFoundException: org.codehaus.plexus.compiler.CompilerException
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230)
    ... 54 more

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.749s
[INFO] Finished at: Fri Jun 21 02:14:32 IST 2013
[INFO] Final Memory: 4M/15M
[INFO] ------------------------------------------------------------------------
**[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project spring-social-twitter4j: Execution default-compile of goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile failed: A required class was missing while executing org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile: org/codehaus/plexus/compiler/CompilerException**
[ERROR] -----------------------------------------------------
[ERROR] realm =    plugin>org.apache.maven.plugins:maven-compiler-plugin:2.3.2
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/C:/Users/SS%20Computer/.m2/repository/org/apache/maven/plugins/maven-compiler-plugin/2.3.2/maven-compiler-plugin-2.3.2.jar
[ERROR] urls[1] = file:/C:/Users/SS%20Computer/.m2/repository/org/codehaus/plexus/plexus-utils/1.1/plexus-utils-1.1.jar
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import  from realm ClassRealm[maven.api, parent: null]]
[ERROR]
[ERROR] -----------------------------------------------------: org.codehaus.plexus.compiler.CompilerException
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException
</code>```

Please find below my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.social.samples</groupId>
    <artifactId>spring-social-twitter4j</artifactId>
    <name>Spring Social Twitter4J Sample</name>
    <packaging>war</packaging>
    <version>1.0.0</version>
    <properties>
        <java-version>1.6</java-version>
        <org.springframework.social-version>1.1.0.BUILD-SNAPSHOT</org.springframework.social-version>
        <org.springframework-version>3.2.1.RELEASE</org.springframework-version>
        <org.springframework.security-version>3.1.3.RELEASE</org.springframework.security-version>
        <org.slf4j-version>1.7.2</org.slf4j-version>
    </properties>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springframework.security-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${org.springframework.security-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springframework.security-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-core</artifactId>
            <version>${org.springframework.social-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-web</artifactId>
            <version>${org.springframework.social-version}</version>
        </dependency>

        <!-- Twitter4J -->
        <dependency>
            <groupId>org.twitter4j</groupId>
            <artifactId>twitter4j-core</artifactId>
            <version>2.2.3</version>
        </dependency>

        <!-- JSR 303 with Hibernate Validator -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.1.0.Final</version>
        </dependency>

        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.3.159</version>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- CGLIB, only required and used for @Configuration usage -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jstl-impl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>org.springframework.maven.release</id>
            <name>Spring Maven Release Repository</name>
            <url>http://maven.springframework.org/release</url>
            <releases><enabled>true</enabled></releases>
            <snapshots><enabled>false</enabled></snapshots>
        </repository>
        <!-- For testing against latest Spring snapshots -->
        <repository>
            <id>org.springframework.maven.snapshot</id>
            <name>Spring Maven Snapshot Repository</name>
            <url>http://maven.springframework.org/snapshot</url>
            <releases><enabled>false</enabled></releases>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <!-- For developing against latest Spring milestones -->
        <repository>
            <id>org.springframework.maven.milestone</id>
            <name>Spring Maven Milestone Repository</name>
            <url>http://maven.springframework.org/milestone</url>
            <snapshots><enabled>false</enabled></snapshots>
        </repository>
    </repositories>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <warName>spring-social-twitter4j</warName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <version>1.1</version>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

During maven install my goal is war:war to make WAR of my application.

答:
I think you have Two ways to solve this problem

01. Set Properties

Set Java Build Path as jdk

Right click project ->Java Build Path ->Select Libraries tab ->Select JRE System Library ->Click Edit button ->Click Installed JREs-> add tick to box ->click Edit ->Click Directory->Select jdk

Specifi which kind of jdk version you installed

Right click project ->Project Facets ->tick java and select java version->Apply ->Ok

Update project

Right-click on "project"->Go to Maven->Update

02.Delete .m2 file

If you can't solve your problem using above two topic get this action
Close your project. Delete your full .m2 folder

How to fined .m2 file(windows)

Go to Local Disk(C) ->Users ->Select your PC name ->.m2 file

ContentLicense: CC BY-SA 4.0

Body:
I am using Maven 3.0.5 and Spring Tool Source 3.2 with Maven plugin installed. When I try to do 'Run As---> Maven install', I am getting the following error:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Spring Social Twitter4J Sample 1.0.0
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for org.apache.maven.plugins:maven-compiler-plugin:jar:2.3.2 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[WARNING] The POM for org.apache.maven.plugins:maven-war-plugin:jar:2.1.1 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[WARNING] The POM for org.apache.maven.plugins:maven-install-plugin:jar:2.3.1 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ spring-social-twitter4j ---
[debug] execute contextualize
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 15 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ spring-social-twitter4j ---
[WARNING] The POM for org.apache.maven.plugins:maven-compiler-plugin:jar:2.3.2 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
Jun 21, 2013 2:14:32 AM org.sonatype.guice.bean.reflect.Logs$JULSink warn
WARNING: Error injecting: org.apache.maven.plugin.CompilerMojo
**java.lang.NoClassDefFoundError: org/codehaus/plexus/compiler/CompilerException**
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
    at java.lang.Class.getDeclaredConstructors(Unknown Source)
    at com.google.inject.spi.InjectionPoint.forConstructorOf(InjectionPoint.java:245)
    at com.google.inject.internal.ConstructorBindingImpl.create(ConstructorBindingImpl.java:98)
    at com.google.inject.internal.InjectorImpl.createUninitializedBinding(InjectorImpl.java:629)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:831)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:758)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:255)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:204)
    at com.google.inject.internal.InjectorImpl.getProviderOrThrow(InjectorImpl.java:954)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:987)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:950)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1000)
    at org.sonatype.guice.bean.reflect.AbstractDeferredClass.get(AbstractDeferredClass.java:45)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:84)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:52)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:100)
    at org.sonatype.guice.plexus.lifecycles.PlexusLifecycleManager.onProvision(PlexusLifecycleManager.java:138)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:108)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:55)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:45)
    at com.google.inject.internal.InjectorImpl$3$1.call(InjectorImpl.java:965)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1011)
    at com.google.inject.internal.InjectorImpl$3.get(InjectorImpl.java:961)
    at com.google.inject.Scopes$1$1.get(Scopes.java:59)
    at org.sonatype.guice.bean.locators.LazyBeanEntry.getValue(LazyBeanEntry.java:83)
    at org.sonatype.guice.plexus.locators.LazyPlexusBean.getValue(LazyPlexusBean.java:49)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:253)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:245)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:455)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:92)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: java.lang.ClassNotFoundException: org.codehaus.plexus.compiler.CompilerException
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230)
    ... 54 more

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.749s
[INFO] Finished at: Fri Jun 21 02:14:32 IST 2013
[INFO] Final Memory: 4M/15M
[INFO] ------------------------------------------------------------------------
**[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project spring-social-twitter4j: Execution default-compile of goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile failed: A required class was missing while executing org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile: org/codehaus/plexus/compiler/CompilerException**
[ERROR] -----------------------------------------------------
[ERROR] realm =    plugin>org.apache.maven.plugins:maven-compiler-plugin:2.3.2
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/C:/Users/SS%20Computer/.m2/repository/org/apache/maven/plugins/maven-compiler-plugin/2.3.2/maven-compiler-plugin-2.3.2.jar
[ERROR] urls[1] = file:/C:/Users/SS%20Computer/.m2/repository/org/codehaus/plexus/plexus-utils/1.1/plexus-utils-1.1.jar
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import  from realm ClassRealm[maven.api, parent: null]]
[ERROR]
[ERROR] -----------------------------------------------------: org.codehaus.plexus.compiler.CompilerException
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException

Please find below my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.social.samples</groupId>
    <artifactId>spring-social-twitter4j</artifactId>
    <name>Spring Social Twitter4J Sample</name>
    <packaging>war</packaging>
    <version>1.0.0</version>
    <properties>
        <java-version>1.6</java-version>
        <org.springframework.social-version>1.1.0.BUILD-SNAPSHOT</org.springframework.social-version>
        <org.springframework-version>3.2.1.RELEASE</org.springframework-version>
        <org.springframework.security-version>3.1.3.RELEASE</org.springframework.security-version>
        <org.slf4j-version>1.7.2</org.slf4j-version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>

                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springframework.security-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${org.springframework.security-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springframework.security-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-core</artifactId>
            <version>${org.springframework.social-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-web</artifactId>
            <version>${org.springframework.social-version}</version>
        </dependency>

        <dependency>
            <groupId>org.twitter4j</groupId>
            <artifactId>twitter4j-core</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.1.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.3.159</version>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jstl-impl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>org.springframework.maven.release</id>
            <name>Spring Maven Release Repository</name>
            <url>http://maven.springframework.org/release</url>
            <releases><enabled>true</enabled></releases>
            <snapshots><enabled>false</enabled></snapshots>
        </repository>

        <repository>
            <id>org.springframework.maven.snapshot</id>
            <name>Spring Maven Snapshot Repository</name>
            <url>http://maven.springframework.org/snapshot</url>
            <releases><enabled>false</enabled></releases>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>

        <repository>
            <id>org.springframework.maven.milestone</id>
            <name>Spring Maven Milestone Repository</name>
            <url>http://maven.springframework.org/milestone</url>
            <snapshots><enabled>false</enabled></snapshots>
        </repository>
    </repositories>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <warName>spring-social-twitter4j</warName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <version>1.1</version>
            </plugin>
        </plugins>
    </build>
</project>

During maven install my goal is war:war to make WAR of my application.


问:
How to split a JSON object into a list (GSON, Android)?
I have some json response:

```<code>{
  "address": "0a1ac9b9a342c3600995845eec7254df664d6aa9",
  "workers": {
    "desktop-380h0l6": {
      "worker": "desktop-380h0l6",
      "hashrate": "92.2 MH/s",
      "reportedHashRate": "81.6 MH/s",
      "validShares": 81,
      "invalidShares": 0,
      "staleShares": 3,
      "workerLastSubmitTime": 1499408997,
      "invalidShareRatio": 0
    },
    "eco-001": {
      "worker": "eco-001",
      "hashrate": "121.1 MH/s",
      "reportedHashRate": "130.1 MH/s",
      "validShares": 109,
      "invalidShares": 0,
      "staleShares": 0,
      "workerLastSubmitTime": 1499408985,
      "invalidShareRatio": 0
    },
    "eco-002": {
      "worker": "eco-002",
      "hashrate": "114.1 MH/s",
      "reportedHashRate": "108.5 MH/s",
      "validShares": 102,
      "invalidShares": 0,
      "staleShares": 1,
      "workerLastSubmitTime": 1499408993,
      "invalidShareRatio": 0
    },
    "eco-003": {
      "worker": "eco-003",
      "hashrate": "125.5 MH/s",
      "reportedHashRate": "129.6 MH/s",
      "validShares": 111,
      "invalidShares": 0,
      "staleShares": 3,
      "workerLastSubmitTime": 1499408969,
      "invalidShareRatio": 0
    }
}
</code>```

I need to split the object "workers" into list. How can I do this? In my project I use Retrofit with GSON. I thought that code like this would help me, but I was wrong:

```<code>public class WorkersDeserializer implements JsonDeserializer<Workers> {
    @Override
    public Workers deserialize(JsonElement json,
                                             Type typeOfT,
                                             JsonDeserializationContext context) throws JsonParseException {

        final JsonObject jsonObject = json.getAsJsonObject();
        List<Worker> list = new LinkedList<>();
        jsonObject.entrySet().forEach(new Consumer<Map.Entry<String, JsonElement>>() {
            @Override
            public void accept(Map.Entry<String, JsonElement> stringJsonElementEntry) {
                list.add(context.deserialize(stringJsonElementEntry.getValue(), Workers.class));
            }
        });

        Workers w =new Workers();
        w.setWorkers(list);
        return w;
    }
}
</code>```

Thank you for your help.

答:
Why not just deserialize it to a Map and then collect its values into a list?

Workers.java:

```<code>public class Workers {
    @SerializedName("address")
    private String mAddress;

    @SerializedName("workers")
    private Map<String, Worker> mWorkers;

    /* ... */
}
</code>```

And then:

```<code>Workers workers = new Gson().fromJson(json, Workers.class);
List<Worker> = new ArrayList<>(workers.getWorkers().values());
</code>```

Body:
I have some json response:

{
  "address": "0a1ac9b9a342c3600995845eec7254df664d6aa9",
  "workers": {
    "desktop-380h0l6": {
      "worker": "desktop-380h0l6",
      "hashrate": "92.2 MH/s",
      "reportedHashRate": "81.6 MH/s",
      "validShares": 81,
      "invalidShares": 0,
      "staleShares": 3,
      "workerLastSubmitTime": 1499408997,
      "invalidShareRatio": 0
    },
    "eco-001": {
      "worker": "eco-001",
      "hashrate": "121.1 MH/s",
      "reportedHashRate": "130.1 MH/s",
      "validShares": 109,
      "invalidShares": 0,
      "staleShares": 0,
      "workerLastSubmitTime": 1499408985,
      "invalidShareRatio": 0
    },
    "eco-002": {
      "worker": "eco-002",
      "hashrate": "114.1 MH/s",
      "reportedHashRate": "108.5 MH/s",
      "validShares": 102,
      "invalidShares": 0,
      "staleShares": 1,
      "workerLastSubmitTime": 1499408993,
      "invalidShareRatio": 0
    },
    "eco-003": {
      "worker": "eco-003",
      "hashrate": "125.5 MH/s",
      "reportedHashRate": "129.6 MH/s",
      "validShares": 111,
      "invalidShares": 0,
      "staleShares": 3,
      "workerLastSubmitTime": 1499408969,
      "invalidShareRatio": 0
    }
}

I need to split the object "workers" into list. How can I do this? In my project I use Retrofit with GSON. I thought that code like this would help me, but I was wrong:

public class WorkersDeserializer implements JsonDeserializer<Workers> {
    @Override
    public Workers deserialize(JsonElement json,
                                             Type typeOfT,
                                             JsonDeserializationContext context) throws JsonParseException {

        final JsonObject jsonObject = json.getAsJsonObject();
        List<Worker> list = new LinkedList<>();
        jsonObject.entrySet().forEach(new Consumer<Map.Entry<String, JsonElement>>() {
            @Override
            public void accept(Map.Entry<String, JsonElement> stringJsonElementEntry) {
                list.add(context.deserialize(stringJsonElementEntry.getValue(), Workers.class));
            }
        });

        Workers w =new Workers();
        w.setWorkers(list);
        return w;
    }
}

Thank you for your help.

Body:
Why not just deserialize it to a Map and then collect its values into a list?

Workers.java:

public class Workers {
    @SerializedName("address")
    private String mAddress;

    @SerializedName("workers")
    private Map<String, Worker> mWorkers;

    /* ... */
}

And then:

Workers workers = new Gson().fromJson(json, Workers.class);
List<Worker> = new ArrayList<>(workers.getWorkers().values());


问:
How to enable /std:c++17 in VS2017 with CMake
I'm trying to add the /std:c++17 compiler flag to VS2017 with CMake. I'm using the "modern" cross-platform way so far:

```<code>set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) # -std=c++11 instead of -std=gnu++11
set(MY_CXX_COMPILE_FEATURES cxx_generic_lambdas cxx_range_for cxx_strong_enums)

add_library(mylib INTERFACE)
target_compile_features(mylib INTERFACE ${MY_CXX_COMPILE_FEATURES})
</code>```

This adds /std:c++14 in VS2017 (which might be the default anyway?).
However I'm having trouble switching this to C++17 (i.e. having it add /std:c++17). If I just add it manually, I get the not-so-nice warning because both flags are present:

1>cl : Command line warning D9025: overriding '/std:c++14' with '/std:c++17'

I've tried set(CMAKE_CXX_STANDARD 17) but it has no effect, in fact the CMake documentation mentions that CMAKE_CXX_STANDARD has no effect on VS anyway.

As for adding a C++17 feature to target_compile_features, it doesn't seem like there are any yet (even in CMake-3.9.0-rc5), and even if there were, I'm specifically only using std::optional from C++17, and there's no target_compile_features flags for library features like std::optional.

So my question is, what's the best (or least ugly) way to do this with CMake? And in a way so it'll also work for gcc and clang? I'm happy to use a very recent CMake version (3.8 or 3.9). I prefer it to be "nice" and not manually looping through CXX_COMPILE_FLAGS and removing the string "/std:c++14" or some hack like that.

(Edit: It can also be the VS/std:c++latest switch - whichever is possible. Both work for the purpose.)

答:
Turning my comment into an answer

The CMake team is working on it for VS2017 (as for July 2017, for upcoming CMake version 3.10):

CMake: MSVC standard version switches

Those flags seem to be rather new switches (as related to the date of this question):

VS 2017 15.3 preview now supports /std:c++17

So for Visual Studio you have to "manually" replace or append the compiler switches until CMake officially does support it.

Here is a code snippet that I've tested for std:c++latest (which is already supported e.g. in my CMake 3.8.0 version):

if (MSVC_VERSION GREATER_EQUAL "1900")
    include(CheckCXXCompilerFlag)
    CHECK_CXX_COMPILER_FLAG("/std:c++latest" _cpp_latest_flag_supported)
    if (_cpp_latest_flag_supported)
        add_compile_options("/std:c++latest")
    endif()
endif()
```

For CLang and GNU the support was merged into the main source code branch begin of 2017 and is part of CMake version 3.8 and above:

CMake: Features: Add support for C++ 17 language standard

Body:
I'm trying to add the /std:c++17 compiler flag to VS2017 with CMake. I'm using the "modern" cross-platform way so far:

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) # -std=c++11 instead of -std=gnu++11
set(MY_CXX_COMPILE_FEATURES cxx_generic_lambdas cxx_range_for cxx_strong_enums)

add_library(mylib INTERFACE)
target_compile_features(mylib INTERFACE ${MY_CXX_COMPILE_FEATURES})

This adds /std:c++14 in VS2017 (which might be the default anyway?).
However I'm having trouble switching this to C++17 (i.e. having it add /std:c++17). If I just add it manually, I get the not-so-nice warning because both flags are present:

1>cl : Command line warning D9025: overriding '/std:c++14' with '/std:c++17'

I've tried set(CMAKE_CXX_STANDARD 17) but it has no effect, in fact the CMake documentation mentions that CMAKE_CXX_STANDARD has no effect on VS anyway.

As for adding a C++17 feature to target_compile_features, it doesn't seem like there are any yet (even in CMake-3.9.0-rc5), and even if there were, I'm specifically only using std::optional from C++17, and there's no target_compile_features flags for library features like std::optional.

So my question is, what's the best (or least ugly) way to do this with CMake? And in a way so it'll also work for gcc and clang? I'm happy to use a very recent CMake version (3.8 or 3.9). I prefer it to be "nice" and not manually looping through CXX_COMPILE_FLAGS and removing the string "/std:c++14" or some hack like that.

(Edit: It can also be the VS/std:c++latest switch - whichever is possible. Both work for the purpose.)

Body:
Turning my comment into an answer

The CMake team is working on it for VS2017 (as for July 2017, for upcoming CMake version 3.10):

CMake: MSVC standard version switches

Those flags seem to be rather new switches (as related to the date of this question):

VS 2017 15.3 preview now supports /std:c++17

So for Visual Studio you have to "manually" replace or append the compiler switches until CMake officially does support it.

Here is a code snippet that I've tested for std:c++latest (which is already supported e.g. in my CMake 3.8.0 version):

if (MSVC_VERSION GREATER_EQUAL "1900")
    include(CheckCXXCompilerFlag)
    CHECK_CXX_COMPILER_FLAG("/std:c++latest" _cpp_latest_flag_supported)
    if (_cpp_latest_flag_supported)
        add_compile_options("/std:c++latest")
    endif()
endif()

For CLang and GNU the support was merged into the main source code branch begin of 2017 and is part of CMake version 3.8 and above:

CMake: Features: Add support for C++ 17 language standard


问:
When is space allocated for local variables?

Example

```<code>function Test: Boolean;
var
  a, b, c: Integer;
begin
  ...
end;
</code>```

When a program containing such code is executed, are a, b, and c allocated each time Test is called, or are they allocated only once somewhere in the initialization phase of the execution? I ask this because such an information is not available in the debugger.

答: Local variables are created in the stack, after the call to the function. They are removed by the called function by default when the function returns.</p>

Body:
Example

function Test: Boolean;
var
  a, b, c: Integer;
begin
  ...
end;

When a program containing such code is executed, are a, b, and c allocated each time Test is called, or are they allocated only once somewhere in the initialization phase of the execution? I ask this because such an information is not available in the debugger.

ContentLicense: CC BY-SA 2.5


问:
Ionic project Typescript errors
I've just installed ionic, cordova, and created an empty project.
Everytime I launch ionic serve it displays browser page with Typescript errors like this:

```<code>**Typescript Error**

All declarations of 'size' must have identical modifiers.
node_modules/typescript/lib/lib.es2015.collection.d.ts
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
Typescript Error
All declarations of 'prototype' must have identical modifiers.
node_modules/typescript/lib/lib.es2015.collection.d.ts
new (): WeakMap<object, any>;
new <K extends object, V>(entries?: [K, V][]): WeakMap<K, V>;
readonly prototype: WeakMap<object, any>;
</code>```

I have searched through the internet, and haven't found any solutions (
Ionic info log:

global packages:

```<code>@ionic/cli-utils : 1.4.0
Ionic CLI        : 3.4.0
</code>```

local packages:

```<code>@ionic/app-scripts              : 1.3.12
@ionic/cli-plugin-ionic-angular : 1.3.1
Ionic Framework                 : ionic-angular 3.5.0
</code>```

System:

```<code>Node       : v7.2.0
OS         : OS X El Capitan
Xcode      : Xcode 8.2.1 Build version 8C1002
ios-deploy : not installed
ios-sim    : not installed
npm        : 4.1.1
</code>```

答:
Not sure if this is a correct solution, what I did is in tsconfig.json
I set the types to empty array:

```<code>"compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "types": []
</code>```

Also this guys suggested to install typings lodash (npm install @types/lodash --save-dev --save-exact) https://stackoverflow.com/a/44032856/4984738

then I set "types": ["lodash"], which is also works. Please give any comments if there is a better solution. Because in my other project it doesnt resolve all the issues, not sure its a project issues or still due to the typescript

Title: Ionic project Typescript errors

Body:
I've just installed ionic, cordova, and created an empty project.
Everytime I launch ionic serve it displays browser page with Typescript errors like this:

**Typescript Error**

All declarations of 'size' must have identical modifiers.
node_modules/typescript/lib/lib.es2015.collection.d.ts
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
Typescript Error
All declarations of 'prototype' must have identical modifiers.
node_modules/typescript/lib/lib.es2015.collection.d.ts
new (): WeakMap<object, any>;
new <K extends object, V>(entries?: [K, V][]): WeakMap<K, V>;
readonly prototype: WeakMap<object, any>;

I have searched through the internet, and haven't found any solutions (
Ionic info log:

global packages:

@ionic/cli-utils : 1.4.0
Ionic CLI        : 3.4.0

local packages:

@ionic/app-scripts              : 1.3.12
@ionic/cli-plugin-ionic-angular : 1.3.1
Ionic Framework                 : ionic-angular 3.5.0

System:

Node       : v7.2.0
OS         : OS X El Capitan
Xcode      : Xcode 8.2.1 Build version 8C1002
ios-deploy : not installed
ios-sim    : not installed
npm        : 4.1.1

Body:
Not sure if this is a correct solution, what I did is in tsconfig.json
I set the types to empty array:

"compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "types": []

Also this guys suggested to install typings lodash (npm install @types/lodash --save-dev --save-exact) https://stackoverflow.com/a/44032856/4984738

then I set "types": ["lodash"], which is also works. Please give any comments if there is a better solution. Because in my other project it doesnt resolve all the issues, not sure its a project issues or still due to the typescript


问:
How to send urlencoded parameters in POST request in python
I'm trying to deploy my production ready code to Heroku to test it. Unfortunately, it is not taking JSON data so we converted into x-www-form-urlencoded.

```<code>params = urllib.parse.quote_plus(json.dumps({
    'grant_type': 'X',
    'username': 'Y',
    'password': 'Z'
}))
r = requests.post(URL, data=params)
print(params)
</code>```

It is showing an error in this line as I guess data=params is not in proper format.

Is there any way to POST the urlencoded parameters to an API?

答:
You don't need to explicitly encode it, simply pass your dict to data argument and it will be encoded automatically.

```<code>>>> r = requests.post(URL, data = {'key':'value'})
</code>```

From the official documentation:

Typically, you want to send some form-encoded data — much like an HTML
form. To do this, simply pass a dictionary to the data argument. Your
dictionary of data will automatically be form-encoded when the request
is made

Body:
I'm trying to deploy my production ready code to Heroku to test it. Unfortunately, it is not taking JSON data so we converted into x-www-form-urlencoded.

params = urllib.parse.quote_plus(json.dumps({
    'grant_type': 'X',
    'username': 'Y',
    'password': 'Z'
}))
r = requests.post(URL, data=params)
print(params)

It is showing an error in this line as I guess data=params is not in proper format.

Is there any way to POST the urlencoded parameters to an API?

Body:
You don't need to explicitly encode it, simply pass your dict to data argument and it will be encoded automatically.

>>> r = requests.post(URL, data = {'key':'value'})

From the official documentation:

Typically, you want to send some form-encoded data — much like an HTML
form. To do this, simply pass a dictionary to the data argument. Your
dictionary of data will automatically be form-encoded when the request
is made


问:
Style first 2 TextViews in Android ListView differently
I have a ListView and I want the first two entries in it to be displayed differently than the rest. Nothing fancy, I want them all to just be text views. But the first two entries need to have different sizes and weights than the rest. I tried modifying the ArrayAdapter class like so:

```<code>private class BusStopAdapter<T> extends ArrayAdapter<T>{

  public BusStopAdapter(
    Context context, int textViewResourceId,
    List<T> objects)
  {
    super(context, textViewResourceId, objects);
  }

  public View getView(int position, View convertView,
    ViewGroup parent)
  {
    TextView toReturn =
      (TextView)super.getView(position, convertView, parent);
    if(position == 0){
     toReturn.setTextSize(12);
     toReturn.setText("Previous Bus: " + toReturn.getText());
     toReturn.setPadding(0,0,0,0);
    }
    else if(position == 1){
      toReturn.setTextSize(20);
      toReturn.setPadding(
        toReturn.getPaddingLeft(),
        0,
        toReturn.getPaddingRight(),
        0
      );
      toReturn.setText("Next Bus: " + toReturn.getText());
      toReturn.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);
    }
    return toReturn;
  }

}
</code>```

But this inadvertantly causes some of the other textviews to take on these special attributes. I think it's because cause textviews get "recycled" in the AbsListAdapter class.

答:
Try like this:

```<code>if(position == 0){
     toReturn.setTextSize(12);
     toReturn.setText("Previous Bus: " + toReturn.getText());
     toReturn.setPadding(0,0,0,0);
    }
    else if(position == 1){
      toReturn.setTextSize(20);
      toReturn.setPadding(
        toReturn.getPaddingLeft(),
        0,
        toReturn.getPaddingRight(),
        0
      );
   else
      style it normally or whatever you want.........
</code>```

Body:
I have a ListView and I want the first two entries in it to be displayed differently than the rest. Nothing fancy, I want them all to just be text views. But the first two entries need to have different sizes and weights than the rest. I tried modifying the ArrayAdapter class like so:

private class BusStopAdapter<T> extends ArrayAdapter<T>{

  public BusStopAdapter(
    Context context, int textViewResourceId,
    List<T> objects)
  {
    super(context, textViewResourceId, objects);
  }

  public View getView(int position, View convertView,
    ViewGroup parent)
  {
    TextView toReturn =
      (TextView)super.getView(position, convertView, parent);
    if(position == 0){
     toReturn.setTextSize(12);
     toReturn.setText("Previous Bus: " + toReturn.getText());
     toReturn.setPadding(0,0,0,0);
    }
    else if(position == 1){
      toReturn.setTextSize(20);
      toReturn.setPadding(
        toReturn.getPaddingLeft(),
        0,
        toReturn.getPaddingRight(),
        0
      );
      toReturn.setText("Next Bus: " + toReturn.getText());
      toReturn.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);
    }
    return toReturn;
  }

}

But this inadvertantly causes some of the other textviews to take on these special attributes. I think it's because cause textviews get "recycled" in the AbsListAdapter class.

Body:
Try like this:

if(position == 0){
     toReturn.setTextSize(12);
     toReturn.setText("Previous Bus: " + toReturn.getText());
     toReturn.setPadding(0,0,0,0);
    }
    else if(position == 1){
      toReturn.setTextSize(20);
      toReturn.setPadding(
        toReturn.getPaddingLeft(),
        0,
        toReturn.getPaddingRight(),
        0
      );
   else
      style it normally or whatever you want.........


问:
Generate all possible choices of elements each from a distinct set
Suppose that we have k sets each of which contains q elements. I want to generate all possible sets in which we select exactly 1 element from each set. Assume that the sets are represented as a table where each row is a set and its columns are its elements. Also assume that all elements are indexed row-wise like this

Set 1: 1 2 3

Set 2: 4 5 6

Set 3: 7 8 9

The thing is that k,q may vary so I cannot use nested for loops. I work in C++ and this structure is actually a std::vector of std::vector of int, but I am not asking for code here, just an idea on how to do this.

答:
Recursive

```<code>using sets = vector<vector<int>>;

void rec(int index, const sets& s, vector<int>& v) {
    for (int next : s[index]) {
        v[index] = next;
        if (index + 1 == s.size()) {
            output(v);
        } else {
            rec(index+1, s, v);
        }
    }
}

int main() {
    sets s = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int q = s[0].size();
    vector<int> v(q);
    rec(0, s, v);
    return 0;
}
</code>```

Non recursive

The main idea is that every choice can be encoded by a number in base-q numeral system. And all you need to do is to iterate through all base-q numbers with length <= n. Every digit of the number is an index in the corresponding set.

For example, we have 2 sets with 3 numbers. You need to iterate through {00, 01, 02, 10, 11, 12, 20, 21, 22}.

```<code>using sets = vector<vector<int>>;

void non_rec(const sets& s) {
    int q = s[0].size();
    int k = s.size();
    vector<int> v(q);
    int cnt = (int)pow(q, k);

    for (int i = 0; i < cnt; ++i) {
        int tmp = i;
        for (int j = 0; j < k; ++j) {
            v[j] = s[j][tmp % q];
            tmp /= q;
        }
        output(v);
    }
}

int main() {
    sets s = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    non_rec(s);
    return 0;
}
</code>```

http://ideone.com/V58I7W

Body:
Recursive

using sets = vector<vector<int>>;

void rec(int index, const sets& s, vector<int>& v) {
    for (int next : s[index]) {
        v[index] = next;
        if (index + 1 == s.size()) {
            output(v);
        } else {
            rec(index+1, s, v);
        }
    }
}

int main() {
    sets s = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int q = s[0].size();
    vector<int> v(q);
    rec(0, s, v);
    return 0;
}

Non recursive

The main idea is that every choice can be encoded by a number in base-q numeral system. And all you need to do is to iterate through all base-q numbers with length <= n. Every digit of the number is an index in the corresponding set.

For example, we have 2 sets with 3 numbers. You need to iterate through {00, 01, 02, 10, 11, 12, 20, 21, 22}.

using sets = vector<vector<int>>;

void non_rec(const sets& s) {
    int q = s[0].size();
    int k = s.size();
    vector<int> v(q);
    int cnt = (int)pow(q, k);

    for (int i = 0; i < cnt; ++i) {
        int tmp = i;
        for (int j = 0; j < k; ++j) {
            v[j] = s[j][tmp % q];
            tmp /= q;
        }
        output(v);
    }
}

int main() {
    sets s = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    non_rec(s);
    return 0;
}

http://ideone.com/V58I7W


问:
How to correctly swap some characters in string
I have a string that represents a date:

```<code>"12.27.1995"
</code>```

I need to swap the month and the day to get:

```<code>"27.12.1995"
</code>```

I did:

```<code>date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]
</code>```

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

答:
While the answer by @sawa is perfectly valid and should be used here, I would show some technic which is wrong and should not be used here, but might be helpful for anybody to swap two fixed parts of the string:

```<code>"12.27.1995".tap { |s| s[0..1], s[3..4] = s[3..4], s[0..1] }
#⇒ "27.12.1995"
</code>```

Body:
I have a string that represents a date:

"12.27.1995"

I need to swap the month and the day to get:

"27.12.1995"

I did:

date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

Body:
While the answer by @sawa is perfectly valid and should be used here, I would show some technic which is wrong and should not be used here, but might be helpful for anybody to swap two fixed parts of the string:

"12.27.1995".tap { |s| s[0..1], s[3..4] = s[3..4], s[0..1] }
#⇒ "27.12.1995"


问:
StringBuilder and string equality check
I am trying this sample of code and OpTest when System.Console.WriteLine(s == t); it returns false. Can somebody explain this?

```<code>public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "строка";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
    System.Console.Write(sb);
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}
</code>```

答:
Your generic method will basically be performing a reference equality check - and the values of s1 and s2 refer to different but equal strings. You can show this more easily like this:

```<code>string x = "test";
string y = new string(x.ToCharArray());
Console.WriteLine(x == y); // Use string overload, checks for equality, result = true
Console.WriteLine(x.Equals(y)); // Use overridden Equals method, result = true
Console.WriteLine(ReferenceEquals(x, y)); // False because they're different objects
Console.WriteLine((object) x == (object) y); // Reference comparison again - result = false
</code>```

Note that your constraint in OpTest doesn't change which == operator is used. That's determined at compile-time, based on the constraints on T. Note that operators are never overridden, only overloaded. That means the implementation is chosen at compile-time, regardless of the type at execution time.

If you constrained T to derive from some type which overloads the == operator, then the compiler will use that overload. For example:

```<code>using System;

class SillyClass
{
    public static string operator ==(SillyClass x, SillyClass y) => "equal";
    public static string operator !=(SillyClass x, SillyClass y) => "not equal";
}

class SillySubclass : SillyClass
{
    public static string operator ==(SillySubclass x, SillySubclass y) => "sillier";
    public static string operator !=(SillySubclass x, SillySubclass y) => "very silly";
}

class Test
{
    static void Main()
    {
        var x = new SillySubclass();
        var y = new SillySubclass();
        OpTest(x, y);
    }

    static void OpTest<T>(T x, T y) where T : SillyClass
    {
        Console.WriteLine(x == y);
        Console.WriteLine(x != y);
    }
}
</code>```

Here the OpTest method does use the overloaded operators - but only ever the ones from SillyClass, not SillySubclass.

Title: StringBuilder and string equality check

Body:
I am trying this sample of code and OpTest when System.Console.WriteLine(s == t); it returns false. Can somebody explain this?

public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "строка";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
    System.Console.Write(sb);
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}

Body:
Your generic method will basically be performing a reference equality check - and the values of s1 and s2 refer to different but equal strings. You can show this more easily like this:

string x = "test";
string y = new string(x.ToCharArray());
Console.WriteLine(x == y); // Use string overload, checks for equality, result = true
Console.WriteLine(x.Equals(y)); // Use overridden Equals method, result = true
Console.WriteLine(ReferenceEquals(x, y)); // False because they're different objects
Console.WriteLine((object) x == (object) y); // Reference comparison again - result = false

Note that your constraint in OpTest doesn't change which == operator is used. That's determined at compile-time, based on the constraints on T. Note that operators are never overridden, only overloaded. That means the implementation is chosen at compile-time, regardless of the type at execution time.

If you constrained T to derive from some type which overloads the == operator, then the compiler will use that overload. For example:

using System;

class SillyClass
{
    public static string operator ==(SillyClass x, SillyClass y) => "equal";
    public static string operator !=(SillyClass x, SillyClass y) => "not equal";
}

class SillySubclass : SillyClass
{
    public static string operator ==(SillySubclass x, SillySubclass y) => "sillier";
    public static string operator !=(SillySubclass x, SillySubclass y) => "very silly";
}

class Test
{
    static void Main()
    {
        var x = new SillySubclass();
        var y = new SillySubclass();
        OpTest(x, y);
    }

    static void OpTest<T>(T x, T y) where T : SillyClass
    {
        Console.WriteLine(x == y);
        Console.WriteLine(x != y);
    }
}

Here the OpTest method does use the overloaded operators - but only ever the ones from SillyClass, not SillySubclass.


问:
Partition a spark dataframe based on column value?
i have a dataframe from a sql source which looks like:

```<code>User(id: Long, fname: String, lname: String, country: String)

[1, Fname1, Lname1, Belarus]
[2, Fname2, Lname2, Belgium]
[3, Fname3, Lname3, Austria]
[4, Fname4, Lname4, Australia]
</code>```

I want to partition and write this data into csv files where each partition is based on initial letter of the country, so Belarus and Belgium should be one in output file, Austria and Australia in other.

答:
One alternative to solve this problem would be to first create a column containing only the first letter of each country. Having done this step, you could use partitionBy to save each partition to separate files.

```<code>dataFrame.write.partitionBy("column").format("com.databricks.spark.csv").save("/path/to/dir/")
</code>```

Body:
i have a dataframe from a sql source which looks like:

User(id: Long, fname: String, lname: String, country: String)

[1, Fname1, Lname1, Belarus]
[2, Fname2, Lname2, Belgium]
[3, Fname3, Lname3, Austria]
[4, Fname4, Lname4, Australia]

I want to partition and write this data into csv files where each partition is based on initial letter of the country, so Belarus and Belgium should be one in output file, Austria and Australia in other.

Body:
One alternative to solve this problem would be to first create a column containing only the first letter of each country. Having done this step, you could use partitionBy to save each partition to separate files.

dataFrame.write.partitionBy("column").format("com.databricks.spark.csv").save("/path/to/dir/")


问:
eXML-PARSER output contains unwanted hash references
So I wrote a parser routine to take one xml file and reparse into another one. This code I later modified to split a large xml file into many small xml files.

I am having a problem with an output. Parsing works fine the only thing output also includes unwanted strings like HASH(0x19f9b58), I am not sure why and need set of friendly eyes.

```<code> use Encode;
    use XML::Parser;
    my $parser = XML::Parser->new( Handlers => {Start => \&handle_elem_start,
End => \&handle_elem_end,Char => \&handle_char_data,});
    my $record;
    my $file = shift @ARGV;

    if( $file ) {$parser->parsefile( $file );}
    exit;

    sub handle_elem_start
    {
        my( $expat, $name, %atts ) = @_;

        if ($name eq 'articles'){$file="_data.xml";unlink($file);}
        $record .= "<";
        $record .= "$name";
        foreach my $key (keys %atts){$record .= " $key=\"$atts{$key}\"";}
        $record .= ">";
    }
    sub handle_char_data
    {
        my( $expat, $text ) = @_;
        $text = decode_utf8( $text );
        $record .= "$text";
    }
    sub handle_elem_end
    {
        my( $expat, $name ) = @_;
        $record .= "</$name>";
        if( $name eq 'article' )
        {
            open (MYFILE, '>>'.$file);
            print MYFILE $record;
            close (MYFILE);
            print $record;
            $record = {};
        }
        return unless( $name eq 'article' );
    }
</code>```

Sample output:

```<code>...
</article>HASH(0x19f9b40)
<article doi="10.1103/PhysRevSeriesI.9.304">
<journal short="Phys. Rev. (Series I)" jcode="PRI">Physical Review (Series I)</journal>
<volume>9</volume>
<issue printdate="1899-11-00">5</issue>
<fpage>304</fpage>
<lpage>309</lpage>
<seqno>1</seqno>
<price></price><tocsec>Articles</tocsec>
<arttype type="article"></arttype><doi>10.1103/PhysRevSeriesI.9.304</doi>
<title>An Investigation of the Magnetic Qualities of Building Brick</title>
<authgrp>
<author><givenname>O.</givenname><middlename>A.</middlename><surname>Gage</surname></author>
<author><givenname>H.</givenname><middlename>E.</middlename><surname>Lawrence</surname></author>
</authgrp>
<cpyrt>
<cpyrtdate date="1899"></cpyrtdate><cpyrtholder>The American Physical Society</cpyrtholder>
</cpyrt>
</article>HASH(0x19f9b58)
...
</code>```

HASH strings are not wanted, please advise.

答:
```<code>$record = {};
</code>```

sets $record to contain a reference to an empty hash.  But everywhere else, you treat $record as a string, and append to it.  When you treat a hashref as a string, you get a string like HASH(0x19f9b58) (the number varies).

You probably meant

```<code>$record = q{};
</code>```

which sets $record to the empty string (just using alternate quotes).

Body:
So I wrote a parser routine to take one xml file and reparse into another one. This code I later modified to split a large xml file into many small xml files.

I am having a problem with an output. Parsing works fine the only thing output also includes unwanted strings like HASH(0x19f9b58), I am not sure why and need set of friendly eyes.

 use Encode;
    use XML::Parser;
    my $parser = XML::Parser->new( Handlers => {Start => \&handle_elem_start,
End => \&handle_elem_end,Char => \&handle_char_data,});
    my $record;
    my $file = shift @ARGV;

    if( $file ) {$parser->parsefile( $file );}
    exit;

    sub handle_elem_start
    {
        my( $expat, $name, %atts ) = @_;

        if ($name eq 'articles'){$file="_data.xml";unlink($file);}
        $record .= "<";
        $record .= "$name";
        foreach my $key (keys %atts){$record .= " $key=\"$atts{$key}\"";}
        $record .= ">";
    }
    sub handle_char_data
    {
        my( $expat, $text ) = @_;
        $text = decode_utf8( $text );
        $record .= "$text";
    }
    sub handle_elem_end
    {
        my( $expat, $name ) = @_;
        $record .= "</$name>";
        if( $name eq 'article' )
        {
            open (MYFILE, '>>'.$file);
            print MYFILE $record;
            close (MYFILE);
            print $record;
            $record = {};
        }
        return unless( $name eq 'article' );
    }

Sample output:

...

HASH(0x19f9b40)

<journal short="Phys. Rev. (Series I)" jcode="PRI">Physical Review (Series I)</journal>
<volume>9</volume>
<issue printdate="1899-11-00">5</issue>
<fpage>304</fpage>
<lpage>309</lpage>
<seqno>1</seqno>
<price></price><tocsec>Articles</tocsec>
<arttype type="article"></arttype><doi>10.1103/PhysRevSeriesI.9.304</doi>
<title>An Investigation of the Magnetic Qualities of Building Brick</title>
<authgrp>
<author><givenname>O.</givenname><middlename>A.</middlename><surname>Gage</surname></author>
<author><givenname>H.</givenname><middlename>E.</middlename><surname>Lawrence</surname></author>
</authgrp>
<cpyrt>
<cpyrtdate date="1899"></cpyrtdate><cpyrtholder>The American Physical Society</cpyrtholder>
</cpyrt>

HASH(0x19f9b58)
...

HASH strings are not wanted, please advise.

Body:
$record = {};

sets $record to contain a reference to an empty hash.  But everywhere else, you treat $record as a string, and append to it.  When you treat a hashref as a string, you get a string like HASH(0x19f9b58) (the number varies).

You probably meant

$record = q{};

which sets $record to the empty string (just using alternate quotes).