问:
Mixing parentheses and square brackets in array initialization
The following code snippet assigns some values by mixing parentheses and square brackets without any error, however most of the other combinations (e.g. parentheses inside square brackets) don't work at all.

```<code>var myItems = [];
myItems[5] = ("A1", "B1", ["C1","C2","C3"]);
</code>```

When I print the values, they are exactly the same in two different browsers.

```<code>myItems[5]: C1,C2,C3
myItems[5][0]: C1
myItems[5][1]: C2
myItems[5][2]: C3
myItems[5][2][0]: C
myItems[5][2][1]: 3
myItems[5][2][2]: undefined
</code>```

It seems that only the part inside square brackets is considered. Is this outcome defined by the JavaScript standard (ECMA-262)? Or is it just what the interpreter/engine (Chrome and Firefox in my case) did in the face of an illegal use?

var myItems = [];

//myItems[5] = ["A1", "B1", ["C1","C2","C3"]];
myItems[5] = ("A1", "B1", ["C1","C2","C3"]);

document.getElementById("demo").innerHTML =
"myItems[5]:       " + myItems[5]       + "
" +
"myItems[5][0]:    " + myItems[5][0]    + "
" +
"myItems[5][1]:    " + myItems[5][1]    + "
" +
"myItems[5][2]:    " + myItems[5][2]    + "
" +
"myItems[5][2][0]: " + myItems[5][2][0] + "
" +
"myItems[5][2][1]: " + myItems[5][2][1] + "
" +
"myItems[5][2][2]: " + myItems[5][2][2] + "
" +
"";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo"></p></code>```

EDIT: I know the correct use of brackets (my fiddle already had it), but I'm asking if the outcome is deterministic at such a wrong use. Since the interpreters I've tried don't produce any error and give the same results, I want to know if these results are ensured by the standard and/or all the other interpreters will do the same.

答:
The comma operator , "evaluates each of its operands (from left to right) and returns the value of the last operand." (You can take that quote from Mozilla as gospel, or try to decipher what ECMA has to say on the matter.)

The grouping operator ( ) "controls the precedence of evaluation in expressions," according to Mozilla. (Obligatory link to ECMA.)

In this instance, the grouping operator does essentially nothing, since there is only one expression being grouped. So this is a simple comma-separated list of values, the last one of which is an array. This is what gets assigned.

The comma operator is often seen when assigning variables in bulk, e.g. var foo = 1, bar = 2, baz = 3; The spec states that even though only the last item is returned, each item must be evaluated "because it may have observable
side‑effects." In this most common of use cases, the variables each have values assigned to them.

Body:
The following code snippet assigns some values by mixing parentheses and square brackets without any error, however most of the other combinations (e.g. parentheses inside square brackets) don't work at all.

var myItems = [];
myItems[5] = ("A1", "B1", ["C1","C2","C3"]);

When I print the values, they are exactly the same in two different browsers.

myItems[5]: C1,C2,C3
myItems[5][0]: C1
myItems[5][1]: C2
myItems[5][2]: C3
myItems[5][2][0]: C
myItems[5][2][1]: 3
myItems[5][2][2]: undefined

It seems that only the part inside square brackets is considered. Is this outcome defined by the JavaScript standard (ECMA-262)? Or is it just what the interpreter/engine (Chrome and Firefox in my case) did in the face of an illegal use?

var myItems = [];

//myItems[5] = ["A1", "B1", ["C1","C2","C3"]];
myItems[5] = ("A1", "B1", ["C1","C2","C3"]);

document.getElementById("demo").innerHTML =
"myItems[5]:       " + myItems[5]       + "
" +
"myItems[5][0]:    " + myItems[5][0]    + "
" +
"myItems[5][1]:    " + myItems[5][1]    + "
" +
"myItems[5][2]:    " + myItems[5][2]    + "
" +
"myItems[5][2][0]: " + myItems[5][2][0] + "
" +
"myItems[5][2][1]: " + myItems[5][2][1] + "
" +
"myItems[5][2][2]: " + myItems[5][2][2] + "
" +
"";

EDIT: I know the correct use of brackets (my fiddle already had it), but I'm asking if the outcome is deterministic at such a wrong use. Since the interpreters I've tried don't produce any error and give the same results, I want to know if these results are ensured by the standard and/or all the other interpreters will do the same.


来源: stackexchange

问:
Typescript "Compile on Save" is not working on VS 2015 Update 3
The "Compile on save" feature isn't working for me in my Visual Studio 2015 with update 3.I am start working on Angular2 project with MVC5.Thats why I need to re compile or when change in .ts file is detect and show updated output on my browser.

my tsconfig.json file have below code:

```<code>{
    "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true
},
"compileOnSave": true,
    "exclude": [
    "node_modules/*",
    "**/*-aot.ts"
 ]
}
</code>```

I have Typescript 2.4.1.0 tools for Visual Studio 2015 installed. Image Ref:

or in my PC I have Typescript 2.4.1 is installed.  Image Ref:

I also tried to add entry in path variable. As Ref in this
link and Image:

I checked my typescript version is updated or out dated but I found this:

This is my .csproc file code:

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <TypeScriptCompileOnSaveEnabled>true</TypeScriptCompileOnSaveEnabled>
    <TypeScriptRemoveComments>true</TypeScriptRemoveComments>
    <TypeScriptSourceMap>false</TypeScriptSourceMap>
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
    <TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
    <TypeScriptModuleKind>CommonJS</TypeScriptModuleKind>
    <TypeScriptRemoveComments>False</TypeScriptRemoveComments>
</PropertyGroup>
</code>```

I also check Image Ref:

Last one which I try and got error is on the below link from which I follow
Mikaël Mayer answer:

Here is my error which I got while building:

Severity   Code    Description Project File    Line    Suppression State
  Error       The specified task executable "cmd.exe" could not be run. The working directory "F:\Projects\ecommerce\ecommerce\js" does not exist.    ecommerce   F:\Projects\ecommerce\ecommerce\ecommerce.csproj    352

Image:

Below is the other references on which I tried but nothing is working for me:

Ref#1

Ref#2

Ref#3

Ref#4

Ref#5

Ref#6

答:
I've experienced a similar problem in the past and I resolved it by changing the project property:

```<code><TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
</code>```

This can be found on the Typescript Build tab of the project properties:

Hope this gets you going.  Good luck!

ContentLicense: CC BY-SA 3.0

Body:
The "Compile on save" feature isn't working for me in my Visual Studio 2015 with update 3.I am start working on Angular2 project with MVC5.Thats why I need to re compile or when change in .ts file is detect and show updated output on my browser.

my tsconfig.json file have below code:

{
    "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true
},
"compileOnSave": true,
    "exclude": [
    "node_modules/*",
    "**/*-aot.ts"
 ]
}

I have Typescript 2.4.1.0 tools for Visual Studio 2015 installed. Image Ref:

or in my PC I have Typescript 2.4.1 is installed.  Image Ref:

I also tried to add entry in path variable. As Ref in this
link and Image:

I checked my typescript version is updated or out dated but I found this:

This is my .csproc file code:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <TypeScriptCompileOnSaveEnabled>true</TypeScriptCompileOnSaveEnabled>
    <TypeScriptRemoveComments>true</TypeScriptRemoveComments>
    <TypeScriptSourceMap>false</TypeScriptSourceMap>
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
    <TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
    <TypeScriptModuleKind>CommonJS</TypeScriptModuleKind>
    <TypeScriptRemoveComments>False</TypeScriptRemoveComments>
</PropertyGroup>

I also check Image Ref:

Last one which I try and got error is on the below link from which I follow
Mikaël Mayer answer:

Here is my error which I got while building:

Severity   Code    Description Project File    Line    Suppression State
  Error       The specified task executable "cmd.exe" could not be run. The working directory "F:\Projects\ecommerce\ecommerce\js" does not exist.    ecommerce   F:\Projects\ecommerce\ecommerce\ecommerce.csproj    352

Image:

Below is the other references on which I tried but nothing is working for me:

Ref#1

Ref#2

Ref#3

Ref#4

Ref#5

Ref#6

Body:
I've experienced a similar problem in the past and I resolved it by changing the project property:

<TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>

This can be found on the Typescript Build tab of the project properties:

Hope this gets you going.  Good luck!


问:
FirebaseCrash is not working for InstantApps
I m implementing and InstantApp in which I added FirebaseCrash.

I follow all the steps to set it up and when I run the app using the build configuration for the installable version it works like a charm but when I try to run the build configuration for the InstantApp FirebaseCrash is crashing the app.

The app crash in this line where I am emulating a crash just to check if it works:

```<code>FirebaseCrash.logcat(Log.ERROR, "Firebase", "I am broken!!");
</code>```

This is the crash when I run it for the InstantApp:

```<code>Process: uk.co.alpha.test.app, PID: 3516
java.lang.RuntimeException: Unable to start activity
ComponentInfo{[package.class]}: java.lang.IllegalStateException:
Default FirebaseApp is not initialized in this process [package] Make
sure to call FirebaseApp.initializeApp(Context) first.
</code>```

I tried adding FirebaseApp.initializeApp(Context) in the onCreate of the class where it is crashing and I also try adding it in the class that extends from Application but the same crash appears.

I check stackoverflow and the official Firebase documentation and I didnt find anything specific for InstantApps

It works for the installable version but I added my gradle files just in case it can help to solve it:

./build.gradle

```<code>buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://maven.google.com'}
        //Dexcount Gradle Plugin
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
        //Dexcount Gradle Plugin
        classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.7.0-SNAPSHOT'
    }
}

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

task clean(type: Delete) {
    delete rootProject.buildDir
}

ext {
    buildTools = '25.0.2'
    compileSdk = 25
    minSdk = 23
    versionCode = 11
    versionName = '4.0'
    supportLib = '25.3.1'
    playServices = "11.0.0"
}
</code>```

features/build.gradle

```<code>buildscript {
    repositories {
        jcenter()
    }
}
apply plugin: 'com.android.feature'

repositories {
    jcenter()
    mavenCentral()
}

android {
    compileSdkVersion rootProject.compileSdk
    buildToolsVersion rootProject.buildTools

    baseFeature true
    defaultConfig {
        minSdkVersion rootProject.minSdk
        targetSdkVersion rootProject.compileSdk
        versionCode rootProject.versionCode
        versionName rootProject.versionName
    }

    compileOptions {
    targetCompatibility JavaVersion.VERSION_1_8
    sourceCompatibility JavaVersion.VERSION_1_8
}

signingConfigs {
    release {
        storeFile file("instantApp_keystore")
        storePassword "..."
        keyAlias "..."
        keyPassword "..."
    }
}

buildTypes {
    debug {
        buildConfigField "String", "PARSE_BACKUP", "\"" + PARSE_BACKUP + "\""
        buildConfigField "String", "PARSE", "\"" + PARSE_LIVE + "\""
        buildConfigField "String", "PARSE_APP_ID", "\"" + parseAppId_LIVE + "\""
        buildConfigField "String", "PARSE_CLIENT_KEY", "\"" + parseClientKey_LIVE + "\""
    }
    release {
        signingConfig signingConfigs.release
        buildConfigField "String", "PARSE_BACKUP", "\"" + PARSE_BACKUP + "\""
        buildConfigField "String", "PARSE", "\"" + PARSE_LIVE + "\""
        buildConfigField "String", "PARSE_APP_ID", "\"" + parseAppId_LIVE + "\""
        buildConfigField "String", "PARSE_CLIENT_KEY", "\"" + parseClientKey_LIVE + "\""
    }
}

packagingOptions {
    exclude 'META-INF/rxjava.properties'
}
}

dependencies {
    compile "com.android.support:appcompat-v7:${rootProject.supportLib}"
    compile "com.android.support:design:${rootProject.supportLib}"
    compile "com.google.android.gms:play-services-analytics:${rootProject.playServices}"

    compile 'com.parse:parse-android:1.14.1'
    compile 'com.squareup:otto:1.3.8'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile ('cn.trinea.android.view.autoscrollviewpager:android-auto-scroll-view-pager:1.1.2'){
        exclude module: 'support-v4'
    }
    compile 'me.relex:circleindicator:1.2.2@aar'
    compile 'com.squareup.picasso:picasso:2.5.2'

    compile "com.google.firebase:firebase-crash:${rootProject.playServices}"
}
apply plugin: 'com.google.gms.google-services'
</code>```

Thanks in advance!!!! ;)

答:
Unfortunately Firebase Crash Reporting does not work with Instant Apps nor are there plans to specifically update it to work with Instant Apps. This is because Fabric is now part of the Firebase team, Fabric Crashlytics is where future effort will be spent. The Firebase docs mention this as well.

Crashlytics already works with Instant Apps, see this post for information on setting it up:

How do I integrate Crashlytics with Android Instant Apps?

Body:
I m implementing and InstantApp in which I added FirebaseCrash.

I follow all the steps to set it up and when I run the app using the build configuration for the installable version it works like a charm but when I try to run the build configuration for the InstantApp FirebaseCrash is crashing the app.

The app crash in this line where I am emulating a crash just to check if it works:

FirebaseCrash.logcat(Log.ERROR, "Firebase", "I am broken!!");

This is the crash when I run it for the InstantApp:

Process: uk.co.alpha.test.app, PID: 3516
java.lang.RuntimeException: Unable to start activity
ComponentInfo{[package.class]}: java.lang.IllegalStateException:
Default FirebaseApp is not initialized in this process [package] Make
sure to call FirebaseApp.initializeApp(Context) first.

I tried adding FirebaseApp.initializeApp(Context) in the onCreate of the class where it is crashing and I also try adding it in the class that extends from Application but the same crash appears.

I check stackoverflow and the official Firebase documentation and I didnt find anything specific for InstantApps

It works for the installable version but I added my gradle files just in case it can help to solve it:

./build.gradle

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://maven.google.com'}
        //Dexcount Gradle Plugin
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
        //Dexcount Gradle Plugin
        classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.7.0-SNAPSHOT'
    }
}

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

task clean(type: Delete) {
    delete rootProject.buildDir
}

ext {
    buildTools = '25.0.2'
    compileSdk = 25
    minSdk = 23
    versionCode = 11
    versionName = '4.0'
    supportLib = '25.3.1'
    playServices = "11.0.0"
}

features/build.gradle

buildscript {
    repositories {
        jcenter()
    }
}
apply plugin: 'com.android.feature'

repositories {
    jcenter()
    mavenCentral()
}

android {
    compileSdkVersion rootProject.compileSdk
    buildToolsVersion rootProject.buildTools

    baseFeature true
    defaultConfig {
        minSdkVersion rootProject.minSdk
        targetSdkVersion rootProject.compileSdk
        versionCode rootProject.versionCode
        versionName rootProject.versionName
    }

    compileOptions {
    targetCompatibility JavaVersion.VERSION_1_8
    sourceCompatibility JavaVersion.VERSION_1_8
}

signingConfigs {
    release {
        storeFile file("instantApp_keystore")
        storePassword "..."
        keyAlias "..."
        keyPassword "..."
    }
}

buildTypes {
    debug {
        buildConfigField "String", "PARSE_BACKUP", "\"" + PARSE_BACKUP + "\""
        buildConfigField "String", "PARSE", "\"" + PARSE_LIVE + "\""
        buildConfigField "String", "PARSE_APP_ID", "\"" + parseAppId_LIVE + "\""
        buildConfigField "String", "PARSE_CLIENT_KEY", "\"" + parseClientKey_LIVE + "\""
    }
    release {
        signingConfig signingConfigs.release
        buildConfigField "String", "PARSE_BACKUP", "\"" + PARSE_BACKUP + "\""
        buildConfigField "String", "PARSE", "\"" + PARSE_LIVE + "\""
        buildConfigField "String", "PARSE_APP_ID", "\"" + parseAppId_LIVE + "\""
        buildConfigField "String", "PARSE_CLIENT_KEY", "\"" + parseClientKey_LIVE + "\""
    }
}

packagingOptions {
    exclude 'META-INF/rxjava.properties'
}
}

dependencies {
    compile "com.android.support:appcompat-v7:${rootProject.supportLib}"
    compile "com.android.support:design:${rootProject.supportLib}"
    compile "com.google.android.gms:play-services-analytics:${rootProject.playServices}"

    compile 'com.parse:parse-android:1.14.1'
    compile 'com.squareup:otto:1.3.8'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile ('cn.trinea.android.view.autoscrollviewpager:android-auto-scroll-view-pager:1.1.2'){
        exclude module: 'support-v4'
    }
    compile 'me.relex:circleindicator:1.2.2@aar'
    compile 'com.squareup.picasso:picasso:2.5.2'

    compile "com.google.firebase:firebase-crash:${rootProject.playServices}"
}
apply plugin: 'com.google.gms.google-services'

Thanks in advance!!!! ;)


问:
Add a label to a panel or groupbox on button click
Is there a way to add a label or content to a panel/groupbox once a button has been clicked ?

So for instance, lets say I wrote some content in the above textbox and I hit Post button. Is there a way to add this content in the below panel/groupbox ? And if I can't add to a panel/groupbox, which tool should I use ?

答:
How to Display content from a TextBox when Clicked.

Please check on your MSVC under Solution Properties for all the Buttons, Text and Panels properties. Example; Button1, TextBox1 etc. Then make functions calls and assignments by these reference.

protected void Button1_Click(object sender, EventArgs e)
{

```<code> MessageBox.Show(" "+ TextBox1.Text);
</code>```

}

This will display your content to a Pop up window. You can also try TextBox1.Content instead of TextBox1.Text.

NB: This code should be placed on your POST button.

Body:
How to Display content from a TextBox when Clicked.

Please check on your MSVC under Solution Properties for all the Buttons, Text and Panels properties. Example; Button1, TextBox1 etc. Then make functions calls and assignments by these reference.

protected void Button1_Click(object sender, EventArgs e)
{

 MessageBox.Show(" "+ TextBox1.Text);

}

This will display your content to a Pop up window. You can also try TextBox1.Content instead of TextBox1.Text.

NB: This code should be placed on your POST button.


问:
Javascript onClick function SyntaxError: expected expression, got '}'
I am trying to pass a parameter from a onClick event using javascript but got a undefined value error, after reading from the questions here at SO and as suggested you need to add and escape the parameter by using \'\ but when applying the solution i am getting the SyntaxError: expected expression, got '}' on execution, Any suggestions would be great!

Here is my actual code.

```<code>rootRef.on("child_added", snap => {

   var valkey = snap.key;
   var name = snap.child("Name").val();
   var email = snap.child("Email").val();

   $('#table_body').append('<tr><td>'+ name +'</td><td>'+ email +'</td><td><a onClick="deleteMe(' + "'" + valkey + "'" + ')">delete</a></td></tr>');

});

function deleteMe(valkey){
    var cKey = valkey;
    console.log(cKey);

}
</code>```

Here is a code snippet similar to my problem.

$(document).ready(function(){

var valkey = "hello!";

$('#table_body').append("delete");

function deleteMe(valkey){

    var cKey = valkey;

    console.log(cKey);

}

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="table_body">

</div></code>```

答:
Try this:</p>

```<code>$('#table_body').append('<tr><td>'+ name +'</td><td>'+ email +'</td><td><a onClick="deleteMe(' + "'" + valkey + "'" + ')">delete</a></td></tr>');
</code>```

Body:
I am trying to pass a parameter from a onClick event using javascript but got a undefined value error, after reading from the questions here at SO and as suggested you need to add and escape the parameter by using \'\ but when applying the solution i am getting the SyntaxError: expected expression, got '}' on execution, Any suggestions would be great!

Here is my actual code.

rootRef.on("child_added", snap => {

   var valkey = snap.key;
   var name = snap.child("Name").val();
   var email = snap.child("Email").val();

   $('#table_body').append('
'+ name +'	'+ email +'	delete
');

});

function deleteMe(valkey){
    var cKey = valkey;
    console.log(cKey);

}

Here is a code snippet similar to my problem.

$(document).ready(function(){

var valkey = "hello!";

$('#table_body').append("delete");

function deleteMe(valkey){

    var cKey = valkey;

    console.log(cKey);

}

});

Body:
Try this:

$('#table_body').append('<tr><td>'+ name +'</td><td>'+ email +'</td><td><a onClick="deleteMe(' + "'" + valkey + "'" + ')">delete</a></td></tr>');


问:
Facebook webhook making multiple calls for the same message?
I made and echo bot on AWS with Python and serverless.

I keep getting the same request again and again.
I read the faq where it says u have to deliver a status code 200 else it will keep retrying the webhook.

I'm not sure How I do this.

I have noticed that the sequence number is always the same for the calls so I assume the reply I sent was not acknowledged.
my code is here

```<code>import os
import json
import requests
import random
from datetime import datetime
######################
# helper functions
######################
##recursively look/return for an item in dict given key
def find_item(obj, key):
    item = None
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = find_item(v, key)
            if item is not None:
                return item

##recursivley check for items in a dict given key
def keys_exist(obj, keys):
    for key in keys:
        if find_item(obj, key) is None:
            return(False)
    return(True)

##send txt via messenger to id
def send_message(send_id, msg_txt):
    print("Send message called")
    print (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
    headers = {"statusCode": "200","Content-Type": "application/json"}
    data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                       "message": {"text": msg_txt}})

    r = requests.post("https://graph.facebook.com/v2.9/me/messages", params=params, headers=headers, data=data)
    print (r.text)

    if r.status_code != 200:
        print(r.status_code)
        print(r.text)

#-----------------------------------------------------------

def hello(event, context):
    #debug
    event=json.loads(json.dumps(event))
    print("event:" )
    print(event)
    # print("context")
    # print(context)

    #handle webhook challenge
    try:

        if keys_exist(event, ["queryStringParameters","hub.verify_token","hub.challenge"]):
            print("subscribe to webhook invoked")
            v_token   = str(find_item(event, 'hub.verify_token'))
            challenge = find_item(event, 'hub.challenge')
            if ("strongtoken" == v_token):
                response = {
                    "statusCode": 200,
                    "body": str(challenge)
                }
                print(challenge)
                return response

        #handle messaging events
        if keys_exist(event, ['body']):
            event_entry=json.loads(event['body'])
            if ((len(event_entry['entry'])>0) & (keys_exist(event_entry['entry'][0],['messaging'])) ):
                messaging_event = event_entry['entry'][0]['messaging'][0]
                if (keys_exist(messaging_event,['message'])):
                    msg_txt   = messaging_event['message']['text']
                    sender_id = messaging_event['sender']['id']
                    print(sender_id)
                    first_word = msg_txt.split(" ")[0]
                    send_message(sender_id, msg_txt)
                else:
                    print("Did not send message")
                    pass
            else:
                print("Did not send message")
                pass

        else:
            pass
    except:
        pass
</code>```

I have given the status code 200 in soo many places and I'm not sure y I still keep getting the same problem.

答: As an alternative, you can use chatbotproxy.com which always return 200 in 1ms and pass the exact same request to your endpoint. Since immediate response is very important for Facebook Messenger platform, 1 millisecond time is a very promising feature. If you need help to try, let me know.</p>

Body:
I made and echo bot on AWS with Python and serverless.

I keep getting the same request again and again.
I read the faq where it says u have to deliver a status code 200 else it will keep retrying the webhook.

I'm not sure How I do this.

I have noticed that the sequence number is always the same for the calls so I assume the reply I sent was not acknowledged.
my code is here

import os
import json
import requests
import random
from datetime import datetime
######################
# helper functions
######################
##recursively look/return for an item in dict given key
def find_item(obj, key):
    item = None
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = find_item(v, key)
            if item is not None:
                return item

##recursivley check for items in a dict given key
def keys_exist(obj, keys):
    for key in keys:
        if find_item(obj, key) is None:
            return(False)
    return(True)

##send txt via messenger to id
def send_message(send_id, msg_txt):
    print("Send message called")
    print (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
    headers = {"statusCode": "200","Content-Type": "application/json"}
    data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                       "message": {"text": msg_txt}})

    r = requests.post("https://graph.facebook.com/v2.9/me/messages", params=params, headers=headers, data=data)
    print (r.text)

    if r.status_code != 200:
        print(r.status_code)
        print(r.text)

#-----------------------------------------------------------

def hello(event, context):
    #debug
    event=json.loads(json.dumps(event))
    print("event:" )
    print(event)
    # print("context")
    # print(context)

    #handle webhook challenge
    try:

        if keys_exist(event, ["queryStringParameters","hub.verify_token","hub.challenge"]):
            print("subscribe to webhook invoked")
            v_token   = str(find_item(event, 'hub.verify_token'))
            challenge = find_item(event, 'hub.challenge')
            if ("strongtoken" == v_token):
                response = {
                    "statusCode": 200,
                    "body": str(challenge)
                }
                print(challenge)
                return response

        #handle messaging events
        if keys_exist(event, ['body']):
            event_entry=json.loads(event['body'])
            if ((len(event_entry['entry'])>0) & (keys_exist(event_entry['entry'][0],['messaging'])) ):
                messaging_event = event_entry['entry'][0]['messaging'][0]
                if (keys_exist(messaging_event,['message'])):
                    msg_txt   = messaging_event['message']['text']
                    sender_id = messaging_event['sender']['id']
                    print(sender_id)
                    first_word = msg_txt.split(" ")[0]
                    send_message(sender_id, msg_txt)
                else:
                    print("Did not send message")
                    pass
            else:
                print("Did not send message")
                pass

        else:
            pass
    except:
        pass

I have given the status code 200 in soo many places and I'm not sure y I still keep getting the same problem.


问:
Docker Compose gulp is not found in $PATH
I have just started learning docker-compose and I am using a nodejs image. I want to install gulp to create some tasks and have one of them working on the background.

When I run: docker-compose run --rm -d server gulp watch-less

I get this error: ERROR: oci runtime error: container_linux.go:247: starting container process caused "exec: \"gulp\": executable file not found in $PATH"

Here are my file:

```<code># Dockerfile
FROM node:6.10.2

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app
RUN npm install --quiet

COPY . /usr/src/app

CMD ["npm", "start"]
</code>```

```<code># docker-compose.yml
version: "2"
services:
  server:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - ./:/usr/src/app
</code>```

I also have a .dockerignore to ignore the node_modules folder and the npm-debug.log

EDIT:

When I run docker-compose run --rm server npm install package-name I don't have any problem and the package is installed.

答:
I find that just referencing gulp via

./node_modules/.bin/gulp

instead of directly works fine. ./node_modules/.bin isn't in the path by default. Another option would be to add that dir to the PATH.

Body:
I have just started learning docker-compose and I am using a nodejs image. I want to install gulp to create some tasks and have one of them working on the background.

When I run: docker-compose run --rm -d server gulp watch-less

I get this error: ERROR: oci runtime error: container_linux.go:247: starting container process caused "exec: \"gulp\": executable file not found in $PATH"

Here are my file:

# Dockerfile
FROM node:6.10.2

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app
RUN npm install --quiet

COPY . /usr/src/app

CMD ["npm", "start"]

# docker-compose.yml
version: "2"
services:
  server:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - ./:/usr/src/app

I also have a .dockerignore to ignore the node_modules folder and the npm-debug.log

EDIT:

When I run docker-compose run --rm server npm install package-name I don't have any problem and the package is installed.


问:
Where clause on linq query against dictionary?
I have fixed the problem of it not listing the data which was related to a wrong field on the spawn dictionary but still i would like to question if the way I am approaching it is ok ?

I have a few checkboxs that if true should add check the item status and include it on the list.

So not really knowing what to do, this is what I came up with:

```<code>        HashSet<int> status = new HashSet<int>();
        if (OptionsForm.filterPlayer.Checked) status.Add(0);
        if (OptionsForm.filterEnemy.Checked) status.Add(1);
        if (OptionsForm.filterSummon.Checked) status.Add(2);
        if (OptionsForm.filterNPC.Checked) status.Add(3);
        if (OptionsForm.filterObject.Checked) status.Add(4);
        if (OptionsForm.filterMonster.Checked) status.Add(5);
        if (OptionsForm.filterGatherable.Checked) status.Add(6);
        if (OptionsForm.filterUnk.Checked) status.Add(7);

        var query = from SpawnList item in spawnEntities.Values
                    where status.Contains(item.Status)
                    orderby item.Name ascending
                    select item;
</code>```

But currently it is not returning me any errors or items that should have been returned.

spawnEntities is a dictionary with uint, SpawnList.

SpawnList is a simple class:

```<code>public class SpawnList
{
    public string Name { get; set; }
    public int Status { get; set; }
    // some more data not needed for the question
}
</code>```

答:
My comment to the previous answered byt further explained. You can use the Flags attribute instead, which will make it easier to check your status.

```<code>[Flags]
enum YourEnum
{
     none,
     Val1,
     Val2,
     Val3,
     Val4,
}
</code>```

Set your status to:

```<code>public YourEnum Status {get; set;}
</code>```

Create your combined status like:

```<code>YourStatus status = YourEnum.None;
if(OptionsForm.filterPlayer.Checked) status = status | YourEnum.Val1;
if(OptionsForm.filterEnemy.Checked) status = status | YourEnum.Val2;
<etc>
</code>```

The you'll get a linq like:

```<code>    var query = from SpawnList item in spawnEntities.Values
                where status & itemStatus != YourEnum.None
                orderby item.Name ascending
                select item;
</code>```

Read more about the flags attribute here: http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx

ContentLicense: CC BY-SA 2.5

Body:
I have fixed the problem of it not listing the data which was related to a wrong field on the spawn dictionary but still i would like to question if the way I am approaching it is ok ?

I have a few checkboxs that if true should add check the item status and include it on the list.

So not really knowing what to do, this is what I came up with:

        HashSet<int> status = new HashSet<int>();
        if (OptionsForm.filterPlayer.Checked) status.Add(0);
        if (OptionsForm.filterEnemy.Checked) status.Add(1);
        if (OptionsForm.filterSummon.Checked) status.Add(2);
        if (OptionsForm.filterNPC.Checked) status.Add(3);
        if (OptionsForm.filterObject.Checked) status.Add(4);
        if (OptionsForm.filterMonster.Checked) status.Add(5);
        if (OptionsForm.filterGatherable.Checked) status.Add(6);
        if (OptionsForm.filterUnk.Checked) status.Add(7);

        var query = from SpawnList item in spawnEntities.Values
                    where status.Contains(item.Status)
                    orderby item.Name ascending
                    select item;

But currently it is not returning me any errors or items that should have been returned.

spawnEntities is a dictionary with uint, SpawnList.

SpawnList is a simple class:

public class SpawnList
{
    public string Name { get; set; }
    public int Status { get; set; }
    // some more data not needed for the question
}

Body:
My comment to the previous answered byt further explained. You can use the Flags attribute instead, which will make it easier to check your status.

[Flags]
enum YourEnum
{
     none,
     Val1,
     Val2,
     Val3,
     Val4,
}

Set your status to:

public YourEnum Status {get; set;}

Create your combined status like:

YourStatus status = YourEnum.None;
if(OptionsForm.filterPlayer.Checked) status = status | YourEnum.Val1;
if(OptionsForm.filterEnemy.Checked) status = status | YourEnum.Val2;
<etc>

The you'll get a linq like:

    var query = from SpawnList item in spawnEntities.Values
                where status & itemStatus != YourEnum.None
                orderby item.Name ascending
                select item;

Read more about the flags attribute here: http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx


问:
Convert eBay Link Generator results into bitly.com link
I managed a small PHP script that takes the eBay product searched and converts it into promote eBay link.

It goes like this:

user searches for example: ocz vertex

clicks on "Submit" and gets the results in following format

http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=ocz
  vertex&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg

(Can't fix that space in the link generated between ocz and vertex words)

Now, the result is nice, but I want to shorten it via bitly.com account using their API.

Basicly I want it to generate and convert the full eBay link results into small bitly.com link (http://ebay.to/2scU91k for example) and to see that link on my bitly account.

The process would go like this:

User search for term like ocz vertex

click on "Submit"

get the ebay.to short link (while the real process is in background,
converts to rover.ebay.com address and then to ebay.to using my
bitly.com credentials)

I found that and that and especially that, but didn't understand how do I implement the results as a new bitly convert.

Here's the PHP code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="css/screen.css">
<style type="text/css">
    body{
        margin:0px;
        font-size:0.7em;
        font-family:trebuchet ms;
                            color:#222;
    }
    #mainContainer{
        width:840px;
        margin:5px;
    }
    table,tr,td{
        vertical-align:top;
    }
    .textInput{
        width:300px;
    }
    html{
        margin:0px;
    }
    .formButton{
        width:75px;
    }
    textarea,input,select{
        font-family:helvetica;
    }
    i{
        font-size:0.9em;
    }

    </style>
<script language="Javascript">
<!--
var copytoclip=1
function HighlightAll(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
if (document.all&&copytoclip==1){
therange=tempval.createTextRange()
therange.execCommand("Copy")
window.status="Contents highlighted and copied to clipboard!"
setTimeout("window.status=''",1800)
}
}
//-->
</script>

</head>
<table width="80%" height="100px" align="center" style="margin:0 auto"><tr><td align="center">
<h2>Link Generator Online</h2>
</td><tr></table>
<table width="80%" align="center" style="margin:0 auto"><tr><td align="center">
       </div>

 </td><td valign="top">
 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<br>
URL<br>
<input type=text style="font-size: 13px; font-family: tahoma,arial; font-weight: bold; color: #000000; BORDER: #555 1px solid ; BACKGROUND-COLOR: #FFF" input name="url"  size="20">
<br>

<br>
<input type="SUBMIT" name="submit" VALUE="Submit">
</form>
</td></tr></table>
<?php
if(isset($_POST['submit'])){
$url = $_POST['url'];
$name=array($url);
foreach ($name as $name)
{
if (ereg("^\.",$url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
 Die();
}
if (ereg("\<", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
 Die();
}
if (ereg("\[", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
 Die();
}
if (ereg("\'", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
 Die();
}
if (ereg("\#", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
 Die();
}
if (ereg("\`", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
 Die();
}

if (!strlen($url)) {
echo "<br><center><font color=\"red\">Empty Field.</center>";

Die();
}
if (strlen($url) > 100) {
echo "<br><center><font color=\"red\">The field cannot contain more than 150 characters.</center>";

 Die();
}
}
?>
<br>
<center>
<form name="vini">
<a class="highlighttext" href="javascript:HighlightAll('vini.select1')">Select All</a><br>
<textarea name="select1" rows=3 cols=75 style="font-family:tahoma;color:#555;border:1px dashed #ccc">
http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=<?php echo $url ?>&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg
</textarea>
<br>
</form>

<?php
}
?>
</body>
</html>
</code>```

See on live: Ebay link Generator

答:
I built a small solution that works without external libraries. It essentially boils down to this:

Acquire an API key from the "Register an application" dashboard or an oauth token from the oauth API

Make the request to the /v3/shorten API endpoint with your token and URL

First step: Get the token

You only need to do this once. Bitly's documentation lists a few examples how you can do it using curl, I think that is the easiest way. You could also do it with PHP. Simply make this POST request (taken from here):

```<code>curl -u "username:password" -X POST "https://api-ssl.bitly.com/oauth/access_token"
</code>```

The result is something like this:

```<code>e663e30818201d28dd07803e57333bed4f15803a
</code>```

That is your token.

Second step: Make the request

Insert the token and url-encoded URL into the HTTP request to the /v3/shorten endpoint:

```<code><?php
$ebay_url = "http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=ocz%20vertex&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg"

$token = "e663e30818201d28dd07803e57333bed4f15803a"; // change this
$endpoint = "https://api-ssl.bitly.com/v3/shorten?access_token=".$token."&longUrl=".urlencode($ebay_url)."";
$result = file_get_contents($endpoint);
$json = json_decode($result, true);
$short_url = $json["data"]["url"];
echo $short_url;
?>
</code>```

The result of the API call is JSON and needs to be decoded. An example is in the documentation. This code example does not take into consideration API timeouts or other errors that might occur (such as token expiry, which is currently not an issue).

The complete code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="css/screen.css">
<style type="text/css">
    body{
        margin:0px;
        font-size:0.7em;
        font-family:trebuchet ms;
                            color:#222;
    }
    #mainContainer{
        width:840px;
        margin:5px;
    }
    table,tr,td{
        vertical-align:top;
    }
    .textInput{
        width:300px;
    }
    html{
        margin:0px;
    }
    .formButton{
        width:75px;
    }
    textarea,input,select{
        font-family:helvetica;
    }
    i{
        font-size:0.9em;
    }
    </style>
<script language="Javascript">
<!--
var copytoclip=1
function HighlightAll(theField) {
    var tempval=eval("document."+theField)
    tempval.focus()
    tempval.select()
    if (document.all&&copytoclip==1){
        therange=tempval.createTextRange()
        therange.execCommand("Copy")
        window.status="Contents highlighted and copied to clipboard!"
        setTimeout("window.status=''",1800)
    }
}
//-->
</script>

</head>
<table width="80%" height="100px" align="center" style="margin:0 auto"><tr><td align="center">
<h2>Link Generator Online</h2>
</td><tr></table>
<table width="80%" align="center" style="margin:0 auto"><tr><td align="center">
       </div>

 </td><td valign="top">
 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<br>
Insert keywords:<br>
<input type=text style="font-size: 13px; font-family: tahoma,arial; font-weight: bold; color: #000000; BORDER: #555 1px solid ; BACKGROUND-COLOR: #FFF" input name="url"  size="20">
<br>

<br>
<input type="SUBMIT" name="submit" VALUE="Submit">
</form>
</td></tr></table>
<?php
if(isset($_POST['submit'])){
$url = $_POST['url'];
$name = array($url);
foreach ($name as $name) {
    if (preg_match("/^[\.\<\[#`]/",$url)) {
        echo "<br><center><font color=\"red\">Invalid Characters.</center>";
        Die();
    }
    if (!strlen($url)) {
       echo "<br><center><font color=\"red\">Empty Field.</center>";
       Die();
    }
    if (strlen($url) > 100) {
       echo "<br><center><font color=\"red\">The field cannot contain more than 150 characters.</center>";
       Die();
    }
}

$ebay_url = "http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=".urlencode($url)."&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg";

$token = "e663e30818201d28dd07803e57333bed4f15803a";
$endpoint = "https://api-ssl.bitly.com/v3/shorten?access_token=".$token."&longUrl=".urlencode($ebay_url);
$result = file_get_contents($endpoint);
$json = json_decode($result, true);
$short_url = $json["data"]["url"];

?>
<br>
<center>
<form name="vini">
<a class="highlighttext" href="javascript:HighlightAll('vini.select1')">Select All</a><br>
<textarea name="select1" rows=3 cols=75 style="font-family:tahoma;color:#555;border:1px dashed #ccc">
<?php echo $short_url; ?>
</textarea>
<br>
</form>

<?php
}
?>
</body>
</html>
</code>```

Note: I changed your ereg calls to preg_match for compatibility with PHP7 and shortened the ifs with a regular expression. I also used urlencode($url) so that spaces won't break the link.

ContentLicense: CC BY-SA 4.0

Body:
I managed a small PHP script that takes the eBay product searched and converts it into promote eBay link.

It goes like this:

user searches for example: ocz vertex

clicks on "Submit" and gets the results in following format

http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=ocz
  vertex&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg

(Can't fix that space in the link generated between ocz and vertex words)

Now, the result is nice, but I want to shorten it via bitly.com account using their API.

Basicly I want it to generate and convert the full eBay link results into small bitly.com link (http://ebay.to/2scU91k for example) and to see that link on my bitly account.

The process would go like this:

User search for term like ocz vertex

click on "Submit"

get the ebay.to short link (while the real process is in background,
converts to rover.ebay.com address and then to ebay.to using my
bitly.com credentials)

I found that and that and especially that, but didn't understand how do I implement the results as a new bitly convert.

Here's the PHP code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="stylesheet" type="text/css" href="css/screen.css">

Link Generator Online

 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

URL

<input type=text style="font-size: 13px; font-family: tahoma,arial; font-weight: bold; color: #000000; BORDER: #555 1px solid ; BACKGROUND-COLOR: #FFF" input name="url"  size="20">

<input type="SUBMIT" name="submit" VALUE="Submit">
</form>

<?php
if(isset($_POST['submit'])){
$url = $_POST['url'];
$name=array($url);
foreach ($name as $name)
{
if (ereg("^\.",$url)) {
echo "
Invalid Characters.";
 Die();
}
if (ereg("\<", $url)) {
echo "
Invalid Characters.";
 Die();
}
if (ereg("\[", $url)) {
echo "
Invalid Characters.";
 Die();
}
if (ereg("\'", $url)) {
echo "
Invalid Characters.";
 Die();
}
if (ereg("\#", $url)) {
echo "
Invalid Characters.";
 Die();
}
if (ereg("\`", $url)) {
echo "
Invalid Characters.";
 Die();
}

if (!strlen($url)) {
echo "
Empty Field.";

Die();
}
if (strlen($url) > 100) {
echo "
The field cannot contain more than 150 characters.";

 Die();
}
}
?>

<form name="vini">
Select All

<textarea name="select1" rows=3 cols=75 style="font-family:tahoma;color:#555;border:1px dashed #ccc">
http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=<?php echo $url ?>&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg
</textarea>

</form>

<?php
}
?>

See on live: Ebay link Generator

Body:
I built a small solution that works without external libraries. It essentially boils down to this:

Acquire an API key from the "Register an application" dashboard or an oauth token from the oauth API

Make the request to the /v3/shorten API endpoint with your token and URL

First step: Get the token

You only need to do this once. Bitly's documentation lists a few examples how you can do it using curl, I think that is the easiest way. You could also do it with PHP. Simply make this POST request (taken from here):

curl -u "username:password" -X POST "https://api-ssl.bitly.com/oauth/access_token"

The result is something like this:

e663e30818201d28dd07803e57333bed4f15803a

That is your token.

Second step: Make the request

Insert the token and url-encoded URL into the HTTP request to the /v3/shorten endpoint:

<?php
$ebay_url = "http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=ocz%20vertex&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg"

$token = "e663e30818201d28dd07803e57333bed4f15803a"; // change this
$endpoint = "https://api-ssl.bitly.com/v3/shorten?access_token=".$token."&longUrl=".urlencode($ebay_url)."";
$result = file_get_contents($endpoint);
$json = json_decode($result, true);
$short_url = $json["data"]["url"];
echo $short_url;
?>

The result of the API call is JSON and needs to be decoded. An example is in the documentation. This code example does not take into consideration API timeouts or other errors that might occur (such as token expiry, which is currently not an issue).

The complete code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="css/screen.css">
<style type="text/css">
    body{
        margin:0px;
        font-size:0.7em;
        font-family:trebuchet ms;
                            color:#222;
    }
    #mainContainer{
        width:840px;
        margin:5px;
    }
    table,tr,td{
        vertical-align:top;
    }
    .textInput{
        width:300px;
    }
    html{
        margin:0px;
    }
    .formButton{
        width:75px;
    }
    textarea,input,select{
        font-family:helvetica;
    }
    i{
        font-size:0.9em;
    }
    </style>
<script language="Javascript">
<!--
var copytoclip=1
function HighlightAll(theField) {
    var tempval=eval("document."+theField)
    tempval.focus()
    tempval.select()
    if (document.all&&copytoclip==1){
        therange=tempval.createTextRange()
        therange.execCommand("Copy")
        window.status="Contents highlighted and copied to clipboard!"
        setTimeout("window.status=''",1800)
    }
}
//-->
</script>

</head>
<table width="80%" height="100px" align="center" style="margin:0 auto"><tr><td align="center">
<h2>Link Generator Online</h2>
</td><tr></table>
<table width="80%" align="center" style="margin:0 auto"><tr><td align="center">
       </div>

 </td><td valign="top">
 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<br>
Insert keywords:<br>
<input type=text style="font-size: 13px; font-family: tahoma,arial; font-weight: bold; color: #000000; BORDER: #555 1px solid ; BACKGROUND-COLOR: #FFF" input name="url"  size="20">
<br>

<br>
<input type="SUBMIT" name="submit" VALUE="Submit">
</form>
</td></tr></table>
<?php
if(isset($_POST['submit'])){
$url = $_POST['url'];
$name = array($url);
foreach ($name as $name) {
    if (preg_match("/^[\.\<\[#`]/",$url)) {
        echo "<br><center><font color=\"red\">Invalid Characters.</center>";
        Die();
    }
    if (!strlen($url)) {
       echo "<br><center><font color=\"red\">Empty Field.</center>";
       Die();
    }
    if (strlen($url) > 100) {
       echo "<br><center><font color=\"red\">The field cannot contain more than 150 characters.</center>";
       Die();
    }
}

$ebay_url = "http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=".urlencode($url)."&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg";

$token = "e663e30818201d28dd07803e57333bed4f15803a";
$endpoint = "https://api-ssl.bitly.com/v3/shorten?access_token=".$token."&longUrl=".urlencode($ebay_url);
$result = file_get_contents($endpoint);
$json = json_decode($result, true);
$short_url = $json["data"]["url"];

?>
<br>
<center>
<form name="vini">
<a class="highlighttext" href="javascript:HighlightAll('vini.select1')">Select All</a><br>
<textarea name="select1" rows=3 cols=75 style="font-family:tahoma;color:#555;border:1px dashed #ccc">
<?php echo $short_url; ?>
</textarea>
<br>
</form>

<?php
}
?>
</body>
</html>

Note: I changed your ereg calls to preg_match for compatibility with PHP7 and shortened the ifs with a regular expression. I also used urlencode($url) so that spaces won't break the link.


问:
Angular 2 deep linking not working properly
I just start to learn Angular 2 and I have created an Angular 2 app with Angular2VisualStudioTemplate template. In my app-routing.module.ts I have the next routes declared:

```<code>const routes: Routes = [
    { path: '', component: LoginComponent },
    { path: 'login', component: LoginComponent },
    { path: 'distribution', component: DistributionComponent },
    { path: 'dashboard', component: DashboardComponent }
];
</code>```

The root component just has the <router-outlet></router-outlet> directive.
In the LoginComponent view there is an input with [routerLink]="['/dashboard'] directive so when the user click on the button you can navigate to /dashboard.

The problem is that if I want to navigate to /dashboard or any other path, typing the URL in the broswer's navigation bar it just doesn't work. The page just displays the login view and it doesn't change to the dashboard component or any other. Notice that I haven't implemented some login mechanism, there are just dummy views and components.

I've seen similar questions referring to problems like mine but I can't figured out how to solve this. Thanks in advance

答:
Does your app.module.ts has this import array or similar?

```<code>@NgModule({
imports: [
RouterModule.forRoot(routes)
// other imports here
], ...
 })
</code>```

Body:
I just start to learn Angular 2 and I have created an Angular 2 app with Angular2VisualStudioTemplate template. In my app-routing.module.ts I have the next routes declared:

const routes: Routes = [
    { path: '', component: LoginComponent },
    { path: 'login', component: LoginComponent },
    { path: 'distribution', component: DistributionComponent },
    { path: 'dashboard', component: DashboardComponent }
];

The root component just has the <router-outlet></router-outlet> directive.
In the LoginComponent view there is an input with [routerLink]="['/dashboard'] directive so when the user click on the button you can navigate to /dashboard.

The problem is that if I want to navigate to /dashboard or any other path, typing the URL in the broswer's navigation bar it just doesn't work. The page just displays the login view and it doesn't change to the dashboard component or any other. Notice that I haven't implemented some login mechanism, there are just dummy views and components.

I've seen similar questions referring to problems like mine but I can't figured out how to solve this. Thanks in advance

Body:
Does your app.module.ts has this import array or similar?

@NgModule({
imports: [
RouterModule.forRoot(routes)
// other imports here
], ...
 })


问:
Cython cannot convert float ndarray to int ndarray
I am having a very weird error when I cast a numpy ndarray from one type to the other in Cython. For instance when I write the following convert_test.pyx:

```<code>cimport cython
import numpy as np
cimport numpy as np

DTYPE = np.float32
ctypedef np.float32_t DTYPE_t

def convert_to_int(np.ndarray[DTYPE_t, ndim=2] float_matrix):
    cdef np.ndarray[np.int, ndim=2] int_matrix=float_matrix.astype(np.int)
    return int_matrix
</code>```

compile it and test:

```<code>from convert_test import convert_to_int
a_int=convert_to_int(np.zeros((2,2)).astype(np.float32))
</code>```

I got the very familiar message:

ValueError: Buffer dtype mismatch, expected 'int object' but got 'long'

It is probably super obvious but I don't quite see it yet.

答:
Why don't you just do this?  Compiles and works just fine on my computer:

```<code>cimport cython
import numpy as np
cimport numpy as np

DTYPE = np.float32
ctypedef np.float32_t DTYPE_t

def convert_to_int(np.ndarray[DTYPE_t, ndim=2] float_matrix):
    int_matrix = np.array(float_matrix, dtype=np.int32)
    return int_matrix
</code>```

Or if you really want a memoryview:

```<code>def convert_to_int(DTYPE_t[:,:] float_matrix):
    cdef int[:,:] int_matrix = np.array(float_matrix, dtype=np.int32)
    return np.asarray(int_matrix)
</code>```

The second answer I just converted the older ndarray parameters to the modern typed memoryviews syntax for int_matrix and float_matrix.  The style above is your contiguous memory format [:,:] for a matrix (like NumPy defaults to with numpy.zeros for example).

Note that the function you posted is just going to truncate everything after the decimal point (no rounding up/down) so be sure that's what you intended.

Body:
I am having a very weird error when I cast a numpy ndarray from one type to the other in Cython. For instance when I write the following convert_test.pyx:

cimport cython
import numpy as np
cimport numpy as np

DTYPE = np.float32
ctypedef np.float32_t DTYPE_t

def convert_to_int(np.ndarray[DTYPE_t, ndim=2] float_matrix):
    cdef np.ndarray[np.int, ndim=2] int_matrix=float_matrix.astype(np.int)
    return int_matrix

compile it and test:

from convert_test import convert_to_int
a_int=convert_to_int(np.zeros((2,2)).astype(np.float32))

I got the very familiar message:

ValueError: Buffer dtype mismatch, expected 'int object' but got 'long'

It is probably super obvious but I don't quite see it yet.

Body:
Why don't you just do this?  Compiles and works just fine on my computer:

cimport cython
import numpy as np
cimport numpy as np

DTYPE = np.float32
ctypedef np.float32_t DTYPE_t

def convert_to_int(np.ndarray[DTYPE_t, ndim=2] float_matrix):
    int_matrix = np.array(float_matrix, dtype=np.int32)
    return int_matrix

Or if you really want a memoryview:

def convert_to_int(DTYPE_t[:,:] float_matrix):
    cdef int[:,:] int_matrix = np.array(float_matrix, dtype=np.int32)
    return np.asarray(int_matrix)

The second answer I just converted the older ndarray parameters to the modern typed memoryviews syntax for int_matrix and float_matrix.  The style above is your contiguous memory format [:,:] for a matrix (like NumPy defaults to with numpy.zeros for example).

Note that the function you posted is just going to truncate everything after the decimal point (no rounding up/down) so be sure that's what you intended.


问:
How to get remote file size from a shell script?
Is there a way to get the size of a remote file like

```<code>http://api.twitter.com/1/statuses/public_timeline.json
</code>```

in shell script?

答:
Similar to codaddict's answer, but without the call to grep:

```<code>curl -sI http://api.twitter.com/1/statuses/public_timeline.json | awk '/Content-Length/ { print $2 }'
</code>```

Body:
Is there a way to get the size of a remote file like

http://api.twitter.com/1/statuses/public_timeline.json

in shell script?

Body:
Similar to codaddict's answer, but without the call to grep:

curl -sI http://api.twitter.com/1/statuses/public_timeline.json | awk '/Content-Length/ { print $2 }'


问:
How do I share Neo4j graphs with Non-technical users?
Neo4j visualizations are fantastic but when I share it with non technical users they get confused. Is there any way to have a version of the portal with just the nodes view, along with some prebuild cypher queries they can click, or maybe even parameterized queries where they don't see the cypher.

I feel like Neo4j has a very powerful user interface but it's only accessible to developers. I'm sure they can click the cypher queries in the star'ed queries section but I'd like to hide them from any code as it may confuse them.

答:
For custom browser guides please have a look at the developer page, this should help you create slides for you users that guide them through your data.

http://localhost:8000/developer/resources/guide-create-neo4j-browser-guide/


问:
Column outline overriden by row highlight? (html table, css formatting)
I used a derivation of ThinkingStiff's answer to this question cols, colgroups and css :hover psuedoclass to create a table that outlines columns and highlights rows on hover. (Vertical column headers intentionally not outlined).

See below:

table {
  overflow: hidden;
}
caption {
  background-color: #fff;
  padding: 0px
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
  width: 100%
}
th, td {
    width: 100px;
    height: 50px;
    position: relative;
}
tr:hover {
  background-color: #FBFEFD;
}

td:hover::after {
  content: "";
  position: absolute;
  outline: solid black 2px !important;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="ComparisonTable">
 <caption>Comparison Table</caption>
  <tbody>
    <tr>
      <th class="CompTabProdCat">Category</th>
      <td>ProdCat1</td>
      <td>ProdCat2</td>
      <td>ProdCat3</td>
      <td>ProdCat4</td>
      <td>ProdCat5</td>
    </tr>
    <tr>
      <th class="CompTabProdName">ProdName</th>
      <td>ProdName1</td>
      <td>ProdName2</td>
      <td>ProdName3</td>
      <td>ProdName4</td>
      <td>ProdName5</td>
    </tr>
    <tr>
      <th class="CompTabProdRat">Rating</th>
      <td>ProdRating1</td>
      <td>ProdRating2</td>
      <td>ProdRating3</td>
      <td>ProdRating4</td>
      <td>ProdRating5</td>
    </tr>
    <tr>
      <th class="CompTabProdPho">Photo</th>
      <td>ProdImage1</td>
      <td>ProdImage2</td>
      <td>ProdImage3</td>
      <td>ProdImage4</td>
      <td>ProdImage5</td>
    </tr>
    <tr>
      <th class="CompTabProdSum">Summary</th>
      <td>ProdSum1</td>
      <td>ProdSum2</td>
      <td>ProdSum3</td>
      <td>ProdSum4</td>
      <td>ProdSum5</td>
    </tr>
  </tbody>
</table></code>```

Does anyone know why the column outline disappears for the selected row? I thought the !important tag would maintain that outline, but apparently not. Any other workarounds available to maintain that outline?

Bonus question is why I'm losing the rightmost border (less stuck and less concerned with that question).

Thanks a ton; I appreciate it!

答:
After monkeying around a bit, I think I have a working solution for you.

```<code>table {
  overflow: hidden;
  overflow-x: visible;
  display: block;
}

tbody {
  overflow-y: hidden;
  display: block;
  margin-top: 19px;
  position: relative;
}

caption {
  background-color: #fff;
  padding: 0px;
  width: 617px;
  z-index: 20;
  position: absolute;
  border: 1px solid black;
  border-bottom: 0;
}

table,
th,
td {
  border-collapse: collapse;
  text-align: center;
  width: 100%
}

th,
td {
  width: 100px;
  height: 50px;
  position: relative;
  border: 1px solid black;
}

tr:hover {
  background-color: #FBFEFD;
}

td:hover::after {
  content: "";
  position: absolute;
  outline: solid black 2px !important;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  /*z-index: -1;*/
}
</code>```

JSFiddle example: https://jsfiddle.net/jennifergoncalves/rntyt13u/2/

I can help you tweak it from here if more work is needed.

Body:
I used a derivation of ThinkingStiff's answer to this question cols, colgroups and css :hover psuedoclass to create a table that outlines columns and highlights rows on hover. (Vertical column headers intentionally not outlined).

See below:

table {
  overflow: hidden;
}
caption {
  background-color: #fff;
  padding: 0px
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
  width: 100%
}
th, td {
    width: 100px;
    height: 50px;
    position: relative;
}
tr:hover {
  background-color: #FBFEFD;
}

td:hover::after {
  content: "";
  position: absolute;
  outline: solid black 2px !important;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}

Comparison Table

      Category
      ProdCat1
      ProdCat2
      ProdCat3
      ProdCat4
      ProdCat5

      ProdName
      ProdName1
      ProdName2
      ProdName3
      ProdName4
      ProdName5

      Rating
      ProdRating1
      ProdRating2
      ProdRating3
      ProdRating4
      ProdRating5

      Photo
      ProdImage1
      ProdImage2
      ProdImage3
      ProdImage4
      ProdImage5

      Summary
      ProdSum1
      ProdSum2
      ProdSum3
      ProdSum4
      ProdSum5

Does anyone know why the column outline disappears for the selected row? I thought the !important tag would maintain that outline, but apparently not. Any other workarounds available to maintain that outline?

Bonus question is why I'm losing the rightmost border (less stuck and less concerned with that question).

Thanks a ton; I appreciate it!

Body:
After monkeying around a bit, I think I have a working solution for you.

table {
  overflow: hidden;
  overflow-x: visible;
  display: block;
}

tbody {
  overflow-y: hidden;
  display: block;
  margin-top: 19px;
  position: relative;
}

caption {
  background-color: #fff;
  padding: 0px;
  width: 617px;
  z-index: 20;
  position: absolute;
  border: 1px solid black;
  border-bottom: 0;
}

table,
th,
td {
  border-collapse: collapse;
  text-align: center;
  width: 100%
}

th,
td {
  width: 100px;
  height: 50px;
  position: relative;
  border: 1px solid black;
}

tr:hover {
  background-color: #FBFEFD;
}

td:hover::after {
  content: "";
  position: absolute;
  outline: solid black 2px !important;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  /*z-index: -1;*/
}

JSFiddle example: https://jsfiddle.net/jennifergoncalves/rntyt13u/2/

I can help you tweak it from here if more work is needed.


答:
this work for me. remove \' and '

```<code>replace this <a onClick='deleteMe(\'" + valkey + "\')'>
for this     <a onClick=deleteMe('" + valkey + "')>
</code>```

Paste this in console and try, work for me

```<code>var email ="email";
var valkey ="valueyodelete";
$('#table_body').append("<tr><td>"+ name +"</td><td>"+ email +"</td><td><a onClick=deleteMe('" + valkey + "')>delete</a></td></tr>");

function deleteMe(valkey){
    var cKey = valkey;
    console.log(cKey);

}
</code>```

Title: Javascript onClick function SyntaxError: expected expression, got '}'

Body:
this work for me. remove \' and '

replace this <a onClick='deleteMe(\'" + valkey + "\')'>
for this     <a onClick=deleteMe('" + valkey + "')>

Paste this in console and try, work for me

var email ="email";
var valkey ="valueyodelete";
$('#table_body').append("<tr><td>"+ name +"</td><td>"+ email +"</td><td><a onClick=deleteMe('" + valkey + "')>delete</a></td></tr>");

function deleteMe(valkey){
    var cKey = valkey;
    console.log(cKey);

}


问:
What is the difference between no-cache and no-store in Cache-control?
I don't find get the practical difference between Cache-Control:no-store and Cache-Control:no-cache.

As far as I know, no-store means that no cache device is allowed to cache that response. In the other hand, no-cache means that no cache device is allowed to serve a cached response without validate it first with the source. But what is that validation about? Conditional get?

What if a response has no-cache, but it has no Last-Modified or ETag?

Regards.

答:
As you identified, no-cache doesn't mean there is never caching, but rather that the user agent has to always ask the server if it's OK to use what it cached. By contrast, no-store says to not even keep a copy, which means there's nothing to ask about. If you know the answer to "Can I reuse this?" is always no, you get a performance boost by skipping cache validation and saving room in the cache for other data.

Aside from performance, there is a behavior difference with browser history. HTTP 1.1 section 13.13 says that "expiration time does not apply to history mechanisms." The no-cache header describes expiration, and so doesn't apply to history mechanisms such as the back button. Thus, the user can navigate backward to a previous page with no-cache without the server being contacted.

The no-store header, on the other hand, prevents the data from being stored outside of a session, in which case it simply isn't available for a history mechanism to use. With no-store, if the user ends his session by navigating to another domain and then goes back, the only way for browser to know what to display is to get the initial page again from the server.

Here's how a Chromium issue on this topic makes the distinction:

no-cache doesn't mean "don't cache this" (that would be no-store). no-cache means don't use this for normal loads unless the resource is revalidated for freshness. History navigations are not normal loads.


问:
Nested child components undefined input properties
I have a component that has dataModel as an Input, the dataModel is undefined when the constructor is called.

```<code><div class="container">
    <dataViewer [dataModel]="data"></dataViewer>
</div>
</code>```

Component

```<code>@Input() dataModel: DataModel;

// ..

constructor(private element: ElementRef) {
   this.htmlElement = this.element.nativeElement;
   this.selectorElement = d3.select(this.element.nativeElement);

   if (this.dataModel== undefined) { throw 'dataModel is undefined' };

}
</code>```

The parent component has a route resolver, how can I ensure the dataModel is set when the dataViewer component is constructed? Could I delay the construction of any child components to ensure it is not undefined?

```<code>this.route.data
            .subscribe(( data: { foo: Bar[] }) => {
                self.foo = foo;
            });
</code>```

答:
Consider moving the code from the constructor to the ngOnChanges event of the nested component. That event will occur when the dataModel property is set or changed.

You'll still need an if around the code to ensure you don't see an undefined when the component is first loaded.

Body:
I have a component that has dataModel as an Input, the dataModel is undefined when the constructor is called.

    <dataViewer [dataModel]="data"></dataViewer>

Component

@Input() dataModel: DataModel;

// ..

constructor(private element: ElementRef) {
   this.htmlElement = this.element.nativeElement;
   this.selectorElement = d3.select(this.element.nativeElement);

   if (this.dataModel== undefined) { throw 'dataModel is undefined' };

}

The parent component has a route resolver, how can I ensure the dataModel is set when the dataViewer component is constructed? Could I delay the construction of any child components to ensure it is not undefined?

this.route.data
            .subscribe(( data: { foo: Bar[] }) => {
                self.foo = foo;
            });


问:
Rails 3: Why the field with error is not wrapped with "field_with_errors" div when validation fails?
My Product class has price field, which has an appropriate column in Products table in the database, and new_shop helper field (which is defined as attr_accessor, and does not has an appropriate column in Products table in the database).

When validation on price fails, the input field is wrapped with field_with_errors div, but when the validation on new_shop fails, it is not wrapped with field_with_errors div. Why ?

Here is the generated HTML for these input fields:

```<code><input type="text" name="product[price]" id="product_price">
<input type="text" value="" name="product[new_shop]" id="product_new_shop">
</code>```

Some more info:

```<code>class Product < ActiveRecord::Base
  attr_accessor :new_shop
  accepts_nested_attributes_for :shop
  validates_presence_of :price
  ...
end

class Shop < ActiveRecord::Base
  validates_presence_of :name
  ...
end
</code>```

When the form is submitted, the new_shop value is passed to product's shop_attributes[:name].

答:
So it's the :name attribute that actually fails validation?  That is why new_shop doesn't get the fieldWithErrors div then: this looks at @product.errors to decide on a field by field basis whether it has errors.  ie</p>

```<code>#comes to do the :new_shop field
#looks to see if @product.errors.on(:new_shop) is not blank
#if it isn't blank, wraps the error div round it.
</code>```

Body:
My Product class has price field, which has an appropriate column in Products table in the database, and new_shop helper field (which is defined as attr_accessor, and does not has an appropriate column in Products table in the database).

When validation on price fails, the input field is wrapped with field_with_errors div, but when the validation on new_shop fails, it is not wrapped with field_with_errors div. Why ?

Here is the generated HTML for these input fields:

<input type="text" name="product[price]" id="product_price">
<input type="text" value="" name="product[new_shop]" id="product_new_shop">

Some more info:

class Product < ActiveRecord::Base
  attr_accessor :new_shop
  accepts_nested_attributes_for :shop
  validates_presence_of :price
  ...
end

class Shop < ActiveRecord::Base
  validates_presence_of :name
  ...
end

When the form is submitted, the new_shop value is passed to product's shop_attributes[:name].

Body:
So it's the :name attribute that actually fails validation?  That is why new_shop doesn't get the fieldWithErrors div then: this looks at @product.errors to decide on a field by field basis whether it has errors.  ie

#comes to do the :new_shop field
#looks to see if @product.errors.on(:new_shop) is not blank
#if it isn't blank, wraps the error div round it.


问:
Trim part of string from column headers in a pandas dataframe
I am working on a pandas dataframe  imported from a .csv file where there are about 18 columns. Each column has a item name and an image description in html format as column header. It is something like this:

```<code>A  <img width="300" alt="A" height="300".jpg">`  ` B <img width="400" alt="B" height="600".jpg"`......
</code>```

and so on.

What I am trying to achieve is to get only the item name for my column headers and trim the image part. I tried this replace function:

```<code>df.rename(columns=lambda x: x.replace('<img width="300" alt="A" height="300".jpg">', ''), inplace=True)
</code>```

But it is not possible to give every column name as there are 30 similar files like this one and every image has a different description. I am looking for a more elegant solution here. I want my output to be something like:

```<code>A   B   C   D   ......so on
</code>```

Any help would be greatly appreciated.

答:
I'd use a regular expression</p>

```<code>df.columns = df.columns.str.replace('\s*<.*>\s*$', '')
</code>```

Body:
I am working on a pandas dataframe  imported from a .csv file where there are about 18 columns. Each column has a item name and an image description in html format as column header. It is something like this:

A  `  ` B <img width="400" alt="B" height="600".jpg"`......

and so on.

What I am trying to achieve is to get only the item name for my column headers and trim the image part. I tried this replace function:

df.rename(columns=lambda x: x.replace('', ''), inplace=True)

But it is not possible to give every column name as there are 30 similar files like this one and every image has a different description. I am looking for a more elegant solution here. I want my output to be something like:

A   B   C   D   ......so on

Any help would be greatly appreciated.

Body:
I'd use a regular expression

df.columns = df.columns.str.replace('\s*<.*>\s*$', '')


问:
How to find keys in hash by number of values? (Ruby)
I want to search through a hash for keys with only one value, and divide that value by 2.  How do I go about this?

Example

```<code>hash = { a => [4], b => [2, 4, 5], c => [3, 5] }
</code>```

Result sought

```<code>hash = { a => [2], b => [2, 4, 5], c => [3, 5] }
</code>```

答:
This should do the trick, just iterate over each key/value pair and check the length of the values, if it only has 1 item, set the key in the hash to be equal to half the original value.</p>

```<code>hash = { a: [4], b:  [2, 4, 5], c: [3, 5] }
# => {:a=>[4], :b=>[2, 4, 5], :c=>[3, 5]}

hash.each do |key, values|
  if 1 == values.length
    hash[key] = [values.first / 2]
  end
end
# => {:a=>[2], :b=>[2, 4, 5], :c=>[3, 5]}
</code>```

Body:
I want to search through a hash for keys with only one value, and divide that value by 2.  How do I go about this?

Example

hash = { a => [4], b => [2, 4, 5], c => [3, 5] }

Result sought

hash = { a => [2], b => [2, 4, 5], c => [3, 5] }

Body:
This should do the trick, just iterate over each key/value pair and check the length of the values, if it only has 1 item, set the key in the hash to be equal to half the original value.

hash = { a: [4], b:  [2, 4, 5], c: [3, 5] }
# => {:a=>[4], :b=>[2, 4, 5], :c=>[3, 5]}

hash.each do |key, values|
  if 1 == values.length
    hash[key] = [values.first / 2]
  end
end
# => {:a=>[2], :b=>[2, 4, 5], :c=>[3, 5]}


问:
Laravel Polymorphic Relation using full model name
I have a polymorphic relationship set up in Laravel 5.4.  The relationship is working but the query is using the fully qualified model name.

```<code>select * from `contact_info`
where `contact_info`.`entity_id` = '25'
and `contact_info`.`entity_id` is not null
and `contact_info`.`entity_type` = 'App\Modules\User\Model\User'
limit 1
</code>```

The relationship is set on the User model:

```<code>/**
 * @description Method handles polymorphic contact relationship.
 * @return \Illuminate\Database\Eloquent\Relations\MorphOne
 */
public function contact()
{
    return $this->morphOne('App\Modules\Common\ContactInfo', 'entity');
}
</code>```

and the ContactInfo model:

```<code>/**
 * @description Method establishes polymorphic relationship (tenant/user).
 * @return \Illuminate\Database\Eloquent\Relations\MorphTo
 */
public function entity()
{
    return $this->morphTo();
}
</code>```

The actual table has the values set to 'user', 'tenant' and 'referrer' instead of the model names/namespaces.  I found a little bit of information about relationship maps but don't know if that'll solve my issue here.

Basically I need to find out how to tell the code that 'App\Modules\User\Model\User' should be 'user' in the database.

答:
MorphMaps were the way to go.  I added this to my AppServiceProvider boot method and it started pulling the data as expected:

```<code>use App\Modules\User;
use App\Modules\Tenant
Relation::morphMap([
    'user' => User::class,
    'tenant' => Tenant::class
]);
</code>```

Query is now:

```<code>select * from `contact_info`
where `contact_info`.`entity_id` = '25'
and `contact_info`.`entity_id` is not null
and `contact_info`.`entity_type` = 'user' limit 1
</code>```

This article helped me out tremendously.

Body:
I have a polymorphic relationship set up in Laravel 5.4.  The relationship is working but the query is using the fully qualified model name.

select * from `contact_info`
where `contact_info`.`entity_id` = '25'
and `contact_info`.`entity_id` is not null
and `contact_info`.`entity_type` = 'App\Modules\User\Model\User'
limit 1

The relationship is set on the User model:

/**
 * @description Method handles polymorphic contact relationship.
 * @return \Illuminate\Database\Eloquent\Relations\MorphOne
 */
public function contact()
{
    return $this->morphOne('App\Modules\Common\ContactInfo', 'entity');
}

and the ContactInfo model:

/**
 * @description Method establishes polymorphic relationship (tenant/user).
 * @return \Illuminate\Database\Eloquent\Relations\MorphTo
 */
public function entity()
{
    return $this->morphTo();
}

The actual table has the values set to 'user', 'tenant' and 'referrer' instead of the model names/namespaces.  I found a little bit of information about relationship maps but don't know if that'll solve my issue here.

Basically I need to find out how to tell the code that 'App\Modules\User\Model\User' should be 'user' in the database.

Body:
MorphMaps were the way to go.  I added this to my AppServiceProvider boot method and it started pulling the data as expected:

use App\Modules\User;
use App\Modules\Tenant
Relation::morphMap([
    'user' => User::class,
    'tenant' => Tenant::class
]);

Query is now:

select * from `contact_info`
where `contact_info`.`entity_id` = '25'
and `contact_info`.`entity_id` is not null
and `contact_info`.`entity_type` = 'user' limit 1

This article helped me out tremendously.


问:
HTTP authentication logout via PHP
What is the correct way to log out of HTTP authentication protected folder?

There are workarounds that can achieve this, but they are potentially dangerous because they can be buggy or don't work in certain situations / browsers. That is why I am looking for correct and clean solution.

答:
Workaround (not a clean, nice (or even working! see comments) solution):

Disable his credentials one time.

You can move your HTTP authentication logic to PHP by sending the appropriate headers (if not logged in):

```<code>Header('WWW-Authenticate: Basic realm="protected area"');
Header('HTTP/1.0 401 Unauthorized');
</code>```

And parsing the input with:

```<code>$_SERVER['PHP_AUTH_USER'] // httpauth-user
$_SERVER['PHP_AUTH_PW']   // httpauth-password
</code>```

So disabling his credentials one time should be trivial.

OwnerDisplayName: JS

Title: HTTP authentication logout via PHP

LastEditorDisplayName: JS

Body:
Workaround (not a clean, nice (or even working! see comments) solution):

Disable his credentials one time.

You can move your HTTP authentication logic to PHP by sending the appropriate headers (if not logged in):

Header('WWW-Authenticate: Basic realm="protected area"');
Header('HTTP/1.0 401 Unauthorized');

And parsing the input with:

$_SERVER['PHP_AUTH_USER'] // httpauth-user
$_SERVER['PHP_AUTH_PW']   // httpauth-password

So disabling his credentials one time should be trivial.

OwnerDisplayName: Karsten