问:
failed to resolve :com.android:android 2.2.1
app build.gradel

```<code> apply plugin: 'com.android.application'
//apply plugin: 'me.tatarka.retrolambda'
def AAVersion = '3.3.2'
buildscript {
repositories {
    mavenCentral()
}
dependencies {
    // classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
}
}
repositories {
     mavenCentral()
     mavenLocal()
     jcenter()
     maven {
          url 'http://maven.localytics.com/public'
     }
     maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
    }
android {
     compileSdkVersion 26
     buildToolsVersion "27.0.0"
     defaultConfig {
          applicationId "com.packagename"
          minSdkVersion 14
          targetSdkVersion 26
          versionCode 1
          versionName "1.0"
          testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
         vectorDrawables.useSupportLibrary = true
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/DEPENDENCIES'
    pickFirst 'AndroidManifest.xml'
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
 }
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
//implementation 'com.android.support:appcompat-v7:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
api 'com.android.support:design:26.1.0'
//){
//        exclude group:'com.android.support' , module: 'support-annotations' version '26.1.0'
//        exclude group:'com.android.support' , module: 'support-v4' version '26.1.0'
//        exclude group:'com.android.support' , module: 'multidex' version '1.0.1'
//        exclude group:'com.android.support' , module: 'cardview-v7' version '26.1.0'
//
//    }
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support:multidex:1.0.1'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:support-annotations:26.1.0'
//implementation 'com.google.android.gms:play-services-ads:11.6.0'
//implementation 'com.google.android.gms:play-services-auth:11.6.0'
api 'com.google.android.gms:play-services:11.6.0'
//implementation 'com.google.android.gms:play-services-gcm:11.6.0'
implementation "org.androidannotations:androidannotations-api:$AAVersion"
//    implementation('com.github.afollestad.material-dialogs:core:0.8.5.7@aar') {
//        transitive = true
//    }
//    implementation('com.github.afollestad.material-dialogs:commons:0.8.5.7@aar') {
//        transitive = true
//    }
implementation 'com.afollestad.material-dialogs:core:0.9.5.0'
implementation 'com.afollestad.material-dialogs:commons:0.9.5.0'
//api 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.daprlabs.aaron:cardstack:0.3.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.google.guava:guava:20.0'
implementation 'com.squareup.retrofit:retrofit:1.9.0'
implementation 'com.squareup.okhttp:okhttp:2.4.0'
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
implementation 'com.rengwuxian.materialedittext:library:2.1.4'
implementation 'com.facebook.android:facebook-android-sdk:4.17.0'
implementation 'com.nineoldandroids:library:2.4.0'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.github.traex.rippleeffect:library:1.3'
implementation 'com.adobe.creativesdk.foundation:auth:0.9.1062'
implementation 'com.adobe.creativesdk:image:4.6.3'
implementation 'com.localytics.android:library:3.8.0'
// implementation 'com.github.fengdai:alertdialogpro-core:0.2.7-20161111.083903-7'
//  implementation 'com.github.fengdai:alertdialogpro-theme-material:0.2.7-20161110.030043-6'
implementation 'com.eowise:recyclerview-stickyheaders:0.5.2@aar'
implementation 'com.mikepenz:iconics-core:2.5.2@aar'
implementation 'com.mikepenz:community-material-typeface:1.3.41.1@aar'
}
</code>```

Root build.gradel

```<code>  // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha9'
  //  classpath 'me.tatarka:gradle-retrolambda:3.3.0-beta4'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}
allprojects {
 repositories {
    google()
    jcenter()
    mavenCentral()
    /* 3) Add the Creative SDK Maven repo URL */
    maven {
        url 'https://repo.adobe.com/nexus/content/repositories/releases/'
    }
 }
 }
task clean(type: Delete) {
 delete rootProject.buildDir
}
</code>```

Gradelwapper.property

```<code>#Mon Nov 13 11:59:09 IST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-rc-1-all.zip
</code>```

When its run perfectly in 2.3.3 but when i upgrade on 3.0 it gives error
so i create new blank projct in 3.0 and move all java and resource file
also incluede all lib but it show this error
merging code from android studio 2.3.3 to 3.0 canary
Thanks in advance

答:
So first update to Android Studio 3.0

Then in gradle-wrapper.properties:

change distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-rc-1-all.zip

to distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

And in your build.gradle try this (you'll have to change the applicationId):

```<code>apply plugin: 'com.android.application'

repositories {
    mavenLocal()
    maven {
        url 'http://maven.localytics.com/public'
    }
    maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}
android {
    compileSdkVersion 26
//    buildToolsVersion "27.0.0"
    defaultConfig {
        applicationId "com.custom.test"
        minSdkVersion  14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/DEPENDENCIES'
        pickFirst 'AndroidManifest.xml'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

ext {
    supportLibVersion = '26.1.0'
    AAVersion = '3.3.2'
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    androidTestImplementation 'com.android.support.test:runner:1.0.1'

    testImplementation 'junit:junit:4.12'

    implementation "com.android.support:design:$supportLibVersion"
    implementation "com.android.support:support-v4:$supportLibVersion"
    implementation 'com.android.support:multidex:1.0.1'
    implementation "com.android.support:cardview-v7:$supportLibVersion"
    implementation "com.android.support:support-annotations:$supportLibVersion"

    api 'com.google.android.gms:play-services:11.6.0' // Avoid that. Import only what is needed
    implementation "org.androidannotations:androidannotations-api:$AAVersion"

    implementation 'com.afollestad.material-dialogs:core:0.9.5.0'
    implementation 'com.afollestad.material-dialogs:commons:0.9.5.0'

    implementation 'com.adobe.creativesdk.foundation:auth:0.9.1062'
    implementation 'com.adobe.creativesdk:image:4.6.3'

    implementation 'com.mikepenz:iconics-core:2.5.2@aar'
    implementation 'com.mikepenz:community-material-typeface:1.3.41.1@aar'

    implementation 'com.squareup.okhttp:okhttp:2.4.0'
    implementation 'com.squareup.retrofit:retrofit:1.9.0'
    implementation 'com.squareup.picasso:picasso:2.5.2'

    implementation 'com.daprlabs.aaron:cardstack:0.3.0'
    implementation 'com.eowise:recyclerview-stickyheaders:0.5.2@aar'
    implementation 'com.facebook.android:facebook-android-sdk:4.17.0'
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'com.github.traex.rippleeffect:library:1.3'
    implementation 'com.google.guava:guava:20.0'
    implementation 'com.localytics.android:library:3.8.0'
    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    implementation 'com.rengwuxian.materialedittext:library:2.1.4'
}
</code>```

Body:
app build.gradel

 apply plugin: 'com.android.application'
//apply plugin: 'me.tatarka.retrolambda'
def AAVersion = '3.3.2'
buildscript {
repositories {
    mavenCentral()
}
dependencies {
    // classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
}
}
repositories {
     mavenCentral()
     mavenLocal()
     jcenter()
     maven {
          url 'http://maven.localytics.com/public'
     }
     maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
    }
android {
     compileSdkVersion 26
     buildToolsVersion "27.0.0"
     defaultConfig {
          applicationId "com.packagename"
          minSdkVersion 14
          targetSdkVersion 26
          versionCode 1
          versionName "1.0"
          testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
         vectorDrawables.useSupportLibrary = true
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/DEPENDENCIES'
    pickFirst 'AndroidManifest.xml'
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
 }
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
//implementation 'com.android.support:appcompat-v7:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
api 'com.android.support:design:26.1.0'
//){
//        exclude group:'com.android.support' , module: 'support-annotations' version '26.1.0'
//        exclude group:'com.android.support' , module: 'support-v4' version '26.1.0'
//        exclude group:'com.android.support' , module: 'multidex' version '1.0.1'
//        exclude group:'com.android.support' , module: 'cardview-v7' version '26.1.0'
//
//    }
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support:multidex:1.0.1'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:support-annotations:26.1.0'
//implementation 'com.google.android.gms:play-services-ads:11.6.0'
//implementation 'com.google.android.gms:play-services-auth:11.6.0'
api 'com.google.android.gms:play-services:11.6.0'
//implementation 'com.google.android.gms:play-services-gcm:11.6.0'
implementation "org.androidannotations:androidannotations-api:$AAVersion"
//    implementation('com.github.afollestad.material-dialogs:core:0.8.5.7@aar') {
//        transitive = true
//    }
//    implementation('com.github.afollestad.material-dialogs:commons:0.8.5.7@aar') {
//        transitive = true
//    }
implementation 'com.afollestad.material-dialogs:core:0.9.5.0'
implementation 'com.afollestad.material-dialogs:commons:0.9.5.0'
//api 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.daprlabs.aaron:cardstack:0.3.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.google.guava:guava:20.0'
implementation 'com.squareup.retrofit:retrofit:1.9.0'
implementation 'com.squareup.okhttp:okhttp:2.4.0'
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
implementation 'com.rengwuxian.materialedittext:library:2.1.4'
implementation 'com.facebook.android:facebook-android-sdk:4.17.0'
implementation 'com.nineoldandroids:library:2.4.0'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.github.traex.rippleeffect:library:1.3'
implementation 'com.adobe.creativesdk.foundation:auth:0.9.1062'
implementation 'com.adobe.creativesdk:image:4.6.3'
implementation 'com.localytics.android:library:3.8.0'
// implementation 'com.github.fengdai:alertdialogpro-core:0.2.7-20161111.083903-7'
//  implementation 'com.github.fengdai:alertdialogpro-theme-material:0.2.7-20161110.030043-6'
implementation 'com.eowise:recyclerview-stickyheaders:0.5.2@aar'
implementation 'com.mikepenz:iconics-core:2.5.2@aar'
implementation 'com.mikepenz:community-material-typeface:1.3.41.1@aar'
}

Root build.gradel

  // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha9'
  //  classpath 'me.tatarka:gradle-retrolambda:3.3.0-beta4'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}
allprojects {
 repositories {
    google()
    jcenter()
    mavenCentral()
    /* 3) Add the Creative SDK Maven repo URL */
    maven {
        url 'https://repo.adobe.com/nexus/content/repositories/releases/'
    }
 }
 }
task clean(type: Delete) {
 delete rootProject.buildDir
}

Gradelwapper.property

#Mon Nov 13 11:59:09 IST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-rc-1-all.zip

When its run perfectly in 2.3.3 but when i upgrade on 3.0 it gives error
so i create new blank projct in 3.0 and move all java and resource file
also incluede all lib but it show this error
merging code from android studio 2.3.3 to 3.0 canary
Thanks in advance

Body:
So first update to Android Studio 3.0

Then in gradle-wrapper.properties:

change distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-rc-1-all.zip

to distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

And in your build.gradle try this (you'll have to change the applicationId):

apply plugin: 'com.android.application'

repositories {
    mavenLocal()
    maven {
        url 'http://maven.localytics.com/public'
    }
    maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}
android {
    compileSdkVersion 26
//    buildToolsVersion "27.0.0"
    defaultConfig {
        applicationId "com.custom.test"
        minSdkVersion  14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/DEPENDENCIES'
        pickFirst 'AndroidManifest.xml'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

ext {
    supportLibVersion = '26.1.0'
    AAVersion = '3.3.2'
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    androidTestImplementation 'com.android.support.test:runner:1.0.1'

    testImplementation 'junit:junit:4.12'

    implementation "com.android.support:design:$supportLibVersion"
    implementation "com.android.support:support-v4:$supportLibVersion"
    implementation 'com.android.support:multidex:1.0.1'
    implementation "com.android.support:cardview-v7:$supportLibVersion"
    implementation "com.android.support:support-annotations:$supportLibVersion"

    api 'com.google.android.gms:play-services:11.6.0' // Avoid that. Import only what is needed
    implementation "org.androidannotations:androidannotations-api:$AAVersion"

    implementation 'com.afollestad.material-dialogs:core:0.9.5.0'
    implementation 'com.afollestad.material-dialogs:commons:0.9.5.0'

    implementation 'com.adobe.creativesdk.foundation:auth:0.9.1062'
    implementation 'com.adobe.creativesdk:image:4.6.3'

    implementation 'com.mikepenz:iconics-core:2.5.2@aar'
    implementation 'com.mikepenz:community-material-typeface:1.3.41.1@aar'

    implementation 'com.squareup.okhttp:okhttp:2.4.0'
    implementation 'com.squareup.retrofit:retrofit:1.9.0'
    implementation 'com.squareup.picasso:picasso:2.5.2'

    implementation 'com.daprlabs.aaron:cardstack:0.3.0'
    implementation 'com.eowise:recyclerview-stickyheaders:0.5.2@aar'
    implementation 'com.facebook.android:facebook-android-sdk:4.17.0'
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'com.github.traex.rippleeffect:library:1.3'
    implementation 'com.google.guava:guava:20.0'
    implementation 'com.localytics.android:library:3.8.0'
    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    implementation 'com.rengwuxian.materialedittext:library:2.1.4'
}


来源: stackexchange

问:
How to create two colors gradient effect from center using css?
In excel I created this effect with a plus sign in it.
I have been looking to create this with CSS, but I am not getting close!
How can I do this? Is there any good web site that teaches how to work with gradients?

Regards,
Elio Fernandes

答:
With CSS you can reach Radial Gradient, is similar, but not with Excel output.

#grad1 {
  height: 150px;
  width: 200px;
  background: red;
  /* For browsers that do not support gradients */
  background: -webkit-radial-gradient(red 5%, yellow 15%, green 60%);
  /* Safari 5.1-6.0 */
  background: -o-radial-gradient(red 5%, yellow 15%, green 60%);
  /* For Opera 11.6 to 12.0 */
  background: -moz-radial-gradient(red 5%, yellow 15%, green 60%);
  /* For Firefox 3.6 to 15 */
  background: radial-gradient(red 5%, yellow 15%, green 60%);
  /* Standard syntax (must be last) */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="grad1"></div></code>```

Note: Internet Explorer 9 and earlier versions do not support gradients.

ContentLicense: CC BY-SA 3.0

Body:
With CSS you can reach Radial Gradient, is similar, but not with Excel output.

#grad1 {
  height: 150px;
  width: 200px;
  background: red;
  /* For browsers that do not support gradients */
  background: -webkit-radial-gradient(red 5%, yellow 15%, green 60%);
  /* Safari 5.1-6.0 */
  background: -o-radial-gradient(red 5%, yellow 15%, green 60%);
  /* For Opera 11.6 to 12.0 */
  background: -moz-radial-gradient(red 5%, yellow 15%, green 60%);
  /* For Firefox 3.6 to 15 */
  background: radial-gradient(red 5%, yellow 15%, green 60%);
  /* Standard syntax (must be last) */
}

<div id="grad1"></div>

Note: Internet Explorer 9 and earlier versions do not support gradients.


问:
How to dm person who used command in discord
This is my code to dm the person doing the command:

```<code> @client.command()
 async def test(pass_context=True):
     await message.author.sendMessage("test")
</code>```

what my code is supposed to do is when someone does (this is an example) !test then they would receive a Direct Message saying something. When I try this it tells me: NameError: name 'message' is not defined. And I have no idea what to do about it.

答:
```<code> @client.command(pass_context=True)
 async def test(ctx):
     await client.send_message(ctx.message.author, "test")
</code>```

You're passing context, you can use that context to send directly to the author of the message.

You're also using pass_context=True in the wrong place, it needs to be where you're creating the command, not defining it.

(i.e ctx.message.author, ctx.message.channel)

Body:
This is my code to dm the person doing the command:

 @client.command()
 async def test(pass_context=True):
     await message.author.sendMessage("test")

what my code is supposed to do is when someone does (this is an example) !test then they would receive a Direct Message saying something. When I try this it tells me: NameError: name 'message' is not defined. And I have no idea what to do about it.

Body:
 @client.command(pass_context=True)
 async def test(ctx):
     await client.send_message(ctx.message.author, "test")

You're passing context, you can use that context to send directly to the author of the message.

You're also using pass_context=True in the wrong place, it needs to be where you're creating the command, not defining it.

(i.e ctx.message.author, ctx.message.channel)


问:
tensorflow argmax returns tuple?
I' trying to construct neural network in tensorflow with tf.contrib.estimator
but

```<code> logits = tf.reduce_mean(conv2, axis=[1, 2])

    y = tf.argmax(logits, axis=1),
    # If prediction mode, early return
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode, predictions=y)

    loss_op = tf.losses.softmax_cross_entropy(onehot_labels=y_onehot, logits=logits)
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())

    # Add evaluation metrics (for EVAL mode)
    acc_op = tf.contrib.metrics.accuracy(labels=y_, predictions=tf.cast(y, tf.uint8))
</code>```

returns an error:

```<code> raise TypeError('{} must be Tensor, given: {}'.format(tensor_name, x)) TypeError: predictions must be Tensor, given: (<tf.Tensor  'ArgMax:0' shape=(10,) dtype=int64>,)
</code>```

答:
Problem was in comma at the ending</p>

```<code>y = tf.argmax(logits, axis=1),
</code>```

Title: tensorflow argmax returns tuple?

Body:
I' trying to construct neural network in tensorflow with tf.contrib.estimator
but

 logits = tf.reduce_mean(conv2, axis=[1, 2])

    y = tf.argmax(logits, axis=1),
    # If prediction mode, early return
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode, predictions=y)

    loss_op = tf.losses.softmax_cross_entropy(onehot_labels=y_onehot, logits=logits)
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())

    # Add evaluation metrics (for EVAL mode)
    acc_op = tf.contrib.metrics.accuracy(labels=y_, predictions=tf.cast(y, tf.uint8))

returns an error:

 raise TypeError('{} must be Tensor, given: {}'.format(tensor_name, x)) TypeError: predictions must be Tensor, given: (<tf.Tensor  'ArgMax:0' shape=(10,) dtype=int64>,)

Body:
Problem was in comma at the ending

y = tf.argmax(logits, axis=1),


问:
How to display validation errors on same dialog?
I am using codeigniter HMVC. I'm trying to create a sign up form that opens when sign up button is clicked. However, validation errors for the sign-up form appears on the parent page where the login form is located the dialog also closes after submitting data. What I want to do is to display the errors on the sign-up form dialog.

vw_login.php

```<code><button  id="show-sign-up-dialog">Sign Up</button>
<dialog  id="sign-up-dialog" >
<button  id="close"><i class="fa fa-times"></i></button>

<?php echo form_open('user/sign_up', 'id = "reg_form" class="form-horizontal" role="form"');  ?>
 <!-- REGISTER USERNAME -->
 <div class="form-group">
 <div class="col-12">
 <label for="name"></label>

 <?php
   $regi_username_attrib = array(
                'name' =>'register_username',
                'class'=>'form-control mdl-input-login',
                'rows' =>'4',
                'placeholder'=>'Username'
                );
   echo form_error('register_username');
  echo form_input($regi_username_attrib, set_value('register_username', ''));
  ?>

 </div>
 </div>
//Script to submit sign up form
    <script>
$(document).on("click", "#btn_sign_up", function ()
{
    $.ajax({
            type: "POST",
            url: "<?php echo base_url('user/sign_up');?>",
            data: $(this).serialize(),
            success: function(data) {
            var obj = $.parseJSON(data);
                if(obj!==null)
                {
                   $('#error_msg').html(obj['error_message']);
                }
                }});

});

</script>
//Script to open sign up form
<script>
   var dialog_AddEntry = document.querySelector('#sign-up-dialog');
   var showDialogButton_AddEntry = document.querySelector('#show-sign-up-dialog');
   if (! dialog_AddEntry.showModal) {
      dialogPolyfill.registerDialog(dialog_AddEntry);
    }
       showDialogButton_AddEntry.addEventListener('click', function() {
       dialog_AddEntry.showModal();
});
      dialog_AddEntry.querySelector('#close').addEventListener('click', function() {
      dialog_AddEntry.close();
});

</script>
</code>```

Controller
    class User extends My_Controller {

```<code>public function index()
{
    $this->load->view('vw_login');
}

public function login()
{
    //|is_unique[tbl_user.user_username]
    $this->load->library('form_validation');
    $this->form_validation->set_rules('username', 'Username', 'trim|required');
    $this->form_validation->set_rules('password', 'Password', 'trim|required');
    if ($this->form_validation->run() == FALSE) // If username and password is invalid
    {
        $this->load->view('vw_login');
    }
    else
    {

    }

}
public function sign_up()
{
    $this->load->library('form_validation');
    $this->form_validation->set_rules('register_username', 'Username', 'trim|required');
    if ($this->form_validation->run() == FALSE) // If username and password is invalid
    {
        $this->load->view('vw_login');
        $data = array('error_message' => form_error('register_username'));
        echo json_encode($data);
    }
    else
    {

    }

}
</code>```

}

答:
Add the following

```<code><span id="error_msg"></span>
</code>```

after

```<code><label for="name"></label>
</code>```

Body:
I am using codeigniter HMVC. I'm trying to create a sign up form that opens when sign up button is clicked. However, validation errors for the sign-up form appears on the parent page where the login form is located the dialog also closes after submitting data. What I want to do is to display the errors on the sign-up form dialog.

vw_login.php

<button  id="show-sign-up-dialog">Sign Up</button>
<dialog  id="sign-up-dialog" >
<button  id="close"></button>

<?php echo form_open('user/sign_up', 'id = "reg_form" class="form-horizontal" role="form"');  ?>

 <?php
   $regi_username_attrib = array(
                'name' =>'register_username',
                'class'=>'form-control mdl-input-login',
                'rows' =>'4',
                'placeholder'=>'Username'
                );
   echo form_error('register_username');
  echo form_input($regi_username_attrib, set_value('register_username', ''));
  ?>

//Script to submit sign up form

//Script to open sign up form

Controller
    class User extends My_Controller {

public function index()
{
    $this->load->view('vw_login');
}

public function login()
{
    //|is_unique[tbl_user.user_username]
    $this->load->library('form_validation');
    $this->form_validation->set_rules('username', 'Username', 'trim|required');
    $this->form_validation->set_rules('password', 'Password', 'trim|required');
    if ($this->form_validation->run() == FALSE) // If username and password is invalid
    {
        $this->load->view('vw_login');
    }
    else
    {

    }

}
public function sign_up()
{
    $this->load->library('form_validation');
    $this->form_validation->set_rules('register_username', 'Username', 'trim|required');
    if ($this->form_validation->run() == FALSE) // If username and password is invalid
    {
        $this->load->view('vw_login');
        $data = array('error_message' => form_error('register_username'));
        echo json_encode($data);
    }
    else
    {

    }

}

}

Body:
Add the following

<span id="error_msg"></span>

after

<label for="name"></label>


问:
jquery - bug with displaying select options
I have multiple select menus where the pattern is :

```<code><select name='device$num' id='device$num' size='8' multiple='multiple' >"
</code>```

I want to display the values out when any one of these select changes.

I tried this but sometimes I get undefined values from the alert. what is wrong?

```<code><script>
    \$("select[id^=device]").change(function () {
        \$("#paramselection").html(" ");
        \$("#voltageselection").html(" ");

        // IF THE DATA HAS CHANGED, FIND OUT WHICH DATA SECTIONS ARE STILL VALID

        \$("select[id^=device] :selected").val(function(index, value) {
            alert(value);
        });
    });
</script>
</code>```

Another question, how do i pattern match such that id^=device\d+? Sorry, I am more familar with perl

答:
In order to avoid redundant DOM selection, cache the device elements, and use that to get the selected values of all of them

From the devices set, use find()(docs) with the selected-selector(docs) to get the selected <option> elements.

Then use map()(docs) to create a jQuery object containing the values, then get()(docs) to retrieve the Array from the object.

```<code>  // cache all the "device" elements as you assign the "change" handler
var devices = $("select[id^=device]").change(function () {
    $("#paramselection").html(" ");
    $("#voltageselection").html(" ");

         // from the "devices" variable, find selected options, and
         //    create an Array of the values
    var selected = devices.find('option:selected')
                          .map(function(){
                              return this.value;
                          }).get();

    alert( selected ); // will alert an array of the selected values
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have multiple select menus where the pattern is :

<select name='device$num' id='device$num' size='8' multiple='multiple' >"

I want to display the values out when any one of these select changes.

I tried this but sometimes I get undefined values from the alert. what is wrong?

Another question, how do i pattern match such that id^=device\d+? Sorry, I am more familar with perl

Body:
In order to avoid redundant DOM selection, cache the device elements, and use that to get the selected values of all of them

From the devices set, use find()(docs) with the selected-selector(docs) to get the selected <option> elements.

Then use map()(docs) to create a jQuery object containing the values, then get()(docs) to retrieve the Array from the object.

  // cache all the "device" elements as you assign the "change" handler
var devices = $("select[id^=device]").change(function () {
    $("#paramselection").html(" ");
    $("#voltageselection").html(" ");

         // from the "devices" variable, find selected options, and
         //    create an Array of the values
    var selected = devices.find('option:selected')
                          .map(function(){
                              return this.value;
                          }).get();

    alert( selected ); // will alert an array of the selected values
});


问:
What is stored in variable cols in : var $cols = $('.sortdivs').on('click',function(){...});
```<code>var $cols = $('.sortdivs').on('click',function(){…});
</code>```

I know that the function will run when any element with sortdivs class is clicked.
I dont know what is being stored in variable cols and how it can be used.
I tried printing variable cols and i got 'object Object' as the output.Thanks in advance.

答: You can see access all the property store in variable by writing $cols[0] like ATTRIBUTE_NODE,canHaveChildren, canHaveHTML etc. You can debug and see what is inside $col[0] and based on your requirement you can manipulate them. I hope this will be helpful for you.</p>

Body:
var $cols = $('.sortdivs').on('click',function(){…});

I know that the function will run when any element with sortdivs class is clicked.
I dont know what is being stored in variable cols and how it can be used.
I tried printing variable cols and i got 'object Object' as the output.Thanks in advance.


问:
ERangeError on Delphi XE
I'm migrating a software from Delphi 5 to Delphi XE.
I've already corrected a lot of differences, and i can now compile my code.

The problem happening is that sometimes (in some places of the code), I'm getting the error "Range Check Error".

For exemple, in this code:

```<code>function CopyChar(Ori : string; var Des : Array of char) : Boolean;
var Msg     : string;
    Counter : integer;
    SizeDes : integer;
begin
    SizeDes:= SizeOf(Des);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= ' ';
    end;
    Ori:= Trim(Ori);
    Msg:= '';
    SizeDes:= Min(Length(Ori),SizeDes);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= char(Ori[Counter]);
    end;
    CopyChar:= True;
end;
</code>```

I get the error at runtime when passing by the line Des[Counter-1] := ' ';
The error occurr not at the first time it passes through the loop, but after lot of times.

I've tried to disable Rance Checking ($R) but it does nos solves my problem.
I've also tried to change the type of "Counter" to Cardinal and LongWord, with no success

I would be glad for any helpful idea!

Thanks.

答: Another problem could be a corrupted input of either Ori or Des, so if the problem is not solved by Davids solution, you should check the calling code, too.</p>

Title: ERangeError on Delphi XE

Body:
I'm migrating a software from Delphi 5 to Delphi XE.
I've already corrected a lot of differences, and i can now compile my code.

The problem happening is that sometimes (in some places of the code), I'm getting the error "Range Check Error".

For exemple, in this code:

function CopyChar(Ori : string; var Des : Array of char) : Boolean;
var Msg     : string;
    Counter : integer;
    SizeDes : integer;
begin
    SizeDes:= SizeOf(Des);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= ' ';
    end;
    Ori:= Trim(Ori);
    Msg:= '';
    SizeDes:= Min(Length(Ori),SizeDes);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= char(Ori[Counter]);
    end;
    CopyChar:= True;
end;

I get the error at runtime when passing by the line Des[Counter-1] := ' ';
The error occurr not at the first time it passes through the loop, but after lot of times.

I've tried to disable Rance Checking ($R) but it does nos solves my problem.
I've also tried to change the type of "Counter" to Cardinal and LongWord, with no success

I would be glad for any helpful idea!

Thanks.


问:
How to generate a report in excel (xls, xlsx) format on ODOO?
In purchase module, I want to generate the details which is being printed in the purchase order button as a pdf report. My requirement is how to print the report in excel format in odoo 10?</p>

答:
You can export the current tree view as an excel file with this module: web_export_view

Or you can build your own excel report with this other modules: report_xls report_xlsx

There are modules that already use the report_xls module, but you can look for them in the Odoo Apps or in the OCA repository


问:
How to set DateComponentFormatter's local other than current?
Situation

I have a function that uses DateComponentFormatter's function fun string(from: Date, to: Date) to return a formatted string based on the time difference between two dates and it works perfectly. However I want to return this formatted string always in English (currently formatting according to device's local).

Questions

How do you set the DateComponentFormatter's local like what you can do with DateFormatter's? If you can't, how would you proceed?

Code:

```<code>import Foundation

func returnRemainingTimeAsString(currentDate: Date, nextDate: Date)->String {

  let dateComponentsFormatter = DateComponentsFormatter()
  dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
  dateComponentsFormatter.allowedUnits = [.day, .hour, .minute, .second]
  dateComponentsFormatter.maximumUnitCount = 1

  let differenceAsString = dateComponentsFormatter.string(from: currentDate, to: nextDate)!

  return differenceAsString
}

let currentDate = Date()
let futureDate = currentDate.addingTimeInterval(3604)
returnRemainingTimeAsString(currentDate: currentDate, nextDate: futureDate)

// prints 1 hour (if devices local is English) or 1 hora (if Spanish),
// and I want it to return always 1 hour.
</code>```

答:
DateComponentsFormatter has a calendar property.

Get the current calendar, set its locale and assign the calendar to the formatter.

```<code>let dateComponentsFormatter = DateComponentsFormatter()
var calendar = Calendar.current
calendar.locale = Locale(identifier: "en_US_POSIX")
dateComponentsFormatter.calendar = calendar
dateComponentsFormatter.unitsStyle = .full
...
</code>```

Body:
Situation

I have a function that uses DateComponentFormatter's function fun string(from: Date, to: Date) to return a formatted string based on the time difference between two dates and it works perfectly. However I want to return this formatted string always in English (currently formatting according to device's local).

Questions

How do you set the DateComponentFormatter's local like what you can do with DateFormatter's? If you can't, how would you proceed?

Code:

import Foundation

func returnRemainingTimeAsString(currentDate: Date, nextDate: Date)->String {

  let dateComponentsFormatter = DateComponentsFormatter()
  dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
  dateComponentsFormatter.allowedUnits = [.day, .hour, .minute, .second]
  dateComponentsFormatter.maximumUnitCount = 1

  let differenceAsString = dateComponentsFormatter.string(from: currentDate, to: nextDate)!

  return differenceAsString
}

let currentDate = Date()
let futureDate = currentDate.addingTimeInterval(3604)
returnRemainingTimeAsString(currentDate: currentDate, nextDate: futureDate)

// prints 1 hour (if devices local is English) or 1 hora (if Spanish),
// and I want it to return always 1 hour.

Body:
DateComponentsFormatter has a calendar property.

Get the current calendar, set its locale and assign the calendar to the formatter.

let dateComponentsFormatter = DateComponentsFormatter()
var calendar = Calendar.current
calendar.locale = Locale(identifier: "en_US_POSIX")
dateComponentsFormatter.calendar = calendar
dateComponentsFormatter.unitsStyle = .full
...


问:
Fail to bind the options data in JS
I want to display a select-only-one combo box using html+js.

What I want to show is like this:

But now I just get a blank drop down list like this：

The HTML code:

```<code><div style="width:200px;height:100%;float:left;padding-left: 0px">
    <oj-combobox-one id="en" aria-label="en Select" options="{{ens}}" value="{{selectedEn}}"render-mode="native" style="max-width:20em" >
  </oj-combobox-one>
</div>
</code>```

The JS code:

```<code>self.ens = ko.observableArray([]);
self.selectedEn = ko.observable("a"); //Default to show
var en = ["a","b","c"];
self.ens(en);
</code>```

Could you please help to find out where the issue is? Thanks in advance.

答:
Check out this page of the documentation. Each option requires the actual value (which is used by the JS file), as well as the label (which is what the user will see on the screen).

So you need to change your variable en to:

```<code>var en = [{value: 'a', label: 'a'},
          {value: 'b', label: 'b'},
          {value: 'c', label: 'c'}];
</code>```

Title: Fail to bind the options data in JS

Body:
I want to display a select-only-one combo box using html+js.

What I want to show is like this:

But now I just get a blank drop down list like this：

The HTML code:

    <oj-combobox-one id="en" aria-label="en Select" options="{{ens}}" value="{{selectedEn}}"render-mode="native" style="max-width:20em" >
  </oj-combobox-one>

The JS code:

self.ens = ko.observableArray([]);
self.selectedEn = ko.observable("a"); //Default to show
var en = ["a","b","c"];
self.ens(en);

Could you please help to find out where the issue is? Thanks in advance.

Body:
Check out this page of the documentation. Each option requires the actual value (which is used by the JS file), as well as the label (which is what the user will see on the screen).

So you need to change your variable en to:

var en = [{value: 'a', label: 'a'},
          {value: 'b', label: 'b'},
          {value: 'c', label: 'c'}];


问:
Passing reference outside of function
I am using https://github.com/futurepress/react-native-static-server. There are two functions, server.start() in order to start the server and server.stop() in order to stop the server.
Starting the server from a function is done in _startServer(). However, how would I stop the server (_stopServer())? I am not sure how to pass the reference to the server properly to _stopServer().

```<code>export default class Foo extends Component {

    _startServer = () => {
        server.start()
            .then((localServer) => {
                this.setState({
                    serverRunning: true,
                    localServer: localServer
                })
            });
     }

     _stopServer = (refToServer) => {
          refToServer.stop();
     }

     ...

     render() {
         return (
            <TouchableOpacity
                onPress={() => this._startServer()} />

            <TouchableOpacity
                onPress={() => this._stopServer(??)} />
         )
     }
}
</code>```

答:
you assign the localServer to the Component's state with this call:

```<code>this.setState({
               serverRunning: true,
               localServer: localServer
           })
</code>```

so, you can get the server with this.state.localServer and stop it with this.state.localServer.stop()

something like this:

```<code>_stopServer = () => {
          this.state.localServer.stop();
     }
</code>```

Title: Passing reference outside of function

Body:
I am using https://github.com/futurepress/react-native-static-server. There are two functions, server.start() in order to start the server and server.stop() in order to stop the server.
Starting the server from a function is done in _startServer(). However, how would I stop the server (_stopServer())? I am not sure how to pass the reference to the server properly to _stopServer().

export default class Foo extends Component {

    _startServer = () => {
        server.start()
            .then((localServer) => {
                this.setState({
                    serverRunning: true,
                    localServer: localServer
                })
            });
     }

     _stopServer = (refToServer) => {
          refToServer.stop();
     }

     ...

     render() {
         return (
            <TouchableOpacity
                onPress={() => this._startServer()} />

            <TouchableOpacity
                onPress={() => this._stopServer(??)} />
         )
     }
}

Body:
you assign the localServer to the Component's state with this call:

this.setState({
               serverRunning: true,
               localServer: localServer
           })

so, you can get the server with this.state.localServer and stop it with this.state.localServer.stop()

something like this:

_stopServer = () => {
          this.state.localServer.stop();
     }


问:
Exclude integer values from list that have difference less than 80
I have a list that contains many values like

```<code>mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ]
</code>```

In case I have values that have difference less than 80,  like 4868,4878 I want to exclude the second one and keep only 4868 and get the indexes of the those that are deleted.

The new resulted list will be

```<code>my_list = [4361, 4868, 5395, 5940, 6539, 7164]
</code>```

Is there an easy way to achieve this?

答:
Assuming the list is sorted, just compare the current value to the last value in the result list, if any, and append it if the difference is sufficiently large.</p>

```<code>mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ]
n = 80
result, deleted = [], []
for i, x in enumerate(mylist):
    if result == [] or x - result[-1] > n:
        result.append(x)
    else:
        deleted.append(i)
print(result)  # [4361, 4868, 5395, 5940, 6539, 7164]
print(deleted) # [2, 6]
</code>```

Body:
I have a list that contains many values like

mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ]

In case I have values that have difference less than 80,  like 4868,4878 I want to exclude the second one and keep only 4868 and get the indexes of the those that are deleted.

The new resulted list will be

my_list = [4361, 4868, 5395, 5940, 6539, 7164]

Is there an easy way to achieve this?

Body:
Assuming the list is sorted, just compare the current value to the last value in the result list, if any, and append it if the difference is sufficiently large.

mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ]
n = 80
result, deleted = [], []
for i, x in enumerate(mylist):
    if result == [] or x - result[-1] > n:
        result.append(x)
    else:
        deleted.append(i)
print(result)  # [4361, 4868, 5395, 5940, 6539, 7164]
print(deleted) # [2, 6]


问:
How to make a Python list based on another list
I have a master list and then a whole bunch (100s) of sublists cherry-picked from the master list. However, over time items in the master list will be removed. I want to also remove those items from each of the sublists. I imagine having a list that is only pointers to the master list. As the pointer goes stale then the list gets smaller. The sublists are normally in objects not easily accessible at the point where the master list is edited. Is this possible?</p>

```<code>master = ["first","last","middle","top","bottom","left","right","inside"]

sides = []
sides.append(master[2])
sides.append(master[3])
sides.append(master[4])

centre = []
centre.append(master[0])
centre.append(master[2])
centre.append(master[7])

print(master)
['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
print(sides)
['middle', 'top', 'bottom']
print(centre)
['first', 'middle', 'inside']

master.remove("middle")

print(master)
['first', 'last', 'top', 'bottom', 'left', 'right', 'inside']
print(sides) # Ideal outcome
['top', 'bottom']
print(centre) # Ideal outcome
['first', 'inside']
</code>```

答:
The list element needs to be removed for every list that it is in.
All you need to do to implement this is -</p>

```<code>print(master)
['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
print(sides)
['middle', 'top', 'bottom']
print(centre)
['first', 'middle', 'inside']

master.remove("middle")
sides.remove("middle")
centre.remove("middle")

print(master)
['first', 'last', 'top', 'bottom', 'left', 'right', 'inside']
print(sides) # Ideal outcome
['top', 'bottom']
print(centre) # Ideal outcome
['first', 'inside']
</code>```

Body:
I have a master list and then a whole bunch (100s) of sublists cherry-picked from the master list. However, over time items in the master list will be removed. I want to also remove those items from each of the sublists. I imagine having a list that is only pointers to the master list. As the pointer goes stale then the list gets smaller. The sublists are normally in objects not easily accessible at the point where the master list is edited. Is this possible?

master = ["first","last","middle","top","bottom","left","right","inside"]

sides = []
sides.append(master[2])
sides.append(master[3])
sides.append(master[4])

centre = []
centre.append(master[0])
centre.append(master[2])
centre.append(master[7])

print(master)
['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
print(sides)
['middle', 'top', 'bottom']
print(centre)
['first', 'middle', 'inside']

master.remove("middle")

print(master)
['first', 'last', 'top', 'bottom', 'left', 'right', 'inside']
print(sides) # Ideal outcome
['top', 'bottom']
print(centre) # Ideal outcome
['first', 'inside']

Body:
The list element needs to be removed for every list that it is in.
All you need to do to implement this is -

print(master)
['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
print(sides)
['middle', 'top', 'bottom']
print(centre)
['first', 'middle', 'inside']

master.remove("middle")
sides.remove("middle")
centre.remove("middle")

print(master)
['first', 'last', 'top', 'bottom', 'left', 'right', 'inside']
print(sides) # Ideal outcome
['top', 'bottom']
print(centre) # Ideal outcome
['first', 'inside']


问:
Remove header from Primefaces Dialog
Is there a way to remove the header from a dialog opened with the Primefaces Dialog Framework?
I know I can set a custom header (see code snipped), but how to remove it at all? I don't want to remove it from all dialog, so overriding the CSS class .ui-dialog .ui-dialog-titlebar is not an option.

```<code> Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("width", 640);
        options.put("height", 340);
        options.put("contentWidth", "100%");
        options.put("contentHeight", "100%");
        options.put("headerElement", "customheader");

        RequestContext.getCurrentInstance().openDialog("viewCars", options, null);
</code>```

答:
You can do it with help of jQuery's Class Selector.

Add following java script inside page where you want to show dialog

```<code>        <script type="text/javascript">
            function removeDialogHeader(xhr, status, args){
                var showHeader=args.showDialogHeader;
                if (!showHeader){
                    //jquery gets all elements with class name ui-dialog-titlebar
                    var elements= $(".ui-dialog-titlebar");
                    //to remove elements
                    elements.remove();
                    //or you can achive the same effect by inserting display:none into element style
                    //elements.css("display", "none");
                }
            }
        </script>
</code>```

modify managed bean method to make header visibility configurable

```<code>public void viewCars() {
    Map<String,Object> options = new HashMap<String, Object>();
    options.put("resizable", false);
    //...
    RequestContext.getCurrentInstance().openDialog("viewCars", options, null);
    RequestContext.getCurrentInstance().addCallbackParam("showDialogHeader", false);
}
</code>```

and, assuming that you have p:commandButton to show dialog, call JS function after Ajax is completed

```<code><p:commandButton value="Show dialog" actionListener="#{testBean.viewCars()}" oncomplete="removeDialogHeader(xhr, status, args);"/>
</code>```

Title: Remove header from Primefaces Dialog

Body:
Is there a way to remove the header from a dialog opened with the Primefaces Dialog Framework?
I know I can set a custom header (see code snipped), but how to remove it at all? I don't want to remove it from all dialog, so overriding the CSS class .ui-dialog .ui-dialog-titlebar is not an option.

 Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("width", 640);
        options.put("height", 340);
        options.put("contentWidth", "100%");
        options.put("contentHeight", "100%");
        options.put("headerElement", "customheader");

        RequestContext.getCurrentInstance().openDialog("viewCars", options, null);

Body:
You can do it with help of jQuery's Class Selector.

Add following java script inside page where you want to show dialog

        <script type="text/javascript">
            function removeDialogHeader(xhr, status, args){
                var showHeader=args.showDialogHeader;
                if (!showHeader){
                    //jquery gets all elements with class name ui-dialog-titlebar
                    var elements= $(".ui-dialog-titlebar");
                    //to remove elements
                    elements.remove();
                    //or you can achive the same effect by inserting display:none into element style
                    //elements.css("display", "none");
                }
            }
        </script>

modify managed bean method to make header visibility configurable

public void viewCars() {
    Map<String,Object> options = new HashMap<String, Object>();
    options.put("resizable", false);
    //...
    RequestContext.getCurrentInstance().openDialog("viewCars", options, null);
    RequestContext.getCurrentInstance().addCallbackParam("showDialogHeader", false);
}

and, assuming that you have p:commandButton to show dialog, call JS function after Ajax is completed

<p:commandButton value="Show dialog" actionListener="#{testBean.viewCars()}" oncomplete="removeDialogHeader(xhr, status, args);"/>


问:
Windows. Change drop-down menu position
Is there a way to change the position of the popup menu. With top-level windows I can do it by CBTProc Callback Function and MoveWindow. Can I do the same with menus? Needs to be done so that the pop-up menu is located only in the area of its parent window. Something like a light window manager. </p>

答:
Yes, in a WH_CBT hook callback, you'll be notified with an 'nCode' of HCBT_CREATEWND whenever a menu window is created. Test for the class name, standard menu/submenu windows would have a class name of '#32768'. You can then send a MN_GETHMENU message to the window to find out which menu is about to be activated. But as documented, it is too early to move the window when the notification is received, the menu is not even visible yet, so you might need to sub-class the window and process additional messages.

Note that you don't need a hook to be notified when a menu window is shown, you can put a handler for the WM_ENTERIDLE message, test for 'wParam' to see if a menu caused the message, get the menu window from 'lParam' and again send a 'MN_GETHMENU' to find out the specific menu. It is possible to move the window at this point without further message handling. Just be aware that 'WM_ENTERIDLE' will be called multiple times so you need to keep track of you've already moved a particular window or not.

Title: Windows. Change drop-down menu position


问:
android studio 3.0 version showing following error while adding recyclerview dependency in bulild.gradle
Error image

I recently updated my android studio to 3.0 and while i was adding dependency for recycler view in build.gradle(module.app) whereas card view is working fine.It's showing the shown error.Below is my dependency code.

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.m.listviewslow"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

答:
add  maven { url 'https://maven.google.com' } in your project level build.gradle .

```<code>    allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}
</code>```

https://developer.android.com/topic/libraries/support-library/setup.html

Body:
Error image

I recently updated my android studio to 3.0 and while i was adding dependency for recycler view in build.gradle(module.app) whereas card view is working fine.It's showing the shown error.Below is my dependency code.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.m.listviewslow"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Body:
add  maven { url 'https://maven.google.com' } in your project level build.gradle .

    allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

https://developer.android.com/topic/libraries/support-library/setup.html


问:
Change the date format before appending with string builder
I have a grid with eight columns and n number of rows in which two columns are dates with the format dd-mmm-yyyy (e.g. 18 oct 2017). Now I need to append this all data and write to a text file but before appending I have to convert the date format to yyyymmdd (e.g. 20171018).

答:
The solution is very simple, assume you have a variable with date

```<code>var sourceDate=DateTime.Now;
StringBuilder myString = new StringBuilder();
myString.Append(sourceDate.ToString("yyyyMMdd")); //This will do the job.
</code>```

You can loop through each Rows, take the date value from the respective columns to a date variable, sourceDate.ToString("yyyyMMdd") (here sourceDate is the date variable) will give you the formatted output format.

Body:
The solution is very simple, assume you have a variable with date

var sourceDate=DateTime.Now;
StringBuilder myString = new StringBuilder();
myString.Append(sourceDate.ToString("yyyyMMdd")); //This will do the job.

You can loop through each Rows, take the date value from the respective columns to a date variable, sourceDate.ToString("yyyyMMdd") (here sourceDate is the date variable) will give you the formatted output format.


问:
Git tries to push commit to GitHub as wrong user
I have two GitHub accounts. First is main, second is for some tests (I'm new in git). In my C:\Users\<Username>\.gitconfig file I have user name and email similar to main GitHub account. Now I've created local repository and change its .git\config file with username and email similar to my second account. But still when I push, it tries to push as user of main account and I have this error:

```<code> Permission to <2nd username>/test.git denied to <1st username>.
</code>```

I thought that only email address is a way how git and GitHub are bounded, and that .git\config will override C:\Users\<Username>\.gitconfig for that repository.

But it seems that I'm wrong...

UPD:

As I remember in my very first push to GitHub git opened a window where I was needed to enter login and password of GitHub. And I entered main account login and paswsword. I have expected that this window opened again, after i tryed to push with new email...

答:
Git by itself doesn't care which name and/or email address you use when you commit when dealing with pushes.

All it cares about is whether it is allowed to push or not.

The last paragraph in your question is the important bit. You've told git to use your 1st account when authenticating with github, and now you're trying to push to your 2nd account without the 1st account having access.

Again, what you have told git to use when committing is completely irrelevant at this point.

To switch to the 2nd account find and open "Windows Credential Manager", find your github account setting and delete it, then try to repush. Git should again ask you for login details.

Or, give the 1st user push access to the 2nd users repository.

Body:
I have two GitHub accounts. First is main, second is for some tests (I'm new in git). In my C:\Users\<Username>\.gitconfig file I have user name and email similar to main GitHub account. Now I've created local repository and change its .git\config file with username and email similar to my second account. But still when I push, it tries to push as user of main account and I have this error:

 Permission to <2nd username>/test.git denied to <1st username>.

I thought that only email address is a way how git and GitHub are bounded, and that .git\config will override C:\Users\<Username>\.gitconfig for that repository.

But it seems that I'm wrong...

UPD:

As I remember in my very first push to GitHub git opened a window where I was needed to enter login and password of GitHub. And I entered main account login and paswsword. I have expected that this window opened again, after i tryed to push with new email...


问:
How to keep data sources synchronized with firebase realtime database with Swift?
I am using Firebase realtime database. Data structure is an array of posts, which user can also comment and like.

I retrieve data like this and put them into a local posts array:

```<code>ref.observe(.childAdded, with: { (snapshot) -> Void in
  self.posts.append(snapshot)
  self.tableView.reloadData()
})
</code>```

They are displayed correctly and no problems so far. Now let's say user likes a post. I add his id to likers array of post in local posts array. However firebase database don't know this yet.

My question is what is the correct way to keep local data and firebase data synchronized?

答:
You should use DatabaseHandler. You should listen your database and then remove handler when you leave your viewcontroller.

```<code>fileprivate lazy var ref = Database.database().reference().child("...")
private var yourHandler: DatabaseHandle?

override func viewDidLoad() {
   super.viewDidLoad()

   yourHandler = ref.observe(.childAdded, with: { (snapshot) -> in
      self.posts.append(snapshot)

      DispatchQueue.main.async {
         self.tableView.reloadData()
      }
   })
 }

deinit {
   if let handler = yourHandler {
      ref.removeObserver(withHandle: handler)
   }
}
</code>```

Now, when you add new item to database, your handler get this item and display it in your viewcontroller.
Note: Always call the reloadData () method on the main thread

Body:
I am using Firebase realtime database. Data structure is an array of posts, which user can also comment and like.

I retrieve data like this and put them into a local posts array:

ref.observe(.childAdded, with: { (snapshot) -> Void in
  self.posts.append(snapshot)
  self.tableView.reloadData()
})

They are displayed correctly and no problems so far. Now let's say user likes a post. I add his id to likers array of post in local posts array. However firebase database don't know this yet.

My question is what is the correct way to keep local data and firebase data synchronized?

Body:
You should use DatabaseHandler. You should listen your database and then remove handler when you leave your viewcontroller.

fileprivate lazy var ref = Database.database().reference().child("...")
private var yourHandler: DatabaseHandle?

override func viewDidLoad() {
   super.viewDidLoad()

   yourHandler = ref.observe(.childAdded, with: { (snapshot) -> in
      self.posts.append(snapshot)

      DispatchQueue.main.async {
         self.tableView.reloadData()
      }
   })
 }

deinit {
   if let handler = yourHandler {
      ref.removeObserver(withHandle: handler)
   }
}

Now, when you add new item to database, your handler get this item and display it in your viewcontroller.
Note: Always call the reloadData () method on the main thread


问:
Require JS with parameter
I am new to ReqireJs. I am trying to do the following:

I have a file(mymodule.js) with the following code:

```<code>require([
    'jquery'
], function ($) {
    var name;
    $(document).ready(function() {
       //do some load stuff
    });
});
</code>```

I am trying to include the file into some other file as follows:

```<code>require(['modules/mymodule.js']);
</code>```

which works fine. My question is that how can I pass some parameters from require(['modules/mymodule.js']); into mymodules.js?

Thanks and regards.

答:
I have found the solution here:

http://blog.novanet.no/4-strategies-for-passing-parameters-to-requirejs-modules/

I have used the code from 1st step from above link "Passing parameter to method" as follows:

```<code>define(
    [
        'jquery'
    ],
    function($){
        return {
            sayHello: function(name){
                alert("Hello " + name);
            }
        };
    }
);
</code>```

Then I have passed the parameter as follows:

```<code>require(['modules/mymodule.js'], function(mymodule){
    mymodule.sayHello("World");
});
</code>```

Title: Require JS with parameter

Body:
I am new to ReqireJs. I am trying to do the following:

I have a file(mymodule.js) with the following code:

require([
    'jquery'
], function ($) {
    var name;
    $(document).ready(function() {
       //do some load stuff
    });
});

I am trying to include the file into some other file as follows:

require(['modules/mymodule.js']);

which works fine. My question is that how can I pass some parameters from require(['modules/mymodule.js']); into mymodules.js?

Thanks and regards.

Body:
I have found the solution here:

http://blog.novanet.no/4-strategies-for-passing-parameters-to-requirejs-modules/

I have used the code from 1st step from above link "Passing parameter to method" as follows:

define(
    [
        'jquery'
    ],
    function($){
        return {
            sayHello: function(name){
                alert("Hello " + name);
            }
        };
    }
);

Then I have passed the parameter as follows:

require(['modules/mymodule.js'], function(mymodule){
    mymodule.sayHello("World");
});


问:
Fill first available column based on a string in R
Happy Monday -

I've used grep to create df2, subsetting df1 to return only those rows with a specific string.

What I'm after is a way to fill only the first available column (from A, B or C) with the value from the string (in this case 3).

```<code>df2 <- df1[grep("DW 3*", df1$D), ]
</code>```

df2:

```<code>ID A B C D
1  3 3   DW 3*
2  4     DW 3*
3  4 3   DW 3*
4  3     DW 3*
</code>```

So I end up with

```<code>ID A B C  D
 1  3 3 3  DW 3*
 2  4 3    DW 3*
 3  4 3 3  DW 3*
 4  3 3    DW 3*
</code>```

I hope that is clear - feel free to ask for clarification, and thanks in advance.

答:
Iterate using apply to find first NA value and replace it with 3

```<code>data.frame(t(apply(df2, 1,
                   function(x) {x[which(is.na(x))[1]] <- 3; x})))
</code>```

Body:
Happy Monday -

I've used grep to create df2, subsetting df1 to return only those rows with a specific string.

What I'm after is a way to fill only the first available column (from A, B or C) with the value from the string (in this case 3).

df2 <- df1[grep("DW 3*", df1$D), ]

df2:

ID A B C D
1  3 3   DW 3*
2  4     DW 3*
3  4 3   DW 3*
4  3     DW 3*

So I end up with

ID A B C  D
 1  3 3 3  DW 3*
 2  4 3    DW 3*
 3  4 3 3  DW 3*
 4  3 3    DW 3*

I hope that is clear - feel free to ask for clarification, and thanks in advance.

Body:
Iterate using apply to find first NA value and replace it with 3

data.frame(t(apply(df2, 1,
                   function(x) {x[which(is.na(x))[1]] <- 3; x})))


问:
Intellij Idea: Tomcat configuration removed each time the IDE is restarted
I am using Intellij Idea 2016.1 and I recently started to get this issue where each time I start/restart the IDE it forgets the tomcat conrfiguration and I have to reconfigure it. Any ideas why that might be and how can I fix it? Thanks in advance. </p>

答: I just checked that "Share" checkbox and it started working for me, now when I restart the IDE it doens't forget that tomcat configuration.


问:
flex 3 getting webserice call to wait for result
i have a function which retrieves values from a webservice , then loops through the returned values and for each returned value does another webservice lookup.

Im having a problem however that when i make the second webservice call within the for loop that the function does not wait for the reuslt and just keeps processing and in turn giving me no value

the code looks like this;

```<code>    private function getResult(e:ResultEvent):void{

   var lengthOfResult:int = e.result.length;
   var arrayCollResults:ArrayCollection = new ArrayCollection();
   var resultArray:Array = new Array(e.result);

       for(var i:int = 0 ; i < lengthOfResult; i++){
      var currentName:String = e.result[i].toString();
      arrayCollResults.addItem(e.result[i] + ws.getMatches(currentName));
   }

   acu.dataProvider = arrayCollResults;
   }
</code>```

what can i do to insure that the value of ws.getMatches(currentName) actually returns a value before moving to next line?

答: As far as I know flex/as3 cannot do a blocking wait for the result - you have to add a listener and wait to be notified.</p>

OwnerDisplayName: luckoftheirish

Body:
i have a function which retrieves values from a webservice , then loops through the returned values and for each returned value does another webservice lookup.

Im having a problem however that when i make the second webservice call within the for loop that the function does not wait for the reuslt and just keeps processing and in turn giving me no value

the code looks like this;

    private function getResult(e:ResultEvent):void{

   var lengthOfResult:int = e.result.length;
   var arrayCollResults:ArrayCollection = new ArrayCollection();
   var resultArray:Array = new Array(e.result);

       for(var i:int = 0 ; i < lengthOfResult; i++){
      var currentName:String = e.result[i].toString();
      arrayCollResults.addItem(e.result[i] + ws.getMatches(currentName));
   }

   acu.dataProvider = arrayCollResults;
   }

what can i do to insure that the value of ws.getMatches(currentName) actually returns a value before moving to next line?

OwnerDisplayName: Simon Groenewolt


问:
How to resize parent window size from iframe?
I have a XUL file with iframe:

```<code><window>
    <iframe src="chrome://plugin/content/options.html"
    style="width: 290px; height: 320px; padding: 0px; margin: 0px"/>
    <script>
        window.frames[0].parent = window;
    </script>
</window>
</code>```

How can i resize parent window size from options.html?

答:
Within regular frames you can use "top" to get the topmost window.  I don't know about an iframe, but you could try:</p>

```<code>top.resizeTo(width, height);
</code>```

Body:
I have a XUL file with iframe:

<window>

</window>

How can i resize parent window size from options.html?

Body:
Within regular frames you can use "top" to get the topmost window.  I don't know about an iframe, but you could try:

top.resizeTo(width, height);


问:
how to update the number component in a list of strings
I have a list:

```<code>['a1', 'a2', 'a3']
</code>```

I want to update it so that each number component is incremented by 1:

```<code>['a2', 'a3', 'a4']
</code>```

What would be the most efficient way to do it?

答:
If your list keeps this form, this should do nicely:

```<code>for x in range(len(l)):
    l[x] = l[x][0] + str(int(l[x][1:]) + 1)
</code>```

Works for any number, and if the "a" part is longer, adjust l[x][**1**:] to the length of your numberless string.

Body:
I have a list:

['a1', 'a2', 'a3']

I want to update it so that each number component is incremented by 1:

['a2', 'a3', 'a4']

What would be the most efficient way to do it?

Body:
If your list keeps this form, this should do nicely:

for x in range(len(l)):
    l[x] = l[x][0] + str(int(l[x][1:]) + 1)

Works for any number, and if the "a" part is longer, adjust l[x][**1**:] to the length of your numberless string.


问:
Curl API request value in body always null
I have the following controller  I am trying to use Curl to test it.  The problem is that fiscalId is always null its not reading my post body from curl.

Controler:

```<code>  [Route("api/token")]
  public class TokenController : Controller
  {
    [HttpPost("changefiscal")]
    [Authorize]
    public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
    {
      //fiscalId is always 0
    }
  }
</code>```

I have checked the documentation here which says to use the -d parameter and post it as a json object. Unfortunately thats not working

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/data

I have tried

```<code>curl -d "fiscalId=21875" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal
</code>```

and

```<code>curl -d "{"fiscalId":"21875"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal
</code>```

and

```<code>curl -d "{"fiscalId":"21875"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal
</code>```

and

```<code>curl -d "{\"fiscalId\":\"21875\"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal
</code>```

and everything else i can think of

I can see in the log that it appears to be sending it

Rebuilt URL to: POST/

timeout on name lookup is not supported

getaddrinfo(3) failed for POST:80

Couldn't resolve host 'POST'

Closing connection 0 curl: (6) Couldn't resolve host 'POST'

timeout on name lookup is not supported

Trying ::1...

TCP_NODELAY set

Trying 127.0.0.1...

TCP_NODELAY set

Connected to localhost (127.0.0.1) port 5000 (#1)

POST /api/token/changefiscal HTTP/1.1
    Host: localhost:5000
    User-Agent: curl/7.53.1
    Accept: /
    Content-Type: application/json
    Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjI2OTAzNzc0NjYyNzc4RDM1MzE2QUUwQUU1MjIyQUU1REIzM0M0NUEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJKcEEzZEdZbmVOTlRGcTRLNVNJcTVkc3p4Rm8ifQ.eyJuYmYiOjE1MTA1NjcxNzMsImV4cCI6MTUxMDU3MDc3MywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJ0ZXN0YXBpIl0sImNsaWVudF9pZCI6IlNlcnZpY2VBY2NvdW50QWNjZXNzIiwic3ViIjoiMjEyNDg1ODIiLCJhdXRoX3RpbWUiOjE1MTA1NjcxNzMsImlkcCI6ImxvY2FsIiwibmFtZSI6ImxpbGF3IiwiZS1tYWlsIjoibGlsYXdAZWcuZGsiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwidGVzdGFwaSJdLCJhbXIiOlsicGFzc3dvcmQiXX0.Q_oJ-xOIKdTtGoRqJbtNjwLV82cQQLhJUVl2Ey-4riZdp45rPIrmfOw9VdknUOLpm8RYZ0iLFC31gCpn1vKb4zLiTmBuTuzYsKxnAvf-UkCj1L8soH4W2lCvx560bZeS7B67tJ4nK9t36OiMLQY4m-_NRTSRBs5QtsXBd5VQGPsTpxf_MxVbQm6Hj6Ot3FGRIa08gmwD3iEr9vsCU6732InbGzU26wtm-WLWp_A_k66Z29G8ms_U8x6gg-aOlQG9_0v_DEjTXCkKNcgWoL0IvaCC0psiYkdIjQxaOwz-e_fcqXpKEFmuoSqmGd1l-eMl3HimOomdOHwqploWGxnJ4Q
    Content-Length: 7

upload completely sent off: 7 out of 7 bytes

However when i check fiscalId its always 0 i even tried to change fiscalId to a string and its just null.

答:
When you POST data as JSON object, like -d '{"fiscalId": 21875}',  your action method should expect some simple class with corresponding properties. In your case:

```<code>public class Dto
{
   public long fiscalId {get; set;}
}
</code>```

and

```<code>public async Task<ActionResult> ChangeFiscal([FromBody] Dto data)
</code>```

Body:
I have the following controller  I am trying to use Curl to test it.  The problem is that fiscalId is always null its not reading my post body from curl.

Controler:

  [Route("api/token")]
  public class TokenController : Controller
  {
    [HttpPost("changefiscal")]
    [Authorize]
    public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
    {
      //fiscalId is always 0
    }
  }

I have checked the documentation here which says to use the -d parameter and post it as a json object. Unfortunately thats not working

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/data

I have tried

curl -d "fiscalId=21875" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal

and

curl -d "{"fiscalId":"21875"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal

and

curl -d "{"fiscalId":"21875"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal

and

curl -d "{\"fiscalId\":\"21875\"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal

and everything else i can think of

I can see in the log that it appears to be sending it

Rebuilt URL to: POST/

timeout on name lookup is not supported

getaddrinfo(3) failed for POST:80

Couldn't resolve host 'POST'

Closing connection 0 curl: (6) Couldn't resolve host 'POST'

timeout on name lookup is not supported

Trying ::1...

TCP_NODELAY set

Trying 127.0.0.1...

TCP_NODELAY set

Connected to localhost (127.0.0.1) port 5000 (#1)

POST /api/token/changefiscal HTTP/1.1
    Host: localhost:5000
    User-Agent: curl/7.53.1
    Accept: /
    Content-Type: application/json
    Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjI2OTAzNzc0NjYyNzc4RDM1MzE2QUUwQUU1MjIyQUU1REIzM0M0NUEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJKcEEzZEdZbmVOTlRGcTRLNVNJcTVkc3p4Rm8ifQ.eyJuYmYiOjE1MTA1NjcxNzMsImV4cCI6MTUxMDU3MDc3MywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJ0ZXN0YXBpIl0sImNsaWVudF9pZCI6IlNlcnZpY2VBY2NvdW50QWNjZXNzIiwic3ViIjoiMjEyNDg1ODIiLCJhdXRoX3RpbWUiOjE1MTA1NjcxNzMsImlkcCI6ImxvY2FsIiwibmFtZSI6ImxpbGF3IiwiZS1tYWlsIjoibGlsYXdAZWcuZGsiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwidGVzdGFwaSJdLCJhbXIiOlsicGFzc3dvcmQiXX0.Q_oJ-xOIKdTtGoRqJbtNjwLV82cQQLhJUVl2Ey-4riZdp45rPIrmfOw9VdknUOLpm8RYZ0iLFC31gCpn1vKb4zLiTmBuTuzYsKxnAvf-UkCj1L8soH4W2lCvx560bZeS7B67tJ4nK9t36OiMLQY4m-_NRTSRBs5QtsXBd5VQGPsTpxf_MxVbQm6Hj6Ot3FGRIa08gmwD3iEr9vsCU6732InbGzU26wtm-WLWp_A_k66Z29G8ms_U8x6gg-aOlQG9_0v_DEjTXCkKNcgWoL0IvaCC0psiYkdIjQxaOwz-e_fcqXpKEFmuoSqmGd1l-eMl3HimOomdOHwqploWGxnJ4Q
    Content-Length: 7

upload completely sent off: 7 out of 7 bytes

However when i check fiscalId its always 0 i even tried to change fiscalId to a string and its just null.

Body:
When you POST data as JSON object, like -d '{"fiscalId": 21875}',  your action method should expect some simple class with corresponding properties. In your case:

public class Dto
{
   public long fiscalId {get; set;}
}

and

public async Task<ActionResult> ChangeFiscal([FromBody] Dto data)


问:
PHPExcel putting string date into .xls
guys. I have dates at DB as strings "d/m/Y".
When I put this dates into Excel, it shows me normal dates like 03/10/2000, but when I click on the cell, it show me the value  '03/10/2000. So, the value is string, and not date as required for me.

So, I transformed the date from DB to a PHP date object and get sure with var_dump that date is Date object with that code :

```<code>$date = date_create_from_format('d/m/Y', $array[$i-20]['Date']);
              $date->format('m/d/Y');
</code>```

but anyway, the values in generated .xls are with  ' before value.

Why it appears and how can I solve it ?

答:
MS Excel stores dates as a serialized timestamp, the number of days since 1st January 1900 (or 1st January 1904 if using the Mac calendar). To store a value as a date (and not simply as a string), you need to convert your string date to a serialized timestamp, and then set the format mask for the cell.

```<code>$date = date_create_from_format('d/m/Y', $array[$i-20]['Date']);
$excelDate = PHPExcel_Shared_Date::PHPToExcel($date);
</code>```

Set $excelDate as the cell value

```<code>$objPHPExcel->getActiveSheet()->setCellValue('C11', $excelDate );
</code>```

and then apply the format mask to that cell

```<code>$objPHPExcel->getActiveSheet()
    ->getStyle('C11')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
</code>```

The 02types.php example script in the `/Examples` folder demonstrates this

EDIT

You can (and it's more efficient to) apply a style  to a range of cells: just specify the range in the getStyle() call.

```<code>$objPHPExcel->getActiveSheet()
    ->getStyle('C11:C200')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
</code>```

To get details of available format: PHPExcel has a number of pre-defined formats built-in, and those can be found as constants in Classes/PHPExcel/Style/NumberFormat.php. However, you're not limited to that set of formats; and (in the same way that MS Excel lets you define "custom" formats) you can simply pass a string defining the format (e.g. "d-mmm-yyyy") using pretty much any of the rules that can be used for MS Excel number format masks as the format

Title: PHPExcel putting string date into .xls

Body:
guys. I have dates at DB as strings "d/m/Y".
When I put this dates into Excel, it shows me normal dates like 03/10/2000, but when I click on the cell, it show me the value  '03/10/2000. So, the value is string, and not date as required for me.

So, I transformed the date from DB to a PHP date object and get sure with var_dump that date is Date object with that code :

$date = date_create_from_format('d/m/Y', $array[$i-20]['Date']);
              $date->format('m/d/Y');

but anyway, the values in generated .xls are with  ' before value.

Why it appears and how can I solve it ?

Body:
MS Excel stores dates as a serialized timestamp, the number of days since 1st January 1900 (or 1st January 1904 if using the Mac calendar). To store a value as a date (and not simply as a string), you need to convert your string date to a serialized timestamp, and then set the format mask for the cell.

$date = date_create_from_format('d/m/Y', $array[$i-20]['Date']);
$excelDate = PHPExcel_Shared_Date::PHPToExcel($date);

Set $excelDate as the cell value

$objPHPExcel->getActiveSheet()->setCellValue('C11', $excelDate );

and then apply the format mask to that cell

$objPHPExcel->getActiveSheet()
    ->getStyle('C11')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);

The 02types.php example script in the `/Examples` folder demonstrates this

EDIT

You can (and it's more efficient to) apply a style  to a range of cells: just specify the range in the getStyle() call.

$objPHPExcel->getActiveSheet()
    ->getStyle('C11:C200')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);

To get details of available format: PHPExcel has a number of pre-defined formats built-in, and those can be found as constants in Classes/PHPExcel/Style/NumberFormat.php. However, you're not limited to that set of formats; and (in the same way that MS Excel lets you define "custom" formats) you can simply pass a string defining the format (e.g. "d-mmm-yyyy") using pretty much any of the rules that can be used for MS Excel number format masks as the format


问:
DataTable From Session Memory has No Columns
Im trying to retrieve a datatable that I put into a session variable, however when i do it apears that there are no columns...

I have done this before in VB.NET, I'n now using C#, and it worked perfectly, and as far as i can see there is no change in the code other than the obvious syntax changes.

EDIT:

The dt (in part 2) variable has the right data when i look in the data visulization window, but i have noticed that the other properties associated with a datatable are abscent. When i hover over a normal looking datatable with my mouse it looks like the following: " dt ----- {System.Data.DataTable}" but in the class im working on it just looks like "dt ----- {}".  Also, after I return the session variable into the dt I clone it (dtclone = dt.clone(); ) and the clone is empty in the data visulizer.... what on earth!

EDIT 2:

I have now also tried converting the first datatable to a dataset, putting this in the session variable, and recoverting it back to a datatable in the class.

Am starting to wonder if it is a probelm with:

```<code>    dt.Load(sqlReader);
</code>```

The data does appear after this step though in the dataset visualiser, but not after being cloned.

Code below.

All help very welcome!

Thanks in advance

Chris

1) SQL command in a webhandler, the results of which populate the datatable to be put into the session variable.

```<code>    DataTable dt = new DataTable();

    SqlDataReader sqlReader= default(SqlDataReader);
    SqlDataAdapter sqlAdapter = new SqlDataAdapter();

    sqlReader = storedProc.ExecuteReader(CommandBehavior.CloseConnection);

    dt.Load(sqlReader);
    System.Web.HttpContext.Current.Session["ResultsTable"] = dt;
</code>```

2) Part of the code in a class which performs calculations on the table:

```<code>    DataTable dt = (DataTable)HttpContext.Current.Session["ResultsTable"];
</code>```

答:
did you call DataTable dispose after setting Session Var?
Because if you do this, solution is like this:</p>

```<code>System.Web.HttpContext.Current.Session["ResultsTable"] = dt.Copy();
</code>```

Body:
Im trying to retrieve a datatable that I put into a session variable, however when i do it apears that there are no columns...

I have done this before in VB.NET, I'n now using C#, and it worked perfectly, and as far as i can see there is no change in the code other than the obvious syntax changes.

EDIT:

The dt (in part 2) variable has the right data when i look in the data visulization window, but i have noticed that the other properties associated with a datatable are abscent. When i hover over a normal looking datatable with my mouse it looks like the following: " dt ----- {System.Data.DataTable}" but in the class im working on it just looks like "dt ----- {}".  Also, after I return the session variable into the dt I clone it (dtclone = dt.clone(); ) and the clone is empty in the data visulizer.... what on earth!

EDIT 2:

I have now also tried converting the first datatable to a dataset, putting this in the session variable, and recoverting it back to a datatable in the class.

Am starting to wonder if it is a probelm with:

    dt.Load(sqlReader);

The data does appear after this step though in the dataset visualiser, but not after being cloned.

Code below.

All help very welcome!

Thanks in advance

Chris

1) SQL command in a webhandler, the results of which populate the datatable to be put into the session variable.

    DataTable dt = new DataTable();

    SqlDataReader sqlReader= default(SqlDataReader);
    SqlDataAdapter sqlAdapter = new SqlDataAdapter();

    sqlReader = storedProc.ExecuteReader(CommandBehavior.CloseConnection);

    dt.Load(sqlReader);
    System.Web.HttpContext.Current.Session["ResultsTable"] = dt;

2) Part of the code in a class which performs calculations on the table:

    DataTable dt = (DataTable)HttpContext.Current.Session["ResultsTable"];

Body:
did you call DataTable dispose after setting Session Var?
Because if you do this, solution is like this:

System.Web.HttpContext.Current.Session["ResultsTable"] = dt.Copy();


问:
"Days in column" dots explanation
I'm trying to work out the logic behind the Days in Column dots on JIRA boards but can't quite get it right.

It's almost the following:

A grey dot is 1 day

An orange dot is 2 days

A red dot is 3 days

Only show dots for up to 12 days

But those rules don't work for a handful of cases.

Here's my data, taken from a snapshot of one of my boards:

https://docs.google.com/spreadsheets/d/16oGvpQomtJEaS6hmhNfFaDub-4nafmi1jJ32PYMSyvQ/edit?usp=sharing

Does anyone know the logic behind this?

答:
See the "Using Days in column" on the online help:

Blank dot → 1 day

  Grey dot → 2 days

  Yellow dot → 3 days

  1 red dot → 5 days

  2 red dots → 8 days

  3 red dots → 12 days

  4 red dots → 20 or more days

Note that if you move an issue back to a column where it's previously been, the indicator gives you the cumulative number of days the issue has stayed in that column.

The logic has also changed recently according to this post stating "the new dots behaviour is available only in Cloud".

There is an outstanding bug where the weekends are counted as days. This might explain why your data doesn't align.

Title: "Days in column" dots explanation

ContentLicense: CC BY-SA 4.0


问:
Passing the value of a td cell thru onclick Javascript function
I have a single column html table with 20 rows, containing strings (used as tags):

```<code><table id="table_of_tags">
  <tr>
    <td id="c_01" onclick="Pass_Content_Of_Cell(_param)">Tree</td>
    </tr>
  <tr>
    <td id="c_02" onclick="Pass_Content_Of_Cell(_param)">Flower</td>
    </tr>
  ....
  </table>
</code>```

The function Pass_Content_of_Cell() must pass the contents of the cells clicked and concatenate the tags in a single string of tags: "Flower;Tree;" (WHAT it does is not relevant).

The user can click randomly on any tag and in any order he likes.

Question: What exactly should I use for _param ? I tried this.value and this.text and didn't get anything useful.

答:
```<code><script type="text/javascript">
function save(val1)
{
alert("you have saved Employee "+document.getElementById(val1).innerText);
}
function del(val1)
{
    alert("you have deleted Employee "+document.getElementById(val1).innerText);
}
</script>
<table border="1">
  <tr>
    <th>EmployeeID</th>
    <th>Name</th>
    <th>Email</th>
     <th>Phone</th>
      <th>Option</th>
  </tr>
  <tr>
    <td>1590</td>
    <td id="c1">Venkatesh</td>
    <td>venki@w3s.com</td>
    <td>9943243433</td>
    <td><input type="checkbox" name="chk" id="chk"></td>
    <td><input type="button" value="Delete" id="dlt1" name="dlt1" onclick="del('c1');"><input type="button" value="Save" id="sv1" name="sv1" onclick="save('c1');"></td>
  </tr>
 <tr>
    <td>1591</td>
    <td id="c2">amarnath</td>
    <td>amar@w3s.com</td>
    <td>9943113433</td>
    <td><input type="checkbox" name="chk" id="chk"></td>
    <td><input type="button" value="Delete" id="dlt1" name="dlt1" onclick="del('c2');"><input type="button" value="Save" id="sv1" name="sv1" onclick="save('c2');"></td>
  </tr>
<tr>
    <td>1601</td>
    <td id="c3">naveen</td>
    <td>navs@w3s.com</td>
    <td>9943113433</td>
    <td><input type="checkbox" name="chk" id="chk"></td>
    <td><input type="button" value="Delete" id="dlt1" name="dlt1" onclick="del('c3');"><input type="button" value="Save" id="sv1" name="sv1" onclick="save('c3');"></td>
  </tr>
</table>
</code>```

Body:
I have a single column html table with 20 rows, containing strings (used as tags):

    Tree

    Flower

  ....

The function Pass_Content_of_Cell() must pass the contents of the cells clicked and concatenate the tags in a single string of tags: "Flower;Tree;" (WHAT it does is not relevant).

The user can click randomly on any tag and in any order he likes.

Question: What exactly should I use for _param ? I tried this.value and this.text and didn't get anything useful.


问:
check collection existence - Firestore
Example:

I have to make an appointment with the Firestore before proceeding with the event scheduling function.

```<code>Example in the database:
- Companie1 (Document)
--- name
--- phone
--- Schedules (Collection)
-----Event 1
-----Event 2
</code>```

I have a function that performs a new schedule.

According to the example.
I need to check if the Schedules collection exists.

If it does not exist I execute the scheduling function. If I already exist I need to do another procedure.

I already used this pattern and not right.

```<code>db.collection("Companies").document(IDCOMPANIE1)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {

                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });
</code>```

I need help finding a way to do this before proceeding with the registration.

答:
The achieve this just check for nullity:

```<code>DocumentSnapshot document = task.getResult();
if (document != null) {
    Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
    //Do the registration
} else {
    Log.d(TAG, "No such document");
}
</code>```

The result of this Task is a DocumentSnapshot. Whether or not the underlying document actually exists is available via the exists() method.

If the document does exist you can call getData to get at the contents of it.

```<code>db.collection("Companies").document(IDCOMPANIE1)
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (DocumentSnapshot document : task.getResult()) {
                    if(document.exists()) {
                        //Do something
                    } else {
                        //Do something else
                    }

                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });
</code>```

If you want know if the task is empty, please use the following line of code:

```<code>boolean isEmpty = task.getResult().isEmpty();
</code>```

Title: check collection existence - Firestore

Body:
Example:

I have to make an appointment with the Firestore before proceeding with the event scheduling function.

Example in the database:
- Companie1 (Document)
--- name
--- phone
--- Schedules (Collection)
-----Event 1
-----Event 2

I have a function that performs a new schedule.

According to the example.
I need to check if the Schedules collection exists.

If it does not exist I execute the scheduling function. If I already exist I need to do another procedure.

I already used this pattern and not right.

db.collection("Companies").document(IDCOMPANIE1)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {

                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

I need help finding a way to do this before proceeding with the registration.

Body:
The achieve this just check for nullity:

DocumentSnapshot document = task.getResult();
if (document != null) {
    Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
    //Do the registration
} else {
    Log.d(TAG, "No such document");
}

The result of this Task is a DocumentSnapshot. Whether or not the underlying document actually exists is available via the exists() method.

If the document does exist you can call getData to get at the contents of it.

db.collection("Companies").document(IDCOMPANIE1)
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (DocumentSnapshot document : task.getResult()) {
                    if(document.exists()) {
                        //Do something
                    } else {
                        //Do something else
                    }

                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

If you want know if the task is empty, please use the following line of code:

boolean isEmpty = task.getResult().isEmpty();