问:
String matching on a R column
My data frame has a column on which I am trying to run string matching and then update the string upon match.I have tried couple approaches but none seemed to have work. My frame looks like the below. For column "IntNames" row 2, I would like to substitute "clin2|clin3|clin4" with only clin2 and for row3 "clin6|clin7|clin8|clin9|clin10" with only clin6. The idea is to only retain the first element for such values. I appreciate all your help and input on this.  </p>

```<code>DataFrame:

   IntNames                   values1    values2
clin1                           100        10
clin2|clin3|clin4               200         4
clin6|clin7|clin8|clin9|clin10  240         5

This is what I have written:
newIntNames <- ifelse(myFrame$IntNames=="|",myFrame$IntNames[0],myFrame$IntNames)
</code>```

答:
We could do this (assuming that IntNames is a character vector):

```<code>myFrame$IntNames<- unlist(lapply(strsplit(myFrame$IntNames, "[|]"), `[[`, 1))
</code>```

Title: String matching on a R column

Body:
My data frame has a column on which I am trying to run string matching and then update the string upon match.I have tried couple approaches but none seemed to have work. My frame looks like the below. For column "IntNames" row 2, I would like to substitute "clin2|clin3|clin4" with only clin2 and for row3 "clin6|clin7|clin8|clin9|clin10" with only clin6. The idea is to only retain the first element for such values. I appreciate all your help and input on this.

DataFrame:

   IntNames                   values1    values2
clin1                           100        10
clin2|clin3|clin4               200         4
clin6|clin7|clin8|clin9|clin10  240         5

This is what I have written:
newIntNames <- ifelse(myFrame$IntNames=="|",myFrame$IntNames[0],myFrame$IntNames)

Body:
We could do this (assuming that IntNames is a character vector):

myFrame$IntNames<- unlist(lapply(strsplit(myFrame$IntNames, "[|]"), `[[`, 1))


来源: stackexchange

问:
Python requests CAN NOT get cookies
In my case, I need to extract data from a production machine. My co-workers design the following strategy (API) for me.

Login into the application - use cookie to setup your application / scripts;

Access the project home page - lots of projects information in JSON format;

Extract project ID by using the filter and use special API to get the detailed information of each qualified project ...

Here is my code:

```<code>import requests
s = requests.session()
login_data=dict(User='XXXXXX',Password='XXXXXX')
url = 'http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/XXXX-editor-web/spring_security_login'
s.post(url, data=login_data)
r = s.get('http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/XXXX-editor-web/api/projects')
</code>```

I executed the code line by line. After running 's.post(url, data=login_data)' I noticed that though I got 'Response [200]' but the session cookies is empty.

```<code>>>> s.post(url, data=login_data)
<Response [200]>
>>> s.cookies
<RequestsCookieJar[]>
</code>```

After running s.get('...'), I noticed that even I got 'Response [403]', the session cookies is no longer empty.

```<code>>>> s.get('http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/oaqc-editor-web/api/projects')
<Response [403]>
>>> s.cookies.get_dict()
{'AWSELB': '39E1F543067A169F5670C20A97C217D25E0183C29D4C14F38EFC1FC58E993C6F96E88F97B58950E092F4C948A0A99AE42DED20A93E542EFD80F074EB26477729DB0DD1B5469C655062CB6005E3C6F5BDDDCEA57A12', 'JSESSIONID': '61A6DFB9DDDF1BFD7FD4F6B47E7E2B2D'}
</code>```

Then I tried
r = s.get('...', cookies=s.cookies)
but still got 'Response [403]' which means the cookies was not successfully stored and passed into the following request.

Do I make any mistake here?  I searched and found many similar discussions in Stack Overflow but none of them solve my issue. Thanks a lot.

答:
I'm guessing that you're login_data syntax is invalid. You're not providing key-value pairs for the dictionary.

You'll want to provide the login_data as such:

```<code>import requests
s = requests.session()

login_data = {'User':'XXXXX', 'Password': 'XXXXX'} # <----
url = 'http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/XXXX-editor-web/spring_security_login'

s.post(url, data=login_data)
r = s.get('http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/XXXX-editor-web/api/projects')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python requests CAN NOT get cookies

Body:
In my case, I need to extract data from a production machine. My co-workers design the following strategy (API) for me.

Login into the application - use cookie to setup your application / scripts;

Access the project home page - lots of projects information in JSON format;

Extract project ID by using the filter and use special API to get the detailed information of each qualified project ...

Here is my code:

import requests
s = requests.session()
login_data=dict(User='XXXXXX',Password='XXXXXX')
url = 'http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/XXXX-editor-web/spring_security_login'
s.post(url, data=login_data)
r = s.get('http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/XXXX-editor-web/api/projects')

I executed the code line by line. After running 's.post(url, data=login_data)' I noticed that though I got 'Response [200]' but the session cookies is empty.

>>> s.post(url, data=login_data)
<Response [200]>
>>> s.cookies
<RequestsCookieJar[]>

After running s.get('...'), I noticed that even I got 'Response [403]', the session cookies is no longer empty.

>>> s.get('http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/oaqc-editor-web/api/projects')
<Response [403]>
>>> s.cookies.get_dict()
{'AWSELB': '39E1F543067A169F5670C20A97C217D25E0183C29D4C14F38EFC1FC58E993C6F96E88F97B58950E092F4C948A0A99AE42DED20A93E542EFD80F074EB26477729DB0DD1B5469C655062CB6005E3C6F5BDDDCEA57A12', 'JSESSIONID': '61A6DFB9DDDF1BFD7FD4F6B47E7E2B2D'}

Then I tried
r = s.get('...', cookies=s.cookies)
but still got 'Response [403]' which means the cookies was not successfully stored and passed into the following request.

Do I make any mistake here?  I searched and found many similar discussions in Stack Overflow but none of them solve my issue. Thanks a lot.

Body:
I'm guessing that you're login_data syntax is invalid. You're not providing key-value pairs for the dictionary.

You'll want to provide the login_data as such:

import requests
s = requests.session()

login_data = {'User':'XXXXX', 'Password': 'XXXXX'} # <----
url = 'http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/XXXX-editor-web/spring_security_login'

s.post(url, data=login_data)
r = s.get('http://internal-pilot-XXXXXXX-elb-15h4lq2sm46fi-6574XXXXX.us-east-1.elb.amazonaws.com/XXXX-editor-web/api/projects')


问:
mysqli search like only works with 1 parameter
I'm trying to do a mysqli search like query to search based on first and last name. When I type the first and last name into the search, I get no results. However, when I type just the first name or just the last name, I get results.

Here's my code:

```<code><?php
if (isset($_POST['search'])) {
$name = $_POST['search'];
$sql = "SELECT * FROM users WHERE fname LIKE '%$name%' OR lname LIKE '%$name%'";
$res = mysqli_query($conn, $sql);

}
while ($row = mysqli_fetch_assoc($res)) {
    $fname = $row['fname'];
    $lname = $row['lname'];
    $city = $row['city'];
    $state = $row['state'];
    $id = $row['id'];
    $url = '<a href ="profile/?id='.$id.'">';
    if ($id !== ($_SESSION['id'])){
    $pic = "SELECT profilephotopatch FROM users WHERE id = '$id'";
    $res = mysqli_query($conn, $pic);
    $row = mysqli_fetch_assoc($res);
    $picloc = $row['profilephotopatch'];
    $displaypic = '<div id="userphoto"><img src="../'.$picloc. '"style="width: 100%;max-height: 100%"></div>';
    $output = $displaypic. $url. '<div id="name">'. $fname. ' '. $lname. ' '. $city. $state. '</a></div><br>';
 echo ($output);
}
 }
 ?>
</code>```

Thanks in advance for the help!

答:
When you type both firstname and lastname I believe your code will try to find fullname from fname and lname column which of course does not give you result.

For example, you store name 'John Doe' as 'John' in fname and  'Doe' in lname column.

When you are looking with 'John' or 'Doe' you will find it in fname or in lname. But with fullname, both column does not satify criteria and yield no result.

Body:
I'm trying to do a mysqli search like query to search based on first and last name. When I type the first and last name into the search, I get no results. However, when I type just the first name or just the last name, I get results.

Here's my code:

<?php
if (isset($_POST['search'])) {
$name = $_POST['search'];
$sql = "SELECT * FROM users WHERE fname LIKE '%$name%' OR lname LIKE '%$name%'";
$res = mysqli_query($conn, $sql);

}
while ($row = mysqli_fetch_assoc($res)) {
    $fname = $row['fname'];
    $lname = $row['lname'];
    $city = $row['city'];
    $state = $row['state'];
    $id = $row['id'];
    $url = '';
    if ($id !== ($_SESSION['id'])){
    $pic = "SELECT profilephotopatch FROM users WHERE id = '$id'";
    $res = mysqli_query($conn, $pic);
    $row = mysqli_fetch_assoc($res);
    $picloc = $row['profilephotopatch'];
    $displaypic = '

';
    $output = $displaypic. $url. '
'. $fname. ' '. $lname. ' '. $city. $state. '

';
 echo ($output);
}
 }
 ?>

Thanks in advance for the help!


问:
Run immediately then every 4 hours in cron
How do you write a cron job which immediately run, then run on every hour divisible by 4? Say I started the script at 13:25, the job fires up right away, then the next run would be at 16:00, 20:00, 00:00 and so on.</p>

答:
For the first immediate run, just execute the command manually. Then set your cron up like this to have it execute continuously every 4th hour

```<code> 0 */4 * * * yourCommand
</code>```

This will run yourCommand every 4 hours (00:00, 04:00, 08:00......)

Body:
For the first immediate run, just execute the command manually. Then set your cron up like this to have it execute continuously every 4th hour

 0 */4 * * * yourCommand

This will run yourCommand every 4 hours (00:00, 04:00, 08:00......)


问:
Data check between source and the target as per transformation rule
I have two tables one is source and the other is target.

I need to check if the data is properly transformed according to the transformation logic or not.

Here is the source table:EmpIn

```<code>empid year  quarter  amount
5     2007    q1       100
5     2007    q2       200
5     2007    q3       300
5     2007    q3       100
5     2007    q4       50
5     2007    q4       100
5     2007    q4       150
</code>```

Target table after the transformation:EmpOut

```<code>empid   year   quarter   amount    sequence number
 5      2007     q1       100          0
 5      2007     q2       200          0
 5      2007     q3       300          0
 5      2007     q3       400          1
 5      2007     q4       50           0
 5      2007     q4       150          1
 5      2007     q4       300          2
</code>```

Transformation logic is : If there is another entry of amount with respect to same quarter and the same year
                          the amount will be addded to the previous amount and the sequence number will be increased by 1 in the target.

for example in the source table in 2007 q3 we have two amounts the first one is 300 it will go as is to the target with sequence number
of zero
the next entry is a addition to the previous amount which is 400 and the sequence number is incresed by 1.
the same transformation is happening to the fourth quarter also

We(I) need to validate if the data is properly transformed according to this logic to the target table or not.

答:
I guess you can't just validate the transformation algorithm?

Add a field "original_amount" in the destination table

Loop over all rows with sequence no > 0

Subtract the amount from the former row (sequence no - 1) from the current row's amount and update the new field with the result

Update the field with the amount of the same row for sequence no = 0

Compare the two table's amount and amount_original

Like so.

Body:
I have two tables one is source and the other is target.

I need to check if the data is properly transformed according to the transformation logic or not.

Here is the source table:EmpIn

empid year  quarter  amount
5     2007    q1       100
5     2007    q2       200
5     2007    q3       300
5     2007    q3       100
5     2007    q4       50
5     2007    q4       100
5     2007    q4       150

Target table after the transformation:EmpOut

empid   year   quarter   amount    sequence number
 5      2007     q1       100          0
 5      2007     q2       200          0
 5      2007     q3       300          0
 5      2007     q3       400          1
 5      2007     q4       50           0
 5      2007     q4       150          1
 5      2007     q4       300          2

Transformation logic is : If there is another entry of amount with respect to same quarter and the same year
                          the amount will be addded to the previous amount and the sequence number will be increased by 1 in the target.

for example in the source table in 2007 q3 we have two amounts the first one is 300 it will go as is to the target with sequence number
of zero
the next entry is a addition to the previous amount which is 400 and the sequence number is incresed by 1.
the same transformation is happening to the fourth quarter also

We(I) need to validate if the data is properly transformed according to this logic to the target table or not.


问:
iOS 11 - How does one read/parse the NDEF Message from CoreNFC?
I have a bunch of tags that are URL tags that have the content "http://WEBSITE.com". Let's say WEBSITE is youtube so http://youtube.com. When I scan them on Android etc, it keeps the http or https.

I'm trying to scan these same tags using the Core NFC framework. I scan them and I get a bunch of bytes that I convert using NSSString initWithData with UTF8 Encoding. I get back \^Cyoutube.com. I want to get http://youtube.com.

How can I interept the payload to get what I need? If I'm to assume the http in front of the string, how am I supposed to know if it is http or https or even ftp?

Edit 1:

I'm having issues with the below answer code for pure text records. When making a text record for "hello world" I get the following outputs from the console:

2017-06-09 12:45:35.151806-0400 testNFC[2963:190724] Payload string:https://www.enhello world

2017-06-09 12:45:35.154959-0400 testNFC[2963:190724] Payload data:<02656e68 656c6c6f 20776f72 6c64>

To get the string I use

NSString *nfcMessage = [nfcType stringByAppendingString:[[[NSString alloc] initWithData:payload.payload encoding:NSUTF8StringEncoding] substringFromIndex:1]];

nfcType is the return from your function but for the None case I return @"";

I'm expecting to just get hello world.

答:
For this, you will first need to make sure you have properly formatted NDEF tags. You can use an Android phone or one of these reader accessories along with an NDEF writing app.

Implement the following methods:

```<code>- (NSString *)getType:(NSData *)NDEFData {

    NSString *firstByte = [self getFirstByte:NDEFData];

    if ([firstByte isEqualToString:@"00"]) {
        return @"None";
    } else if ([firstByte isEqualToString:@"01"]) {
        return @"http://www.";
    } else if ([firstByte isEqualToString:@"02"]) {
        return @"https://www.";
    } else if ([firstByte isEqualToString:@"03"]) {
        return @"http://";
    } else if ([firstByte isEqualToString:@"04"]) {
        return @"https://";
    } else if ([firstByte isEqualToString:@"05"]) {
        return @"tel:";
    } else if ([firstByte isEqualToString:@"06"]) {
        return @"mailto:";
    } else if ([firstByte isEqualToString:@"07"]) {
        return @"ftp://anonymous:anonymous@";
    } else if ([firstByte isEqualToString:@"08"]) {
        return @"ftp://ftp.";
    } else if ([firstByte isEqualToString:@"09"]) {
        return @"ftps://";
    } else if ([firstByte isEqualToString:@"0A"]) {
        return @"sftp://";
    } else if ([firstByte isEqualToString:@"0B"]) {
        return @"smb://";
    } else if ([firstByte isEqualToString:@"0C"]) {
        return @"nfs://";
    } else if ([firstByte isEqualToString:@"0D"]) {
        return @"ftp://";
    } else if ([firstByte isEqualToString:@"0E"]) {
        return @"dav://";
    } else if ([firstByte isEqualToString:@"0F"]) {
        return @"news:";
    } else if ([firstByte isEqualToString:@"10"]) {
        return @"telnet://";
    } else if ([firstByte isEqualToString:@"11"]) {
        return @"imap:";
    } else if ([firstByte isEqualToString:@"12"]) {
        return @"rtsp://";
    } else if ([firstByte isEqualToString:@"13"]) {
        return @"urn:";
    } else if ([firstByte isEqualToString:@"14"]) {
        return @"pop:";
    } else if ([firstByte isEqualToString:@"15"]) {
        return @"sip:";
    } else if ([firstByte isEqualToString:@"16"]) {
        return @"sips:";
    } else if ([firstByte isEqualToString:@"17"]) {
        return @"tftp:";
    } else if ([firstByte isEqualToString:@"18"]) {
        return @"btspp://";
    } else if ([firstByte isEqualToString:@"19"]) {
        return @"btl2cap://";
    } else if ([firstByte isEqualToString:@"1A"]) {
        return @"btgoep://";
    } else if ([firstByte isEqualToString:@"1B"]) {
        return @"tcpobex://";
    } else if ([firstByte isEqualToString:@"1C"]) {
        return @"irdaobex://";
    } else if ([firstByte isEqualToString:@"1D"]) {
        return @"file://";
    } else if ([firstByte isEqualToString:@"1E"]) {
        return @"urn:epc:id:";
    } else if ([firstByte isEqualToString:@"1F"]) {
        return @"urn:epc:tag:";
    } else if ([firstByte isEqualToString:@"20"]) {
        return @"urn:epc:pat:";
    } else if ([firstByte isEqualToString:@"21"]) {
        return @"urn:epc:raw:";
    } else if ([firstByte isEqualToString:@"22"]) {
        return @"urn:epc:";
    } else if ([firstByte isEqualToString:@"23"]) {
        return @"urn:nfc:";
    }

    return @"";

}

/*!
* gets the the NDEF content
*/
- (NSString *)getNDEFContent:(NSData *)data {
     NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     return [dataString substringFromIndex:2];
}

/*!
 * gets the first byte of the input NSData
 */
- (NSString *)getFirstByte:(NSData *)data {
     return [[self dataToHexString:data] substringToIndex:2];
}

/*!
 * transforms NSData to NSString
 */
- (NSString *)dataToHexString:(NSData *)data;
{
    // get the length of the data
    NSUInteger bytesCount = data.length;
    if (bytesCount) {
        // string with all the Hex characters
        const char *hexChars = "0123456789ABCDEF";
        // put bytes into an array and initialize the response array
        const unsigned char *dataBuffer = data.bytes;
        char *chars = malloc(sizeof(char) * (bytesCount * 2 + 1));
        char *s = chars;
        // go through data bytes making the transformations so a hex will literally translate to a string, so for example 0x0A will translate to "0A"
        for (unsigned i = 0; i < bytesCount; ++i) {
            // get hexChars character at binary AND between the current byte and 0xF0 bitwise to the right by 4 index and assign it to the current chars pointer
            *s++ = hexChars[((*dataBuffer & 0xF0) >> 4)];
            // get hexChars character at binary AND between the current byte and 0x0F index and assign it to the current chars pointer
            *s++ = hexChars[(*dataBuffer & 0x0F)];
            dataBuffer++;
        }
        *s = '\0';
        // chars to string
        NSString *hexString = [NSString stringWithUTF8String:chars];
        free(chars);
        return hexString;
    }
    return @"";
}
</code>```

And call the getType method:

```<code>[self getType:yourNDEFPayloadNSData]
</code>```

I'm assuming that all the methods are in the same class and,

that the payload NSData is NDEF compliant, but I modeled the code based on the NFCNDEFPayload payload

Body:
For this, you will first need to make sure you have properly formatted NDEF tags. You can use an Android phone or one of these reader accessories along with an NDEF writing app.

Implement the following methods:

- (NSString *)getType:(NSData *)NDEFData {

    NSString *firstByte = [self getFirstByte:NDEFData];

    if ([firstByte isEqualToString:@"00"]) {
        return @"None";
    } else if ([firstByte isEqualToString:@"01"]) {
        return @"http://www.";
    } else if ([firstByte isEqualToString:@"02"]) {
        return @"https://www.";
    } else if ([firstByte isEqualToString:@"03"]) {
        return @"http://";
    } else if ([firstByte isEqualToString:@"04"]) {
        return @"https://";
    } else if ([firstByte isEqualToString:@"05"]) {
        return @"tel:";
    } else if ([firstByte isEqualToString:@"06"]) {
        return @"mailto:";
    } else if ([firstByte isEqualToString:@"07"]) {
        return @"ftp://anonymous:anonymous@";
    } else if ([firstByte isEqualToString:@"08"]) {
        return @"ftp://ftp.";
    } else if ([firstByte isEqualToString:@"09"]) {
        return @"ftps://";
    } else if ([firstByte isEqualToString:@"0A"]) {
        return @"sftp://";
    } else if ([firstByte isEqualToString:@"0B"]) {
        return @"smb://";
    } else if ([firstByte isEqualToString:@"0C"]) {
        return @"nfs://";
    } else if ([firstByte isEqualToString:@"0D"]) {
        return @"ftp://";
    } else if ([firstByte isEqualToString:@"0E"]) {
        return @"dav://";
    } else if ([firstByte isEqualToString:@"0F"]) {
        return @"news:";
    } else if ([firstByte isEqualToString:@"10"]) {
        return @"telnet://";
    } else if ([firstByte isEqualToString:@"11"]) {
        return @"imap:";
    } else if ([firstByte isEqualToString:@"12"]) {
        return @"rtsp://";
    } else if ([firstByte isEqualToString:@"13"]) {
        return @"urn:";
    } else if ([firstByte isEqualToString:@"14"]) {
        return @"pop:";
    } else if ([firstByte isEqualToString:@"15"]) {
        return @"sip:";
    } else if ([firstByte isEqualToString:@"16"]) {
        return @"sips:";
    } else if ([firstByte isEqualToString:@"17"]) {
        return @"tftp:";
    } else if ([firstByte isEqualToString:@"18"]) {
        return @"btspp://";
    } else if ([firstByte isEqualToString:@"19"]) {
        return @"btl2cap://";
    } else if ([firstByte isEqualToString:@"1A"]) {
        return @"btgoep://";
    } else if ([firstByte isEqualToString:@"1B"]) {
        return @"tcpobex://";
    } else if ([firstByte isEqualToString:@"1C"]) {
        return @"irdaobex://";
    } else if ([firstByte isEqualToString:@"1D"]) {
        return @"file://";
    } else if ([firstByte isEqualToString:@"1E"]) {
        return @"urn:epc:id:";
    } else if ([firstByte isEqualToString:@"1F"]) {
        return @"urn:epc:tag:";
    } else if ([firstByte isEqualToString:@"20"]) {
        return @"urn:epc:pat:";
    } else if ([firstByte isEqualToString:@"21"]) {
        return @"urn:epc:raw:";
    } else if ([firstByte isEqualToString:@"22"]) {
        return @"urn:epc:";
    } else if ([firstByte isEqualToString:@"23"]) {
        return @"urn:nfc:";
    }

    return @"";

}

/*!
* gets the the NDEF content
*/
- (NSString *)getNDEFContent:(NSData *)data {
     NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     return [dataString substringFromIndex:2];
}

/*!
 * gets the first byte of the input NSData
 */
- (NSString *)getFirstByte:(NSData *)data {
     return [[self dataToHexString:data] substringToIndex:2];
}

/*!
 * transforms NSData to NSString
 */
- (NSString *)dataToHexString:(NSData *)data;
{
    // get the length of the data
    NSUInteger bytesCount = data.length;
    if (bytesCount) {
        // string with all the Hex characters
        const char *hexChars = "0123456789ABCDEF";
        // put bytes into an array and initialize the response array
        const unsigned char *dataBuffer = data.bytes;
        char *chars = malloc(sizeof(char) * (bytesCount * 2 + 1));
        char *s = chars;
        // go through data bytes making the transformations so a hex will literally translate to a string, so for example 0x0A will translate to "0A"
        for (unsigned i = 0; i < bytesCount; ++i) {
            // get hexChars character at binary AND between the current byte and 0xF0 bitwise to the right by 4 index and assign it to the current chars pointer
            *s++ = hexChars[((*dataBuffer & 0xF0) >> 4)];
            // get hexChars character at binary AND between the current byte and 0x0F index and assign it to the current chars pointer
            *s++ = hexChars[(*dataBuffer & 0x0F)];
            dataBuffer++;
        }
        *s = '\0';
        // chars to string
        NSString *hexString = [NSString stringWithUTF8String:chars];
        free(chars);
        return hexString;
    }
    return @"";
}

And call the getType method:

[self getType:yourNDEFPayloadNSData]

I'm assuming that all the methods are in the same class and,

that the payload NSData is NDEF compliant, but I modeled the code based on the NFCNDEFPayload payload


问:
Eddystone (which beacon is interacting?)
From multiple beacons placed at a location, how can we know from which beacon the user accessed the URL ? I am using Nearby notification. Minor value of beacon would help ? If yes then how ? Or pls suggest an alternative solution.

Thanks.

答: Append your url with a parameter identifying the beacon. E.g. http://www.myaddress.com?beaconId=123


问:
Call Python functions from TCL script with arguments
I have a Python script, say, sample.py with 2 functions func1() and func2():

```<code>def func1():
    print("Called Function 1")

def func2():
    print("Called Function 2")
</code>```

How do I call this function func2() from the Tcl script and also how to pass the arguments to that function?

答:
The best method is probably to see if tclpython will work for you. (Download links on http://jfontain.free.fr/; pick the one(s) you need.) That should let you write code like this:</p>

```<code># Set up a python interpreter
package require tclpython
set py [python::interp new]

# Load a file in with your definitions
$py exec {
    # This is Python code, embedded directly in Tcl
    evalfile("sample.py")
}

# Evaluate a python expression (in this case, call an argument-less function)
set result [$py eval func2()]

# Dispose of the python interpreter
python::interp delete $py
</code>```

Body:
I have a Python script, say, sample.py with 2 functions func1() and func2():

def func1():
    print("Called Function 1")

def func2():
    print("Called Function 2")

How do I call this function func2() from the Tcl script and also how to pass the arguments to that function?

Body:
The best method is probably to see if tclpython will work for you. (Download links on http://jfontain.free.fr/; pick the one(s) you need.) That should let you write code like this:

# Set up a python interpreter
package require tclpython
set py [python::interp new]

# Load a file in with your definitions
$py exec {
    # This is Python code, embedded directly in Tcl
    evalfile("sample.py")
}

# Evaluate a python expression (in this case, call an argument-less function)
set result [$py eval func2()]

# Dispose of the python interpreter
python::interp delete $py


问:
How can I make a field required from a drop down list using JS?
I need to make a class fields with an ID of "sales-representative" require when a drop down list value is "Yes". Right now I have this and it's not working. I'm new in Java Script. If someone can help me I'll appreciate it. </p>

```<code>`<script>
    var makeSRFieldsRequired = function(){
if (document.getElementById("soa-coordinated-drp").value = "YES"){
document.getElementById("sales-representative").prop('required', required);}
    };
    </script>`
</code>```

答:
I didn't really understand your question all that well, but from what I gathered you were after a solution to toggle a dropdown dependant upon the action of another dropdown.

Below is the code I wrote in order to do this, we are listening everytime a change is made to the dropdown which in this case has an id of value-to-yes when the change is made we're seeing what the selected index so in this case, 1 is equal to yes.

If it is equal to yes, we show the other dropdown.

If not, then we hide it.

var selectYes = document.querySelector('#value-to-yes');
var sales = document.querySelector('#sales-representative');

selectYes.addEventListener('change', function() {
    if (selectYes.selectedIndex === 1) {
      sales.style.display = 'block';
    } else {
      sales.style.display = 'none';
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="value-to-yes">
  <option selected hidden>Please select an option</option>
  <option value="yes">Yes</option>
  <option value="no">No</option>
</select>

<form id="sales-representative" style="display: none;">
  <input type="text" name="name" placeholder="Name" required>
  <input type="text" name="id" placeholder="ID" required>
  <input type="text" name="phone" placeholder="Phone Number" required>
  <button type="submit">Submit</button>
</form></code>```

Body:
I need to make a class fields with an ID of "sales-representative" require when a drop down list value is "Yes". Right now I have this and it's not working. I'm new in Java Script. If someone can help me I'll appreciate it.

``

Body:
I didn't really understand your question all that well, but from what I gathered you were after a solution to toggle a dropdown dependant upon the action of another dropdown.

Below is the code I wrote in order to do this, we are listening everytime a change is made to the dropdown which in this case has an id of value-to-yes when the change is made we're seeing what the selected index so in this case, 1 is equal to yes.

If it is equal to yes, we show the other dropdown.

If not, then we hide it.

var selectYes = document.querySelector('#value-to-yes');
var sales = document.querySelector('#sales-representative');

selectYes.addEventListener('change', function() {
    if (selectYes.selectedIndex === 1) {
      sales.style.display = 'block';
    } else {
      sales.style.display = 'none';
    }
});

<select id="value-to-yes">
  <option selected hidden>Please select an option</option>
  <option value="yes">Yes</option>
  <option value="no">No</option>
</select>

<form id="sales-representative" style="display: none;">
  <input type="text" name="name" placeholder="Name" required>
  <input type="text" name="id" placeholder="ID" required>
  <input type="text" name="phone" placeholder="Phone Number" required>
  <button type="submit">Submit</button>
</form>


问:
LINQ to NHibernate: could not resolve property
Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.

I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.

```<code>public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}
</code>```

However, when running this method:

```<code>public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }
</code>```

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event

FWIW, I've blurred out the name of the project. ;)

Any idea how to get this query working?

Thanks!
-Steve

EDIT:
Here's my mapping class:

```<code>public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}
</code>```

...and my config:

```<code>public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }
</code>```

I also just tried the Criteria API:

```<code>return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();
</code>```

No workie either.

答:
Here is how you can fix that using the formulas. In your Event class convert those 2 properties into regular properties:

```<code>public class Event
{
    public Event() { }
    ...
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent{ get; set; }
    public virtual Int32 MonthOfEvent { get; set; }
    ...
    public virtual Boolean IsActive { get; set; }
}
</code>```

Then in the mapping add formulas to populate their values.. I'm not very positive about the MySQL syntax for retrieving the year & month but you've got an idea (I used this reference):

```<code>public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.YearOfEvent).Formula("SELECT YEAR(dateOfEvent)");
        Map(x => x.MonthOfEvent).Formula("SELECT MONTH(dateOfEvent)");
        ...
        Map(x => x.IsActive, "isActive");
    }
}
</code>```

Now you can query them just like any other fields using either LINQ or ICriteria:

```<code>return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.

I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.

public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}

However, when running this method:

public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event

FWIW, I've blurred out the name of the project. ;)

Any idea how to get this query working?

Thanks!
-Steve

EDIT:
Here's my mapping class:

public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}

...and my config:

public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }

I also just tried the Criteria API:

return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();

No workie either.

Body:
Here is how you can fix that using the formulas. In your Event class convert those 2 properties into regular properties:

public class Event
{
    public Event() { }
    ...
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent{ get; set; }
    public virtual Int32 MonthOfEvent { get; set; }
    ...
    public virtual Boolean IsActive { get; set; }
}

Then in the mapping add formulas to populate their values.. I'm not very positive about the MySQL syntax for retrieving the year & month but you've got an idea (I used this reference):

public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.YearOfEvent).Formula("SELECT YEAR(dateOfEvent)");
        Map(x => x.MonthOfEvent).Formula("SELECT MONTH(dateOfEvent)");
        ...
        Map(x => x.IsActive, "isActive");
    }
}

Now you can query them just like any other fields using either LINQ or ICriteria:

return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();


问:
make loop read clearer
within my while loop I am doing a test, but it seems really redundant and I think there may be a better solution to implement this such as a "case" structure possibly? If anyone can recommend how to cut down on the redundancy that would be wonderful, thanks! Basically, how can I restructure this loop to be better?

the loop:

```<code> if [ "$cursor" -eq "1" ]
    then
        Links="Links: $(ls -ld / | cut -d" " -f2)"
        Owner="Owner: $(ls -ld / | cut -d" " -f3)"
        Group="Group: $(ls -ld / | cut -d" " -f4)"
        Size="Size: $(ls -ld / | cut -d" " -f5)"
        Modified="Modified: $(ls -ld / | cut -d" " -f6-8)"
        echo "$Links  $Owner  $Group  $Size  $Modified"
    elif [ "$cursor" -eq "2" ]
    then
        Links="Links: $(ls -ld /home | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld /home | cut -d" " -f3)"
                    Group="Group: $(ls -ld /home | cut -d" " -f4)"
                    Size="Size: $(ls -ld /home | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld /home | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
        elif [ "$cursor" -eq "3" ]
    then
        Links="Links: $(ls -ld ~ | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld ~ | cut -d" " -f3)"
                    Group="Group: $(ls -ld ~ | cut -d" " -f4)"
                    Size="Size: $(ls -ld ~ | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld ~ | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
    else
        temp=`expr $cursor - 1`
        curDir=${currentdir[$temp]}
        Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
                    Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
                    Size="Size: $(ls -ld $curDir | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld $curDir | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
fi
</code>```

答:
You can do that no problem. When approaching this problem think about what piece of information is changing in your statements, use a variable to store this information. In the end try to reduce repeated lines by using functions, variables, and ordering.

Move the following block out of your if/else statements. Within each if statement, set the variable curDir="[dir]"

```<code> Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
 Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
 Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
 Size="Size: $(ls -ld $curdir | cut -d" " -f5)"
 Modified="Modified: $(ls -ld $curdir | cut -d" " -f6-8)"
 echo "$Links  $Owner  $Group  $Size  $Modified"
</code>```

Title: make loop read clearer

Body:
within my while loop I am doing a test, but it seems really redundant and I think there may be a better solution to implement this such as a "case" structure possibly? If anyone can recommend how to cut down on the redundancy that would be wonderful, thanks! Basically, how can I restructure this loop to be better?

the loop:

 if [ "$cursor" -eq "1" ]
    then
        Links="Links: $(ls -ld / | cut -d" " -f2)"
        Owner="Owner: $(ls -ld / | cut -d" " -f3)"
        Group="Group: $(ls -ld / | cut -d" " -f4)"
        Size="Size: $(ls -ld / | cut -d" " -f5)"
        Modified="Modified: $(ls -ld / | cut -d" " -f6-8)"
        echo "$Links  $Owner  $Group  $Size  $Modified"
    elif [ "$cursor" -eq "2" ]
    then
        Links="Links: $(ls -ld /home | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld /home | cut -d" " -f3)"
                    Group="Group: $(ls -ld /home | cut -d" " -f4)"
                    Size="Size: $(ls -ld /home | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld /home | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
        elif [ "$cursor" -eq "3" ]
    then
        Links="Links: $(ls -ld ~ | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld ~ | cut -d" " -f3)"
                    Group="Group: $(ls -ld ~ | cut -d" " -f4)"
                    Size="Size: $(ls -ld ~ | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld ~ | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
    else
        temp=`expr $cursor - 1`
        curDir=${currentdir[$temp]}
        Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
                    Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
                    Size="Size: $(ls -ld $curDir | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld $curDir | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
fi

Body:
You can do that no problem. When approaching this problem think about what piece of information is changing in your statements, use a variable to store this information. In the end try to reduce repeated lines by using functions, variables, and ordering.

Move the following block out of your if/else statements. Within each if statement, set the variable curDir="[dir]"

 Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
 Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
 Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
 Size="Size: $(ls -ld $curdir | cut -d" " -f5)"
 Modified="Modified: $(ls -ld $curdir | cut -d" " -f6-8)"
 echo "$Links  $Owner  $Group  $Size  $Modified"


问:
How to set upstream branch to the same name as the branch
If I create a new branch and try to push it, I am told that I have to explicitly say what the name of the upstream branch needs to be.

```<code>> git checkout -b feature/long-branch-name-I-dont-want-to-have-to-type-out
Switched to a new branch 'feature/long-branch-name-I-dont-want-to-have-to-type-out'
> git push
fatal: The current branch feature/long-branch-name-I-dont-want-to-have-to-type-out has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin feature/long-branch-name-I-dont-want-to-have-to-type-out
</code>```

Is there some way to do that without having to type out the name of the upstream branch?  I virtually always want it to be the same name on the server as it is locally.

Is there any way to do something like  git push --set-upstream <current_branch_name>, independent of what the current branch name happens to be?

答:
[Edit] sajib khan's first answer, setting push.default to current will enable pushing, but does not actually set the upstream.  This means that after a future git fetch, your Git won't report ahead/behind counts, and your Git won't know the upstream to use for git rebase or git merge (or git pull either though I advise avoiding git pull).

You can use [edit, as in the second part of his answer]:

```<code>git push -u origin HEAD
</code>```

If needed, this creates the branch on the other Git, so that your Git acquires the origin/ variant.  Then in any case it sets that (maybe new) remote-tracking branch you have as your branch's upstream.  But until origin/feature/long-branch-name-I-dont-want-to-have-to-type-out actually exists, you can't set it as the upstream.1

1Actually, you can, you just can't use git branch --set-upstream to do it.  And, you don't want to type it in again anyway.  To do it "manually" you would need:

```<code>git config \
  branch.feature/long-branch-name-I-dont-want-to-have-to-type-out.remote origin
git config \
  branch.feature/long-branch-name-I-dont-want-to-have-to-type-out.merge \
  feature/long-branch-name-I-dont-want-to-have-to-type-out
</code>```

which means typing it out three times (!), or writing yourself a script.

Body:
If I create a new branch and try to push it, I am told that I have to explicitly say what the name of the upstream branch needs to be.

> git checkout -b feature/long-branch-name-I-dont-want-to-have-to-type-out
Switched to a new branch 'feature/long-branch-name-I-dont-want-to-have-to-type-out'
> git push
fatal: The current branch feature/long-branch-name-I-dont-want-to-have-to-type-out has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin feature/long-branch-name-I-dont-want-to-have-to-type-out

Is there some way to do that without having to type out the name of the upstream branch?  I virtually always want it to be the same name on the server as it is locally.

Is there any way to do something like  git push --set-upstream <current_branch_name>, independent of what the current branch name happens to be?

Body:
[Edit] sajib khan's first answer, setting push.default to current will enable pushing, but does not actually set the upstream.  This means that after a future git fetch, your Git won't report ahead/behind counts, and your Git won't know the upstream to use for git rebase or git merge (or git pull either though I advise avoiding git pull).

You can use [edit, as in the second part of his answer]:

git push -u origin HEAD

If needed, this creates the branch on the other Git, so that your Git acquires the origin/ variant.  Then in any case it sets that (maybe new) remote-tracking branch you have as your branch's upstream.  But until origin/feature/long-branch-name-I-dont-want-to-have-to-type-out actually exists, you can't set it as the upstream.1

1Actually, you can, you just can't use git branch --set-upstream to do it.  And, you don't want to type it in again anyway.  To do it "manually" you would need:

git config \
  branch.feature/long-branch-name-I-dont-want-to-have-to-type-out.remote origin
git config \
  branch.feature/long-branch-name-I-dont-want-to-have-to-type-out.merge \
  feature/long-branch-name-I-dont-want-to-have-to-type-out

which means typing it out three times (!), or writing yourself a script.


问:
Non-interactive authorization with Google OAuth2
I have created a Java application that performs syncing of MS Active Directory with Google Groups. It is non-interactive application that suppose to be executed by the cronjob at night time.
It does work perfectly on my laptop (DEV environment).
My problem is that on the first run it pops up browser window with the dialog asking to authorize access to the Google API. After I click on "Allow" button it happily proceeds to the end.
Now I need to move it to production server which runs CentOS and does not have a browser.
When I run my application in this environment it prints the following message:

```<code>Please open the following address in your browser:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=520105804541-c7d7bfki88qr8dbkv6oahp22i3oq1jq0.apps.googleusercontent.com&redirect_uri=http://localhost:50089/Callback&response_type=code&scope=https://www.googleapis.com/auth/admin.directory.group.member%20https://www.googleapis.com/auth/admin.directory.orgunit%20https://www.googleapis.com/auth/admin.directory.device.mobile.action%20https://www.googleapis.com/auth/admin.directory.orgunit.readonly%20https://www.googleapis.com/auth/admin.directory.userschema%20https://www.googleapis.com/auth/admin.directory.device.chromeos%20https://www.googleapis.com/auth/admin.directory.notifications%20https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly%20https://www.googleapis.com/auth/admin.directory.device.mobile%20https://www.googleapis.com/auth/admin.directory.group.readonly%20https://www.googleapis.com/auth/admin.directory.group.member.readonly%20https://www.googleapis.com/auth/admin.directory.userschema.readonly%20https://www.googleapis.com/auth/admin.directory.user.alias%20https://www.googleapis.com/auth/admin.directory.user.security%20https://www.googleapis.com/auth/admin.directory.device.mobile.readonly%20https://www.googleapis.com/auth/admin.directory.user%20https://www.googleapis.com/auth/admin.directory.user.readonly%20https://www.googleapis.com/auth/admin.directory.user.alias.readonly%20https://www.googleapis.com/auth/admin.directory.group%20https://www.googleapis.com/auth/apps.groups.settings
</code>```

There is no browser on this machine but if I try to run it on another box I am getting error 400 - invalid request.
The reason is clear, because it redirecting to localhost:50089 and nobody is listening on that port on another machine.
Going through the multiple documents and samples on developers.google.com I found a way to bypass the dialog by creating the service account and generating a primary key for it.

```<code>    try {
        GoogleCredential cr = GoogleCredential
             .fromStream(new FileInputStream(keyFile))
             .createScoped(SCOPES);
        Directory directory = new Directory.Builder(httpTransport, jsonFactory, cr)
.setApplicationName(config.getProperty("google.application.name")).build();
    } catch (IOException ex) {
       LOG.error("Failed to establish access credentials : ", ex.getMessage());
    }
</code>```

It does read the key and does create Directory instance, but any request to it results in 403 response code

{   "code" : 403,   "errors" : [ { "domain" : "global", "message" :
  "Not Authorized to access this resource/api", "reason" : "forbidden"

  } ],    "message" : "Not Authorized to access this resource/api" }"

But I have delegated all the privileges for this account to the service account. Don't know what else I can do.
If anyone can help me out of this jam, I appreciate it greatly.

答:
I found solution. The problem is that Google generated JSON key does not set service account user. You have to do it manually like this:</p>

```<code>        GoogleCredential cr = GoogleCredential
             .fromStream(new FileInputStream(keyFile))
             .createScoped(SCOPES);
        GoogleCredential.Builder builder = new GoogleCredential.Builder()
             .setTransport(httpTransport)
             .setJsonFactory(jsonFactory)
             .setServiceAccountScopes(SCOPES)
             .setServiceAccountId(cr.getServiceAccountId())
             .setServiceAccountPrivateKey(cr.getServiceAccountPrivateKey())
             .setServiceAccountPrivateKeyId(cr.getServiceAccountPrivateKeyId())
             .setTokenServerEncodedUrl(cr.getTokenServerEncodedUrl())
             .setServiceAccountUser(user);
        Directory directory = new Directory.Builder(
              httpTransport, jsonFactory, builder.build())
             .setApplicationName(config.getProperty("google.application.name")).build();
</code>```

Body:
I have created a Java application that performs syncing of MS Active Directory with Google Groups. It is non-interactive application that suppose to be executed by the cronjob at night time.
It does work perfectly on my laptop (DEV environment).
My problem is that on the first run it pops up browser window with the dialog asking to authorize access to the Google API. After I click on "Allow" button it happily proceeds to the end.
Now I need to move it to production server which runs CentOS and does not have a browser.
When I run my application in this environment it prints the following message:

Please open the following address in your browser:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=520105804541-c7d7bfki88qr8dbkv6oahp22i3oq1jq0.apps.googleusercontent.com&redirect_uri=http://localhost:50089/Callback&response_type=code&scope=https://www.googleapis.com/auth/admin.directory.group.member%20https://www.googleapis.com/auth/admin.directory.orgunit%20https://www.googleapis.com/auth/admin.directory.device.mobile.action%20https://www.googleapis.com/auth/admin.directory.orgunit.readonly%20https://www.googleapis.com/auth/admin.directory.userschema%20https://www.googleapis.com/auth/admin.directory.device.chromeos%20https://www.googleapis.com/auth/admin.directory.notifications%20https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly%20https://www.googleapis.com/auth/admin.directory.device.mobile%20https://www.googleapis.com/auth/admin.directory.group.readonly%20https://www.googleapis.com/auth/admin.directory.group.member.readonly%20https://www.googleapis.com/auth/admin.directory.userschema.readonly%20https://www.googleapis.com/auth/admin.directory.user.alias%20https://www.googleapis.com/auth/admin.directory.user.security%20https://www.googleapis.com/auth/admin.directory.device.mobile.readonly%20https://www.googleapis.com/auth/admin.directory.user%20https://www.googleapis.com/auth/admin.directory.user.readonly%20https://www.googleapis.com/auth/admin.directory.user.alias.readonly%20https://www.googleapis.com/auth/admin.directory.group%20https://www.googleapis.com/auth/apps.groups.settings

There is no browser on this machine but if I try to run it on another box I am getting error 400 - invalid request.
The reason is clear, because it redirecting to localhost:50089 and nobody is listening on that port on another machine.
Going through the multiple documents and samples on developers.google.com I found a way to bypass the dialog by creating the service account and generating a primary key for it.

    try {
        GoogleCredential cr = GoogleCredential
             .fromStream(new FileInputStream(keyFile))
             .createScoped(SCOPES);
        Directory directory = new Directory.Builder(httpTransport, jsonFactory, cr)
.setApplicationName(config.getProperty("google.application.name")).build();
    } catch (IOException ex) {
       LOG.error("Failed to establish access credentials : ", ex.getMessage());
    }

It does read the key and does create Directory instance, but any request to it results in 403 response code

{   "code" : 403,   "errors" : [ { "domain" : "global", "message" :
  "Not Authorized to access this resource/api", "reason" : "forbidden"

  } ],    "message" : "Not Authorized to access this resource/api" }"

But I have delegated all the privileges for this account to the service account. Don't know what else I can do.
If anyone can help me out of this jam, I appreciate it greatly.

Body:
I found solution. The problem is that Google generated JSON key does not set service account user. You have to do it manually like this:

        GoogleCredential cr = GoogleCredential
             .fromStream(new FileInputStream(keyFile))
             .createScoped(SCOPES);
        GoogleCredential.Builder builder = new GoogleCredential.Builder()
             .setTransport(httpTransport)
             .setJsonFactory(jsonFactory)
             .setServiceAccountScopes(SCOPES)
             .setServiceAccountId(cr.getServiceAccountId())
             .setServiceAccountPrivateKey(cr.getServiceAccountPrivateKey())
             .setServiceAccountPrivateKeyId(cr.getServiceAccountPrivateKeyId())
             .setTokenServerEncodedUrl(cr.getTokenServerEncodedUrl())
             .setServiceAccountUser(user);
        Directory directory = new Directory.Builder(
              httpTransport, jsonFactory, builder.build())
             .setApplicationName(config.getProperty("google.application.name")).build();


问:
Go back to the actual previous page regardless of a form post error
I have a page with a form. On this page there is also "go back to previous page" link, which uses the following JavaScript:

```<code>window.history.go(-1)
</code>```

When the form is posted and there is a validation error, the website returns the user to the same form page. However, clicking on this link in case of a form validation error gets the user to the form page before its submission, not the actual, different previous page.

How can I get the user back to the actual previous page by ONLY using JavaScript? Please note that there could be multiple times of form submission with errors.

答:
You could probably use location.replace() in your redirect after validation error.

This will erase the current page location from the history and replace it with the new one, so it has no effect on page history.

Another option is to use sessionStorage to check if the URL has actually changed after going back one page in the history.

```<code>window.onload = function() {
  document.getElementById("back").onclick = function() {
    sessionStorage.setItem("href",location.href); //store current page into sessionStorage
    history.go(-1); //go back one page
  };
  if (location.href == sessionStorage.getItem("href")) {document.getElementById("back").click();} //if current page is the same as last one, go back one page
  else {sessionStorage.removeItem("href");} //clear sessionStorage
};
</code>```

In the demos below (SO doesn't allow sessionStorage) I had to simulate both "going through the history", and "page load for every history item", so the code looks a little different, using an array and other vars and functions, but the principle should be the same:

codepen: https://codepen.io/anon/pen/OgBgGg?editors=1011

jsfiddle: https://jsfiddle.net/j0ddnboq/2/

ContentLicense: CC BY-SA 4.0

Body:
I have a page with a form. On this page there is also "go back to previous page" link, which uses the following JavaScript:

window.history.go(-1)

When the form is posted and there is a validation error, the website returns the user to the same form page. However, clicking on this link in case of a form validation error gets the user to the form page before its submission, not the actual, different previous page.

How can I get the user back to the actual previous page by ONLY using JavaScript? Please note that there could be multiple times of form submission with errors.

Body:
You could probably use location.replace() in your redirect after validation error.

This will erase the current page location from the history and replace it with the new one, so it has no effect on page history.

Another option is to use sessionStorage to check if the URL has actually changed after going back one page in the history.

window.onload = function() {
  document.getElementById("back").onclick = function() {
    sessionStorage.setItem("href",location.href); //store current page into sessionStorage
    history.go(-1); //go back one page
  };
  if (location.href == sessionStorage.getItem("href")) {document.getElementById("back").click();} //if current page is the same as last one, go back one page
  else {sessionStorage.removeItem("href");} //clear sessionStorage
};

In the demos below (SO doesn't allow sessionStorage) I had to simulate both "going through the history", and "page load for every history item", so the code looks a little different, using an array and other vars and functions, but the principle should be the same:

codepen: https://codepen.io/anon/pen/OgBgGg?editors=1011

jsfiddle: https://jsfiddle.net/j0ddnboq/2/


问:
Converting LPSTR to LPCTSTR
I have a program I am modifying to take command line argument as a variable of the type LPSTR. Currently the value is hardcoded in the program and passes to the desired function in the form _T("program.exe"). The function expects the type LPCTSTR. I have tried to cast my command line argument from a LPSTR to a LPCTSTR to no avail. Similar attempts using a char* as an intermediary have also failed. I know I am probably missing something stupidly simple, but at this point I would appreciate the help.

答:
Since you are dealing with a command-line parameter, you are presumably using argv.

You should instead be using the CommandLineToArgvW function, which produces an argv-like array of Unicode strings.  There is example code at the bottom of the linked documentation, but it goes basically like this:

```<code>argv_wide = CommandLineToArgvW(GetCommandLineW(), &argc_wide);
</code>```

Note that if you had obtained the ANSI string in some other way, e.g., read from a text file, you would instead use the MultiByteToWideChar function to convert it.

Title: Converting LPSTR to LPCTSTR

Body:
Since you are dealing with a command-line parameter, you are presumably using argv.

You should instead be using the CommandLineToArgvW function, which produces an argv-like array of Unicode strings.  There is example code at the bottom of the linked documentation, but it goes basically like this:

argv_wide = CommandLineToArgvW(GetCommandLineW(), &argc_wide);

Note that if you had obtained the ANSI string in some other way, e.g., read from a text file, you would instead use the MultiByteToWideChar function to convert it.


问:
How to debug spring-boot application with IntelliJ IDEA community Edition?
I'm having difficulties in debugging a Java spring-boot application on IntelliJ IDEA community Edition. The main problem is, that the IDE won't stop on a breakpoint, even the program surely executes through it. How can I make the the IntelliJ IDEA to stop on the breakpoint?

As additional information, here is my run configurations:

Maven configuration with a command as: spring-boot:run. Before launch I build the project.

答:
The only way I got it working was by creating a separate, remote debug configuration.

So go to edit configurations-> Remote -> +. Then start your application normally through intelliJ. Then switch to the newly created remote configuration. Instead of running it, press debug. Now debugger should be ready, and you can set breakpoints and the debugger will stop to them.

EDIT: For me the debug port was already enabled, but I see that this is not the case for everyone. If you get an error like

```<code>'Unable to open debugger port (localhost:5005): java.net.ConnectException "Connection refused: connect"
</code>```

Then you need to enable port on your app's pom.xml. Copied from @Gianluca Musa answer:

```<code><plugin>
<groupId>org.springframework.boot</groupId>
<configuration>
<jvmArguments>
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
</jvmArguments>
</configuration>
</plugin>
</code>```

Kudos for @Gianluca Musa for pointing this out in his answer

Body:
The only way I got it working was by creating a separate, remote debug configuration.

So go to edit configurations-> Remote -> +. Then start your application normally through intelliJ. Then switch to the newly created remote configuration. Instead of running it, press debug. Now debugger should be ready, and you can set breakpoints and the debugger will stop to them.

EDIT: For me the debug port was already enabled, but I see that this is not the case for everyone. If you get an error like

'Unable to open debugger port (localhost:5005): java.net.ConnectException "Connection refused: connect"

Then you need to enable port on your app's pom.xml. Copied from @Gianluca Musa answer:

<plugin>
<groupId>org.springframework.boot</groupId>
<configuration>
<jvmArguments>
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
</jvmArguments>
</configuration>
</plugin>

Kudos for @Gianluca Musa for pointing this out in his answer


问:
Delete value from array then resize
For reference, here is the whole code.

```<code>  Sub CalculateOutliers()

                Dim n As Long
                Dim mean As Double
                Dim SD As Double
                Dim k As Long
                Dim DataSet As Variant
                Dim LowConf As Double
                Dim HighConf As Double

            '--------------------------------------------------------
                DataSet = Selection.Value
            'Copies highlighted data into DataSet variable
            'Cell A1 is (1,1) Because it starts at 0 which is out of range
            '--------------------------------------------------------

            '--------------------------------------------------------
                n = Selection.CountLarge
            'Counts number of entries
            '--------------------------------------------------------

            '--------------------------------------------------------
             'DEFINES 95(LowConf) AND 99(HighConf) PERCENT CONFIDENCES BASED ON
             'SAMPLE SIZE

                If n <= 5 Then
                        LowConf = 1.72
                        HighConf = 1.76
                End If

                If n = 6 Then
                        LowConf = 1.89
                        HighConf = 1.97
                End If

                If n = 7 Then
                        LowConf = 2.02
                        HighConf = 2.14
                End If

                If n = 8 Then
                        LowConf = 2.13
                        HighConf = 2.28
                End If

                If n = 9 Then
                        LowConf = 2.21
                        HighConf = 2.39
                End If

                If n = 10 Then
                        LowConf = 2.29
                        HighConf = 2.48
                End If

                If n = 11 Then
                        LowConf = 2.36
                        HighConf = 2.56
                End If

                If n = 12 Then
                        LowConf = 2.41
                        HighConf = 2.64
                End If

                If n = 13 Then
                        LowConf = 2.46
                        HighConf = 2.7
                End If

                If n = 14 Then
                        LowConf = 2.51
                        HighConf = 2.75
                End If

                If n = 15 Then
                        LowConf = 2.55
                        HighConf = 2.81
                End If

                If n = 16 Then
                        LowConf = 2.59
                        HighConf = 2.85
                End If

                If n = 17 Then
                        LowConf = 2.62
                        HighConf = 2.9
                End If

                If n = 18 Then
                        LowConf = 2.65
                        HighConf = 2.93
                End If

                If n = 19 Then
                        LowConf = 2.68
                        HighConf = 2.97
                End If

                If n = 20 Then
                        LowConf = 2.71
                        HighConf = 3
                End If

                If n = 21 Then
                        LowConf = 2.73
                        HighConf = 3.03
                End If

                If n = 22 Then
                        LowConf = 2.76
                        HighConf = 3.06
                End If

                If n = 23 Then
                        LowConf = 2.78
                        HighConf = 3.08
                End If

                If n = 24 Then
                        LowConf = 2.8
                        HighConf = 3.11
                End If

                If n = 25 Then
                        LowConf = 2.82
                        HighConf = 3.14
                End If

                If n = 26 Then
                        LowConf = 2.84
                        HighConf = 3.16
                End If

                If n = 27 Then
                        LowConf = 2.86
                        HighConf = 3.18
                End If

                If n = 28 Then
                        LowConf = 2.88
                        HighConf = 3.2
                End If

                If n = 29 Then
                        LowConf = 2.89
                        HighConf = 3.22
                End If

                If n = 30 Then
                        LowConf = 2.91
                        HighConf = 3.24
                End If

                If n <= 35 And n > 30 Then
                        LowConf = 2.98
                        HighConf = 3.32
                End If

                If n <= 40 And n > 35 Then
                        LowConf = 3.04
                        HighConf = 3.38
                End If

                If n <= 45 And n > 40 Then
                        LowConf = 3.09
                        HighConf = 3.44
                End If

                If n <= 50 And n > 45 Then
                        LowConf = 3.13
                        HighConf = 3.48
                End If

                If n <= 60 And n > 50 Then
                        LowConf = 3.2
                        HighConf = 3.56
                End If

                If n <= 70 And n > 60 Then
                        LowConf = 3.26
                        HighConf = 3.62
                End If

                If n <= 80 And n > 70 Then
                        LowConf = 3.31
                        HighConf = 3.67
                End If

                If n <= 90 And n > 80 Then
                        LowConf = 3.35
                        HighConf = 3.72
                End If

                If n <= 100 And n > 90 Then
                        LowConf = 3.38
                        HighConf = 3.75
                End If

                If n <= 150 And n > 100 Then
                        LowConf = 3.52
                        HighConf = 3.89
                End If

                If n <= 200 And n > 150 Then
                        LowConf = 3.61
                        HighConf = 3.98
                End If

                If n <= 300 And n > 200 Then
                        LowConf = 3.72
                        HighConf = 4.09
                End If

                If n <= 400 And n > 300 Then
                        LowConf = 3.8
                        HighConf = 4.17
                End If

                If n <= 500 And n > 400 Then
                        LowConf = 3.86
                        HighConf = 4.32
                End If

                If n > 500 Then
                        MsgBox "Sample size cannot exceed 500."
                End If
            '--------------------------------------------------------

            '--------------------------------------------------------
                If n < 50 Then
                    k = Int(n / 10)
                Else
                    k = 5
                End If
            'determines k = number of possible outliers
            '--------------------------------------------------------

            Dim i As Long

            For i = 1 To k
            '--------------------------------------------------------
                mean = Application.WorksheetFunction.Average(DataSet)
            'Calculates mean of Data Set
            '--------------------------------------------------------

            '--------------------------------------------------------
                SD = Application.WorksheetFunction.StDev(DataSet)
            'Calculates Standard Deviation of Data Set
            '--------------------------------------------------------

            '--------------------------------------------------------
                Dim Suspect As Double

                If (Abs(Application.WorksheetFunction.Max(DataSet) - mean)) > (Abs(Application.WorksheetFunction.Min(DataSet) - mean)) Then

                    Suspect = Application.WorksheetFunction.Max(DataSet)

                End If

                If (Abs(Application.WorksheetFunction.Max(DataSet) - mean)) < (Abs(Application.WorksheetFunction.Min(DataSet) - mean)) Then

                    Suspect = Application.WorksheetFunction.Min(DataSet)

                End If
            'Defines what the most outlying value is
            '--------------------------------------------------------

            '--------------------------------------------------------
                Dim Retest As Boolean

                If (Abs(Suspect - mean) / SD) > LowConf Then
                    MsgBox "95% outlier: " & Suspect
                    Retest = True
                End If

                If (Abs(Suspect - mean) / SD) > HighConf Then
                    MsgBox "99% outlier: " & Suspect
                    Retest = True
                End If

                If Retest = True Then

            '--------------------------------------------------------
            Next i

            End Sub
</code>```

Talking about this chunk of code, I need to delete Suspect from DataSet then shrink DataSet by 1 but I am not sure how to go about this. Is there a function that will delete the Max or Min value and is there a way to resize DataSet given that it is a variant?

```<code>                        Dim Retest As Boolean

                        If (Abs(Suspect - mean) / SD) > LowConf Then

                            MsgBox "95% outlier: " & Suspect
                            Retest = True

                    End If

                        If (Abs(Suspect - mean) / SD) > HighConf Then

                            MsgBox "99% outlier: " & Suspect
                            Retest = True

                    End If

                        If Retest = True Then
</code>```

答:
Here is how I would implement the solution (similar to @Tim's comment)

```<code>Sub calculateOutliers()
    Dim retest As Boolean, dataSet As Variant, n As Long, found As Range
    Dim lowConf As Double, highConf As Double, suspect As Double, tmp As Double
    Dim mean As Double, stdDev As Double, dataMin As Double, dataMax As Double

    retest = True
    While retest
        dataSet = Selection.Value
        n = Selection.CountLarge
        If Not IsEmpty(dataSet) Then
            updateConfidences dataSet, n, lowConf, highConf
            retest = False
            With Application.WorksheetFunction
                mean = .Average(dataSet)
                stdDev = .StDev(dataSet)
                dataMin = .Min(dataSet)
                dataMax = .Max(dataSet)
            End With
            suspect = IIf(Abs(dataMax - mean) > Abs(dataMin - mean), dataMax, dataMin)
            tmp = Abs(suspect - mean) / stdDev
            Set found = Selection.Find(What:=suspect, LookAt:=xlWhole)
            If tmp > lowConf Then
                With Selection
                    found.Interior.Color = RGB(255, 255, 0)
                    .Value = removeItemFromArray(dataSet, suspect)
                End With
                retest = True
            End If
            If tmp > highConf Then
                found.Interior.Color = RGB(255, 0, 0)
                retest = True
            End If
        End If
    Wend
End Sub
</code>```

```<code>'updates lowConf and highConf (byref)
Private Sub updateConfidences(ByRef dataSet As Variant, ByVal n As Long, _
                              ByRef lowConf As Double, ByRef highConf As Double)

    'DEFINES 95(LowConf) AND 99(HighConf) PERCENT CONFIDENCES BASED ON SAMPLE SIZE
    Select Case True
        Case n <= 5:   lowConf = 1.72:   highConf = 1.76
        Case n = 6:    lowConf = 1.89:   highConf = 1.97
        Case n = 7:    lowConf = 2.02:   highConf = 2.14
        Case n = 8:    lowConf = 2.13:   highConf = 2.28
        Case n = 9:    lowConf = 2.21:   highConf = 2.39
        Case n = 10:   lowConf = 2.29:   highConf = 2.48
        Case n = 11:   lowConf = 2.36:   highConf = 2.56
        Case n = 12:   lowConf = 2.41:   highConf = 2.64
        Case n = 13:   lowConf = 2.46:   highConf = 2.7
        Case n = 14:   lowConf = 2.51:   highConf = 2.75
        Case n = 15:   lowConf = 2.55:   highConf = 2.81
        Case n = 16:   lowConf = 2.59:   highConf = 2.85
        Case n = 17:   lowConf = 2.62:   highConf = 2.9
        Case n = 18:   lowConf = 2.65:   highConf = 2.93
        Case n = 19:   lowConf = 2.68:   highConf = 2.97
        Case n = 20:   lowConf = 2.71:   highConf = 3
        Case n = 21:   lowConf = 2.73:   highConf = 3.03
        Case n = 22:   lowConf = 2.76:   highConf = 3.06
        Case n = 23:   lowConf = 2.78:   highConf = 3.08
        Case n = 24:   lowConf = 2.8:    highConf = 3.11
        Case n = 25:   lowConf = 2.82:   highConf = 3.14
        Case n = 26:   lowConf = 2.84:   highConf = 3.16
        Case n = 27:   lowConf = 2.86:   highConf = 3.18
        Case n = 28:   lowConf = 2.88:   highConf = 3.2
        Case n = 29:   lowConf = 2.89:   highConf = 3.22
        Case n = 30:   lowConf = 2.91:   highConf = 3.24
        Case n <= 35:  lowConf = 2.98:   highConf = 3.32
        Case n <= 40:  lowConf = 3.04:   highConf = 3.38
        Case n <= 45:  lowConf = 3.09:   highConf = 3.44
        Case n <= 50:  lowConf = 3.13:   highConf = 3.48
        Case n <= 60:  lowConf = 3.2:    highConf = 3.56
        Case n <= 70:  lowConf = 3.26:   highConf = 3.62
        Case n <= 80:  lowConf = 3.31:   highConf = 3.67
        Case n <= 90:  lowConf = 3.35:   highConf = 3.72
        Case n <= 100: lowConf = 3.38:   highConf = 3.75
        Case n <= 150: lowConf = 3.52:   highConf = 3.89
        Case n <= 200: lowConf = 3.61:   highConf = 3.98
        Case n <= 300: lowConf = 3.72:   highConf = 4.09
        Case n <= 400: lowConf = 3.8:    highConf = 4.17
        Case n <= 500: lowConf = 3.86:   highConf = 4.32
        Case n > 500:  MsgBox "Sample size cannot exceed 500."
    End Select
End Sub
</code>```

```<code>Private Function removeItemFromArray(ByRef initialArray As Variant, _
                                     ByVal suspect As Double) As Variant

    Const dex As String = "#,###.00000"
    Dim i As Long, j As Long, dim1 As Long, dim2 As Long, arrayCopy As Variant

    dim1 = UBound(initialArray, 1)
    dim2 = UBound(initialArray, 2)

    ReDim arrayCopy(1 To dim1, 1 To dim2)

    For i = 1 To dim1
        For j = 1 To dim2
            If Format(initialArray(i, j), dex) <> Format(suspect, dex) Then
                arrayCopy(i, j) = initialArray(i, j)
            End If
        Next j
    Next i

    removeItemFromArray = arrayCopy

End Function
</code>```

Title: Delete value from array then resize

Body:
For reference, here is the whole code.

  Sub CalculateOutliers()

                Dim n As Long
                Dim mean As Double
                Dim SD As Double
                Dim k As Long
                Dim DataSet As Variant
                Dim LowConf As Double
                Dim HighConf As Double

            '--------------------------------------------------------
                DataSet = Selection.Value
            'Copies highlighted data into DataSet variable
            'Cell A1 is (1,1) Because it starts at 0 which is out of range
            '--------------------------------------------------------

            '--------------------------------------------------------
                n = Selection.CountLarge
            'Counts number of entries
            '--------------------------------------------------------

            '--------------------------------------------------------
             'DEFINES 95(LowConf) AND 99(HighConf) PERCENT CONFIDENCES BASED ON
             'SAMPLE SIZE

                If n <= 5 Then
                        LowConf = 1.72
                        HighConf = 1.76
                End If

                If n = 6 Then
                        LowConf = 1.89
                        HighConf = 1.97
                End If

                If n = 7 Then
                        LowConf = 2.02
                        HighConf = 2.14
                End If

                If n = 8 Then
                        LowConf = 2.13
                        HighConf = 2.28
                End If

                If n = 9 Then
                        LowConf = 2.21
                        HighConf = 2.39
                End If

                If n = 10 Then
                        LowConf = 2.29
                        HighConf = 2.48
                End If

                If n = 11 Then
                        LowConf = 2.36
                        HighConf = 2.56
                End If

                If n = 12 Then
                        LowConf = 2.41
                        HighConf = 2.64
                End If

                If n = 13 Then
                        LowConf = 2.46
                        HighConf = 2.7
                End If

                If n = 14 Then
                        LowConf = 2.51
                        HighConf = 2.75
                End If

                If n = 15 Then
                        LowConf = 2.55
                        HighConf = 2.81
                End If

                If n = 16 Then
                        LowConf = 2.59
                        HighConf = 2.85
                End If

                If n = 17 Then
                        LowConf = 2.62
                        HighConf = 2.9
                End If

                If n = 18 Then
                        LowConf = 2.65
                        HighConf = 2.93
                End If

                If n = 19 Then
                        LowConf = 2.68
                        HighConf = 2.97
                End If

                If n = 20 Then
                        LowConf = 2.71
                        HighConf = 3
                End If

                If n = 21 Then
                        LowConf = 2.73
                        HighConf = 3.03
                End If

                If n = 22 Then
                        LowConf = 2.76
                        HighConf = 3.06
                End If

                If n = 23 Then
                        LowConf = 2.78
                        HighConf = 3.08
                End If

                If n = 24 Then
                        LowConf = 2.8
                        HighConf = 3.11
                End If

                If n = 25 Then
                        LowConf = 2.82
                        HighConf = 3.14
                End If

                If n = 26 Then
                        LowConf = 2.84
                        HighConf = 3.16
                End If

                If n = 27 Then
                        LowConf = 2.86
                        HighConf = 3.18
                End If

                If n = 28 Then
                        LowConf = 2.88
                        HighConf = 3.2
                End If

                If n = 29 Then
                        LowConf = 2.89
                        HighConf = 3.22
                End If

                If n = 30 Then
                        LowConf = 2.91
                        HighConf = 3.24
                End If

                If n <= 35 And n > 30 Then
                        LowConf = 2.98
                        HighConf = 3.32
                End If

                If n <= 40 And n > 35 Then
                        LowConf = 3.04
                        HighConf = 3.38
                End If

                If n <= 45 And n > 40 Then
                        LowConf = 3.09
                        HighConf = 3.44
                End If

                If n <= 50 And n > 45 Then
                        LowConf = 3.13
                        HighConf = 3.48
                End If

                If n <= 60 And n > 50 Then
                        LowConf = 3.2
                        HighConf = 3.56
                End If

                If n <= 70 And n > 60 Then
                        LowConf = 3.26
                        HighConf = 3.62
                End If

                If n <= 80 And n > 70 Then
                        LowConf = 3.31
                        HighConf = 3.67
                End If

                If n <= 90 And n > 80 Then
                        LowConf = 3.35
                        HighConf = 3.72
                End If

                If n <= 100 And n > 90 Then
                        LowConf = 3.38
                        HighConf = 3.75
                End If

                If n <= 150 And n > 100 Then
                        LowConf = 3.52
                        HighConf = 3.89
                End If

                If n <= 200 And n > 150 Then
                        LowConf = 3.61
                        HighConf = 3.98
                End If

                If n <= 300 And n > 200 Then
                        LowConf = 3.72
                        HighConf = 4.09
                End If

                If n <= 400 And n > 300 Then
                        LowConf = 3.8
                        HighConf = 4.17
                End If

                If n <= 500 And n > 400 Then
                        LowConf = 3.86
                        HighConf = 4.32
                End If

                If n > 500 Then
                        MsgBox "Sample size cannot exceed 500."
                End If
            '--------------------------------------------------------

            '--------------------------------------------------------
                If n < 50 Then
                    k = Int(n / 10)
                Else
                    k = 5
                End If
            'determines k = number of possible outliers
            '--------------------------------------------------------

            Dim i As Long

            For i = 1 To k
            '--------------------------------------------------------
                mean = Application.WorksheetFunction.Average(DataSet)
            'Calculates mean of Data Set
            '--------------------------------------------------------

            '--------------------------------------------------------
                SD = Application.WorksheetFunction.StDev(DataSet)
            'Calculates Standard Deviation of Data Set
            '--------------------------------------------------------

            '--------------------------------------------------------
                Dim Suspect As Double

                If (Abs(Application.WorksheetFunction.Max(DataSet) - mean)) > (Abs(Application.WorksheetFunction.Min(DataSet) - mean)) Then

                    Suspect = Application.WorksheetFunction.Max(DataSet)

                End If

                If (Abs(Application.WorksheetFunction.Max(DataSet) - mean)) < (Abs(Application.WorksheetFunction.Min(DataSet) - mean)) Then

                    Suspect = Application.WorksheetFunction.Min(DataSet)

                End If
            'Defines what the most outlying value is
            '--------------------------------------------------------

            '--------------------------------------------------------
                Dim Retest As Boolean

                If (Abs(Suspect - mean) / SD) > LowConf Then
                    MsgBox "95% outlier: " & Suspect
                    Retest = True
                End If

                If (Abs(Suspect - mean) / SD) > HighConf Then
                    MsgBox "99% outlier: " & Suspect
                    Retest = True
                End If

                If Retest = True Then

            '--------------------------------------------------------
            Next i

            End Sub

Talking about this chunk of code, I need to delete Suspect from DataSet then shrink DataSet by 1 but I am not sure how to go about this. Is there a function that will delete the Max or Min value and is there a way to resize DataSet given that it is a variant?

                        Dim Retest As Boolean

                        If (Abs(Suspect - mean) / SD) > LowConf Then

                            MsgBox "95% outlier: " & Suspect
                            Retest = True

                    End If

                        If (Abs(Suspect - mean) / SD) > HighConf Then

                            MsgBox "99% outlier: " & Suspect
                            Retest = True

                    End If

                        If Retest = True Then

Body:
Here is how I would implement the solution (similar to @Tim's comment)

Sub calculateOutliers()
    Dim retest As Boolean, dataSet As Variant, n As Long, found As Range
    Dim lowConf As Double, highConf As Double, suspect As Double, tmp As Double
    Dim mean As Double, stdDev As Double, dataMin As Double, dataMax As Double

    retest = True
    While retest
        dataSet = Selection.Value
        n = Selection.CountLarge
        If Not IsEmpty(dataSet) Then
            updateConfidences dataSet, n, lowConf, highConf
            retest = False
            With Application.WorksheetFunction
                mean = .Average(dataSet)
                stdDev = .StDev(dataSet)
                dataMin = .Min(dataSet)
                dataMax = .Max(dataSet)
            End With
            suspect = IIf(Abs(dataMax - mean) > Abs(dataMin - mean), dataMax, dataMin)
            tmp = Abs(suspect - mean) / stdDev
            Set found = Selection.Find(What:=suspect, LookAt:=xlWhole)
            If tmp > lowConf Then
                With Selection
                    found.Interior.Color = RGB(255, 255, 0)
                    .Value = removeItemFromArray(dataSet, suspect)
                End With
                retest = True
            End If
            If tmp > highConf Then
                found.Interior.Color = RGB(255, 0, 0)
                retest = True
            End If
        End If
    Wend
End Sub

'updates lowConf and highConf (byref)
Private Sub updateConfidences(ByRef dataSet As Variant, ByVal n As Long, _
                              ByRef lowConf As Double, ByRef highConf As Double)

    'DEFINES 95(LowConf) AND 99(HighConf) PERCENT CONFIDENCES BASED ON SAMPLE SIZE
    Select Case True
        Case n <= 5:   lowConf = 1.72:   highConf = 1.76
        Case n = 6:    lowConf = 1.89:   highConf = 1.97
        Case n = 7:    lowConf = 2.02:   highConf = 2.14
        Case n = 8:    lowConf = 2.13:   highConf = 2.28
        Case n = 9:    lowConf = 2.21:   highConf = 2.39
        Case n = 10:   lowConf = 2.29:   highConf = 2.48
        Case n = 11:   lowConf = 2.36:   highConf = 2.56
        Case n = 12:   lowConf = 2.41:   highConf = 2.64
        Case n = 13:   lowConf = 2.46:   highConf = 2.7
        Case n = 14:   lowConf = 2.51:   highConf = 2.75
        Case n = 15:   lowConf = 2.55:   highConf = 2.81
        Case n = 16:   lowConf = 2.59:   highConf = 2.85
        Case n = 17:   lowConf = 2.62:   highConf = 2.9
        Case n = 18:   lowConf = 2.65:   highConf = 2.93
        Case n = 19:   lowConf = 2.68:   highConf = 2.97
        Case n = 20:   lowConf = 2.71:   highConf = 3
        Case n = 21:   lowConf = 2.73:   highConf = 3.03
        Case n = 22:   lowConf = 2.76:   highConf = 3.06
        Case n = 23:   lowConf = 2.78:   highConf = 3.08
        Case n = 24:   lowConf = 2.8:    highConf = 3.11
        Case n = 25:   lowConf = 2.82:   highConf = 3.14
        Case n = 26:   lowConf = 2.84:   highConf = 3.16
        Case n = 27:   lowConf = 2.86:   highConf = 3.18
        Case n = 28:   lowConf = 2.88:   highConf = 3.2
        Case n = 29:   lowConf = 2.89:   highConf = 3.22
        Case n = 30:   lowConf = 2.91:   highConf = 3.24
        Case n <= 35:  lowConf = 2.98:   highConf = 3.32
        Case n <= 40:  lowConf = 3.04:   highConf = 3.38
        Case n <= 45:  lowConf = 3.09:   highConf = 3.44
        Case n <= 50:  lowConf = 3.13:   highConf = 3.48
        Case n <= 60:  lowConf = 3.2:    highConf = 3.56
        Case n <= 70:  lowConf = 3.26:   highConf = 3.62
        Case n <= 80:  lowConf = 3.31:   highConf = 3.67
        Case n <= 90:  lowConf = 3.35:   highConf = 3.72
        Case n <= 100: lowConf = 3.38:   highConf = 3.75
        Case n <= 150: lowConf = 3.52:   highConf = 3.89
        Case n <= 200: lowConf = 3.61:   highConf = 3.98
        Case n <= 300: lowConf = 3.72:   highConf = 4.09
        Case n <= 400: lowConf = 3.8:    highConf = 4.17
        Case n <= 500: lowConf = 3.86:   highConf = 4.32
        Case n > 500:  MsgBox "Sample size cannot exceed 500."
    End Select
End Sub

Private Function removeItemFromArray(ByRef initialArray As Variant, _
                                     ByVal suspect As Double) As Variant

    Const dex As String = "#,###.00000"
    Dim i As Long, j As Long, dim1 As Long, dim2 As Long, arrayCopy As Variant

    dim1 = UBound(initialArray, 1)
    dim2 = UBound(initialArray, 2)

    ReDim arrayCopy(1 To dim1, 1 To dim2)

    For i = 1 To dim1
        For j = 1 To dim2
            If Format(initialArray(i, j), dex) <> Format(suspect, dex) Then
                arrayCopy(i, j) = initialArray(i, j)
            End If
        Next j
    Next i

    removeItemFromArray = arrayCopy

End Function