问:
Using firebase to get multiple individual values given an array of keys
I'm trying to access multiple individual keys in Firebase. I'm using a promise-based function and a for loop to iterate over the given keys.

Here's the code:

```<code>function getFirebaseData(key_arr)
{
   var ref_obj,
       data_obj = {};
   return new Promise(function(resolve)
   {
       for(var i = 0; i < key_arr.length; i++)
       {
           key_str = key_arr[i];
           ref_obj = firebase.database().ref('path/'+key_str);
           ref_obj.on('value', function(snapshot)
           {
               data_obj[key_str] = snapshot.val();
           });
        }
        resolve(data_obj);
   });
}
</code>```

And then I run this as follows:

```<code>var key_arr = ['first_key', 'second_key', 'third_key'];
getFirebaseData(key_arr).then(function(result){console.log(result);});
</code>```

The problem is that the result I get isn't all three keys; I only get one. I guess this is because the code inside the for loop is asynchronous, so resolve only gives me the first key.

How can I rewrite this in such a way that I can wait for the for loop to complete and return the full result.

答:
The previous answer is solid, except the promise returned resolves to an array of data_obj

So, what you need to do is to change each iteration of the loop to a promise, then wait for all promises to resolve using Promise.all

Here is how you would do it using ES2015 - as you're using Promises, ES2015 isn't such a stretch anyway

```<code>function getFirebaseData(key_arr) {
    return Promise.all(key_arr.map(key_str =>
        new Promise((resolve, reject) =>
            firebase.database().ref('path/'+key_str).once('value', snapshot =>
                resolve ([key_str, snapshot.val()])
            )
        )
    )).then(results =>
        results.reduce((result, [key, value]) => {
            result[key] = value;
            return result;
        }, {})
    );
}
</code>```

which transpiles to old school ES5 as:

```<code>function getFirebaseData(key_arr) {
    return Promise.all(key_arr.map(function (key_str) {
        return new Promise(function (resolve, reject) {
            return firebase.database().ref('path/' + key_str).once('value', function (snapshot) {
                return resolve([key_str, snapshot.val()]);
            });
        });
    })).then(function (results) {
        return results.reduce(function (result, item) {
            var key = item[0],
                value = item[1];
            result[key] = value;
            return result;
        }, {});
    });
}
</code>```

Each individual promise now resolves to an array, basically [key, value]

the .then after Promise.all combines all those results to a single object, like: { key1: value1, key2: value2, ...

The code above uses .once('value' rather than .on('value' - as pointed out in the comments, using .on would leave the listener attached. As Promises can only be resolved ONCE, then it makes sense to use .once

Body:
I'm trying to access multiple individual keys in Firebase. I'm using a promise-based function and a for loop to iterate over the given keys.

Here's the code:

function getFirebaseData(key_arr)
{
   var ref_obj,
       data_obj = {};
   return new Promise(function(resolve)
   {
       for(var i = 0; i < key_arr.length; i++)
       {
           key_str = key_arr[i];
           ref_obj = firebase.database().ref('path/'+key_str);
           ref_obj.on('value', function(snapshot)
           {
               data_obj[key_str] = snapshot.val();
           });
        }
        resolve(data_obj);
   });
}

And then I run this as follows:

var key_arr = ['first_key', 'second_key', 'third_key'];
getFirebaseData(key_arr).then(function(result){console.log(result);});

The problem is that the result I get isn't all three keys; I only get one. I guess this is because the code inside the for loop is asynchronous, so resolve only gives me the first key.

How can I rewrite this in such a way that I can wait for the for loop to complete and return the full result.

Body:
The previous answer is solid, except the promise returned resolves to an array of data_obj

So, what you need to do is to change each iteration of the loop to a promise, then wait for all promises to resolve using Promise.all

Here is how you would do it using ES2015 - as you're using Promises, ES2015 isn't such a stretch anyway

function getFirebaseData(key_arr) {
    return Promise.all(key_arr.map(key_str =>
        new Promise((resolve, reject) =>
            firebase.database().ref('path/'+key_str).once('value', snapshot =>
                resolve ([key_str, snapshot.val()])
            )
        )
    )).then(results =>
        results.reduce((result, [key, value]) => {
            result[key] = value;
            return result;
        }, {})
    );
}

which transpiles to old school ES5 as:

function getFirebaseData(key_arr) {
    return Promise.all(key_arr.map(function (key_str) {
        return new Promise(function (resolve, reject) {
            return firebase.database().ref('path/' + key_str).once('value', function (snapshot) {
                return resolve([key_str, snapshot.val()]);
            });
        });
    })).then(function (results) {
        return results.reduce(function (result, item) {
            var key = item[0],
                value = item[1];
            result[key] = value;
            return result;
        }, {});
    });
}

Each individual promise now resolves to an array, basically [key, value]

the .then after Promise.all combines all those results to a single object, like: { key1: value1, key2: value2, ...

The code above uses .once('value' rather than .on('value' - as pointed out in the comments, using .on would leave the listener attached. As Promises can only be resolved ONCE, then it makes sense to use .once


来源: stackexchange

问:
In Typescript, define a type for an array where the first element is more specific than the rest
I would like to define a type for an array whose first element is a specific type (e.g. Function), and the remaining elements are the empty type. For example:

```<code>type FAs = [Function, {}, {}, {}, ...]; // pseudo code
</code>```

Is such a thing possible?

The purpose is to provide a single-argument function like this:

```<code>const myCaller = ([fun, ...args]: FAs) => fun.apply(args);
</code>```

An alternative approach would be to use two arguments to myCaller, like this:

```<code>const myCaller = (fun: Function, args: any[]) => fun.apply(args);
</code>```

but for aesthetic reasons I would prefer to use a single argument. I also wonder if the type system supports what is arguably an arbitrary-length tuple. Maybe such a thing is undesirable for computer science reasons I don't understand.

答:
If you define

```<code>type FAs = [Function, {}];
</code>```

Then values of type FAs will require a first element of type Function, a second element of type {}, and succeeding elements of Function | {}. That is how TypeScript literal array types work. From the TS docs:

When accessing an element outside the set of known indices, a union type is used instead:

This should do everything you want except for the fact that you will be able to pass in a Function-typed value as the third element etc. of the array. But actually that would be the case anyway, since Function is compatible with {}.

There is no way around this. There is no way in TS to define an array type where the first n elements are of some specific type(s), and there are an arbitrary number of remaining elements of some other specific type.

I also wonder if the type system supports what is arguably an arbitrary-length tuple.

Actually, the type system only supports arbitrary-length tuples. If you say

```<code>type Tuple = [number, number];
</code>```

this type is compatible with any array, of length two or greater, that contains numbers. If you say

```<code>type Tuple = [string, number];
</code>```

this type is compatible with any array, of length two or longer, that has a string as its first element, a number as its second, and either a string or number as its third etc. I would not call the reasons for this behavior "computer-science based"; it's more a matter of what it's feasible for TS to check.

An alternate approach

```<code>interface Arglist {
  [index: number]: object;
  0: Function;
}

const a1: Arglist = [func];
const a2: Arglist = [22];                  // fails
const a3: Arglist = [func, "foo"];         // fails
const a4: Arglist = [func, obj];
const a5: Arglist = [func, obj, obj];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to define a type for an array whose first element is a specific type (e.g. Function), and the remaining elements are the empty type. For example:

type FAs = [Function, {}, {}, {}, ...]; // pseudo code

Is such a thing possible?

The purpose is to provide a single-argument function like this:

const myCaller = ([fun, ...args]: FAs) => fun.apply(args);

An alternative approach would be to use two arguments to myCaller, like this:

const myCaller = (fun: Function, args: any[]) => fun.apply(args);

but for aesthetic reasons I would prefer to use a single argument. I also wonder if the type system supports what is arguably an arbitrary-length tuple. Maybe such a thing is undesirable for computer science reasons I don't understand.

Body:
If you define

type FAs = [Function, {}];

Then values of type FAs will require a first element of type Function, a second element of type {}, and succeeding elements of Function | {}. That is how TypeScript literal array types work. From the TS docs:

When accessing an element outside the set of known indices, a union type is used instead:

This should do everything you want except for the fact that you will be able to pass in a Function-typed value as the third element etc. of the array. But actually that would be the case anyway, since Function is compatible with {}.

There is no way around this. There is no way in TS to define an array type where the first n elements are of some specific type(s), and there are an arbitrary number of remaining elements of some other specific type.

I also wonder if the type system supports what is arguably an arbitrary-length tuple.

Actually, the type system only supports arbitrary-length tuples. If you say

type Tuple = [number, number];

this type is compatible with any array, of length two or greater, that contains numbers. If you say

type Tuple = [string, number];

this type is compatible with any array, of length two or longer, that has a string as its first element, a number as its second, and either a string or number as its third etc. I would not call the reasons for this behavior "computer-science based"; it's more a matter of what it's feasible for TS to check.

An alternate approach

interface Arglist {
  [index: number]: object;
  0: Function;
}

const a1: Arglist = [func];
const a2: Arglist = [22];                  // fails
const a3: Arglist = [func, "foo"];         // fails
const a4: Arglist = [func, obj];
const a5: Arglist = [func, obj, obj];


问:
Configuring Android Studio to use NDK (android-ndk-r10d, Windows 64-bit)
I have an application I'm trying to compile, which uses *.c files.

To compile this I must use NDK.

Downloaded the 64bit version and browsed the net to find tips on configuring gradle.

It seems the config is ok, and gradle attempts to run the NDK build process.

It does this by calling ndk-build.cmd and stops with this error:

\AppData\Local\VirtualStore\Windows\SysWOW64\android-ndk-r10d\ndk-build.cmd": CreateProcess error=2, The system cannot find the file specified

I searched the whole folder for ndk-build.cmd, but there is none.

What in the world am I missing?

EDIT1: The NDK is installed here:

```<code>#ndk.dir=C\:\\Users\\user\\AppData\\Local\\VirtualStore\\Windows\\SysWOW64\\android-ndk-r10d
</code>```

EDIT2: I did try my system path is OK, this is not the problem. I did however instal the 32-bit version, and this one does have the *.cmd file.

I can now compile the *.c files.

I used this command in the AndroidStudio Terminal:

```<code>ndk-build -C C:\Users\Thatisme\AndroidStudioProjects\DeezerAP2\app\src\main\jni
</code>```

All *.c, *.h, *.mk and *.sh were placed in the jni folder as seen in the picture bellow.

EDIT3: I can now generate *.so files, but for some reason, the native methods are not found.

EDIT4:

This is how my project looks like:

I manually copied the *.so files in the jniLibs folder.

Is the declaration of the *.c function OK?

```<code>JNIEXPORT jobject JNICALL Java_com_lexample_liggy_ldeezerap_SerialPort_open
  (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)
</code>```

EDIT5: I finally did it. The correct name of the function is:

```<code>JNIEXPORT jobject JNICALL Java_com_example_iggy_deezerap_SerialPort_open
  (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)
</code>```

```<code>Package name is: com.example.iggy.deezerap
Java file calling the function "open()" is: SerialPort
The source file containing the native function is named: SerialPort.c
The function beeing called is: open()
</code>```

I recompiled the *.c files, copied them also in jniLibs, recompiled the Android project and now it works.

I'm pretty sure I had this before and I strongly suspect it was due to some sort of mismatch error in the *.c functions.

About the thing in bold:

JNIEXPORT jobject JNICALL Java_com_example_iggy_deezerap_SerialPort_open
      (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)

Does this refer to the *.c file or the *.java file?

答:
You can do it in these ways.

a. add the ANDROID_NDK environgment variable by add export ANDROID_NDK='/Users/roofe/Documents/android-ndk-r14b' to .bash_profile. Then use source ./.bash_profile to load it.

b. add the sdk.dir=/Users/roofe/Library/Android/sdk to local.properties of Android Studio.

c.
File > Project Structure

download NDK or set the path.

Body:
I have an application I'm trying to compile, which uses *.c files.

To compile this I must use NDK.

Downloaded the 64bit version and browsed the net to find tips on configuring gradle.

It seems the config is ok, and gradle attempts to run the NDK build process.

It does this by calling ndk-build.cmd and stops with this error:

\AppData\Local\VirtualStore\Windows\SysWOW64\android-ndk-r10d\ndk-build.cmd": CreateProcess error=2, The system cannot find the file specified

I searched the whole folder for ndk-build.cmd, but there is none.

What in the world am I missing?

EDIT1: The NDK is installed here:

#ndk.dir=C\:\\Users\\user\\AppData\\Local\\VirtualStore\\Windows\\SysWOW64\\android-ndk-r10d

EDIT2: I did try my system path is OK, this is not the problem. I did however instal the 32-bit version, and this one does have the *.cmd file.

I can now compile the *.c files.

I used this command in the AndroidStudio Terminal:

ndk-build -C C:\Users\Thatisme\AndroidStudioProjects\DeezerAP2\app\src\main\jni

All *.c, *.h, *.mk and *.sh were placed in the jni folder as seen in the picture bellow.

EDIT3: I can now generate *.so files, but for some reason, the native methods are not found.

EDIT4:

This is how my project looks like:

I manually copied the *.so files in the jniLibs folder.

Is the declaration of the *.c function OK?

JNIEXPORT jobject JNICALL Java_com_lexample_liggy_ldeezerap_SerialPort_open
  (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)

EDIT5: I finally did it. The correct name of the function is:

JNIEXPORT jobject JNICALL Java_com_example_iggy_deezerap_SerialPort_open
  (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)

Package name is: com.example.iggy.deezerap
Java file calling the function "open()" is: SerialPort
The source file containing the native function is named: SerialPort.c
The function beeing called is: open()

I recompiled the *.c files, copied them also in jniLibs, recompiled the Android project and now it works.

I'm pretty sure I had this before and I strongly suspect it was due to some sort of mismatch error in the *.c functions.

About the thing in bold:

JNIEXPORT jobject JNICALL Java_com_example_iggy_deezerap_SerialPort_open
      (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)

Does this refer to the *.c file or the *.java file?


问:
AWS cannot signed CloudFront urls
Excepted: I want to get signed urls with my AWS CloudFront url.

What I have done: I have created a AWS CloudFront instence and enabled Restrict Viewer Access function, Trusted Signers is Self.

Below is the php code I want to sign the url

```<code>function getSignedURL()
{
    $resource = 'http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp';
    $timeout = 300;

    //This comes from key pair you generated for cloudfront
    $keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";

    $expires = time() + $timeout; //Time out in seconds
    $json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';

    //Read Cloudfront Private Key Pair
    $fp=fopen("private_key.pem","r");
    $priv_key=fread($fp,8192);
    fclose($fp);

    //Create the private key
    $key = openssl_get_privatekey($priv_key);
    if(!$key)
    {
            echo "<p>Failed to load private key!</p>";
            return;
    }

    //Sign the policy with the private key
    if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
    {
            echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
            return;
    }

    //Create url safe signed policy
    $base64_signed_policy = base64_encode($signed_policy);
    $signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

    //Construct the URL
    $url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

    return $url;
}
</code>```

For $keyPairId and private_key.pem, I logged in my root account and generated this two variables in Security Credentials->CloudFront Key Pairs section.

If I access http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp on browser directly. It will response like

```<code><Error>
  <Code>MissingKey</Code>
  <Message>
    Missing Key-Pair-Id query parameter or cookie value
  </Message>
</Error>
</code>```

After I run the function, I got a long signed url, parse the url on chrome browser, it will response like

```<code><Error>
  <Code>InvalidKey</Code>
  <Message>Unknown Key</Message>
</Error>
</code>```

Question: I have search AWS document and google much time about this, Could anyone tell me why this happened or if I miss something? Thanks in advance!

答:
Thanks @imperalix for answering this question.

I have solved this issue,

Inspired by this site, I found I used the wrong CloudFront url to be signed.

Before: http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp

After: http://d2qui8qg6d31zk.cloudfront.net/140-140.bmp

Because I create the CloudFront distribution for the richardcuicks3sample bucket, so don't need include this bucket name in the url. After I changed the url, the signed url works well.

Title: AWS cannot signed CloudFront urls

Body:
Excepted: I want to get signed urls with my AWS CloudFront url.

What I have done: I have created a AWS CloudFront instence and enabled Restrict Viewer Access function, Trusted Signers is Self.

Below is the php code I want to sign the url

function getSignedURL()
{
    $resource = 'http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp';
    $timeout = 300;

    //This comes from key pair you generated for cloudfront
    $keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";

    $expires = time() + $timeout; //Time out in seconds
    $json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';

    //Read Cloudfront Private Key Pair
    $fp=fopen("private_key.pem","r");
    $priv_key=fread($fp,8192);
    fclose($fp);

    //Create the private key
    $key = openssl_get_privatekey($priv_key);
    if(!$key)
    {
            echo "
Failed to load private key!
";
            return;
    }

    //Sign the policy with the private key
    if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
    {
            echo '
Failed to sign policy: '.openssl_error_string().'
';
            return;
    }

    //Create url safe signed policy
    $base64_signed_policy = base64_encode($signed_policy);
    $signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

    //Construct the URL
    $url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

    return $url;
}

For $keyPairId and private_key.pem, I logged in my root account and generated this two variables in Security Credentials->CloudFront Key Pairs section.

If I access http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp on browser directly. It will response like

<Error>
  MissingKey
  <Message>
    Missing Key-Pair-Id query parameter or cookie value
  </Message>
</Error>

After I run the function, I got a long signed url, parse the url on chrome browser, it will response like

<Error>
  InvalidKey
  <Message>Unknown Key</Message>
</Error>

Question: I have search AWS document and google much time about this, Could anyone tell me why this happened or if I miss something? Thanks in advance!


问:
Python Script runs fine manually but errors out when I run with Cronjob
I have a Python Script below that will just run hostname on 4 different hosts and then it will save it to a file. It then will open that file and save these each line or output into a variable which the program will use later. It works fine when I run it manually although everytime I use cronjob I am getting an error.

Note: the whole script is obviously not here if you wondering how I can SSH into these hosts just by the below lines. But the script is failing at the part that I have put below.

Python Script:

```<code>#! /usr/bin/python

import os

hostname=['a','b','c','d']

for i in hostname:

    os.system('hostname >> hostlist.txt')

data = open('hostlist.txt')
hosta, hostb, hostc, hostd = data.read().splitlines()
</code>```

Error:

```<code>ValueError: too many values to unpack
</code>```

Cronjob looks like:

```<code>00 14 * * * python /tmp/hostname.py &> /tmp/hostnamerror.log
</code>```

Update:::

Ok I am pretty sure I know the problem after more troubleshooting. It seems that when I run it with Cronjob that it is not creating the file hostlist.txt, although if I ran it manually then it does create this file. So in the Cronjob it opens hostlist.txt as a new file with no variables hence giving me the error message. Does anyone have any idea why running the Python Script as a Cronjob would cause the redirect in the first os.system command not to create a append and create a file?

答:
Interesting and fun.

Have you checked that the file hostlist.txt isn't exceeding 4 values?

The script

I've copied your script and experienced this when running on my host:

```<code>user@DESKTOP-RR909JI ~
$ python file.py
Traceback (most recent call last):
  File "file.py", line 12, in <module>
    hosta, hostb, hostc, hostd = data.read().splitlines()
ValueError: too many values to unpack
</code>```

That happened when the file had more than 4 lines (since you're appending with >> that file will grow all the time) If I had less than 4 values I would receive the error:

```<code>ValueError: need more than 3 values to unpack
</code>```

To avoid that problem I've modified your script by defining a number of hosts, validating that the file isn't empty and finally only reading the amount of lines I need which is the number of hosts I've defined.

```<code>#! /usr/bin/python

import os

#---- define the amount of hosts
hosts = 4

for i in range(0, hosts) :
        os.system('hostname >> hostlist.txt')

#---- check if the file isn't empty
if os.stat("hostlist.txt").st_size == 0 :
    print 'you need values in that file'
else :
    with open("hostlist.txt") as myfile:
        # only read lines up to the number of hosts
        hosta, hostb, hostc, hostd = [next(myfile) for x in xrange(hosts)]

        print 'this is variable hosta: ' +hosta
        print 'this is variable hostb: ' +hostb
        print 'this is variable hostc: ' +hostc
        print 'this is variable hostd: ' +hostd
</code>```

I got some inspiration from here, here and here to create the script.

Here's my output:

```<code>user@DESKTOP-RR909JI ~
$ python file.py
this is variable hosta: DESKTOP-RR909JI

this is variable hostb: DESKTOP-RR909JI

this is variable hostc: DESKTOP-RR909JI

this is variable hostd: DESKTOP-RR909JI

$ cat hostlist.txt
DESKTOP-RR909JI
DESKTOP-RR909JI
DESKTOP-RR909JI
DESKTOP-RR909JI
</code>```

The cron job

Are you using root to run that task? Seems like you're adding the job in /etc/crontab* and not using crontab -e because you aren't defining a user.

It could to be related to the user somehow, try to add a different type of crontab job specifying the user like this:

crontab -u  -e

This will open the crontab for the specified user (use the account you said to be working when running manually the script).

Be carefull, crontab -e requires explicitly a user to run tasks while /etc/crontab doesn't that's why the amount of columns are different between both options.

Body:
I have a Python Script below that will just run hostname on 4 different hosts and then it will save it to a file. It then will open that file and save these each line or output into a variable which the program will use later. It works fine when I run it manually although everytime I use cronjob I am getting an error.

Note: the whole script is obviously not here if you wondering how I can SSH into these hosts just by the below lines. But the script is failing at the part that I have put below.

Python Script:

#! /usr/bin/python

import os

hostname=['a','b','c','d']

for i in hostname:

    os.system('hostname >> hostlist.txt')

data = open('hostlist.txt')
hosta, hostb, hostc, hostd = data.read().splitlines()

Error:

ValueError: too many values to unpack

Cronjob looks like:

00 14 * * * python /tmp/hostname.py &> /tmp/hostnamerror.log

Update:::

Ok I am pretty sure I know the problem after more troubleshooting. It seems that when I run it with Cronjob that it is not creating the file hostlist.txt, although if I ran it manually then it does create this file. So in the Cronjob it opens hostlist.txt as a new file with no variables hence giving me the error message. Does anyone have any idea why running the Python Script as a Cronjob would cause the redirect in the first os.system command not to create a append and create a file?

Body:
Interesting and fun.

Have you checked that the file hostlist.txt isn't exceeding 4 values?

The script

I've copied your script and experienced this when running on my host:

user@DESKTOP-RR909JI ~
$ python file.py
Traceback (most recent call last):
  File "file.py", line 12, in <module>
    hosta, hostb, hostc, hostd = data.read().splitlines()
ValueError: too many values to unpack

That happened when the file had more than 4 lines (since you're appending with >> that file will grow all the time) If I had less than 4 values I would receive the error:

ValueError: need more than 3 values to unpack

To avoid that problem I've modified your script by defining a number of hosts, validating that the file isn't empty and finally only reading the amount of lines I need which is the number of hosts I've defined.

#! /usr/bin/python

import os

#---- define the amount of hosts
hosts = 4

for i in range(0, hosts) :
        os.system('hostname >> hostlist.txt')

#---- check if the file isn't empty
if os.stat("hostlist.txt").st_size == 0 :
    print 'you need values in that file'
else :
    with open("hostlist.txt") as myfile:
        # only read lines up to the number of hosts
        hosta, hostb, hostc, hostd = [next(myfile) for x in xrange(hosts)]

        print 'this is variable hosta: ' +hosta
        print 'this is variable hostb: ' +hostb
        print 'this is variable hostc: ' +hostc
        print 'this is variable hostd: ' +hostd

I got some inspiration from here, here and here to create the script.

Here's my output:

user@DESKTOP-RR909JI ~
$ python file.py
this is variable hosta: DESKTOP-RR909JI

this is variable hostb: DESKTOP-RR909JI

this is variable hostc: DESKTOP-RR909JI

this is variable hostd: DESKTOP-RR909JI

$ cat hostlist.txt
DESKTOP-RR909JI
DESKTOP-RR909JI
DESKTOP-RR909JI
DESKTOP-RR909JI

The cron job

Are you using root to run that task? Seems like you're adding the job in /etc/crontab* and not using crontab -e because you aren't defining a user.

It could to be related to the user somehow, try to add a different type of crontab job specifying the user like this:

crontab -u  -e

This will open the crontab for the specified user (use the account you said to be working when running manually the script).

Be carefull, crontab -e requires explicitly a user to run tasks while /etc/crontab doesn't that's why the amount of columns are different between both options.


问:
Azure Automation RunBook Download File from Blob To VM
Is there a way to use Azure Automation to download a file from azure storage? I can currently connect to the VM using templates from the gallery to create files/folder but how would I download a file from storage?

I am currently trying to use Get-AzureStorageBlob command from Invoke-command -ScriptBlock

答:
If you want to do this, based on my experience, you need do the following steps.

1.Install Azure PowerShell on your target VM.

2.Enable Winrm on your VM, you need open port 5986 on Windows Firewall and Azure NSG. You also need configuration certificate on your VM. You could check this blog that step by step to enable winrm on Azure VM.

Note: You should enable winrm listening on https, if you enable it on http, you could not winrm your VM on runbook script.

3.Login to your Azure subscription in runbook, you could refer to this link about this.

4.Use New-PSSession to login your VM in runbook and execute your PowerShell cmlet. You could check my answer about this.


问:
Initialize static string (either C-type or std::string) with respect to Google C++ Style Guide
As per Google C++ Style Guide, section "Static and Global Variables" claims that: "As a result we only allow static variables to contain POD data. This rule completely disallows std::vector (use C arrays instead), or string (use const char [])." Suppose that my program need some static strings that are stored in a configuration file and will be loaded at runtime. Then how would it be possible to load strings into a const char[]?

答:
You will have to specify the length of the string at compile time. You will need to know the maximum length that a string can be before execution.

Given the length:

```<code>const std::size_t len = 2048;   // can store 2047 characters with null-terminating '\0'
</code>```

You can do this in c style

```<code>char buffer[len];
</code>```

Or better yet, use std::array

```<code>#include <array>
std::array<char,len> buffer;
</code>```

Then open your file into an ifstream, and parse the data appropriately.

Body:
You will have to specify the length of the string at compile time. You will need to know the maximum length that a string can be before execution.

Given the length:

const std::size_t len = 2048;   // can store 2047 characters with null-terminating '\0'

You can do this in c style

char buffer[len];

Or better yet, use std::array

#include <array>
std::array<char,len> buffer;

Then open your file into an ifstream, and parse the data appropriately.


问:
Google api library install error, due to guzzle has been installed previous
I get the following error when I install google-api-client, previously I was installed guzzle6 due to project need. Now I'm trying to merge two project in one.

```<code>Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for google/apiclient 2.0 -> satisfiable by google/apiclient[v2.0.0].
    - google/apiclient v2.0.0 requires google/auth 0.8 -> satisfiable by google/auth[v0.8].
    - Conclusion: don't install guzzlehttp/psr7 1.3.1
    - google/auth v0.8 requires guzzlehttp/psr7 1.2.* -> satisfiable by guzzlehttp/psr7[1.2.0, 1.2.1, 1.2.2, 1.2.3].
    - Can only install one of: guzzlehttp/psr7[1.2.0, 1.3.1].
    - Can only install one of: guzzlehttp/psr7[1.2.1, 1.3.1].
    - Can only install one of: guzzlehttp/psr7[1.2.2, 1.3.1].
    - Can only install one of: guzzlehttp/psr7[1.2.3, 1.3.1].
    - Installation request for guzzlehttp/psr7 (locked at 1.3.1) -> satisfiable by guzzlehttp/psr7[1.3.1].

Installation failed, reverting ./composer.json to its original content.
</code>```

答:
Try to run:

```<code>composer require google/apiclient:2.1.2
</code>```

instead of composer require google/apiclient:^2.0.

Body:
I get the following error when I install google-api-client, previously I was installed guzzle6 due to project need. Now I'm trying to merge two project in one.

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for google/apiclient 2.0 -> satisfiable by google/apiclient[v2.0.0].
    - google/apiclient v2.0.0 requires google/auth 0.8 -> satisfiable by google/auth[v0.8].
    - Conclusion: don't install guzzlehttp/psr7 1.3.1
    - google/auth v0.8 requires guzzlehttp/psr7 1.2.* -> satisfiable by guzzlehttp/psr7[1.2.0, 1.2.1, 1.2.2, 1.2.3].
    - Can only install one of: guzzlehttp/psr7[1.2.0, 1.3.1].
    - Can only install one of: guzzlehttp/psr7[1.2.1, 1.3.1].
    - Can only install one of: guzzlehttp/psr7[1.2.2, 1.3.1].
    - Can only install one of: guzzlehttp/psr7[1.2.3, 1.3.1].
    - Installation request for guzzlehttp/psr7 (locked at 1.3.1) -> satisfiable by guzzlehttp/psr7[1.3.1].

Installation failed, reverting ./composer.json to its original content.

Body:
Try to run:

composer require google/apiclient:2.1.2

instead of composer require google/apiclient:^2.0.


问:
keras: Smooth L1 loss
Try to customize loss function(smooth L1 loss) in keras like below

ValueError: Shape must be rank 0 but is rank 5 for 'cond/Switch' (op: 'Switch') with input shapes: [?,24,24,24,?], [?,24,24,24,?].

```<code>from keras import backend as K
import numpy as np

def smooth_L1_loss(y_true, y_pred):
    THRESHOLD = K.variable(1.0)
    mae = K.abs(y_true-y_pred)
    flag = K.greater(mae, THRESHOLD)
    loss = K.mean(K.switch(flag, (mae - 0.5), K.pow(mae, 2)), axis=-1)
    return loss
</code>```

答:
```<code>def smoothL1(y_true, y_pred):
    x = K.abs(y_true - y_pred)
    if K._BACKEND == 'tensorflow':
        import tensorflow as tf
        x = tf.where(x < HUBER_DELTA, 0.5 * x ** 2, HUBER_DELTA * (x - 0.5 * HUBER_DELTA))
        return  K.sum(x)
</code>```

Title: keras: Smooth L1 loss

Body:
Try to customize loss function(smooth L1 loss) in keras like below

ValueError: Shape must be rank 0 but is rank 5 for 'cond/Switch' (op: 'Switch') with input shapes: [?,24,24,24,?], [?,24,24,24,?].

from keras import backend as K
import numpy as np

def smooth_L1_loss(y_true, y_pred):
    THRESHOLD = K.variable(1.0)
    mae = K.abs(y_true-y_pred)
    flag = K.greater(mae, THRESHOLD)
    loss = K.mean(K.switch(flag, (mae - 0.5), K.pow(mae, 2)), axis=-1)
    return loss


问:
Username in HTTP Header for SSO
I am looking to add single sign on (SSO) to one of my web applications. I don't want anything heavy at the moment, I just want to know the userId of the logged in user, without the need for them to enter a username.

The web app is an internal application, so I can guarantee they are coming from a Windows PC etc.

I have looked at jCIFS, but this doesn't seem to be supported any more, and recommends a commercial product.

I have also looked at WAFFLE, but I am building SSO for a playframework application, which does not use a Servlet stack, so I can't make use of the SecurityFilter. I have tried to make sense of the WindowsLoginModule, but couldn't really understand what I had to do to implement it.

Is it possible to just get the username from the HTTP header, or does it require some negotiation first before it will post the header?

答:
You want the windows user to automagically login to your intranet webapp. So the user accounts would sit in an active directory and the usual microsoft way would be to use a protocol like NTML oder Kerberos. Applications are generally advised not to use NTLM, although there are enterprises still using NTML (and jCIFS) for SSO.

A quick search on Kerberos and Java showed this article. It seems to depend on the  Java EE stack (JAAS).

For a more stripped down approach: Usually, you cannot sent the username in a http request in a portable way. With ActivX you could do:

```<code>var wshshell=new ActiveXObject("wscript.shell");
var username=wshshell.ExpandEnvironmentStrings("%username%");
</code>```

On the server side, you can parse the http header and extract the username with your technology of choice.

Well, security doesn't matter in your playframework application?
Why don't you use long-living cookies?

Hope it helps!

ContentLicense: CC BY-SA 2.5

Title: Username in HTTP Header for SSO

Body:
You want the windows user to automagically login to your intranet webapp. So the user accounts would sit in an active directory and the usual microsoft way would be to use a protocol like NTML oder Kerberos. Applications are generally advised not to use NTLM, although there are enterprises still using NTML (and jCIFS) for SSO.

A quick search on Kerberos and Java showed this article. It seems to depend on the  Java EE stack (JAAS).

For a more stripped down approach: Usually, you cannot sent the username in a http request in a portable way. With ActivX you could do:

var wshshell=new ActiveXObject("wscript.shell");
var username=wshshell.ExpandEnvironmentStrings("%username%");

On the server side, you can parse the http header and extract the username with your technology of choice.

Well, security doesn't matter in your playframework application?
Why don't you use long-living cookies?

Hope it helps!


问:
ILI9340/41 cheap 2.4" LCD display SPI - can't read from the controller
In one of my projects I use the cheap 2.4" 320x240 TFT display with a ILI9340/41 controller. It works quite good, taking into consideration the price, and I do not have any problems when I display something. But I can’t read anything. I think that it uses 4 wire SPI

But unfortunately any read attempt is unsuccessful. On the first dummy write, I see some strange activity on the MISO line and MISO is driven high.

```<code>void LCD_SendCommand(SPI_TypeDef * volatile SPIx, int command)
{
    ReSetBit(CS_PORT,CS);
    ReSetBit(DC_PORT,DC);
    while(!(SPIx -> SR & SPI_SR_TXE));
        *(volatile uint8_t *)&SPIx -> DR = (uint8_t)command;
    while(!(SPIx -> SR & SPI_SR_TXE));
    while(SPIx -> SR & SPI_SR_BSY);
    SetBit(CS_PORT,CS);

}

void LCD_SendPar(SPI_TypeDef * volatile SPIx, int par)
{
    ReSetBit(CS_PORT,CS);
    SetBit(DC_PORT,DC);
    *(volatile uint8_t *)&(SPIx -> DR) = (uint8_t)(par);
    while(!(SPIx -> SR & SPI_SR_TXE));
    while(SPIx -> SR & SPI_SR_BSY);
    SetBit(CS_PORT,CS);
}
</code>```

Maybe someone knows where the problem is. I have tried literally everything.

答:
From your code it looks like you only ever send one byte and then de-assert CS again. I suspect that's where you run into trouble.

Page 35 of the datasheet says that CS can be deasserted between command and parameter for write cycles. Read cycles don't explicitly allow it. Page 38 of the datasheet shows read cycles without deasserting CS in-between.

Also notice that for reads other than 8-bit a dummy clock cycle is needed. This might mean you need to manually generate the dummy clock cycle as the stm32 family in general only has 8-bit and 16-bit SPI communication. Maybe you can cheat and just read 3/4 bytes and lose the last bit and have the value shifted by one bit. Another idea might be to use a USART and switch between 8-bit and 9-bit synchronous modes. You'd have to adjust the Endianness of commands/data then, though.

ContentLicense: CC BY-SA 4.0

Body:
In one of my projects I use the cheap 2.4" 320x240 TFT display with a ILI9340/41 controller. It works quite good, taking into consideration the price, and I do not have any problems when I display something. But I can’t read anything. I think that it uses 4 wire SPI

But unfortunately any read attempt is unsuccessful. On the first dummy write, I see some strange activity on the MISO line and MISO is driven high.

void LCD_SendCommand(SPI_TypeDef * volatile SPIx, int command)
{
    ReSetBit(CS_PORT,CS);
    ReSetBit(DC_PORT,DC);
    while(!(SPIx -> SR & SPI_SR_TXE));
        *(volatile uint8_t *)&SPIx -> DR = (uint8_t)command;
    while(!(SPIx -> SR & SPI_SR_TXE));
    while(SPIx -> SR & SPI_SR_BSY);
    SetBit(CS_PORT,CS);

}

void LCD_SendPar(SPI_TypeDef * volatile SPIx, int par)
{
    ReSetBit(CS_PORT,CS);
    SetBit(DC_PORT,DC);
    *(volatile uint8_t *)&(SPIx -> DR) = (uint8_t)(par);
    while(!(SPIx -> SR & SPI_SR_TXE));
    while(SPIx -> SR & SPI_SR_BSY);
    SetBit(CS_PORT,CS);
}

Maybe someone knows where the problem is. I have tried literally everything.


答:
The fact that you have a string stored in a configuration file has NOTHING to do on how you're going to load it. You can load the data to const char[] or to an std::string or anything else, depending on what's convenient for you at your specific case.

The rule is just about not allowing non-POD global/static variables... that's it.

Title: Initialize static string (either C-type or std::string) with respect to Google C++ Style Guide

Body: As per Google C++ Style Guide, section "Static and Global Variables" claims that: "As a result we only allow static variables to contain POD data. This rule completely disallows std::vector (use C arrays instead), or string (use const char [])." Suppose that my program need some static strings that are stored in a configuration file and will be loaded at runtime. Then how would it be possible to load strings into a const char[]?


问:
how to receive strings from user to receive empty string and print them in c
how to receive strings from user to the empty string in c
receive the string and put into an array and then print it.

```<code>int main() {
    int i=0;
    char st[LEN];
    char ch;

    while(st[0]!='\0') {
        i=0;
        printf("Enter name of student:");

        while(ch!='\n') {
            ch=getchar();
            st[i]=ch;
            i++;
        }
    }
}
</code>```

答:
sample code</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define LEN 32

typedef struct student {
    char *name;
} Student;

void atEnd(Student *s, int n, const char *message, int exit_code){
    for(int i = 0; i < n; ++i){
        free(s[i].name);
    }
    free(s);
    fputs(message, stderr);
    exit(exit_code);
}

int main(void) {
    Student *students = NULL;
    int n = 0;//number of students

    while(true){
        char st[LEN];
        int i, ch;

        printf("Enter name of student:");

        for(i = 0; (ch = getchar())!= EOF && ch != '\n' && i < LEN-1; ++i){
            st[i]=ch;
        }
        if(i == 0)
            break;
        else if(i == LEN-1 && ch != '\n'){
            char *mes =
                "Your name is longer than the programmer assumes.\n"
                "Please tell the programmer to change the program.\n"
            ;
            atEnd(students, n, mes, EXIT_FAILURE);
        }
        st[i] = 0;
        Student *temp = realloc(students, (n+1)*sizeof(*students));
        if(!temp){
            atEnd(students, n, "realloc failed.\n", EXIT_FAILURE);
        }
        students = temp;
        if(NULL == (students[n++].name = malloc(strlen(st)+1))){
            atEnd(students, n, "malloc failed.\n", EXIT_FAILURE);
        }
        strcpy(students[n-1].name, st);
    }

    for(int i = 0; i < n; ++i){
        puts(students[i].name);
    }
    atEnd(students, n, "", EXIT_SUCCESS);
}
</code>```

Body:
how to receive strings from user to the empty string in c
receive the string and put into an array and then print it.

int main() {
    int i=0;
    char st[LEN];
    char ch;

    while(st[0]!='\0') {
        i=0;
        printf("Enter name of student:");

        while(ch!='\n') {
            ch=getchar();
            st[i]=ch;
            i++;
        }
    }
}

Body:
sample code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define LEN 32

typedef struct student {
    char *name;
} Student;

void atEnd(Student *s, int n, const char *message, int exit_code){
    for(int i = 0; i < n; ++i){
        free(s[i].name);
    }
    free(s);
    fputs(message, stderr);
    exit(exit_code);
}

int main(void) {
    Student *students = NULL;
    int n = 0;//number of students

    while(true){
        char st[LEN];
        int i, ch;

        printf("Enter name of student:");

        for(i = 0; (ch = getchar())!= EOF && ch != '\n' && i < LEN-1; ++i){
            st[i]=ch;
        }
        if(i == 0)
            break;
        else if(i == LEN-1 && ch != '\n'){
            char *mes =
                "Your name is longer than the programmer assumes.\n"
                "Please tell the programmer to change the program.\n"
            ;
            atEnd(students, n, mes, EXIT_FAILURE);
        }
        st[i] = 0;
        Student *temp = realloc(students, (n+1)*sizeof(*students));
        if(!temp){
            atEnd(students, n, "realloc failed.\n", EXIT_FAILURE);
        }
        students = temp;
        if(NULL == (students[n++].name = malloc(strlen(st)+1))){
            atEnd(students, n, "malloc failed.\n", EXIT_FAILURE);
        }
        strcpy(students[n-1].name, st);
    }

    for(int i = 0; i < n; ++i){
        puts(students[i].name);
    }
    atEnd(students, n, "", EXIT_SUCCESS);
}


问:
Send email using "on behalf of" using apache common Email
I want to send email from my application by adding "on behalf of" address. Currently I am using apache common Email to send email and it seems I couldn't specify sender in there. As I can see email headers I need to set different values for sender and from to show email receive as "on behalf of" in the mail client.

Can anyone please help me to do this using java email client or can I achieve this using same apache common client? Solution needs to be work with most of common email clients like outlook, gmail etc..

答:
As per link

you can do

```<code> msg.addHeader("Sender", "My Friend <xxxxxx@xxxxx.com>");
</code>```

Body:
As per link

you can do

 msg.addHeader("Sender", "My Friend <xxxxxx@xxxxx.com>");


问:
why the Value is nil although i created a new variable for the model
I am working on a ruby on rails project and I am new to it. I have created a model named Category and added properties attr_accessor :name in it.

Then to add a new Category to the database I wrote in rails console
category = Category.new(:name => "GAMES").

After writing this I still get ("Category id = nil, name:nil..").

Then after that I did category.save the id number changes but the name field remains nil.

Well the code goes like this:

```<code>rails g model category name:string (in git hub)
</code>```

Then in the ruby file

```<code>Class Category > ApplicationRecord
  attr_accessor :name
  has_many :posts
end
</code>```

Then back to Github:

```<code>category = Category.new(:name => "Games")
category.save
</code>```

The value of name remains nil after doing this.
Why is this happening. I am using Heroku git and O didnt commit and push the models after I created it. Is it because of that? or are there some other reasons?.

Please help Thank you

答: Remove attr_accessor :name as it overrides ActiveRecord default behavior.

Body:
I am working on a ruby on rails project and I am new to it. I have created a model named Category and added properties attr_accessor :name in it.

Then to add a new Category to the database I wrote in rails console
category = Category.new(:name => "GAMES").

After writing this I still get ("Category id = nil, name:nil..").

Then after that I did category.save the id number changes but the name field remains nil.

Well the code goes like this:

rails g model category name:string (in git hub)

Then in the ruby file

Class Category > ApplicationRecord
  attr_accessor :name
  has_many :posts
end

Then back to Github:

category = Category.new(:name => "Games")
category.save

The value of name remains nil after doing this.
Why is this happening. I am using Heroku git and O didnt commit and push the models after I created it. Is it because of that? or are there some other reasons?.

Please help Thank you


答:
Ignoring the merits of Google's C++ style guide, you would presumably store it in a const char* variable which gets its pointer via dynamic allocation:

```<code>static const char *my_static_string = nullptr;

...

void load_static_string()
{
  if(!my_static_string)
  {
    std::string str = //Read string from file.
    my_static_string = new char[str.size() + 1];
    strncpy(my_static_string, str.data(), str.size() + 1);
  }
}
</code>```

Body:
Ignoring the merits of Google's C++ style guide, you would presumably store it in a const char* variable which gets its pointer via dynamic allocation:

static const char *my_static_string = nullptr;

...

void load_static_string()
{
  if(!my_static_string)
  {
    std::string str = //Read string from file.
    my_static_string = new char[str.size() + 1];
    strncpy(my_static_string, str.data(), str.size() + 1);
  }
}


问:
I want to open a program by JavaScript on the clients computer? (WScript.shell)
I tried to open a program using this code:

```<code><head>
<title></title>
<script language="javascript" type="text/javascript">
    function run() {
        var shell = new ActiveXObject("WScript.shell");
        if (shell) {
            shell.run('"C:\\Program Files (x86)\\BitTorrent\\BitTorrent.exe"', 1);
        }
        else
        { alert("BitTorrent is not installed on your system."); }
    }
</script>
</head>
<body onload="run()">

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

But it doesn't work.
Any help, please?

答:
Why would you want to open BitTorrent anyways? I believe you can achieve the desired effect using magnet links

PD: Check their developers page

Update: I'm not sure if this is "legal" here, or considered "spam", if it easy please remove it, but here's a link to a site that implements magnet links to achieve what I think you might want to be doing: eztv.it. Check their

Body:
I tried to open a program using this code:

<title></title>

But it doesn't work.
Any help, please?


问:
VB.NET Object with custom name to store property?
I'm not familiar with the type of structure or whatever I need to use to achieve this, but I know that there is one.

I'm trying to make it so that I can reference things something like this:

racerlist(x).compatibilityArr.john.CleatScore

instead of what I have to do now:

racerlist(x).compatibilityArr.CleatScoreArr(y).name/.score

So essentially, I want to add items to the compatibilityarr (will probably have to change to a list which is fine) and be able to reference the racer as their own name, instead of by using an index.

答:
As @Codexer mentioned, I used a dictionary to achieve this.

In my list of Racers (RacerList), I have RacerCompatibility, which I created similar to below:

```<code>Public RacerCompatibility As New Dictionary(Of String, Compatibility)
</code>```

Compatibility is created like:

```<code>Public Class Compatibility
    Public Cleat As Boolean
    Public Skill As Integer
    Public Height As Integer
End Class
</code>```

So now I can access the compatibility of a racer inside the list like:

RacerList(x).RacerCompatibility.Item("John")

Body:
As @Codexer mentioned, I used a dictionary to achieve this.

In my list of Racers (RacerList), I have RacerCompatibility, which I created similar to below:

Public RacerCompatibility As New Dictionary(Of String, Compatibility)

Compatibility is created like:

Public Class Compatibility
    Public Cleat As Boolean
    Public Skill As Integer
    Public Height As Integer
End Class

So now I can access the compatibility of a racer inside the list like:

RacerList(x).RacerCompatibility.Item("John")


问:
How do I check if a column is empty or null in MySQL?
I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?</p>

```<code>(e.g. null or '' or '  ' or '      ' and ...)
</code>```

答:
```<code>SELECT column_name FROM table_name WHERE column_name IN (NULL, '')
</code>```

Body:
I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?

(e.g. null or '' or '  ' or '      ' and ...)


问:
"git reset --hard HEAD" in master branch deleted unstaged changes in local branch
I have some local changes in master branch which I merged into local branch.

```<code>local>git merge master
</code>```

After this I wanted a clean master repository so I went to master and did git reset head.

```<code>local>git checkout master
master> git reset --hard HEAD
</code>```

Then I went back to local branch and noticed that all my unstaged changes in local has been lost. Why is it so?

答:
When you switched from local to master via git checkout master, your changes in the working directory remained intact as they were.  Except now you were on the master branch.  When you did:

```<code>git reset --hard HEAD
</code>```

from the master branch, you reset both your working directory and stage to the HEAD commit from the master branch.  Hence, I expect that your working directory changes are lost.

There is one possibility to recover your working directory though.  If you are using a good IDE like IntelliJ, then it may remember the state of the files you modified before Git reset them.  To test this, just look at a file in question and try doing an undo.  If you are lucky, you may get your old changes back this way.

For future reference, if you had working changes on local and you wanted to switch branches in this way, you could have tried doing one of the following

Use git stash to make a stash with your work

Make a temporary commit on local.

If you stash, you can later apply those changes again via git stash apply.  In the case of a temporary commit, when you return to local later on you can complete your work and then amend that temporary commit via:

```<code>git commit --amend
</code>```

Note that under the hood git stash itself makes 2 (sometimes three) commits to persist the working directory and stage on a given branch.

Body:
I have some local changes in master branch which I merged into local branch.

local>git merge master

After this I wanted a clean master repository so I went to master and did git reset head.

local>git checkout master
master> git reset --hard HEAD

Then I went back to local branch and noticed that all my unstaged changes in local has been lost. Why is it so?

Body:
When you switched from local to master via git checkout master, your changes in the working directory remained intact as they were.  Except now you were on the master branch.  When you did:

git reset --hard HEAD

from the master branch, you reset both your working directory and stage to the HEAD commit from the master branch.  Hence, I expect that your working directory changes are lost.

There is one possibility to recover your working directory though.  If you are using a good IDE like IntelliJ, then it may remember the state of the files you modified before Git reset them.  To test this, just look at a file in question and try doing an undo.  If you are lucky, you may get your old changes back this way.

For future reference, if you had working changes on local and you wanted to switch branches in this way, you could have tried doing one of the following

Use git stash to make a stash with your work

Make a temporary commit on local.

If you stash, you can later apply those changes again via git stash apply.  In the case of a temporary commit, when you return to local later on you can complete your work and then amend that temporary commit via:

git commit --amend

Note that under the hood git stash itself makes 2 (sometimes three) commits to persist the working directory and stage on a given branch.


问:
The JS arent working on my Rails project
so, i get that form HTML template:
https://codepen.io/colorlib/pen/rxddKy

but after implemented, it arent working ):

The login View:

```<code><% if flash[:notice] %>
    <div class="notice"><%= flash[:notice] %></div> <% end %>

<div class="login-page">   <div class="form">
    <form class="register-form">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>
      <p class="message">Já é registrado? <a href="#">Login</a></p>
    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>
      <p class="message">Não está registrado <a href="#">Criar uma conta</a></p>
    </form>
    <% if session[:user] %>
        <a href="/login/sair">Sair sessão <%= @user.nome %> </a>
    <% end %>   </div> </div>
</code>```

the login JS:

```<code>$(document).ready(function(){
    $('.message a').click(function(){
        $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    });
});
</code>```

the application.js are with:

```<code>//= require jquery
//= require rails-ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
</code>```

and also, i've been included the gem 'jquery' on my gemfile.

Nothing is happing when i click on the hiperlink "create account":
https://s13.postimg.org/8wzhw1tjr/Screenshot_20170606_224605.png

The CTRL+U on the browser:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>V2Michel</title>
    <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="D47bHUTHcwdqpFlaiDZA3LJr4236jZSSppt9q/FBwK0DPDmc76zIcsfeZSlBMFVJUNxqpFM0u/kM/AfhdNePXw==" />

    <link rel="stylesheet" media="all" href="/assets/fornecedors.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/home.self-d58d58b8f163d83cd8eab0042d14c22afb73ea76b61d7cd85bca19a5d2eee2ce.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/login.self-a6ac1a027c5fa2959e7c8dc0a7e2483f324f0b0833b337aa2c9560848d55a040.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/produtos.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/scaffolds.self-2404dddc0e44f7051d6852d95406118fcf78ccd9df57e634c29cf011ebdb47cb.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/application.self-451e5f1e26abd1c402b1a9c60a4af0e0d30f25a334b1266b6270d9fe17346210.css?body=1" data-turbolinks-track="reload" />
    <script src="/assets/jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/jquery_ujs.self-784a997f6726036b1993eb2217c9cb558e1cbb801c6da88105588c56f13b466a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/rails-ujs.self-56055fe2ac3f3902deb9d12c17b2d725d432162b48fc443946daf7dfbc96d88a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/turbolinks.self-1d1fddf91adc38ac2045c51f0a3e05ca97d07d24d15a4dcbf705009106489e69.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/transition.self-6ad2488465135ab731a045a8ebbe3ea2fc501aed286042496eda1664fdd07ba9.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/alert.self-742145c5bb847aafdadc6e339be795628f8bc25f177e851f03a8c42278eb0312.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/button.self-126ac9bf0e7f2d8568f8da3a00fd5f0fac6eae0946331003370161fbf8d7975e.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/carousel.self-e47323f363ceb3dc0bdbce05e36e709ed428e339833a41140a85cb0af24b8127.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/collapse.self-2eb697f62b587bb786ff940d82dd4be88cdeeaf13ca128e3da3850c5fcaec301.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/dropdown.self-561cca1cbaf67474e01e9536f106bad541594860a6df997004591c1c1957a147.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/modal.self-3e78617ade5663314b7ee0ea10375a5b34d59ffbade44939e3f2a4e4ef2019b3.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/tab.self-5bf7078b682f8b131332eefa46b45fa5eff2eca745fc0d03e2991450888f7c28.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/affix.self-6d6f1a7fc5c8aabf3547fa1b794fab6268f54bc55ad815e55873c71f52513517.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/scrollspy.self-969f3c5f48cdf1e439c7fa1154c13b948715f5c689f87837c0b64521d3b46ef6.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/tooltip.self-05afb177e08f98997ccfc84fa08a215e4b27d48d5fe4d049080675e9dffd8199.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/popover.self-0aa93860b59fe7393f1dd490f54b3cb994f9d6155adffce034d4e14ae361b041.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap-sprockets.self-fbfa5ad7d9aa0afe439ec4ff3883acc4cb92b62cb67c40d674320c9aa1d4642d.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/action_cable.self-be3674a79bb9d13d41d259b2c17fad23aef20946dab3603b9d02374ea795005f.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/cable.self-8484513823f404ed0c0f039f75243bfdede7af7919dda65f2e66391252443ce9.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/fornecedors.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/home.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/login.self-144986660d26a713be586866e762e4bc122ae13576cf144f04c7bf36ee4dcc31.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/produtos.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/application.self-d9c1df0d36a69bf8167ebb20070284ed3c5f931e7f6efe185b0936aad00629a6.js?body=1" data-turbolinks-track="reload"></script>
  </head>

  <body>

<div class="login-page">
  <div class="form">
    <form class="register-form">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>
      <p class="message">Já é registrado? <a href="#">Login</a></p>
    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>
      <p class="message">Não está registrado <a href="#">Criar uma conta</a></p>
    </form>
  </div>
</div>
  </body>
</html>
</code>```

I've deleted the attribute href on the hiperlink "create account" and Works ! lololol

答: Change your non action links from # to "javascript:;"</p>

Body:
so, i get that form HTML template:
https://codepen.io/colorlib/pen/rxddKy

but after implemented, it arent working ):

The login View:

<% if flash[:notice] %>

<%= flash[:notice] %>
 <% end %>

    <form class="register-form">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>

Já é registrado? Login

    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>

Não está registrado Criar uma conta

    </form>
    <% if session[:user] %>
        Sair sessão <%= @user.nome %>
    <% end %>

the login JS:

$(document).ready(function(){
    $('.message a').click(function(){
        $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    });
});

the application.js are with:

//= require jquery
//= require rails-ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

and also, i've been included the gem 'jquery' on my gemfile.

Nothing is happing when i click on the hiperlink "create account":
https://s13.postimg.org/8wzhw1tjr/Screenshot_20170606_224605.png

The CTRL+U on the browser:

<!DOCTYPE html>

    <title>V2Michel</title>
    <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="D47bHUTHcwdqpFlaiDZA3LJr4236jZSSppt9q/FBwK0DPDmc76zIcsfeZSlBMFVJUNxqpFM0u/kM/AfhdNePXw==" />

    <link rel="stylesheet" media="all" href="/assets/fornecedors.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/home.self-d58d58b8f163d83cd8eab0042d14c22afb73ea76b61d7cd85bca19a5d2eee2ce.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/login.self-a6ac1a027c5fa2959e7c8dc0a7e2483f324f0b0833b337aa2c9560848d55a040.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/produtos.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/scaffolds.self-2404dddc0e44f7051d6852d95406118fcf78ccd9df57e634c29cf011ebdb47cb.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/application.self-451e5f1e26abd1c402b1a9c60a4af0e0d30f25a334b1266b6270d9fe17346210.css?body=1" data-turbolinks-track="reload" />

    <form class="register-form">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>

Já é registrado? Login

    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>

Não está registrado Criar uma conta

    </form>

I've deleted the attribute href on the hiperlink "create account" and Works ! lololol


问:
How can I get this value to 2 decimal places?
dub = Application.Sum(wb.Sheets("Sheet1").range("A:A"))

I have tried .numberformat "0.00" and setting the variable type as double with no luck.

Thanks in advance.

答:
Try:

```<code>dub = Round(Application.Sum(wb.Sheets("Sheet1").range("A:A")),2)
</code>```

Round(number, precision) function rounds numbers according to the specified precision.

Hope I have helped you!

Body:
Try:

dub = Round(Application.Sum(wb.Sheets("Sheet1").range("A:A")),2)

Round(number, precision) function rounds numbers according to the specified precision.

Hope I have helped you!


问:
Why does C# disallow readonly local variables?
Having a friendly debate with a co-worker about this.  We have some thoughts about this, but wondering what the SO crowd thinks about this?</p>

答:
I was that coworker and it wasn't friendly! (just kidding)

I would not eliminate the feature because it's better to write short methods. It's a bit like saying you shouldn't use threads because they're hard. Give me the knife and let me be responsible for not cutting myself.

Personally, I wanted another "var" type keyword like "inv" (invarient) or "rvar" to avoid clutter. I've been studying F# as of late and find the immutable thing appealing.

Never knew Java had this.

OwnerDisplayName: Brian Genisio

OwnerDisplayName: Mike


问:
Drone Deploy Export to Amazon S3
Good afternoon, my apologies if this simple question/answer is in the DroneDeploy GitBooks but I am in the initial stages of developing a geoprocessing app for your platform and was wondering, what is the recommended way to auto-export either a processed orthomosaic or DSM from DroneDeploy to an Amazon S3 bucket? In the Exporter examples it seems like the default behavior is to generate a link then send that link via a defined email address - however is there a method to directly send it to Amazon? Is this the "webhook" function as outlined in the documentation?

webhook: {
url: 'http://www.url-to-ping-on-complete.com/any-params-here' // recieve the export document when its complete
}

Thank you,
Matt

答:
At high level here is how you can accomplish this.

When you use the dronedeploy embedded api to start your export you would pass the url to your server in the webhook field.

When the export finishes dronedeploy will POST the the export document to the webhook you specified.

On your server you will select the exportDocument.download_path and download the file.

Once the file is downloaded you can then upload it to aws.

Please note some of the exports can be rather large and it will take considerable time to download and upload the export. If another export happens before you've finished the last export your server might be blocked from accepting the next request. It might be a good idea to use a lambda service such as firebase cloud functions or aws lambda.

Title: Drone Deploy Export to Amazon S3


问:
Crash on shouldAutorotate() method when UIAlertview show in Landscape viewcontroller?
I am working on a app in which I am using only one orientation which is Portrait. This is device orientation setting:

But In my app there is Video player (Custom Player of MPMoviePlayerViewController) which I wanted to show in Landscape Right mode only and It should not be rotated.
This is working fine, I mean this Custom Player is showing in Landscape Right perfectly, but when I am using an UIAlertview then application is crashed on this method:

```<code>- (BOOL)shouldAutorotate {

    return NO;

}
</code>```

These are some other orientation methods :

```<code>- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight; // or Right of course
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
#endif
{
    return UIInterfaceOrientationMaskLandscape;
}
</code>```

I am getting this Error:

```<code> *** Terminating app due to uncaught exception 'UIApplicationInvalidInterfaceOrientation', reason: 'Supported orientations has no common orientation with the application, and [UIAlertController shouldAutorotate] is returning YES'
</code>```

答:
iOS8 :UIAlertController</p>

```<code>#import "UIAlertController+Portrait.h"

@implementation UIAlertController (Portrait)

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

@end
</code>```

Body:
I am working on a app in which I am using only one orientation which is Portrait. This is device orientation setting:

But In my app there is Video player (Custom Player of MPMoviePlayerViewController) which I wanted to show in Landscape Right mode only and It should not be rotated.
This is working fine, I mean this Custom Player is showing in Landscape Right perfectly, but when I am using an UIAlertview then application is crashed on this method:

- (BOOL)shouldAutorotate {

    return NO;

}

These are some other orientation methods :

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight; // or Right of course
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
#endif
{
    return UIInterfaceOrientationMaskLandscape;
}

I am getting this Error:

 *** Terminating app due to uncaught exception 'UIApplicationInvalidInterfaceOrientation', reason: 'Supported orientations has no common orientation with the application, and [UIAlertController shouldAutorotate] is returning YES'

Body:
iOS8 :UIAlertController

#import "UIAlertController+Portrait.h"

@implementation UIAlertController (Portrait)

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

@end


问:
Javascript returning Nan when all the variables are numbers?
My js is returning NaN after "your total is." But I don't have the slightest idea as to why. I think I have all my variables properly declared; is there another reason why this is happening?

Here's my code below. Everything else in the js seems to be working fine.

function book() {
  var city = document.getElementsByName('city').value;
  var hotel = document.getElementsByName('hotel').value;
  var people = document.getElementsByName('numtravel').value;
  var days = document.getElementsByName('numdays').value;
  var wifi;
    if ( document.getElementsByName('wifi').checked = false)
    wifi = 0;
    if ( document.getElementsByName('wifi').checked = true)
    wifi = 10;
  var seat;
    if ( document.getElementsByName('sausage').checked = false) seat = 0;
    if ( document.getElementsByName('sausage').checked = true) seat = 20;
  var meal = document.getElementById('meal').value;
  var price1 = people * meal;
  var price2 = people * seat;
  var price3 = hotel * days;

  document.getElementById("p1").innerHTML = 'Your total is ' + ( city + price3 + wifi + price1 + price2 );

  return false;
}

/*   Total eggs, man. ( ͡° ͜ʖ ͡°) */```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main_content
        {
            background-color: lightgoldenrodyellow;
            overflow: hidden;
            text-align: center;
            border: 5px dotted lightblue
        }

body    {
            background-color: lightgrey;
        }
#content

        {
            background-color: lightgoldenrodyellow;
            overflow: hidden;
            text-align: center;
            border: 5px dotted lightblue
        }</code>```

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Make a Reservation!</title>

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

      Home

      Contact Us

      Make a Reservation

      Join Our Email List

 Make a Reservation!

 First Name: <input type="text" id="first" name="FirstName"/>

 Last Name: <input type="text" id="last" name="LastName"/>

 Where is your arrival city?

 St. Louis ($40) <input type="radio" value="40" name="city" />

 Milwaukee ($20) <input type="radio" value="20" name="city"/>

 Detroit ($35) <input type="radio" value="35" name="city"/>

Hotel Choice?

 Economy ($50/day) <input type="radio" value="50" name='hotel'/>

 Standard ($70/day) <input type="radio" value="70" name='hotel'/>

 Upscale ($120/day) <input type="radio" value="120" name="hotel"/>

 Amount of travelers?

        <select id="travelers" name="numtravel">
          <option value="1"> 1 </option>
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
          <option value="4"> 4 </option>
          <option value="5"> 5 </option>
          <option value="6"> 6 </option>
        </select>

 Amount of days?

        <select id="days" name="numdays">
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
          <option value="4"> 4 </option>
          <option value="5"> 5 </option>
          <option value="6"> 6 </option>
          <option value="7"> 7 </option>
        </select>

 Extra emenities:

 Wifi ($10) <input type="checkbox" value='20' name="wifi">

 Fully-Reclining Seat ($20) <input type="checkbox" name="sausage" value='30'>

 Meal choice?

        <select id="meal" name="meal">
          <option value="0"> None </option>
          <option value="5"> Snack ($5) </option>
          <option value="10"> Full Meal ($10) </option>
        </select>

 Special Requests?

 <textarea name="txtRequests" col="25" rows="5" style='width:300px;resize:vertical;'> </textarea>

 <button onclick="book()">Book your Trip!</button>

```

答:
You have to convert your values to the correct datatype before performing any arithmetic opetraion

```<code>var days = document.getElementById('numdays').value;
</code>```

should be

```<code>var days = parseInt(document.getElementById('numdays').value); //convert to integer
if(isNaN(days)) {
    alert("Days must be a valid number");
    return;
}
</code>```

Do this for all other values

You can then do days * people, etc

Body:
My js is returning NaN after "your total is." But I don't have the slightest idea as to why. I think I have all my variables properly declared; is there another reason why this is happening?

Here's my code below. Everything else in the js seems to be working fine.

function book() {
  var city = document.getElementsByName('city').value;
  var hotel = document.getElementsByName('hotel').value;
  var people = document.getElementsByName('numtravel').value;
  var days = document.getElementsByName('numdays').value;
  var wifi;
    if ( document.getElementsByName('wifi').checked = false)
    wifi = 0;
    if ( document.getElementsByName('wifi').checked = true)
    wifi = 10;
  var seat;
    if ( document.getElementsByName('sausage').checked = false) seat = 0;
    if ( document.getElementsByName('sausage').checked = true) seat = 20;
  var meal = document.getElementById('meal').value;
  var price1 = people * meal;
  var price2 = people * seat;
  var price3 = hotel * days;

  document.getElementById("p1").innerHTML = 'Your total is ' + ( city + price3 + wifi + price1 + price2 );

  return false;
}

/*   Total eggs, man. ( ͡° ͜ʖ ͡°) */

#main_content
        {
            background-color: lightgoldenrodyellow;
            overflow: hidden;
            text-align: center;
            border: 5px dotted lightblue
        }

body    {
            background-color: lightgrey;
        }
#content

        {
            background-color: lightgoldenrodyellow;
            overflow: hidden;
            text-align: center;
            border: 5px dotted lightblue
        }

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Make a Reservation!</title>

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

      Home

      Contact Us

      Make a Reservation

      Join Our Email List

 Make a Reservation!

 First Name: <input type="text" id="first" name="FirstName"/>

 Last Name: <input type="text" id="last" name="LastName"/>

 Where is your arrival city?

 St. Louis ($40) <input type="radio" value="40" name="city" />

 Milwaukee ($20) <input type="radio" value="20" name="city"/>

 Detroit ($35) <input type="radio" value="35" name="city"/>

Hotel Choice?

 Economy ($50/day) <input type="radio" value="50" name='hotel'/>

 Standard ($70/day) <input type="radio" value="70" name='hotel'/>

 Upscale ($120/day) <input type="radio" value="120" name="hotel"/>

 Amount of travelers?

        <select id="travelers" name="numtravel">
          <option value="1"> 1 </option>
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
          <option value="4"> 4 </option>
          <option value="5"> 5 </option>
          <option value="6"> 6 </option>
        </select>

 Amount of days?

        <select id="days" name="numdays">
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
          <option value="4"> 4 </option>
          <option value="5"> 5 </option>
          <option value="6"> 6 </option>
          <option value="7"> 7 </option>
        </select>

 Extra emenities:

 Wifi ($10) <input type="checkbox" value='20' name="wifi">

 Fully-Reclining Seat ($20) <input type="checkbox" name="sausage" value='30'>

 Meal choice?

        <select id="meal" name="meal">
          <option value="0"> None </option>
          <option value="5"> Snack ($5) </option>
          <option value="10"> Full Meal ($10) </option>
        </select>

 Special Requests?

 <textarea name="txtRequests" col="25" rows="5" style='width:300px;resize:vertical;'> </textarea>

 <button onclick="book()">Book your Trip!</button>

Body:
You have to convert your values to the correct datatype before performing any arithmetic opetraion

var days = document.getElementById('numdays').value;

should be

var days = parseInt(document.getElementById('numdays').value); //convert to integer
if(isNaN(days)) {
    alert("Days must be a valid number");
    return;
}

Do this for all other values

You can then do days * people, etc


问:
How to select data to array field?
TableA:

```<code>idA: 1, name: John;
</code>```

TableB:

```<code>idB: 1, product: milk, idA: 1;
idB: 2, product: egg, idA: 1;
</code>```

And I want the finally JSON result look like that:

```<code>[
    {
        "idA": 1,
        "name": "John",
        "TableB": [
            {
                "idB": 1,
                "product": "milk",
                "idA": 1
            },
            {
                "idB": 2,
                "product": "egg",
                "idA": 1
            }
        ]
    }
]
</code>```

I'm using PHP and mySQL.
How's the query should be?
Thanks too much!
I'm so sorry because my English isn't well.

答:
this query will returns to you a single row. I did not test it but it should work just fine.

```<code>select tA.idA,name, group_concat(idB) as cIdB,
 group_concat(product) as cProduct ,
 group_concat(tB.idA) as cIdA
from Table A tA
left join Table B tB on tA.idA = tB.idA group by tB.idA
</code>```

it should returns an array looks like this :

```<code>idA          1
name         Jhon
cIdB         1,2
cProduct     milk,egg
cIdA         1,1
</code>```

Hope it helps.

Title: How to select data to array field?

Body:
TableA:

idA: 1, name: John;

TableB:

idB: 1, product: milk, idA: 1;
idB: 2, product: egg, idA: 1;

And I want the finally JSON result look like that:

[
    {
        "idA": 1,
        "name": "John",
        "TableB": [
            {
                "idB": 1,
                "product": "milk",
                "idA": 1
            },
            {
                "idB": 2,
                "product": "egg",
                "idA": 1
            }
        ]
    }
]

I'm using PHP and mySQL.
How's the query should be?
Thanks too much!
I'm so sorry because my English isn't well.

Body:
this query will returns to you a single row. I did not test it but it should work just fine.

select tA.idA,name, group_concat(idB) as cIdB,
 group_concat(product) as cProduct ,
 group_concat(tB.idA) as cIdA
from Table A tA
left join Table B tB on tA.idA = tB.idA group by tB.idA

it should returns an array looks like this :

idA          1
name         Jhon
cIdB         1,2
cProduct     milk,egg
cIdA         1,1

Hope it helps.


问:
Flattening an array results in maximum memory exceeded error
I have this snippet that flattens a multi-dimensional array.
I want to generate the arrays from the function arguments and use it as my data source. I however runs into Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes).

If I however passes an array parameter to the function and use it as the data source everything works normal, but I want to gather the inputs from the function arguments.

Here is my code:

```<code>public function flatten()
{

    $data = func_get_args();

    return is_array($data) ? array_reduce($data, function($c, $a){
        return array_merge($c, $this->flatten($a));
    }, []) : [$data];

}
</code>```

答:
Your error message means that you have stackoverflow because infinitive calling of recursion function

```<code>public function flatten()
{

    $data = func_get_args();
    // $data is always array after this

    return is_array($data) ? array_reduce($data, function($c, $a){
    // so, you need to move this condition inside anonymous function
        return array_merge($c, $this->flatten($a));
        // there is you are calling function with the same argument, you need to use variadic
    }, []) : [$data];

}
</code>```

Edited function.

```<code><?php

class Foo {

public function flatten()
{

    $data = func_get_args();

    return array_reduce($data, function($c, $a){
        return  array_merge($c, is_array($a) ?$this->flatten(...$a) : [$a]);
    }, []) ;

}

}

var_dump((new Foo())->flatten(1));
var_dump((new Foo())->flatten());
var_dump((new Foo())->flatten(1, [2], [3, [4,5]]));
</code>```

https://3v4l.org/uRUpK

Body:
I have this snippet that flattens a multi-dimensional array.
I want to generate the arrays from the function arguments and use it as my data source. I however runs into Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes).

If I however passes an array parameter to the function and use it as the data source everything works normal, but I want to gather the inputs from the function arguments.

Here is my code:

public function flatten()
{

    $data = func_get_args();

    return is_array($data) ? array_reduce($data, function($c, $a){
        return array_merge($c, $this->flatten($a));
    }, []) : [$data];

}

Body:
Your error message means that you have stackoverflow because infinitive calling of recursion function

public function flatten()
{

    $data = func_get_args();
    // $data is always array after this

    return is_array($data) ? array_reduce($data, function($c, $a){
    // so, you need to move this condition inside anonymous function
        return array_merge($c, $this->flatten($a));
        // there is you are calling function with the same argument, you need to use variadic
    }, []) : [$data];

}

Edited function.

<?php

class Foo {

public function flatten()
{

    $data = func_get_args();

    return array_reduce($data, function($c, $a){
        return  array_merge($c, is_array($a) ?$this->flatten(...$a) : [$a]);
    }, []) ;

}

}

var_dump((new Foo())->flatten(1));
var_dump((new Foo())->flatten());
var_dump((new Foo())->flatten(1, [2], [3, [4,5]]));

https://3v4l.org/uRUpK


问:
Logon failure: unknown user name or bad password while reading from Active directory
I have wrapper web services to read from Active Directory. It works fine on DEV; but on Staging / QA, I am getting this error

Logon failure: unknown user name or bad password.

I am able telnet to the Active directory server on 389 (LDAP port) from both DEV & Staging boxes. I tried with different user accounts who has even read only access to active directory; all worked fine on DEV but not on Staging / QA. Any clues?

答: That could be a lot of things, from improperly escaping the password (it probably has characters that are not in "normal" strings in whatever language you're using) to not including the AD DOMAIN name in the username (DOMAIN\username)</p>


问:
How to access AzureAd ->Users and groups - User settings
I want to access the

Azure Portal -> Azure Active Directory->User Settings

via a powershell commandlet.

Currently I have tried

Get-MsolCompanyInformation

which gives limited data about these settings. Not all settings access (true/false) comes up with this commandlet.

Can someone give the commandlet(s) by which I can get whether these settings are enabled/disabled for a tenant?

答:
For now, there is no command to list those informations in msol powershell module and Azure AD powershell module v2.

As a workaround, we can use role to control those permission.

We can use Azure AD powershell V2 to list roles:Get-AzureADDirectoryRole.
Then we can use this command to list the members of this role: Get-AzureADDirectoryRoleMember.

To create role, we can list the role template with this commmand Get-AzureADDirectoryRoleTemplate

```<code>PS C:\Users> Get-AzureADDirectoryRoleTemplate

ObjectId                             DisplayName                        Description
--------                             -----------                        -----------
729827e3-9c14-49f7-bb1b-9608f156bbb8 Helpdesk Administrator             Helpdesk Administrator has access to perform common helpdesk related tasks.
f023fd81-a637-4b56-95fd-791ac0226033 Service Support Administrator      Service Support Administrator has access to perform common support tasks.
b0f54661-2d74-4c50-afa3-1ec803f12efe Billing Administrator              Billing Administrator has access to perform common billing related tasks.
4ba39ca4-527c-499a-b93d-d9b492c50246 Partner Tier1 Support              Allows ability to perform tier1 support tasks.
e00e864a-17c5-4a4b-9c06-f5b95a8d5bd8 Partner Tier2 Support              Allows ability to perform tier2 support tasks.
88d8e3e3-8f55-4a1e-953a-9b9898b8876b Directory Readers                  Allows access to various read only tasks in the directory.
29232cdf-9323-42fd-ade2-1d097af3e4de Exchange Service Administrator     Exchange Service Administrator.
75941009-915a-4869-abe7-691bff18279e Lync Service Administrator         Lync Service Administrator.
fe930be7-5e62-47db-91af-98c3a49a38b1 User Account Administrator         User Account Administrator has access to perform common user management related tasks.
9360feb5-f418-4baa-8175-e2a00bac4301 Directory Writers                  Allows access read tasks and a subset of write tasks in the directory.
62e90394-69f5-4237-9190-012177145e10 Company Administrator              Company Administrator role has full access to perform any operation in the company scope.
a0b1b346-4d3e-4e8b-98f8-753987be4970 User                               Every user is implicitly considered to be a member of the User Role.
f28a1f50-f6e7-4571-818b-6a12f2af6b6c SharePoint Service Administrator   SharePoint Service Administrator.
d405c6df-0af8-4e3b-95e4-4d06e542189e Device Users                       Device Users
9f06204d-73c1-4d4c-880a-6edb90606fd8 Device Administrators              Device Administrators
9c094953-4995-41c8-84c8-3ebb9b32c93f Device Join                        Device Join
c34f683f-4d5a-4403-affd-6615e00e3a7f Workplace Device Join              Workplace Device Join
17315797-102d-40b4-93e0-432062caca18 Compliance Administrator           Compliance administrator.
d29b2b05-8046-44ba-8758-1e26182fcf32 Directory Synchronization Accounts Directory Synchronization Accounts
2b499bcd-da44-4968-8aec-78e1674fa64d Device Managers                    Allows access to read and edit device properties.
9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3 Application Administrator          Application Administrator role has access to perform common application management related tasks.
cf1c38e5-3621-4004-a7cb-879624dced7c Application Developer              Application Developer role has ability to create single-tenant applications.
5d6b6bb7-de71-4623-b4af-96380a352509 Security Reader                    Security Reader allows ability to read security information and reports.
194ae4cb-b126-40b2-bd5b-6091b380977d Security Administrator             Security Administrator allows ability to read and manage security configuration and reports.
e8611ab8-c189-46e8-94e1-60213ab1f814 Privileged Role Administrator      Privileged Role Administrator has access to perform common role management related tasks.
3a2c62db-5318-420d-8d74-23affee5d9d5 Intune Service Administrator       Intune Service Administrator has full access in the Intune Service.
158c047a-c907-4556-b7ef-446551a6b5f7 Cloud Application Administrator    Cloud Application Administrator has the ability to create applications and update all cloud properties of applications.
5c4f9dcd-47dc-4cf7-8c9a-9e4207cbfc91 Customer LockBox Access Approver   Customer LockBox Access Approver has approval access to user data requests.
44367163-eba1-44c3-98af-f5787879f96a CRM Service Administrator          CRM Service Administrator has full access in the CRM Service.
a9ea8996-122f-4c74-9520-8edcd192826c Power BI Service Administrator     Full access in the Power BI Service.
95e79109-95c0-4d8e-aee3-d01accf2d47b Guest Inviter                      Guest Inviter has access to invite guest users.
b1be1c3e-b65d-4f19-8427-f6fa0d97feb9 Conditional Access Administrator   Allows management of all conditional access capabilities.
</code>```

More information about Azure AD powershell V2, please refer to this link.

Body:
For now, there is no command to list those informations in msol powershell module and Azure AD powershell module v2.

As a workaround, we can use role to control those permission.

We can use Azure AD powershell V2 to list roles:Get-AzureADDirectoryRole.
Then we can use this command to list the members of this role: Get-AzureADDirectoryRoleMember.

To create role, we can list the role template with this commmand Get-AzureADDirectoryRoleTemplate

PS C:\Users> Get-AzureADDirectoryRoleTemplate

ObjectId                             DisplayName                        Description
--------                             -----------                        -----------
729827e3-9c14-49f7-bb1b-9608f156bbb8 Helpdesk Administrator             Helpdesk Administrator has access to perform common helpdesk related tasks.
f023fd81-a637-4b56-95fd-791ac0226033 Service Support Administrator      Service Support Administrator has access to perform common support tasks.
b0f54661-2d74-4c50-afa3-1ec803f12efe Billing Administrator              Billing Administrator has access to perform common billing related tasks.
4ba39ca4-527c-499a-b93d-d9b492c50246 Partner Tier1 Support              Allows ability to perform tier1 support tasks.
e00e864a-17c5-4a4b-9c06-f5b95a8d5bd8 Partner Tier2 Support              Allows ability to perform tier2 support tasks.
88d8e3e3-8f55-4a1e-953a-9b9898b8876b Directory Readers                  Allows access to various read only tasks in the directory.
29232cdf-9323-42fd-ade2-1d097af3e4de Exchange Service Administrator     Exchange Service Administrator.
75941009-915a-4869-abe7-691bff18279e Lync Service Administrator         Lync Service Administrator.
fe930be7-5e62-47db-91af-98c3a49a38b1 User Account Administrator         User Account Administrator has access to perform common user management related tasks.
9360feb5-f418-4baa-8175-e2a00bac4301 Directory Writers                  Allows access read tasks and a subset of write tasks in the directory.
62e90394-69f5-4237-9190-012177145e10 Company Administrator              Company Administrator role has full access to perform any operation in the company scope.
a0b1b346-4d3e-4e8b-98f8-753987be4970 User                               Every user is implicitly considered to be a member of the User Role.
f28a1f50-f6e7-4571-818b-6a12f2af6b6c SharePoint Service Administrator   SharePoint Service Administrator.
d405c6df-0af8-4e3b-95e4-4d06e542189e Device Users                       Device Users
9f06204d-73c1-4d4c-880a-6edb90606fd8 Device Administrators              Device Administrators
9c094953-4995-41c8-84c8-3ebb9b32c93f Device Join                        Device Join
c34f683f-4d5a-4403-affd-6615e00e3a7f Workplace Device Join              Workplace Device Join
17315797-102d-40b4-93e0-432062caca18 Compliance Administrator           Compliance administrator.
d29b2b05-8046-44ba-8758-1e26182fcf32 Directory Synchronization Accounts Directory Synchronization Accounts
2b499bcd-da44-4968-8aec-78e1674fa64d Device Managers                    Allows access to read and edit device properties.
9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3 Application Administrator          Application Administrator role has access to perform common application management related tasks.
cf1c38e5-3621-4004-a7cb-879624dced7c Application Developer              Application Developer role has ability to create single-tenant applications.
5d6b6bb7-de71-4623-b4af-96380a352509 Security Reader                    Security Reader allows ability to read security information and reports.
194ae4cb-b126-40b2-bd5b-6091b380977d Security Administrator             Security Administrator allows ability to read and manage security configuration and reports.
e8611ab8-c189-46e8-94e1-60213ab1f814 Privileged Role Administrator      Privileged Role Administrator has access to perform common role management related tasks.
3a2c62db-5318-420d-8d74-23affee5d9d5 Intune Service Administrator       Intune Service Administrator has full access in the Intune Service.
158c047a-c907-4556-b7ef-446551a6b5f7 Cloud Application Administrator    Cloud Application Administrator has the ability to create applications and update all cloud properties of applications.
5c4f9dcd-47dc-4cf7-8c9a-9e4207cbfc91 Customer LockBox Access Approver   Customer LockBox Access Approver has approval access to user data requests.
44367163-eba1-44c3-98af-f5787879f96a CRM Service Administrator          CRM Service Administrator has full access in the CRM Service.
a9ea8996-122f-4c74-9520-8edcd192826c Power BI Service Administrator     Full access in the Power BI Service.
95e79109-95c0-4d8e-aee3-d01accf2d47b Guest Inviter                      Guest Inviter has access to invite guest users.
b1be1c3e-b65d-4f19-8427-f6fa0d97feb9 Conditional Access Administrator   Allows management of all conditional access capabilities.

More information about Azure AD powershell V2, please refer to this link.


答:
There are three stages in Git,

Unstaged changes (dirty, working code)

Staged changes (clean, commitable code)

Committed, Pushed changes (fully-tested, deployable code)

When you reset, all dirty working code (in Stage 1) will be deleted for no branch takes ownership for that.

If you want to "save" local dirty working copies, try git stash.

A more visual aided way to show the stage of your changes is via git gui.

Title: "git reset --hard HEAD" in master branch deleted unstaged changes in local branch