问:
Reorder a vector with wrap around in R
Let's say I have a simple vector x in R. It is in the order 'a','b','c','d'. Is there a function that would take the vector and reorder it with wrap around? For example, how can I get x to be 'c','d','a','b'?

```<code>#Vector x
> x <- letters[1:4]
> x
[1] "a" "b" "c" "d"

#What I want:
> somefcn(x, 3)
[1] "c" "d" "a" "b"
</code>```

答:
```<code>x <- letters[1:4]
shiftnum <- 3
c(x[shiftnum:length(x)],x[1:shiftnum-1])

[1] "c" "d" "a" "b"
</code>```

Is a very rough way to do, but it works

Title: Reorder a vector with wrap around in R

Body:
Let's say I have a simple vector x in R. It is in the order 'a','b','c','d'. Is there a function that would take the vector and reorder it with wrap around? For example, how can I get x to be 'c','d','a','b'?

#Vector x
> x <- letters[1:4]
> x
[1] "a" "b" "c" "d"

#What I want:
> somefcn(x, 3)
[1] "c" "d" "a" "b"

Body:
x <- letters[1:4]
shiftnum <- 3
c(x[shiftnum:length(x)],x[1:shiftnum-1])

[1] "c" "d" "a" "b"

Is a very rough way to do, but it works


来源: stackexchange

问:
I have two sets of string,I want get result of combination
I have two sets

```<code>val set1 = { "A", "B", "C" }
val Set2 = { "all", "all", "all" }

//I want get this result :
result[0]={"A", "B", "C"}
result[1]={"all", "B", "C"}
result[2]={"a", "all", "C"}
...
result[n]={"all", "all", "all"}
</code>```

how can I do this function.
Thanks a lot

答:
I don't know if this is the most efficient way. You first want to zip the two sequences, because their elements should always align.

```<code>val seq1 = List("A", "B", "C")
val seq2 = List("all", "all", "all")

val z = seq1 zip seq2 // -> List("A" -> "all", "B" -> "all", "C" -> "all")
</code>```

Then you have to find a way to permutate and assemble (flatMap) all the possibilities:

```<code>def build[A](in: List[(A, A)]): List[List[A]] = in match {
  case Nil => List(Nil)
  case (a, b) :: tail =>
     val tr = build(tail)
     tr.flatMap(xs => List(a :: xs, b :: xs))
}

build(z).foreach(println)

// ->
// List(A, B, C)
// List(all, B, C)
// List(A, all, C)
// List(all, all, C)
// List(A, B, all)
// List(all, B, all)
// List(A, all, all)
// List(all, all, all)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two sets

val set1 = { "A", "B", "C" }
val Set2 = { "all", "all", "all" }

//I want get this result :
result[0]={"A", "B", "C"}
result[1]={"all", "B", "C"}
result[2]={"a", "all", "C"}
...
result[n]={"all", "all", "all"}

how can I do this function.
Thanks a lot

Body:
I don't know if this is the most efficient way. You first want to zip the two sequences, because their elements should always align.

val seq1 = List("A", "B", "C")
val seq2 = List("all", "all", "all")

val z = seq1 zip seq2 // -> List("A" -> "all", "B" -> "all", "C" -> "all")

Then you have to find a way to permutate and assemble (flatMap) all the possibilities:

def build[A](in: List[(A, A)]): List[List[A]] = in match {
  case Nil => List(Nil)
  case (a, b) :: tail =>
     val tr = build(tail)
     tr.flatMap(xs => List(a :: xs, b :: xs))
}

build(z).foreach(println)

// ->
// List(A, B, C)
// List(all, B, C)
// List(A, all, C)
// List(all, all, C)
// List(A, B, all)
// List(all, B, all)
// List(A, all, all)
// List(all, all, all)


问:
Electron packaging errors
I am new to Electron and love it.  Just finished writing a wonderful little app for the entertainment industry and am having trouble packaging it.  Also notice that there is an electron compiler and a packager.  Which one do you use that is most convenient for a windows end user ?  I work with mostly windows people in a certain segment of the entertainment biz, so being a Linux user you get tons of flack if something does not work. Here is the problem :

```<code>package.json:

{
  "name": "Sick Bay Scanner by H.A. Hobson",
  "productName": "SickBayScanner",
  "version": "1.0.1",
  "main": "main.js",
  "devDependencies": {
    "electron-winstaller": "^2.6.3"
  }

}
</code>```

Packaging argument and outome :

```<code>me@debian:/$ electron-packager --electron-version=1.7.9 . sound/SickBayScanner --overwrite --asar=true --platform=win32 --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds
WARNING: --asar does not take any arguments, it only has sub-properties (see --help)
Downloading tmp-6742-0-electron-v1.7.9-win32-x64.zip
[============================================>] 100.0% of 53.89 MB (421.05 kB/s)
Packaging app for platform win32 x64 using electron v1.7.9
EPERM: operation not permitted, open '/dev/core'
</code>```

If you could explain how to create electron apps that are as easy possible for an end user to use, whether packaged or compiled, and point out my own packaging issue, would be very appreciative.  Thanks !

答:
Is this everything included in your package.json? Do you have other dependencies?

If you do, please edit your question, this has been one of the reasons why I have seen this error in the past.

<s>Make sure you install electron-builder and add something like this to you package.json:</s>

<s>"postinstall": "npm install --save electron-builder && npm install
--save [any other dependency you didn't mention] && install-app-deps</s>"

<s>this will ensure you properly install these dependencies for the system you intend to use the app on.</s>

I recommend using electron-packager as it will automatically detect the system for you.

Edit:

okay, you won't need install-app-deps since you don't have any major dependencies that need to be built from source to target windows env, as you mentioned in your comment below. So you just need to install wine. Problem is, i don't think there's a workaround installing it globally on the machine you will be use to package your app. Here's the closest solution i found: https://github.com/rahatarmanahmed/electron-packager-dummy-wine I haven't tested it and please note the readme mentions there are caveats :("

Title: Electron packaging errors

Body:
I am new to Electron and love it.  Just finished writing a wonderful little app for the entertainment industry and am having trouble packaging it.  Also notice that there is an electron compiler and a packager.  Which one do you use that is most convenient for a windows end user ?  I work with mostly windows people in a certain segment of the entertainment biz, so being a Linux user you get tons of flack if something does not work. Here is the problem :

package.json:

{
  "name": "Sick Bay Scanner by H.A. Hobson",
  "productName": "SickBayScanner",
  "version": "1.0.1",
  "main": "main.js",
  "devDependencies": {
    "electron-winstaller": "^2.6.3"
  }

}

Packaging argument and outome :

me@debian:/$ electron-packager --electron-version=1.7.9 . sound/SickBayScanner --overwrite --asar=true --platform=win32 --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds
WARNING: --asar does not take any arguments, it only has sub-properties (see --help)
Downloading tmp-6742-0-electron-v1.7.9-win32-x64.zip
[============================================>] 100.0% of 53.89 MB (421.05 kB/s)
Packaging app for platform win32 x64 using electron v1.7.9
EPERM: operation not permitted, open '/dev/core'

If you could explain how to create electron apps that are as easy possible for an end user to use, whether packaged or compiled, and point out my own packaging issue, would be very appreciative.  Thanks !


问:
Visual Studio Online migration (VSO to VSO)
We are attempting to migrate from one Visual Studio Online account to another Visual Studio Online account. This is different from an on-premise TFS to Visual Studio Online migration. Most articles explain a migration using the on-premise to VSO approach, only.

Accounts

https:\vsoaccount1.visualstudio.com\DefaultCollection

https:\vsoaccount2.visualstudio.com\DefaultCollection

For TFS to VSO, we found a solution by using OpsHub Visual Studio Online Migration Utility.

We also tried to use the same tool to point to another Visual Studio Online account as a source, but it fails stating that we can only point to a TFS instance.

Can this be done via scripting? If so, how? If there is a tool available, that would be great also. This should be a one time migration.

Update:

We need code only, including changesets, no work items. The project is using TFVC.

答:
For others that stumble across this thread, I have found this - the Visual Studio Team Services Sync & Migration Engine an open source project that appears to do TFS-TFS, TFS-VSTS, VSTS-TFS and VSTS-VSTS migration. It is an open source project initiated with the same purpose as the TFS Integration Platform, but to address some of the complexities (and the fact that it is now deprecated).

From the web site:

Visual Studio Team Services Sync & Migration Engine allows you to bulk edit data in Microsoft Team Foundation Server (TFS) and Visual Studio Team Services (VSTS). Supports both migration and bulk update scenarios.


问:
Replace Text in a textfield with Image
I have a form on my website.
Inside this form a some emoji buttons.

If a user clicks one of this buttons they add an emoji to a <textfield>,
but they look like this " :) ".

So how can i replace the :) Emoji with images.

Example: If a user click a button it should add  and display it.

答:
Use the UTF8 characters for the emoji's.  Since the UTF8 emoji's are considered text characters, you don't need to use any HTML for this, and they will render in normal textarea's and text input's without anything special.

Here's a reference for some unicode UTF8 emoji's.  In your buttons code, replace the ;) or whatever with the code for the UTF8 symbol-- for example on the table in the link it shows the code U+1F600 for a smiley face.  In your script you want to say it as \u1F600 in quotes.  This will render the emoji character.  Most browsers, especially on mobile, have good support for these characters, but you can bolster that by importing an emoji font using css.

http://www.unicode.org/emoji/charts/full-emoji-list.html

Addendum:  You can even cut and paste UTF8 emoji's directly into your code.  Since they are valid characters in UTF8, they are valid code.. you could even use them in variable names

Title: Replace Text in a textfield with Image


问:
php generate date/ time in the same format appears mysql datatime
I would like to know if there is a function in php to generate data/time format like in mysql : 0000-00-00 00:00:00 .
I know you can generate data/time in the sql query with CURDATE() but I would like to know if it's possible to generate it with php in the same format mysql datatime format .</p>

答:
This should convert the standard formats:</p>

```<code>$format = 'DATETIME';

$format = str_replace(
    array('DATETIME', 'DATE', 'TIME', 'YEAR'),
    array('DATE TIME', 'Y-m-d', 'H:i:s', 'Y'),
$format);

echo date($format, time());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This should convert the standard formats:

$format = 'DATETIME';

$format = str_replace(
    array('DATETIME', 'DATE', 'TIME', 'YEAR'),
    array('DATE TIME', 'Y-m-d', 'H:i:s', 'Y'),
$format);

echo date($format, time());


问:
Unable to download groovy.jar
Any help appreciated.

I'm new to Maven. I got the below command from tutorials point

```<code>mvn archetype:generate -DgroupId=com.tutorialpoint.app -DartifactId=camel-first-app -DarchetypeGroupId=org.apache.camel.archetypes -DarchetypeArtifactId=camel-archetype-spring -DinteractiveMode=false
</code>```

it is failing with below error:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom ---
Downloading:
http://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.981s
[INFO] Finished at: Tue Nov 14 23:11:42 IST 2017
[INFO] Final Memory: 10M/184M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.0.1:generate (default-cli) on project standalone-pom: Execution default-cli of goal org.apache.maven.plugins:maven-archetype-plugin:3.0.1:generate failed: Plugin org.apache.maven.plugins:maven-archetype-plugin:3.0.1 or one of its dependencies could not be resolved: Could not transfer artifact org.codehaus.groovy:groovy:jar:1.8.3 from/to central (http://repo.maven.apache.org/maven2): GET request of: org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar from central failed: Connection reset -> [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/PluginResolutionException
</code>```

Can someone please help.

答:
The relevant error is pointing to a connection problem:

Could not transfer artifact org.codehaus.groovy:groovy:jar:1.8.3
  from/to central (http://repo.maven.apache.org/maven2):  GET request
  of: org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar from central
  failed: Connection reset

The command which you posted actually runs fine on my machine. If you execute this maven command and you do not have the Groovy libraries yet, you will see that it actually downloads the following files:

https://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.pom

https://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar

It might be that you have only access to the internet via a proxy. In this case you will need to setup a proxy in the Maven configuration.

This blog here contains a fairly good description on how to setup a proxy for Maven, so that Maven can access the repository libraries.

Another option to tackle your problem would be to manually download this file using your browser:

https://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar

And then install it in your repository manually using:

```<code>mvn install:install-file -Dfile=<path-to-file> -DgroupId=org.codehaus.groovy \
    -DartifactId=groovy -Dversion=1.8.3 -Dpackaging=jar
</code>```

But normally you should not have to do this manual download + installation. Maven should be doing this for you.

Title: Unable to download groovy.jar

Body:
Any help appreciated.

I'm new to Maven. I got the below command from tutorials point

mvn archetype:generate -DgroupId=com.tutorialpoint.app -DartifactId=camel-first-app -DarchetypeGroupId=org.apache.camel.archetypes -DarchetypeArtifactId=camel-archetype-spring -DinteractiveMode=false

it is failing with below error:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom ---
Downloading:
http://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.981s
[INFO] Finished at: Tue Nov 14 23:11:42 IST 2017
[INFO] Final Memory: 10M/184M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.0.1:generate (default-cli) on project standalone-pom: Execution default-cli of goal org.apache.maven.plugins:maven-archetype-plugin:3.0.1:generate failed: Plugin org.apache.maven.plugins:maven-archetype-plugin:3.0.1 or one of its dependencies could not be resolved: Could not transfer artifact org.codehaus.groovy:groovy:jar:1.8.3 from/to central (http://repo.maven.apache.org/maven2): GET request of: org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar from central failed: Connection reset -> [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/PluginResolutionException

Can someone please help.

Body:
The relevant error is pointing to a connection problem:

Could not transfer artifact org.codehaus.groovy:groovy:jar:1.8.3
  from/to central (http://repo.maven.apache.org/maven2):  GET request
  of: org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar from central
  failed: Connection reset

The command which you posted actually runs fine on my machine. If you execute this maven command and you do not have the Groovy libraries yet, you will see that it actually downloads the following files:

https://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.pom

https://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar

It might be that you have only access to the internet via a proxy. In this case you will need to setup a proxy in the Maven configuration.

This blog here contains a fairly good description on how to setup a proxy for Maven, so that Maven can access the repository libraries.

Another option to tackle your problem would be to manually download this file using your browser:

https://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar

And then install it in your repository manually using:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=org.codehaus.groovy \
    -DartifactId=groovy -Dversion=1.8.3 -Dpackaging=jar

But normally you should not have to do this manual download + installation. Maven should be doing this for you.


问:
Is there a way I can use inline styling and CSS class at the same time?
I've been trying to do some styling for a page on BigCommerce platform, and for some components, I cannot find the styles and/or I don't want to mess with them.
for an img inside a div as follows:

```<code><div class="col-md-6 col-xs-6 saleBanner"><a href="https://www.MyURL.com/product-sale"><!-- pagebreak --><img class="SaleCategory" src="https://cdn3.bigcommerce.com/s-mystore/product_images/uploaded_images/myimg.png" alt="" /></a></div>
</code>```

I tried to add style="border-radius: 50%" to the div tag, and nothing changed. I'm not sure if it doesn't work this way or the built-in "editor" that I'm using on that platform just wouldn't allow me to do that for whatever reason.
I know this may not be the proper way to style a component, but what would be the best method for styling elements on a page that is already styled?

Thank you

答:
The problem is with using = instead of :

You tried: style="border-radius=50%"

Try instead: style="border-radius: 50%"

Body:
I've been trying to do some styling for a page on BigCommerce platform, and for some components, I cannot find the styles and/or I don't want to mess with them.
for an img inside a div as follows:

I tried to add style="border-radius: 50%" to the div tag, and nothing changed. I'm not sure if it doesn't work this way or the built-in "editor" that I'm using on that platform just wouldn't allow me to do that for whatever reason.
I know this may not be the proper way to style a component, but what would be the best method for styling elements on a page that is already styled?

Thank you


问:
React Router URL Throws Error With Parameter
I am trying to use react router to have dynamic profile pages, preferably having it in slashes rather than like a ? parameter wildcard in the URL. I'm looking for like /profile/{username}/ rather than /profile?user={username} if that makes sense.

Here's the route that I'm using to try and achieve this;

```<code><Route path="/profile/:name/" component={Profile}/>
</code>```

But when I try and go to this route as in `/profile/jeff/' or anything it returns a bundle.js (webpack'd) that is a blank HTML template, which is unexpected to be in the bundle.js and throws an error. Any idea's how I can fix this? Thanks.

Here is the bundle.js that gets returned;

```<code><html>
<body style="margin:0px; padding: 0px;">
    <link rel="stylesheet" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
    <div id = "root" style="margin:0px; padding: 0px;"></div>
    <script src="bundle.js"></script>
</body>
</code>```

Profile component;

```<code>import React from 'react';
import styles from './profile.scss';
import astyles from './allpages.scss';

export default class Profile extends React.Component{
render(){

    console.log("hello!");

    const { match, location, history } = this.props

    console.log(location);
    console.log(match);
    console.log(history);

    return(
        <div className = {styles.borderContainer}>
            <p> {this.props.param.name} </p>
        </div>
    )
}
}
</code>```

Webpack config;

```<code>var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
require('style-loader');
require('css-loader');

const loaders = {
    css: {
        loader: 'css-loader'
    },
    postcss: {
        loader: 'postcss-loader',
        options: {
            plugins: (loader) => [
                autoprefixer({
                    browsers: ['last 2 versions']
                })
            ]
        }
    },
    sass: {
        loader: 'sass-loader',
        options: {
            indentedSyntax: true,
            includePaths: [path.resolve(__dirname, './src/app')]
        }
    }
}

module.exports = {
    context: __dirname,
    entry: './src/app/index.js',
    output: {
        path: __dirname + '/dist/',
        filename: 'bundle.js',
        libraryTarget: 'umd'
    },
    devtool: "sourceMap",
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',

                    // Could also be write as follow:
                    // use: 'css-loader?modules&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader'
                    use: [
                        {
                            loader: 'css-loader',
                            query: {
                                modules: true,
                                localIdentName: '[name]__[local]___[hash:base64:5]'
                            }
                        },
                        'postcss-loader'
                    ]
                }),
            },
            {
                test: /\.scss$/,
                exclude: /node_modules/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',

                    // Could also be write as follow:
                    // use: 'css-loader?modules&importLoader=2&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]!sass-loader'
                    use: [
                        {
                            loader: 'css-loader',
                            query: {
                                modules: true,
                                sourceMap: true,
                                importLoaders: 2,
                                localIdentName: '[name]__[local]___[hash:base64:5]'
                            }
                        },
                        'sass-loader'
                    ]
                }),
            },
        ],
    },
    plugins: [
        new ExtractTextPlugin('styles.css'),
    ],
}
</code>```

答:
I don't have a better source for this, but the development server needs to be configured to handle React Routers dynamic routes because it should always serve the same html file (index.html) because it's an SPA.

https://redux.js.org/docs/advanced/UsageWithReactRouter.html

Edit:

Particularly, I think you are missing this in your webpack config

```<code>devServer: {
  historyApiFallback: true
}
</code>```

Edit 2:

For ExpressJS you would need something like this,

```<code>app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'))
})
</code>```

Body:
I am trying to use react router to have dynamic profile pages, preferably having it in slashes rather than like a ? parameter wildcard in the URL. I'm looking for like /profile/{username}/ rather than /profile?user={username} if that makes sense.

Here's the route that I'm using to try and achieve this;

<Route path="/profile/:name/" component={Profile}/>

But when I try and go to this route as in `/profile/jeff/' or anything it returns a bundle.js (webpack'd) that is a blank HTML template, which is unexpected to be in the bundle.js and throws an error. Any idea's how I can fix this? Thanks.

Here is the bundle.js that gets returned;

    <link rel="stylesheet" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">

Profile component;

import React from 'react';
import styles from './profile.scss';
import astyles from './allpages.scss';

export default class Profile extends React.Component{
render(){

    console.log("hello!");

    const { match, location, history } = this.props

    console.log(location);
    console.log(match);
    console.log(history);

    return(

 {this.props.param.name}

    )
}
}

Webpack config;

var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
require('style-loader');
require('css-loader');

const loaders = {
    css: {
        loader: 'css-loader'
    },
    postcss: {
        loader: 'postcss-loader',
        options: {
            plugins: (loader) => [
                autoprefixer({
                    browsers: ['last 2 versions']
                })
            ]
        }
    },
    sass: {
        loader: 'sass-loader',
        options: {
            indentedSyntax: true,
            includePaths: [path.resolve(__dirname, './src/app')]
        }
    }
}

module.exports = {
    context: __dirname,
    entry: './src/app/index.js',
    output: {
        path: __dirname + '/dist/',
        filename: 'bundle.js',
        libraryTarget: 'umd'
    },
    devtool: "sourceMap",
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',

                    // Could also be write as follow:
                    // use: 'css-loader?modules&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader'
                    use: [
                        {
                            loader: 'css-loader',
                            query: {
                                modules: true,
                                localIdentName: '[name]__[local]___[hash:base64:5]'
                            }
                        },
                        'postcss-loader'
                    ]
                }),
            },
            {
                test: /\.scss$/,
                exclude: /node_modules/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',

                    // Could also be write as follow:
                    // use: 'css-loader?modules&importLoader=2&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]!sass-loader'
                    use: [
                        {
                            loader: 'css-loader',
                            query: {
                                modules: true,
                                sourceMap: true,
                                importLoaders: 2,
                                localIdentName: '[name]__[local]___[hash:base64:5]'
                            }
                        },
                        'sass-loader'
                    ]
                }),
            },
        ],
    },
    plugins: [
        new ExtractTextPlugin('styles.css'),
    ],
}

Body:
I don't have a better source for this, but the development server needs to be configured to handle React Routers dynamic routes because it should always serve the same html file (index.html) because it's an SPA.

https://redux.js.org/docs/advanced/UsageWithReactRouter.html

Edit:

Particularly, I think you are missing this in your webpack config

devServer: {
  historyApiFallback: true
}

Edit 2:

For ExpressJS you would need something like this,

app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'))
})


答: It looks like it's your stylesheet inclusion. My understanding is that you should be using a babel import statement in your component, not link tags, or they will 404 causing the error you are seeing.</p>

Title: React Router URL Throws Error With Parameter


问:
Django - many-to-one relationship - how to select parent models that have children only
Say I have this model relationship in Django 1.2...

```<code>class Section(models.Model):
    title = models.CharField(max_length=200)

class Page(models.Model):
    section = models.OneToOneField(Section)
    title = models.CharField(max_length=200)
</code>```

I want to select Sections that have one or more Pages associated with them, how would I achieve this in a query? Or would I have to select all sections and then filter out one's that do not have pages manually?

答:
Change to:

```<code>class Section(models.Model):
    title = models.CharField(max_length=200)
    page = models.ForeignKey(Page, related_name="section")

class Page(models.Model):
    title = models.CharField(max_length=200)
</code>```

select Sections that have one or more Pages associated:

```<code>result_q = Section.objects.filter(page__isnull=False)
</code>```

Body:
Say I have this model relationship in Django 1.2...

class Section(models.Model):
    title = models.CharField(max_length=200)

class Page(models.Model):
    section = models.OneToOneField(Section)
    title = models.CharField(max_length=200)

I want to select Sections that have one or more Pages associated with them, how would I achieve this in a query? Or would I have to select all sections and then filter out one's that do not have pages manually?

Body:
Change to:

class Section(models.Model):
    title = models.CharField(max_length=200)
    page = models.ForeignKey(Page, related_name="section")

class Page(models.Model):
    title = models.CharField(max_length=200)

select Sections that have one or more Pages associated:

result_q = Section.objects.filter(page__isnull=False)


问:
What is the advantage of the Jenkins SonarQube plugin over adding sonar:sonar to maven build step
I am using Maven as a build tool and Jenkins as a CI tool. Currently I have a Jenkins job configured with a Maven build step.

I started using SonarQube and was wondering what is the advantage of using the Jenkins SonarQube plugin and configuring the SonarQube analysis as a post-build-action over simply adding sonar:sonar to the goals of my existing Maven build step.

Thanks and best regards,

Ronald

答:
I've just changed to maven-sonar-plugin from the Jenkins SonarQube plugin to avoid divergence of information between the pom.xml and sonar-project.properties.

For example, developers elsewhere had bumped the project version number in the pom.xml, but they don't use the Jenkins builds and didn't care about the sonar-project.properties (or probably understand it).  By switching to the maven plugin instead, the project version is defined once and referenced in the sonar property set within the pom.

The downside is that I no longer have the SonarQube link from the project's Jenkins page.

I'm not sure where the responsibility might be for adding this link back for projects using maven-sonar-plugin...  The link is "owned" by the Jenkins SonarQube Plugin, but this is not being used here.  Meanwhile the maven-sonar-plugin component is integrating with maven not Jenkins.

Something would need to observe the build and extract the SonarQube link which is emitted as a [INFO] ANALYSIS SUCCESSFUL, you can browse http://... line in the log.


问:
Java: get type from param and create array of type
Trying to create this:

```<code>class Widget
{
  public Widget(Object type)
  {
    Object typeCheck = type.getClass();
    (typeCheck class)[] = new (typeCheck class)[0];
  {
}
</code>```

Where getting the type of typeCheck and using that to create an array is the troublesome bit.  Is there an actual logical way to do this?  Or should I just parse the result of getClass() and do it that way?

答:
Theres a creator in Array class that accepts Class as argument and returns an Object that is a array.

```<code>Object typeCheck = type.getClass();
Object[] = (Object[]) new Array.newInstance(typeCheck, 0);
</code>```

But you cant cast to the generified type captured from getClass() you have to use Object.

So you have three options.

1) Use the properly type if you know all methods

2) Use reflection all the way down

3) Use Generics with a interface, that also will give you compile time methods to call:

```<code>class Widget<T extends Component> {
    public Widget(T type) {
      T[] ts = new T[0];
    }
}
</code>```

Body:
Trying to create this:

class Widget
{
  public Widget(Object type)
  {
    Object typeCheck = type.getClass();
    (typeCheck class)[] = new (typeCheck class)[0];
  {
}

Where getting the type of typeCheck and using that to create an array is the troublesome bit.  Is there an actual logical way to do this?  Or should I just parse the result of getClass() and do it that way?

Body:
Theres a creator in Array class that accepts Class as argument and returns an Object that is a array.

Object typeCheck = type.getClass();
Object[] = (Object[]) new Array.newInstance(typeCheck, 0);

But you cant cast to the generified type captured from getClass() you have to use Object.

So you have three options.

1) Use the properly type if you know all methods

2) Use reflection all the way down

3) Use Generics with a interface, that also will give you compile time methods to call:

class Widget<T extends Component> {
    public Widget(T type) {
      T[] ts = new T[0];
    }
}


问:
Http Get Request - what data is actually send?
I'm currently building a web spider with java apache commons. I'm crawling basic google search queries like https://google.com/search?q=word&hl=en

Somehow after about 60 queries I get blocked, it seems they recognize me as a bot and I get a 503 Service Unavailable response

Now the important part:
If I visit the same site with firefox/chrome I get the desired result.
If I make a GET Request with my Application using the same http header (user-agent, cookies, cache etc.) I am still blocked.

HOW does Google know whether I'm connecting via Application or Chrome-Browser, when there is only the IP and the HTTP-Header as Information?(maybe I'm wrong?)
Are there more parameters to recognize my App? Something that Google sees and I don't?

(Maybe important: I'm using Chrome Developer Tools and httpbin.org to compare the headers of Browser and Application.)

Thanks a lot

答:
Since you have not specified how quickly you send the 60 queries, I am assuming at a high rate. This is why google is blocking you. Several times I have rapidly done google searches from chrome and it asks for a captcha after a while and then blocks soon after.

Please see the API on Custom Search and this post about terms of Service Replacement for Google API

FAQ on blocked searches: Google FAQ


问:
Get letters from string swift
I want to get all letters into an array from the string.
Suppose I have string which contains letters and numeric then I want to get only all letters of the string.

```<code>let myString = "so123han"
</code>```

Then output should be in array like this:

```<code>let arrayOfLetters = ["s","o","h","a","n"]
</code>```

答:
You can do like this!!</p>

```<code>let myString = "so123han"
var arr = [String]()

for i in myString.unicodeScalars{
    if CharacterSet.letters.contains(i){
        arr.append("\(i)")
    }
}
</code>```

Title: Get letters from string swift

Body:
I want to get all letters into an array from the string.
Suppose I have string which contains letters and numeric then I want to get only all letters of the string.

let myString = "so123han"

Then output should be in array like this:

let arrayOfLetters = ["s","o","h","a","n"]

Body:
You can do like this!!

let myString = "so123han"
var arr = [String]()

for i in myString.unicodeScalars{
    if CharacterSet.letters.contains(i){
        arr.append("\(i)")
    }
}


问:
Constructing a std::string_view from a braced std::string, clang and gcc disagree with -Wconversion
GCC 7.2 and clang 5.0 seem to disagree about the following code when compiled with -std=c++17 -Werror -Wconversion:

```<code>#include <iostream>
#include <string>
#include <string_view>

int main(int argc, char* argv[]) {
    std::string s = "Hello, World";
    std::string_view vs{s};
    std::cout << std::string{vs} << '\n';
    return EXIT_SUCCESS;
}
</code>```

Compiled with clang++ -std=c++17 -Wall -Werror -Wconversion, it compiles correctly (see https://godbolt.org/g/JZn8cL)

However, GCC 7.2 issues a somewhat perplexing diagnostic (see https://godbolt.org/g/kmYbJ3):

```<code><source>: In function 'int main(int, char**)':
7 : <source>:7:26: error: choosing 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type() const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type = std::basic_string_view<char>]' over 'constexpr std::basic_string_view<_CharT, _Traits>::basic_string_view(const std::basic_string_view<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]' [-Werror=conversion]
     std::string_view vs{s};
                          ^
7 : <source>:7:26: error:   for conversion from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'std::basic_string_view<char>' [-Werror=conversion]
7 : <source>:7:26: note:   because conversion sequence for the argument is better
cc1plus: all warnings being treated as errors
Compiler exited with result code 1
</code>```

Both compilers compile the code fine after changing vs{s} to vs(s).

Which compiler is right here? Is brace initialization of a std::string_view from a std::string running afoul of conversion rules somehow, and clang is failing to issue a diagnostic when it could/should? Or is GCC in the wrong and the diagnostic is erroneous?

答:
Which compiler is right here?

Both? Compilers are allowed to give warnings, or not, as they choose. It's just that when you write:

```<code>std::string_view vs{s};
</code>```

You might be under the impression that this is doing something like aggregate initialization or at least invoking a string_view constructor, but it's not - and maybe that impression isn't as likely to happen if you wrote:

```<code>std::string_view vs(s);
</code>```

so gcc gives you a warning (since you asked for one).

The code is fine. Both compilers are fine. Just use ()s to initialize, there's no reason to use {} here (there is no difference in behavior in the two approaches).

Body:
GCC 7.2 and clang 5.0 seem to disagree about the following code when compiled with -std=c++17 -Werror -Wconversion:

#include <iostream>
#include <string>
#include <string_view>

int main(int argc, char* argv[]) {
    std::string s = "Hello, World";
    std::string_view vs{s};
    std::cout << std::string{vs} << '\n';
    return EXIT_SUCCESS;
}

Compiled with clang++ -std=c++17 -Wall -Werror -Wconversion, it compiles correctly (see https://godbolt.org/g/JZn8cL)

However, GCC 7.2 issues a somewhat perplexing diagnostic (see https://godbolt.org/g/kmYbJ3):

<source>: In function 'int main(int, char**)':
7 : <source>:7:26: error: choosing 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type() const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type = std::basic_string_view<char>]' over 'constexpr std::basic_string_view<_CharT, _Traits>::basic_string_view(const std::basic_string_view<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]' [-Werror=conversion]
     std::string_view vs{s};
                          ^
7 : <source>:7:26: error:   for conversion from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'std::basic_string_view<char>' [-Werror=conversion]
7 : <source>:7:26: note:   because conversion sequence for the argument is better
cc1plus: all warnings being treated as errors
Compiler exited with result code 1

Both compilers compile the code fine after changing vs{s} to vs(s).

Which compiler is right here? Is brace initialization of a std::string_view from a std::string running afoul of conversion rules somehow, and clang is failing to issue a diagnostic when it could/should? Or is GCC in the wrong and the diagnostic is erroneous?

Body:
Which compiler is right here?

Both? Compilers are allowed to give warnings, or not, as they choose. It's just that when you write:

std::string_view vs{s};

You might be under the impression that this is doing something like aggregate initialization or at least invoking a string_view constructor, but it's not - and maybe that impression isn't as likely to happen if you wrote:

std::string_view vs(s);

so gcc gives you a warning (since you asked for one).

The code is fine. Both compilers are fine. Just use ()s to initialize, there's no reason to use {} here (there is no difference in behavior in the two approaches).


问:
Remove Ads (In-App Purchase) UWP App
I am a simple uwp app (published in Microsoft/Windows Store), and I have only an ad (banner) in my main page. I want remove the ad when user makes in-app purchase.
I have already followed tutorials from Microsoft and Microsoft Virtual Academy but I can not remove the ad!

```<code>private async void removeAds_Click(object sender, RoutedEventArgs e)
        {
            if (!AppLicenseInformation.ProductLicenses["RemoveAdsOffer"].IsActive)
            {
                try
                {
                    // The customer doesn't own this feature, so
                    // show the purchase dialog.

                    PurchaseResults results = await CurrentAppSimulator.RequestProductPurchaseAsync("RemoveAdsOffer");

                    //Check the license state to determine if the in-app purchase was successful.

                    if (results.Status == ProductPurchaseStatus.Succeeded)
                    {
                        removeAds.Visibility = Visibility.Collapsed;
                        Ad.Visibility = Visibility.Collapsed;
                    }
                }
                catch (Exception ex)
                {
                    // The in-app purchase was not completed because
                    // an error occurred.
                    throw ex;
                }
            }
            else
            {
                // The customer already owns this feature.
            }
}
</code>```

I have the ad (Ad) and a button (removeAds) to remove the advertising on my main page!

The ad and button are removed but when I navigate to another page of my app or close and reopen the app, the ad reappears.

答: What do you expect? You're only processing the logic on the button click. As soon as another page is loaded, the logic is gone. You'll need to check and see if ProductLicenses["RemoveAdsOffer"].IsActive on every page load.

Title: Remove Ads (In-App Purchase) UWP App

Body:
I am a simple uwp app (published in Microsoft/Windows Store), and I have only an ad (banner) in my main page. I want remove the ad when user makes in-app purchase.
I have already followed tutorials from Microsoft and Microsoft Virtual Academy but I can not remove the ad!

private async void removeAds_Click(object sender, RoutedEventArgs e)
        {
            if (!AppLicenseInformation.ProductLicenses["RemoveAdsOffer"].IsActive)
            {
                try
                {
                    // The customer doesn't own this feature, so
                    // show the purchase dialog.

                    PurchaseResults results = await CurrentAppSimulator.RequestProductPurchaseAsync("RemoveAdsOffer");

                    //Check the license state to determine if the in-app purchase was successful.

                    if (results.Status == ProductPurchaseStatus.Succeeded)
                    {
                        removeAds.Visibility = Visibility.Collapsed;
                        Ad.Visibility = Visibility.Collapsed;
                    }
                }
                catch (Exception ex)
                {
                    // The in-app purchase was not completed because
                    // an error occurred.
                    throw ex;
                }
            }
            else
            {
                // The customer already owns this feature.
            }
}

I have the ad (Ad) and a button (removeAds) to remove the advertising on my main page!

The ad and button are removed but when I navigate to another page of my app or close and reopen the app, the ad reappears.


问:
access count number of records with criteria celebrity
i was looking for a solution for my problem for along time, i wish you help me
i have a table with a two column first is a name and two is a town i need to count Sarah from Egpyt how many it repeated but here is the trick i need the result like table 2 below is it possible</p>

```<code>Name    town
Sarah   Egypt
John    Germany
Mick    France
Sarah   Egypt
Sarah   USA
John    Germany
Mick    France
John    Germany

Name    town    duplicate
Sarah   Egypt      1
John    Germany    1
Mick    France     1
Sarah   Egypt      2
Sarah   USA        1
John    Germany    2
Mick    France     2
John    Germany    3
</code>```

答:
Try this,

Create Table:

```<code>create table test (name varchar(20), town varchar(20));
</code>```

Insert Statement:

```<code>insert into test value('Sarah','Egypt');
insert into test values('John','Germany');
insert into test values('Mick','France');
insert into test values('Sarah','Egypt');
insert into test values('Sarah','USA');
insert into test values('John','Germany');
insert into test values('Mick','France');
insert into test values('Sarah','Egypt');
</code>```

Query:

```<code>set @x=1;
set @checkname='';
set @checktown='';
select name, town ,row_number
from ( select name, town, if(@checkname = name && @checktown = town,@x := @x + 1 ,@x := 1) as row_number,
@checkname := name, @checktown := town
from test
order by name, town
) a
</code>```

Body:
i was looking for a solution for my problem for along time, i wish you help me
i have a table with a two column first is a name and two is a town i need to count Sarah from Egpyt how many it repeated but here is the trick i need the result like table 2 below is it possible

Name    town
Sarah   Egypt
John    Germany
Mick    France
Sarah   Egypt
Sarah   USA
John    Germany
Mick    France
John    Germany

Name    town    duplicate
Sarah   Egypt      1
John    Germany    1
Mick    France     1
Sarah   Egypt      2
Sarah   USA        1
John    Germany    2
Mick    France     2
John    Germany    3

Body:
Try this,

Create Table:

create table test (name varchar(20), town varchar(20));

Insert Statement:

insert into test value('Sarah','Egypt');
insert into test values('John','Germany');
insert into test values('Mick','France');
insert into test values('Sarah','Egypt');
insert into test values('Sarah','USA');
insert into test values('John','Germany');
insert into test values('Mick','France');
insert into test values('Sarah','Egypt');

Query:

set @x=1;
set @checkname='';
set @checktown='';
select name, town ,row_number
from ( select name, town, if(@checkname = name && @checktown = town,@x := @x + 1 ,@x := 1) as row_number,
@checkname := name, @checktown := town
from test
order by name, town
) a


问:
How to make a Menu that goes from the header to the footer?
So, I am learning how to code HTML5, CSS3, and all that good stuff. But I have an issue the book doesn't solve. As you may be able to see, The Nav area doesn't go from the header to the footer. I was hoping someone could help me understand how to get it to go from the header to the footer. Maybe it's just a simple padding. But I don't wanna mess up the layout. Hope I am not asking a stupid question.

/*HEADER*/

header {
  border: 3px solid black;
}

/*BODY*/

nav {
  float: left;
  clear: both;
  width: 20%;
  border: 3px solid black;
}

section {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}
article {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang="en-US">
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet"
          type="text/css"
          href="semanticTags.css"/>
    <title>
      Semantic Tags
    </title>
    <body>
      <header>
        <h1>This is my header</h1>
      </header>

      <nav>
        <h2>Navigation</h2>
        <ul>
          <li>Google</li>
          <li>Bing</li>
          <li>Yahoo</li>
          <li>AOL</li>
          <li>Facebook</li>
        </ul>
      </nav>

      <section id="1">
        <h2>
          Section 1
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <section id="2">
        <h2>
          Section 2
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <article>
        <h2>
          Article
        </h2>
        <p>
          Article Body
        </p>
      </article>

      <footer>
        <h2>footer</h2>
        <address>
          DreamRiskers<br>

            email@gmail.com

        </address>
      </footer>

    </body>
  </head>
</html></code>```

答:
There may be two ways that i can advise :

in your html file, add :

< body class="nav" >

and in your css file, make :

.nav {

  float: left;

               clear: both;

```<code>  width: 100%;
  height: 100%;
</code>```

border: 3px solid black;

  background-color:yellow; }

background-color is just for distinguishing.

in your html file, put  tag just after  tag, and
                          tag just before  tag

and make your css file as follows :

nav {

  float: left;

               clear: both;

```<code>  width: 100%;
  height: 100%;
</code>```

border: 3px solid black;

  background-color:yellow; }

Body:
So, I am learning how to code HTML5, CSS3, and all that good stuff. But I have an issue the book doesn't solve. As you may be able to see, The Nav area doesn't go from the header to the footer. I was hoping someone could help me understand how to get it to go from the header to the footer. Maybe it's just a simple padding. But I don't wanna mess up the layout. Hope I am not asking a stupid question.

/*HEADER*/

header {
  border: 3px solid black;
}

/*BODY*/

nav {
  float: left;
  clear: both;
  width: 20%;
  border: 3px solid black;
}

section {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}
article {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border: 3px solid black;
}

<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <link rel="stylesheet"
          type="text/css"
          href="semanticTags.css"/>
    <title>
      Semantic Tags
    </title>

This is my header

Navigation

Google

Bing

Yahoo

AOL

Facebook

          Section 1

          Section Body

          Section 2

          Section Body

          Article

          Article Body

footer

        <address>
          DreamRiskers

            email@gmail.com

        </address>

Body:
There may be two ways that i can advise :

in your html file, add :

< body class="nav" >

and in your css file, make :

.nav {

  float: left;

               clear: both;

  width: 100%;
  height: 100%;

border: 3px solid black;

  background-color:yellow; }

background-color is just for distinguishing.

in your html file, put <nav> tag just after <body> tag, and
                         </nav> tag just before </body> tag

and make your css file as follows :

nav {

  float: left;

               clear: both;

  width: 100%;
  height: 100%;

border: 3px solid black;

  background-color:yellow; }


问:
Add form values dynamically
I have this JavaScript code to dynamically add values on a form as they're entered. However, I'm struggling a little with what I want to do.

I have 4 questions on a quiz, each with 4 answers.

I want to add the values for each of the 4 answer boxes per question. But I can't work out how to use this script more than once on a page. Can anyone advise please?

        <form name="form" >
            Enter a number:
            <input name="sum1" onChange="updatesum1()" />
            and another number:
            <input name="sum2" onChange="updatesum1()" />
            and another number:
            <input name="sum3" onChange="updatesum1()" />
            and another number:
            <input name="sum4" onChange="updatesum1()" />
            Their sum is:
            <input name="sum" readonly style="border:0px;">
        </form>

    ```

答:
Pass the form as an argument to the function, instead of hard-coding it in the function. In the input elements, this.form refers the form that contains it.

function updatesum1(form) {
  form.sum.value = (form.sum1.value - 0) +
    (form.sum2.value - 0) +
    (form.sum3.value - 0) +
    (form.sum4.value - 0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="form">
  Enter a number:
  <input name="sum1" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum2" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum3" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum4" onChange="updatesum1(this.form)" /> <br>
  Their sum is:
  <input name="sum" readonly style="border:0px;">
</form>
<p>
<form name="form">
  Enter a number:
  <input name="sum1" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum2" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum3" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum4" onChange="updatesum1(this.form)" /> <br>
  Their sum is:
  <input name="sum" readonly style="border:0px;">
</form></code>```

Title: Add form values dynamically

Body:
Pass the form as an argument to the function, instead of hard-coding it in the function. In the input elements, this.form refers the form that contains it.

function updatesum1(form) {
  form.sum.value = (form.sum1.value - 0) +
    (form.sum2.value - 0) +
    (form.sum3.value - 0) +
    (form.sum4.value - 0);
}

<form name="form">
  Enter a number:
  <input name="sum1" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum2" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum3" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum4" onChange="updatesum1(this.form)" /> <br>
  Their sum is:
  <input name="sum" readonly style="border:0px;">
</form>
<p>
<form name="form">
  Enter a number:
  <input name="sum1" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum2" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum3" onChange="updatesum1(this.form)" /> <br>
  and another number:
  <input name="sum4" onChange="updatesum1(this.form)" /> <br>
  Their sum is:
  <input name="sum" readonly style="border:0px;">
</form>


问:
Does Docker execute the entrypoint when a container is used in a multistage build?
If define a multistage Dockerfile like so:

```<code>FROM exampleabc:latest
COPY app.go .

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
</code>```

Would the exampleabc:latest have it's entrypoint executed?

答:
From official documentation:

Only the last ENTRYPOINT instruction in the Dockerfile will have an effect.

Body:
If define a multistage Dockerfile like so:

FROM exampleabc:latest
COPY app.go .

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]

Would the exampleabc:latest have it's entrypoint executed?


问:
using the typedef keyword with a struct
What exactly is the purpose of using a typedef together with a struct and giving it two names, often one in capital letters?

Today I was looking at a winsock tutorial and came across the struct definition below.

```<code>// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

typedef struct in_addr {
  union {
    struct {
      u_char s_b1,s_b2,s_b3,s_b4;
    } S_un_b;
    struct {
      u_short s_w1,s_w2;
    } S_un_w;
    u_long S_addr;
  } S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};
</code>```

What exactly does this line do?

IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

答:
What exactly is the purpose of using a typedef together with a struct and giving it two names, often one in capital letters?

There are three primary components to

```<code>typedef struct in_addr {
    // members ...
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;
</code>```

several identifiers that are being declared: IN_ADDR, PIN_ADDR, and LPIN_ADDR.  As far as C is concerned, there is no significance to the fact that these are capitalized; presumably that is an aspect of the chosen coding style.

the types being declared for those identifiers, respectively struct in_addr, struct in_addr * and struct in_addr FAR *.  The type declaration additionally incorporates a definition of type struct in_addr, which is optional because a struct tag (in_addr) is given.  The definition could have instead been given separately or not at all:

```<code>typedef struct in_addr IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

struct in_addr {
    // members ...
};
</code>```

the storage class of the declarations, typedef, which indicates that instead of those identifiers referring to objects with associated storage, they serve as aliases for their declared types.

Overall, then, the statement declares IN_ADDR, PIN_ADDR, and LPIN_ADDR as aliases for three different, but related, types.

Title: using the typedef keyword with a struct

Body:
What exactly is the purpose of using a typedef together with a struct and giving it two names, often one in capital letters?

Today I was looking at a winsock tutorial and came across the struct definition below.

// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

typedef struct in_addr {
  union {
    struct {
      u_char s_b1,s_b2,s_b3,s_b4;
    } S_un_b;
    struct {
      u_short s_w1,s_w2;
    } S_un_w;
    u_long S_addr;
  } S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};

What exactly does this line do?

IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

Body:
What exactly is the purpose of using a typedef together with a struct and giving it two names, often one in capital letters?

There are three primary components to

typedef struct in_addr {
    // members ...
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

several identifiers that are being declared: IN_ADDR, PIN_ADDR, and LPIN_ADDR.  As far as C is concerned, there is no significance to the fact that these are capitalized; presumably that is an aspect of the chosen coding style.

the types being declared for those identifiers, respectively struct in_addr, struct in_addr * and struct in_addr FAR *.  The type declaration additionally incorporates a definition of type struct in_addr, which is optional because a struct tag (in_addr) is given.  The definition could have instead been given separately or not at all:

typedef struct in_addr IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

struct in_addr {
    // members ...
};

the storage class of the declarations, typedef, which indicates that instead of those identifiers referring to objects with associated storage, they serve as aliases for their declared types.

Overall, then, the statement declares IN_ADDR, PIN_ADDR, and LPIN_ADDR as aliases for three different, but related, types.


问:
addAnnotations method only places last annotation from Array
I have problem adding annotations to mapView. I had success with this code:

```<code>func placeAnnotations() {

    for _ in placeDetails {

        let multipleAnnotations = MKPointAnnotation()
        multipleAnnotations.title = place.address
        multipleAnnotations.subtitle = place.phone
        multipleAnnotations.coordinate = CLLocationCoordinate2D(latitude: place.lat, longitude: place.lng)
       mapView.addAnnotation(multipleAnnotations)

    }

}
</code>```

Problem is, it is not conforming to my Place class, thus not showing custom Title, Subtitle and MKAnnotationView. This is code inside viewDidLoad(), where I'm trying to put all the annotations, but it keeps adding only last one. I understood that it overrides all the previous ones from array, but haven't found any other way/method to implement.

```<code>  var placeDetails = [Place]()
    var places = [Place]()

        override func viewDidLoad() {
            super.viewDidLoad()

            downloadPlaceID {
                for obj in places {
                    place.downloadDetails(input: obj.placeId, completed: {
                        self.placeDetails.append(obj)
                     //self.placeAnnotations()
   self.mapView.addAnnotations(self.placeDetails)
                    })

                }
            }
        }
</code>```

And this is my class with all the data conforming to MKAnnotation
protocol, and functions, downloadPlaceID() and downloadDetails()

```<code> class Place: NSObject, MKAnnotation {

        var coordinate: CLLocationCoordinate2D
        var placeId: String!
        var vicinity: String!
        var phone: String!
        var workHours: Bool!
        var lat: Double!
        var lng: Double!
        var address: String!

        var subtitle: String? {
            return phone
        }

        var title: String? {
            return address
        }

        var _placeId: String {
            if placeId == nil {
                placeId = ""
            }
            return placeId
        }

        var _vicinity: String {
            if vicinity == nil {
                vicinity = ""
            }
            return vicinity
        }

        var _phone: String {
            if phone == nil {
                phone = ""
            }
            return phone
        }

        var _workHours: Bool {
            if workHours == nil {
                workHours = false
            }
            return workHours
        }

        var _lat: Double {
            if lat == nil {
                lat = 0.0
            }
            return lat
        }

        var _lng: Double {
            if lng == nil {
                lng = 0.0
            }
            return lng
        }

        var _address: String {
            if address == nil {
                address = ""
            }
            return address
        }

        init(place: [String:Any]) {

            if let ids = place["place_id"] as? String {
                self.placeId = ids
            }

            if let vicinities = place["vicinity"] as? String {
                self.vicinity = vicinities
            }

            self.coordinate = CLLocationCoordinate2DMake(0.0, 0.0)

        }

        func downloadDetails(input: String, completed: @escaping DownloadComplete) {

            let details = "\(detailsBaseURL)\(detailsPlaceId)\(input)\(detailsKey)\(detailsSearchAPIKey)"

            Alamofire.request(details).responseJSON { response in
                let result = response.result

                if let dictionary = result.value as? [String:Any] {

                    if let result = dictionary["result"] as? [String:Any] {

                        if let phoneNumber = result["formatted_phone_number"] as? String {
                            self.phone = phoneNumber
                        }

                        if let  geometry = result["geometry"] as? [String:Any] {
                            if let location = geometry["location"] as? [String:Any] {
                                if let latitude = location["lat"] as? Double {
                                    self.lat = latitude
                                }
                                if let longitude = location["lng"] as? Double {
                                    self.lng = longitude
                                }

                                self.coordinate = CLLocationCoordinate2DMake(self.lat, self.lng)

                            }
                        }

                        if let openingHours = result["opening_hours"] as? [String:Any] {
                            if let openNow = openingHours["open_now"] as? Bool {
                                self.workHours = openNow
                            }
                        }

                        if let addressComponents = result["address_components"] as? [[String:Any]] {
                            let longName = addressComponents[1]["long_name"] as? String
                            let shortName = addressComponents[0]["long_name"] as? String

                            self.address = "\(longName!),\(shortName!)"
                        }
                    }
                }
                completed()
            }
        }
    }

 func downloadPlaceID (completed: @escaping DownloadComplete) {

        let placeURL = URL(string: nearbyURL)

        Alamofire.request(placeURL!).responseJSON { (response) in
            let result = response.result

            if let dictionary = result.value as? [String:Any] {
                if let results = dictionary["results"] as? [[String:Any]] {

                    if let status = dictionary["status"] as? String  {
                        if status == "OK" {
                            for obj in results {
                                place = Place(place: obj)
                                places.append(place)
                            }
                        } else {
                            print("jede govna")
                        }
                    }
                }
            }
            completed()
        }
</code>```

答:
There's some odd mixing of variable names and concepts here that makes your code somewhat hard to understand.

As an example, assigning a variable you call vicinities, plural, to an attribute called vicinity, singular. Or not separating your downloadDetails function from your data model.

That aside, it looks to me like you're unnecessarily adding your MKAnnotations many times to your map, by adding your array of [MKAnnotation] to your map in each loop.

I suspect you've done this because you've made it hard for yourself to know when the whole array is done updating its details.

As a quick fix, I'd suggest changing your downloadDetails function to call the completed function with the place you've just downloaded details for. Here's a really simplified, but working, version of what you are trying to do. First your Place class:

```<code>class Place: NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D

    override init() {
        coordinate = CLLocationCoordinate2DMake(0, 0)
    }

    func downloadDetails(completed: @escaping (Place) -> Void) {
        // Instead of downloading details we are just creating random positions
        self.coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(arc4random_uniform(50)), CLLocationDegrees(arc4random_uniform(50)))

        // Return the object you've just built
        completed(self)
    }
}
</code>```

Now in your view controller, here I am starting with an array of 50 Place objects, getting the details for them and placing them on the map:

```<code>var places = [Place]()
for _ in 1...50 {
    places.append(Place())
}

for place in places {
    place.downloadDetails(completed: { (placeWithDetails) in
        self.mapView.addAnnotation(placeWithDetails)
    })
}
</code>```

This results in the map being populated with 50 random places:

Body:
I have problem adding annotations to mapView. I had success with this code:

func placeAnnotations() {

    for _ in placeDetails {

        let multipleAnnotations = MKPointAnnotation()
        multipleAnnotations.title = place.address
        multipleAnnotations.subtitle = place.phone
        multipleAnnotations.coordinate = CLLocationCoordinate2D(latitude: place.lat, longitude: place.lng)
       mapView.addAnnotation(multipleAnnotations)

    }

}

Problem is, it is not conforming to my Place class, thus not showing custom Title, Subtitle and MKAnnotationView. This is code inside viewDidLoad(), where I'm trying to put all the annotations, but it keeps adding only last one. I understood that it overrides all the previous ones from array, but haven't found any other way/method to implement.

  var placeDetails = [Place]()
    var places = [Place]()

        override func viewDidLoad() {
            super.viewDidLoad()

            downloadPlaceID {
                for obj in places {
                    place.downloadDetails(input: obj.placeId, completed: {
                        self.placeDetails.append(obj)
                     //self.placeAnnotations()
   self.mapView.addAnnotations(self.placeDetails)
                    })

                }
            }
        }

And this is my class with all the data conforming to MKAnnotation
protocol, and functions, downloadPlaceID() and downloadDetails()

 class Place: NSObject, MKAnnotation {

        var coordinate: CLLocationCoordinate2D
        var placeId: String!
        var vicinity: String!
        var phone: String!
        var workHours: Bool!
        var lat: Double!
        var lng: Double!
        var address: String!

        var subtitle: String? {
            return phone
        }

        var title: String? {
            return address
        }

        var _placeId: String {
            if placeId == nil {
                placeId = ""
            }
            return placeId
        }

        var _vicinity: String {
            if vicinity == nil {
                vicinity = ""
            }
            return vicinity
        }

        var _phone: String {
            if phone == nil {
                phone = ""
            }
            return phone
        }

        var _workHours: Bool {
            if workHours == nil {
                workHours = false
            }
            return workHours
        }

        var _lat: Double {
            if lat == nil {
                lat = 0.0
            }
            return lat
        }

        var _lng: Double {
            if lng == nil {
                lng = 0.0
            }
            return lng
        }

        var _address: String {
            if address == nil {
                address = ""
            }
            return address
        }

        init(place: [String:Any]) {

            if let ids = place["place_id"] as? String {
                self.placeId = ids
            }

            if let vicinities = place["vicinity"] as? String {
                self.vicinity = vicinities
            }

            self.coordinate = CLLocationCoordinate2DMake(0.0, 0.0)

        }

        func downloadDetails(input: String, completed: @escaping DownloadComplete) {

            let details = "\(detailsBaseURL)\(detailsPlaceId)\(input)\(detailsKey)\(detailsSearchAPIKey)"

            Alamofire.request(details).responseJSON { response in
                let result = response.result

                if let dictionary = result.value as? [String:Any] {

                    if let result = dictionary["result"] as? [String:Any] {

                        if let phoneNumber = result["formatted_phone_number"] as? String {
                            self.phone = phoneNumber
                        }

                        if let  geometry = result["geometry"] as? [String:Any] {
                            if let location = geometry["location"] as? [String:Any] {
                                if let latitude = location["lat"] as? Double {
                                    self.lat = latitude
                                }
                                if let longitude = location["lng"] as? Double {
                                    self.lng = longitude
                                }

                                self.coordinate = CLLocationCoordinate2DMake(self.lat, self.lng)

                            }
                        }

                        if let openingHours = result["opening_hours"] as? [String:Any] {
                            if let openNow = openingHours["open_now"] as? Bool {
                                self.workHours = openNow
                            }
                        }

                        if let addressComponents = result["address_components"] as? [[String:Any]] {
                            let longName = addressComponents[1]["long_name"] as? String
                            let shortName = addressComponents[0]["long_name"] as? String

                            self.address = "\(longName!),\(shortName!)"
                        }
                    }
                }
                completed()
            }
        }
    }

 func downloadPlaceID (completed: @escaping DownloadComplete) {

        let placeURL = URL(string: nearbyURL)

        Alamofire.request(placeURL!).responseJSON { (response) in
            let result = response.result

            if let dictionary = result.value as? [String:Any] {
                if let results = dictionary["results"] as? [[String:Any]] {

                    if let status = dictionary["status"] as? String  {
                        if status == "OK" {
                            for obj in results {
                                place = Place(place: obj)
                                places.append(place)
                            }
                        } else {
                            print("jede govna")
                        }
                    }
                }
            }
            completed()
        }

Body:
There's some odd mixing of variable names and concepts here that makes your code somewhat hard to understand.

As an example, assigning a variable you call vicinities, plural, to an attribute called vicinity, singular. Or not separating your downloadDetails function from your data model.

That aside, it looks to me like you're unnecessarily adding your MKAnnotations many times to your map, by adding your array of [MKAnnotation] to your map in each loop.

I suspect you've done this because you've made it hard for yourself to know when the whole array is done updating its details.

As a quick fix, I'd suggest changing your downloadDetails function to call the completed function with the place you've just downloaded details for. Here's a really simplified, but working, version of what you are trying to do. First your Place class:

class Place: NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D

    override init() {
        coordinate = CLLocationCoordinate2DMake(0, 0)
    }

    func downloadDetails(completed: @escaping (Place) -> Void) {
        // Instead of downloading details we are just creating random positions
        self.coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(arc4random_uniform(50)), CLLocationDegrees(arc4random_uniform(50)))

        // Return the object you've just built
        completed(self)
    }
}

Now in your view controller, here I am starting with an array of 50 Place objects, getting the details for them and placing them on the map:

var places = [Place]()
for _ in 1...50 {
    places.append(Place())
}

for place in places {
    place.downloadDetails(completed: { (placeWithDetails) in
        self.mapView.addAnnotation(placeWithDetails)
    })
}

This results in the map being populated with 50 random places:


问:
Android: Convert Stream to String without running out of memory
I have an android client that communicates with the server via REST-ful endpoints and JSON. Because of this, I have the need to retrieve the full server response prior to converting it into a Hash. I have this code in place to do that (found on the internet someplace):

```<code>private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
</code>```

The code works for the most part, however I am seeing reports of crashes in the field from clients with an OutOfMemory exception on the line:

```<code>    while ((line = reader.readLine()) != null) {
</code>```

The full stack trace is:

```<code>java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:200)
    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
    at java.lang.Thread.run(Thread.java:1102)
Caused by: java.lang.OutOfMemoryError
    at java.lang.String.(String.java:468)
    at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:659)
    at java.lang.StringBuilder.toString(StringBuilder.java:664)
    at java.io.BufferedReader.readLine(BufferedReader.java:448)
    at com.appspot.myapp.util.RestClient.convertStreamToString(RestClient.java:303)
    at com.appspot.myapp.util.RestClient.executeRequest(RestClient.java:281)
    at com.appspot.myapp.util.RestClient.Execute(RestClient.java:178)
    at com.appspot.myapp.$LoadProfilesTask.doInBackground(GridViewActivity.java:1178)
    at com.appspot.myapp.$LoadProfilesTask.doInBackground(GridViewActivity.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:185)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    ... 4 more
</code>```

My question: is there any way to solve this problem aside from sending smaller chunks of data from the server?

Thanks!

答:
There are different ways to tackle these kinds of problems. One way would be to use a hash function that doesn't require the entire stream to be in memory, i.e. you feed it a character or block of characters at a time. Another is to reduce the size of the response.

If you can't do that and you need the entire stream, then I would avoid using readLine() and just call read() on the buffered input stream and append the character you get from read to the string builder. This will reduce the number of strings you are creating and discarding quite dramatically. (A simple optimization to the code above is to take out the newline in the append() call -- you're creating another string unnecessarily there as well.) Also, if you have any idea how long the resulting string will be, you can also set the initial capacity of the string builder upon construction so that you'll know immediately if you'll be out of memory.

Once you get beyond that you have to start splitting the string into blocks that you store on the filesystem.... gets complicated pretty fast.

Body:
I have an android client that communicates with the server via REST-ful endpoints and JSON. Because of this, I have the need to retrieve the full server response prior to converting it into a Hash. I have this code in place to do that (found on the internet someplace):

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

The code works for the most part, however I am seeing reports of crashes in the field from clients with an OutOfMemory exception on the line:

    while ((line = reader.readLine()) != null) {

The full stack trace is:

java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:200)
    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
    at java.lang.Thread.run(Thread.java:1102)
Caused by: java.lang.OutOfMemoryError
    at java.lang.String.(String.java:468)
    at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:659)
    at java.lang.StringBuilder.toString(StringBuilder.java:664)
    at java.io.BufferedReader.readLine(BufferedReader.java:448)
    at com.appspot.myapp.util.RestClient.convertStreamToString(RestClient.java:303)
    at com.appspot.myapp.util.RestClient.executeRequest(RestClient.java:281)
    at com.appspot.myapp.util.RestClient.Execute(RestClient.java:178)
    at com.appspot.myapp.$LoadProfilesTask.doInBackground(GridViewActivity.java:1178)
    at com.appspot.myapp.$LoadProfilesTask.doInBackground(GridViewActivity.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:185)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    ... 4 more

My question: is there any way to solve this problem aside from sending smaller chunks of data from the server?

Thanks!


问:
edit a JSON file in Robot Framework
I want to add driver=1 to my sample_json.json file but can't figure out a way to write these changes permanently. This code saves the key-value to the object ${json_obj} but does not make any changes to the file sample_json.json

sample_json.json

```<code>{
    "Phones": {

        "debug": "on",

        "phone1": {
            "key":"value"
        },

        "phone2": {
            "key":"value"
        }
    }
}
</code>```

Robot file

```<code>*** Settings ***
Library    JSONLibrary

*** Variables ***
${SUBSCRIBER_A}    phone1

*** Test Cases ***
testcase
   test    ${SUBSCRIBER_A}

*** Keywords ***
test
    [Arguments]    ${SUBSCRIBER_A}
    ${json_obj}=    Load JSON From File     sample_json.json
    ${object_to_add}=   Create Dictionary   driver=1
    ${json_obj}=    Add Object To Json    ${json_obj}    $..${SUBSCRIBER_A}    ${object_to_add}
</code>```

答:
Looks like you haven't fully understood how the library works. When you call Load JSON From File, the library will read the file, and return the data as a variable in memory (in your case, your ${json_obj} variable).

Now at this point, whenever you alter this data, you're only altering the data in memory, not the file itself.

You'll need to overwrite the file with your new data, which you can achieve using the Create File keyword. You'll likely need to convert your JSON dictionary to a string first, using the Convert JSON To String keyword.

Title: edit a JSON file in Robot Framework

Body:
I want to add driver=1 to my sample_json.json file but can't figure out a way to write these changes permanently. This code saves the key-value to the object ${json_obj} but does not make any changes to the file sample_json.json

sample_json.json

{
    "Phones": {

        "debug": "on",

        "phone1": {
            "key":"value"
        },

        "phone2": {
            "key":"value"
        }
    }
}

Robot file

*** Settings ***
Library    JSONLibrary

*** Variables ***
${SUBSCRIBER_A}    phone1

*** Test Cases ***
testcase
   test    ${SUBSCRIBER_A}

*** Keywords ***
test
    [Arguments]    ${SUBSCRIBER_A}
    ${json_obj}=    Load JSON From File     sample_json.json
    ${object_to_add}=   Create Dictionary   driver=1
    ${json_obj}=    Add Object To Json    ${json_obj}    $..${SUBSCRIBER_A}    ${object_to_add}


问:
Alamofire invalid value around character 0
```<code>Alamofire.request(.GET, "url").authenticate(user: "", password: "").responseJSON() {
    (request, response, json, error) in
    println(error)
    println(json)

}
</code>```

This is my request with Alamofire, for a certain request it sometime works, but sometimes i get:

```<code>Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x78e74b80 {NSDebugDescription=Invalid value around character 0.})
</code>```

I've read that this can be due to invalid JSON, but the response is a static json string that i have validated in JSON validator as valid. It does contain å ä ö characters and some HTML.

Why am i getting this error sometimes?

答:
Hey guys this is what I found to be my issue: I was calling Alamofire via a function to Authenticate Users: I used the function "Login User" With the parameters that would be called from the "body"(email: String, password: String)  That would be passed

my errr was exactly:

optional(alamofire.aferror.responseserializationfailed(alamofire.aferror.responseserializationfailurereason.jsonserializationfailed(error domain=nscocoaerrordomain code=3840 "invalid value around character 0." userinfo={nsdebugdescription=invalid value around character 0

character 0 is the key here: meaning the the call for the "email" was not matching the parameters: See the code below

func loginUser(email: String, password: String, completed: @escaping downloadComplete) {
        let lowerCasedEmail = email.lowercased()

```<code>    let header = [
        "Content-Type" : "application/json; charset=utf-8"
    ]
    let body: [String: Any] = [
        "email": lowerCasedEmail,
        "password": password
    ]

    Alamofire.request(LOGIN_USER, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in
        if response.result.error == nil {

            if let data = response.result.value as? Dictionary<String, AnyObject> {
                if let email = data["user"] as? String {
                    self.userEmail = email
                    print(self.userEmail)
                }
                if let token = data["token"] as? String {
                    self.token_Key = token
                    print(self.token_Key)
                }
</code>```

"email" in function parameters must match the let "email" when parsing then it will work..I no longer got the error...And character 0 was the "email" in the "body" parameter for the Alamofire request:

Hope this helps

Body:
Alamofire.request(.GET, "url").authenticate(user: "", password: "").responseJSON() {
    (request, response, json, error) in
    println(error)
    println(json)

}

This is my request with Alamofire, for a certain request it sometime works, but sometimes i get:

Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x78e74b80 {NSDebugDescription=Invalid value around character 0.})

I've read that this can be due to invalid JSON, but the response is a static json string that i have validated in JSON validator as valid. It does contain å ä ö characters and some HTML.

Why am i getting this error sometimes?

Body:
Hey guys this is what I found to be my issue: I was calling Alamofire via a function to Authenticate Users: I used the function "Login User" With the parameters that would be called from the "body"(email: String, password: String)  That would be passed

my errr was exactly:

optional(alamofire.aferror.responseserializationfailed(alamofire.aferror.responseserializationfailurereason.jsonserializationfailed(error domain=nscocoaerrordomain code=3840 "invalid value around character 0." userinfo={nsdebugdescription=invalid value around character 0

character 0 is the key here: meaning the the call for the "email" was not matching the parameters: See the code below

func loginUser(email: String, password: String, completed: @escaping downloadComplete) {
        let lowerCasedEmail = email.lowercased()

    let header = [
        "Content-Type" : "application/json; charset=utf-8"
    ]
    let body: [String: Any] = [
        "email": lowerCasedEmail,
        "password": password
    ]

    Alamofire.request(LOGIN_USER, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in
        if response.result.error == nil {

            if let data = response.result.value as? Dictionary<String, AnyObject> {
                if let email = data["user"] as? String {
                    self.userEmail = email
                    print(self.userEmail)
                }
                if let token = data["token"] as? String {
                    self.token_Key = token
                    print(self.token_Key)
                }

"email" in function parameters must match the let "email" when parsing then it will work..I no longer got the error...And character 0 was the "email" in the "body" parameter for the Alamofire request:

Hope this helps


问:
Google Maps Popover click event fires multiple times
I have a google map with markers.  Each marker when clicked, shows an infowindow.  Inside the infowindow is a button to add some data to a queue.  on the first click of an add to queue button, it fires once, click a second button it fires twice, click a third and it fires three times and so on.

```<code>google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
        $('.show-compare').popover('destroy');
        infowindow.setContent('<div class="add-wrapper"><div class="show-compare" data-toggle="popover" data-placement="top" data-content="Add to compare basket">CLICK ME</div></div>);
        infowindow.setOptions({maxWidth: 200});
        infowindow.open(map, marker);

        $('body').on("click", '.show-compare', function(e) {
                e.preventDefault();
                alert();//this fires x times, only should fire once per click!!

        }
    }) (marker, i));
}
</code>```

HELP! Thank you :)

答:
```<code>$('body').off("click", '.show-compare').one("click", '.show-compare', function(e) {
    e.preventDefault();
    e.stopPropagation();
    alert();
}
</code>```

<p>This worked for me </p>

Body:
I have a google map with markers.  Each marker when clicked, shows an infowindow.  Inside the infowindow is a button to add some data to a queue.  on the first click of an add to queue button, it fires once, click a second button it fires twice, click a third and it fires three times and so on.

google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
        $('.show-compare').popover('destroy');
        infowindow.setContent('

CLICK ME

);
        infowindow.setOptions({maxWidth: 200});
        infowindow.open(map, marker);

        $('body').on("click", '.show-compare', function(e) {
                e.preventDefault();
                alert();//this fires x times, only should fire once per click!!

        }
    }) (marker, i));
}

HELP! Thank you :)

Body:
$('body').off("click", '.show-compare').one("click", '.show-compare', function(e) {
    e.preventDefault();
    e.stopPropagation();
    alert();
}

This worked for me


问:
Is there a way I can use inline styling and CSS class at the same time?
I've been trying to do some styling for a page on BigCommerce platform, and for some components, I cannot find the styles and/or I don't want to mess with them.
for an img inside a div as follows:

```<code><div class="col-md-6 col-xs-6 saleBanner"><a href="https://www.MyURL.com/product-sale"><!-- pagebreak --><img class="SaleCategory" src="https://cdn3.bigcommerce.com/s-mystore/product_images/uploaded_images/myimg.png" alt="" /></a></div>
</code>```

I tried to add style="border-radius: 50%" to the div tag, and nothing changed. I'm not sure if it doesn't work this way or the built-in "editor" that I'm using on that platform just wouldn't allow me to do that for whatever reason.
I know this may not be the proper way to style a component, but what would be the best method for styling elements on a page that is already styled?

Thank you

答:
If I am understanding you correctly, this is what you're trying to accomplish?

.saleBanner{
  height: 10em;
  width: 10em;
  background: red;
  border-radius: 10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="saleBanner" style="border-radius: 50%;">

</div></code>```

Inline css styles will overwrite external css styles because they are more specific. Make sure you are including your semicolons in your inline styles as well, those are still necessary.

Body:
I've been trying to do some styling for a page on BigCommerce platform, and for some components, I cannot find the styles and/or I don't want to mess with them.
for an img inside a div as follows:

I tried to add style="border-radius: 50%" to the div tag, and nothing changed. I'm not sure if it doesn't work this way or the built-in "editor" that I'm using on that platform just wouldn't allow me to do that for whatever reason.
I know this may not be the proper way to style a component, but what would be the best method for styling elements on a page that is already styled?

Thank you

Body:
If I am understanding you correctly, this is what you're trying to accomplish?

.saleBanner{
  height: 10em;
  width: 10em;
  background: red;
  border-radius: 10%;
}

<div class="saleBanner" style="border-radius: 50%;">

</div>

Inline css styles will overwrite external css styles because they are more specific. Make sure you are including your semicolons in your inline styles as well, those are still necessary.


问:
Delete a dictionary item based on a value from a list iteration
I have tried the following:

```<code>losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
    del candidates_and_fp_votes[losers[i]]
print(candidates_and_fp_votes)
</code>```

This just returns the error:

TypeError: list indices must be integers or slices, not str

I would like to iterate over losers and delete every item in candidates_and_fp_votes which has a key in losers

I expect an output of:

```<code>{'a': 24, 'c': 17, 'd': 23}
</code>```

How can I solve this problem?

Thanks in advance.

答:
When you are iterating over an object (in this case a list called 'losers') the variable i is actually the data in the object not the index of the data like you might see in other languages (c/c++). So in the first iteration of the for loop i == 'e' then the second i == 'b' then the loop would end because there is no more data.

So all you need to do is change losers[i] to just i:

del candidates_and_fp_votes[i]

Here is the complete code with the line fixed.

```<code>losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
    del candidates_and_fp_votes[i]
print(candidates_and_fp_votes)
</code>```

Body:
I have tried the following:

losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
    del candidates_and_fp_votes[losers[i]]
print(candidates_and_fp_votes)

This just returns the error:

TypeError: list indices must be integers or slices, not str

I would like to iterate over losers and delete every item in candidates_and_fp_votes which has a key in losers

I expect an output of:

{'a': 24, 'c': 17, 'd': 23}

How can I solve this problem?

Thanks in advance.

Body:
When you are iterating over an object (in this case a list called 'losers') the variable i is actually the data in the object not the index of the data like you might see in other languages (c/c++). So in the first iteration of the for loop i == 'e' then the second i == 'b' then the loop would end because there is no more data.

So all you need to do is change losers[i] to just i:

del candidates_and_fp_votes[i]

Here is the complete code with the line fixed.

losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
    del candidates_and_fp_votes[i]
print(candidates_and_fp_votes)