问:
iOS app crashes with EXC_CRASH (SIGKILL) when launched via TestFlight, but runs fine from Xcode
I'm running into a strange issue whereby an app I'm building crashes shortly after launching as an archived build from TestFlight, but runs without issue when running on the same device directly from Xcode. The application doesn't appear to be terminating fully - if I double-tap the home button, I see what looks like an image of the application in the background from midway through a run, even though the new session crashed long before it would have gotten to the displayed screen. If I then bring the application back to the foreground, it returns to its loading screen and then shuts down again, with a log that looks like this:

```<code>Incident Identifier: 983F8E4E-EFE0-4C93-8F46-D223FD86DF14
CrashReporter Key:   3515df1d8c55a27394a78b6efee5f83946ed9a99
Hardware Model:      iPhone7,2
Process:             FileProvider [218]
Path:                /private/var/containers/Bundle/Application/89708FF4-E848-4F49-BC0D-B2DC9EF536C6/Drive.app/PlugIns/FileProvider.appex/FileProvider
Identifier:          com.google.Drive.FileProviderExtension
Version:             4.2017.25202 (4.2017.25202)
Code Type:           ARM-64 (Native)
Role:                Unspecified
Parent Process:      launchd [1]
Coalition:           com.google.Drive.FileProviderExtension [368]

Date/Time:           2017-06-30 22:59:01.2937 -0700
Launch Time:         2017-06-30 22:59:00.7649 -0700
OS Version:          iPhone OS 10.3.2 (14F89)
Report Version:      104

Exception Type:  EXC_CRASH (SIGKILL)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: Namespace <0xF>, Code 0xdead10cc
Triggered by Thread:  0
</code>```

...Any thoughts on what I should be investigating to understand what's going on here?

App is built in C++ using the Cocos2d-x framework.

Thanks!
_Kevin

答:
Figured out what was going on, if not yet exactly why. Some of the details posted above turned out to be red herrings as I investigated further. What initially appeared to be a difference in behavior between an archived build and a build launched directly from Xcode was actually a difference in behavior between a debug build and a release build.

The solution was to create a new scheme in Xcode to run a release build (Product->Scheme->Manage Schemes in Xcode 8.3), duplicate my default mobile scheme, and then set the new scheme's Run->Info->Build Configuration to Release.

Once I ran a release build with Xcode attached, I found an error (probably an incorrectly-initialized variable but I'm still investigating) that occurred in release builds only.

The reason why crash logs weren't being generated appears to have been that the error was causing an assertion to trip (the CC_ASSERT macro in Cocos2d-x), so iOS considered the app shutdown to be a legitimate termination and didn't log it as a crash.

Body:
I'm running into a strange issue whereby an app I'm building crashes shortly after launching as an archived build from TestFlight, but runs without issue when running on the same device directly from Xcode. The application doesn't appear to be terminating fully - if I double-tap the home button, I see what looks like an image of the application in the background from midway through a run, even though the new session crashed long before it would have gotten to the displayed screen. If I then bring the application back to the foreground, it returns to its loading screen and then shuts down again, with a log that looks like this:

Incident Identifier: 983F8E4E-EFE0-4C93-8F46-D223FD86DF14
CrashReporter Key:   3515df1d8c55a27394a78b6efee5f83946ed9a99
Hardware Model:      iPhone7,2
Process:             FileProvider [218]
Path:                /private/var/containers/Bundle/Application/89708FF4-E848-4F49-BC0D-B2DC9EF536C6/Drive.app/PlugIns/FileProvider.appex/FileProvider
Identifier:          com.google.Drive.FileProviderExtension
Version:             4.2017.25202 (4.2017.25202)
Code Type:           ARM-64 (Native)
Role:                Unspecified
Parent Process:      launchd [1]
Coalition:           com.google.Drive.FileProviderExtension [368]

Date/Time:           2017-06-30 22:59:01.2937 -0700
Launch Time:         2017-06-30 22:59:00.7649 -0700
OS Version:          iPhone OS 10.3.2 (14F89)
Report Version:      104

Exception Type:  EXC_CRASH (SIGKILL)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: Namespace <0xF>, Code 0xdead10cc
Triggered by Thread:  0

...Any thoughts on what I should be investigating to understand what's going on here?

App is built in C++ using the Cocos2d-x framework.

Thanks!
_Kevin


来源: stackexchange

问:
Ajax Error: Unexpected token < in JSON at position 0 on WordPress Contact Form 7 submit
I have a weird issue when posting an contact form.

The loading icon keeps loading and the form does not submit.

The emails are sended and my before_send_mail functions also works. The weird thing is when i uncomment the before_send_mail function, it shows no errors. So it's probably something from my code.

However the frontpage is not changing status and keeps showing the loading icon.

The error message sais:

```<code><div class="ajax-error">Unexpected token < in JSON at position 0</div>
</code>```

Can you guys help me out? Below you'll find the before_send function.

```<code>add_action( 'wpcf7_before_send_mail', 'form_to_crm' );
function form_to_crm( $cf7 ) {
    $wpcf7 = WPCF7_ContactForm::get_current();

    /* Uw naam   => first_name    */ $first_name            = $_POST["your-name"];
    /* Bedrijf   => company_name  */ $company               = $_POST["bedrijf"];
    /* Email     => email         */ $email                 = $_POST["email"];
    /* Adres     => address       */ $address               = $_POST["adres"];
    /* Nummer*   => number        */ $number                = $_POST["huisnummer"];
    /* Postcode  => postcode      */ $postcode              = $_POST["postcode"];
    /* Woonplts* => city          */ $city                  = $_POST["woonplaats"];
    /* Tel       => telephone     */ $telephone             = $_POST["telefoonnummer"];

    if(!empty( $first_name )){          $post_items['first_name']           =  $first_name; }
    if(!empty( $company )){             $post_items['company_name']         =  $company; }
    if(!empty( $email )){               $post_items['email']                =  $email; }
    if(!empty( $address )){             $post_items['address']              =  $address; }
    if(!empty( $number )){              $post_items['number']               =  $number; }
    if(!empty( $postcode )){            $post_items['postcode']             =  $postcode; }
    if(!empty( $city )){                $post_items['city']                 =  $city; }
    if(!empty( $telephone )){           $post_items['telephone']            =  $telephone; }

    if(!empty($postcode) && !empty($number))
    {
        $ch             = curl_init();

        if ( curl_error($ch) != "" )
        {
            return;
        }

        $post_string    = json_encode($post_items);

        $con_url        = 'valid api url';

        curl_setopt($ch, CURLOPT_URL, $con_url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
            "Authorization: Token XXX (censored)"
        ));
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

        $output = curl_exec($ch);

        file_put_contents("curlerror.txt", $output);
        curl_close($ch);
    }
    return $output;
}
</code>```

答:
@Senta 's answer helped me find the cause of the error for me. It turned out that the response being received by CF7's AJAX call wasn't just the JSON response from CF7, but another plugin was adding stuff into it, causing the AJAX to fail because it was expecting a json format, and was now horrendously invalid (what was only supposed to be 1 line of JSON turned into 300+ lines of other stuff prepended to it).

I don't like editing plugins, but I did this to help resolve this issue and allow CF7 to play well with others and it now looks like this:

contact-form-7/includes/js/scripts.js OR if you're using the jQuery validation plugin for Contact Form 7, you'll want jquery-validation-for-contact-form-7/js/jquery.jvcf7_validation.js

```<code>$.ajax({
    type: 'POST',
    url: wpcf7.apiSettings.root + wpcf7.apiSettings.namespace +
        '/contact-forms/' + wpcf7.getId($form) + '/feedback',
    data: formData,
    dataType: 'text',//Changed from 'json' to 'text'
    processData: false,
    contentType: false
    }).done(function(data, status, xhr) {
        var f = data.indexOf('{'); //First opening curly-brace
        var l = data.lastIndexOf('{'); //Last opening curly-brace
        if (f !== l && data.indexOf("{") !== 0 && l !== 0) {
            //If the first and last indices are not the same, and neither the first nor the last are equal to 0,
            //then get the data that starts from the last index
            data = data.substring(l);
        } else if (f === l && f !== 0) {
            //If the first and last indices are the same, but are not the first character,
            //then get the data that starts from the first index
            data = data.substring(f);
        }
        $('.ajax-loader', $form).removeClass('is-active');
        try {
            //Try parsing the data as JSON now and submitting it
            data = JSON.parse(data);
            ajaxSuccess(data, status, xhr, $form);
        } catch (err) {
            //Do the same error stuff as the fail() call if it still fails
            var $e = $('<div class="ajax-error"</div>').text(err);
            $form.after($e);
        }
    }).fail(function(xhr, status, error) {
        $('.ajax-loader', $form).removeClass('is-active');
        var $e = $('<div class="ajax-error"></div>').text(error.message);
        $form.after($e);
});
</code>```

I do not condone editing other developer's plugins, and this may not work for everyone who has this issue. This is just a temporary fix until we can find a different plugin that will play nice with CF7.

Edit:

Today, I came across this error again. Turns out that setting WP_DEBUG to false in your wp-config.php settings also resolves this error, as the stuff that gets prepended to the AJAX response is a bunch of debugging logs. Helpful if you're actually debugging it, but otherwise I'd keep it off on your production environments.

ContentLicense: CC BY-SA 3.0

Body:
I have a weird issue when posting an contact form.

The loading icon keeps loading and the form does not submit.

The emails are sended and my before_send_mail functions also works. The weird thing is when i uncomment the before_send_mail function, it shows no errors. So it's probably something from my code.

However the frontpage is not changing status and keeps showing the loading icon.

The error message sais:

Unexpected token < in JSON at position 0

Can you guys help me out? Below you'll find the before_send function.

add_action( 'wpcf7_before_send_mail', 'form_to_crm' );
function form_to_crm( $cf7 ) {
    $wpcf7 = WPCF7_ContactForm::get_current();

    /* Uw naam   => first_name    */ $first_name            = $_POST["your-name"];
    /* Bedrijf   => company_name  */ $company               = $_POST["bedrijf"];
    /* Email     => email         */ $email                 = $_POST["email"];
    /* Adres     => address       */ $address               = $_POST["adres"];
    /* Nummer*   => number        */ $number                = $_POST["huisnummer"];
    /* Postcode  => postcode      */ $postcode              = $_POST["postcode"];
    /* Woonplts* => city          */ $city                  = $_POST["woonplaats"];
    /* Tel       => telephone     */ $telephone             = $_POST["telefoonnummer"];

    if(!empty( $first_name )){          $post_items['first_name']           =  $first_name; }
    if(!empty( $company )){             $post_items['company_name']         =  $company; }
    if(!empty( $email )){               $post_items['email']                =  $email; }
    if(!empty( $address )){             $post_items['address']              =  $address; }
    if(!empty( $number )){              $post_items['number']               =  $number; }
    if(!empty( $postcode )){            $post_items['postcode']             =  $postcode; }
    if(!empty( $city )){                $post_items['city']                 =  $city; }
    if(!empty( $telephone )){           $post_items['telephone']            =  $telephone; }

    if(!empty($postcode) && !empty($number))
    {
        $ch             = curl_init();

        if ( curl_error($ch) != "" )
        {
            return;
        }

        $post_string    = json_encode($post_items);

        $con_url        = 'valid api url';

        curl_setopt($ch, CURLOPT_URL, $con_url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
            "Authorization: Token XXX (censored)"
        ));
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

        $output = curl_exec($ch);

        file_put_contents("curlerror.txt", $output);
        curl_close($ch);
    }
    return $output;
}

Body:
@Senta 's answer helped me find the cause of the error for me. It turned out that the response being received by CF7's AJAX call wasn't just the JSON response from CF7, but another plugin was adding stuff into it, causing the AJAX to fail because it was expecting a json format, and was now horrendously invalid (what was only supposed to be 1 line of JSON turned into 300+ lines of other stuff prepended to it).

I don't like editing plugins, but I did this to help resolve this issue and allow CF7 to play well with others and it now looks like this:

contact-form-7/includes/js/scripts.js OR if you're using the jQuery validation plugin for Contact Form 7, you'll want jquery-validation-for-contact-form-7/js/jquery.jvcf7_validation.js

$.ajax({
    type: 'POST',
    url: wpcf7.apiSettings.root + wpcf7.apiSettings.namespace +
        '/contact-forms/' + wpcf7.getId($form) + '/feedback',
    data: formData,
    dataType: 'text',//Changed from 'json' to 'text'
    processData: false,
    contentType: false
    }).done(function(data, status, xhr) {
        var f = data.indexOf('{'); //First opening curly-brace
        var l = data.lastIndexOf('{'); //Last opening curly-brace
        if (f !== l && data.indexOf("{") !== 0 && l !== 0) {
            //If the first and last indices are not the same, and neither the first nor the last are equal to 0,
            //then get the data that starts from the last index
            data = data.substring(l);
        } else if (f === l && f !== 0) {
            //If the first and last indices are the same, but are not the first character,
            //then get the data that starts from the first index
            data = data.substring(f);
        }
        $('.ajax-loader', $form).removeClass('is-active');
        try {
            //Try parsing the data as JSON now and submitting it
            data = JSON.parse(data);
            ajaxSuccess(data, status, xhr, $form);
        } catch (err) {
            //Do the same error stuff as the fail() call if it still fails
            var $e = $('<div class="ajax-error"</div>').text(err);
            $form.after($e);
        }
    }).fail(function(xhr, status, error) {
        $('.ajax-loader', $form).removeClass('is-active');
        var $e = $('<div class="ajax-error"></div>').text(error.message);
        $form.after($e);
});

I do not condone editing other developer's plugins, and this may not work for everyone who has this issue. This is just a temporary fix until we can find a different plugin that will play nice with CF7.

Edit:

Today, I came across this error again. Turns out that setting WP_DEBUG to false in your wp-config.php settings also resolves this error, as the stuff that gets prepended to the AJAX response is a bunch of debugging logs. Helpful if you're actually debugging it, but otherwise I'd keep it off on your production environments.


答: It could be as simple as adding an extra column with the formula =IF(ISERROR(MATCH(A2,Sheet2!A:A)),"Not in Sheet2", "In Sheet2"), filling it down, filtering out the values you don't need (i.e. Not in Sheet1), and copying and pasting the rows you have left.

Title: Filter and copy rows based on condition

Body:
Quick question, if I have a situation like this:

Sheet 1:
A            B              C          D
92154   3.463259084 3.453471286 1.413287181
93035   176.4177028 175.9135241 71.26510962
92225   0.363370029 0.362457518 0.169233799
92203   451.6206281 450.3298896 182.8851898

Sheet 2:
A            B              C          D
92203   451.6206281 450.3298896 182.8851898
92128   0.173532938 0.173036996 0.069032896
95991   1.118337369 1.11514121  0.435568007
93720   3.224674108 3.215457886 1.28377433
93430   2.047732493 2.042590079 0.974083112

And I want to copy all rows within Sheet 2, if the zip code (column A) does not match with Sheet 1. So in this case, I would ideally copy and paste the last 4 rows from Sheet 2 into another new tab sheet.


问:
force gridview rows to row hight
I have a table that comes from Access. added the datasource and get this in the grid view. There is a column called comments. This column can have a lot of text in it. When I run it in internet explorer, the rows are inflated to show all the text. Even if I set the row hight in the code, it still pops up like that. I did a lot of google searches, but all points to the row hight, but I can't make it work.

Is there something I missed out? or it simply does force the row hight  to fit all text?

Greetings.

答:
Try applying this CSS to hide the extra stuff.</p>

```<code>.ellipsis {
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 50px;
    display: block;
    overflow: hidden;
}
</code>```

Title: force gridview rows to row hight

Body:
Try applying this CSS to hide the extra stuff.

.ellipsis {
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 50px;
    display: block;
    overflow: hidden;
}


问:
I can´t access my entire local web from Android phone via local network
I been searching for a similar question, but I cannot find someone who has the same problem as me.

I´m using XAMPP V3.2.2 . I can get access to my local web from my Android phone with Chrome (wich it's connected to the same network as my laptop), just by typing my laptop IPV4 address and then /index.php/controller/id (because I´m using Codeigniter framework). So the URL in Chrome of my Android phone is something like:

192.168.xx.xx/index.php/principal/index

At this point I can access to the principal and admin webpages (background image is loaded and also Bootstrap and css) This is how it looks . But here is where some problems begin to appear.

One of them is that the images in the main webpage are not loaded. As I say, the background image load without any problem, but the images of the gallery are not loaded.

Another problem appears when I try to use some functions in the admins webpage like "Delete a photo" or "Upload an image". When y press the submit button of, for example the "Upload an image" form (here is the html):

```<code><form action="http://localhost/index.php/principal/subir_foto" enctype="multipart/form-data" method="post" accept-charset="utf-8">
                <label  class='control-label'>Seleccionar:</label>
                <input id="img" required="true" type='file' name='imagen'/>
            <div class='input-group'>
                <label class='control-label'>Descripción:</label>
                <input type='text' name='alt' placeholder='Descripción'>
            </div>
            <div class='input-group'>
                <input type='submit' name='agregar' value="Agregar">
            </div>
           </form>
</code>```

I put the code just to illustrate, it works fine in my laptop, I can upload photos, delete them, create new categories and so on. But as I was saying before, when I try to do those things in my phone and press the submit button, the browser show me this page -> Error page

So, I hope someone has the same problem and could give my a solution.

Thanks

答:
Well I finally solve the problem...

In the Codeigniter Config.php file, I change:

from

```<code>$config['base_url'] = 'http://localhost/';
</code>```

to

```<code>$localIP = getHostByName(getHostName());
$config['base_url'] = 'http://'.$localIP.'/';
</code>```

So now I´m giving to CodeIgniter the Server IP dynamically, and now mobile devices can search images from the server IP and not from themselves like with "localhost" before.

Body:
I been searching for a similar question, but I cannot find someone who has the same problem as me.

I´m using XAMPP V3.2.2 . I can get access to my local web from my Android phone with Chrome (wich it's connected to the same network as my laptop), just by typing my laptop IPV4 address and then /index.php/controller/id (because I´m using Codeigniter framework). So the URL in Chrome of my Android phone is something like:

192.168.xx.xx/index.php/principal/index

At this point I can access to the principal and admin webpages (background image is loaded and also Bootstrap and css) This is how it looks . But here is where some problems begin to appear.

One of them is that the images in the main webpage are not loaded. As I say, the background image load without any problem, but the images of the gallery are not loaded.

Another problem appears when I try to use some functions in the admins webpage like "Delete a photo" or "Upload an image". When y press the submit button of, for example the "Upload an image" form (here is the html):

<form action="http://localhost/index.php/principal/subir_foto" enctype="multipart/form-data" method="post" accept-charset="utf-8">
                Seleccionar:
                <input id="img" required="true" type='file' name='imagen'/>

                Descripción:
                <input type='text' name='alt' placeholder='Descripción'>

                <input type='submit' name='agregar' value="Agregar">

           </form>

I put the code just to illustrate, it works fine in my laptop, I can upload photos, delete them, create new categories and so on. But as I was saying before, when I try to do those things in my phone and press the submit button, the browser show me this page -> Error page

So, I hope someone has the same problem and could give my a solution.

Thanks

Body:
Well I finally solve the problem...

In the Codeigniter Config.php file, I change:

from

$config['base_url'] = 'http://localhost/';

to

$localIP = getHostByName(getHostName());
$config['base_url'] = 'http://'.$localIP.'/';

So now I´m giving to CodeIgniter the Server IP dynamically, and now mobile devices can search images from the server IP and not from themselves like with "localhost" before.

ContentLicense: CC BY-SA 4.0


问:
Code challenge: finding the divisible in a list
I am playing a code challenge. Simply speaking, the problem is:

Given a list L (max length is of the order of 1000) containing positive integers.
  Find the number of "Lucky Triples", which is L[i] divides L[j], and L[j] divides L[k].

for example, [1,2,3,4,5,6] should give the answer 3 because [1,2,4], [1,2,6],[1,3,6]

My attempt:

Sort the list. (let say there are n elements)

3 For loops: i, j, k (i from 1 to n-2), (j from i+1 to n-1), (k from j+1 to n)

only if L[j] % L[i] == 0, the k for loop will be executed

The algorithm seems to give the correct answer. But the challenge said that my code exceeded the time limit. I tried on my computer for the list [1,2,3,...,2000], count = 40888(I guess it is correct). The time is around 5 second.

Is there any faster way to do that?

This is the code I have written in python.

```<code>def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt
</code>```

答:
Thank you guys for all your suggestions. They are brilliant. But it seems that I still can't pass the speed test or I cannot handle with duplicated elements.

After discussing with my friend, I have just come up with another solution. It should be O(n^2) and I passed the speed test. Thanks all!!

```<code>def answer(lst):
    lst.sort()
    count = 0
    if len(lst) == 2:
        return count

    #for each middle element, count the divisors at the front and the multiples at the back. Then multiply them.
    for i, middle in enumerate(lst[1:len(lst)-1], start = 1):
        countfirst = 0
        countthird = 0
        for first in (lst[0:i]):
            if middle % first == 0:
                countfirst += 1
        for third in (lst[i+1:]):
            if third % middle == 0:
                countthird += 1
        count += countfirst*countthird

    return count
</code>```

Body:
I am playing a code challenge. Simply speaking, the problem is:

Given a list L (max length is of the order of 1000) containing positive integers.
  Find the number of "Lucky Triples", which is L[i] divides L[j], and L[j] divides L[k].

for example, [1,2,3,4,5,6] should give the answer 3 because [1,2,4], [1,2,6],[1,3,6]

My attempt:

Sort the list. (let say there are n elements)

3 For loops: i, j, k (i from 1 to n-2), (j from i+1 to n-1), (k from j+1 to n)

only if L[j] % L[i] == 0, the k for loop will be executed

The algorithm seems to give the correct answer. But the challenge said that my code exceeded the time limit. I tried on my computer for the list [1,2,3,...,2000], count = 40888(I guess it is correct). The time is around 5 second.

Is there any faster way to do that?

This is the code I have written in python.

def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt

Body:
Thank you guys for all your suggestions. They are brilliant. But it seems that I still can't pass the speed test or I cannot handle with duplicated elements.

After discussing with my friend, I have just come up with another solution. It should be O(n^2) and I passed the speed test. Thanks all!!

def answer(lst):
    lst.sort()
    count = 0
    if len(lst) == 2:
        return count

    #for each middle element, count the divisors at the front and the multiples at the back. Then multiply them.
    for i, middle in enumerate(lst[1:len(lst)-1], start = 1):
        countfirst = 0
        countthird = 0
        for first in (lst[0:i]):
            if middle % first == 0:
                countfirst += 1
        for third in (lst[i+1:]):
            if third % middle == 0:
                countthird += 1
        count += countfirst*countthird

    return count


问:
Swift3 Play multiple video files with AVPlayer
I have a little code which allows me to play a local file when I hit a UIButton. But what I want is to play multiple files on 3 different UIButtons because I have 3 video files which I want to attach to my app.

This is the current code:

```<code>import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {

    var playerController = AVPlayerViewController()
    var player:AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let videoString:String? = Bundle.main.path(forResource: "Video", ofType: ".mp4")

        if let url = videoString {

            let videoURL = NSURL(fileURLWithPath: url)

            self.player = AVPlayer(url: videoURL as URL)
            self.playerController.player = self.player

        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func PlayVideo(_ sender: AnyObject) {

        self.present(self.playerController, animated: true, completion: {

            self.playerController.player?.play()

        })

    }

}
</code>```

答:
You can create url for different video file in your button click funtions</p>

```<code>@IBAction func Button1Click(_ sender: AnyObject) {
    let videoString:String? = Bundle.main.path(forResource: "Video1", ofType: ".mp4")

    if let url = videoString {
        let videoURL = NSURL(fileURLWithPath: url)
        self.player = AVPlayer(url: videoURL as URL)
        self.playerController.player = self.player
    }

    self.present(self.playerController, animated: true, completion: {
        self.playerController.player?.play()

    })

}

@IBAction func Button2Click(_ sender: AnyObject) {
    let videoString:String? = Bundle.main.path(forResource: "Video2", ofType: ".mp4")

    if let url = videoString {
        let videoURL = NSURL(fileURLWithPath: url)
        self.player = AVPlayer(url: videoURL as URL)
        self.playerController.player = self.player
    }

    self.present(self.playerController, animated: true, completion: {
        self.playerController.player?.play()

    })

}

@IBAction func Button3Click(_ sender: AnyObject) {
    let videoString:String? = Bundle.main.path(forResource: "Video3", ofType: ".mp4")

    if let url = videoString {
        let videoURL = NSURL(fileURLWithPath: url)
        self.player = AVPlayer(url: videoURL as URL)
        self.playerController.player = self.player
    }

    self.present(self.playerController, animated: true, completion: {
        self.playerController.player?.play()

    })

}
</code>```

Body:
I have a little code which allows me to play a local file when I hit a UIButton. But what I want is to play multiple files on 3 different UIButtons because I have 3 video files which I want to attach to my app.

This is the current code:

import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {

    var playerController = AVPlayerViewController()
    var player:AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let videoString:String? = Bundle.main.path(forResource: "Video", ofType: ".mp4")

        if let url = videoString {

            let videoURL = NSURL(fileURLWithPath: url)

            self.player = AVPlayer(url: videoURL as URL)
            self.playerController.player = self.player

        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func PlayVideo(_ sender: AnyObject) {

        self.present(self.playerController, animated: true, completion: {

            self.playerController.player?.play()

        })

    }

}

Body:
You can create url for different video file in your button click funtions

@IBAction func Button1Click(_ sender: AnyObject) {
    let videoString:String? = Bundle.main.path(forResource: "Video1", ofType: ".mp4")

    if let url = videoString {
        let videoURL = NSURL(fileURLWithPath: url)
        self.player = AVPlayer(url: videoURL as URL)
        self.playerController.player = self.player
    }

    self.present(self.playerController, animated: true, completion: {
        self.playerController.player?.play()

    })

}

@IBAction func Button2Click(_ sender: AnyObject) {
    let videoString:String? = Bundle.main.path(forResource: "Video2", ofType: ".mp4")

    if let url = videoString {
        let videoURL = NSURL(fileURLWithPath: url)
        self.player = AVPlayer(url: videoURL as URL)
        self.playerController.player = self.player
    }

    self.present(self.playerController, animated: true, completion: {
        self.playerController.player?.play()

    })

}

@IBAction func Button3Click(_ sender: AnyObject) {
    let videoString:String? = Bundle.main.path(forResource: "Video3", ofType: ".mp4")

    if let url = videoString {
        let videoURL = NSURL(fileURLWithPath: url)
        self.player = AVPlayer(url: videoURL as URL)
        self.playerController.player = self.player
    }

    self.present(self.playerController, animated: true, completion: {
        self.playerController.player?.play()

    })

}


问:
Creating category to show hours as a KPI
Need help with calculation in Tableau. I have field as priority High, Medium and Low.

For High and medium i have the TAT as 2 hours and for low it is 4 hours.

I need to add a calculation which for each ticket based on their priority level shows respective priority hours as either 2 or 4 hours.

I have added a calculation :

```<code>if [Priority]= "High" then "2 Hours"
ELSEIF [Priority]= "Medium" then "2 Hours"
ELSE "4 Hours"
END
</code>```

however this is a string whereas i need it in hour format so that i can add a flag whether ticket missed or met the SLA.

This i would do basis another column which is time taken to acknowledge.

答:
Let’s consider Start Time = 07/06/2017 5:30:00 AM and End Time = 07/06/2017 8:40:00 AM

Create a calculated field (time_diff_seconds) to calculate time difference between start & end time

```<code>(DATEDIFF('hour’,[Start Time],[End Time]) * 3600) + (DATEDIFF(‘minute’,[Start Time],[End Time]) * 60) + DATEDIFF(’second’,[Start Time],[End Time])
</code>```

Now coming back to your calculated field (SLA_seconds) definition, I would modify it to look something like:

```<code>IF [Priority]= "High" then 2*3600
ELSEIF [Priority]= "Medium" then 2*3600
ELSE 4*3600
END
</code>```

Then finally create your flag as another calculated field i.e. SLA_met

```<code>IF time_diff_seconds <= SLA_seconds THEN “Y”
ELSE “N”
END
</code>```

Hope this helps! Pls don't forget to mention if it solves your problem :)

Body:
Need help with calculation in Tableau. I have field as priority High, Medium and Low.

For High and medium i have the TAT as 2 hours and for low it is 4 hours.

I need to add a calculation which for each ticket based on their priority level shows respective priority hours as either 2 or 4 hours.

I have added a calculation :

if [Priority]= "High" then "2 Hours"
ELSEIF [Priority]= "Medium" then "2 Hours"
ELSE "4 Hours"
END

however this is a string whereas i need it in hour format so that i can add a flag whether ticket missed or met the SLA.

This i would do basis another column which is time taken to acknowledge.

Body:
Let’s consider Start Time = 07/06/2017 5:30:00 AM and End Time = 07/06/2017 8:40:00 AM

Create a calculated field (time_diff_seconds) to calculate time difference between start & end time

(DATEDIFF('hour’,[Start Time],[End Time]) * 3600) + (DATEDIFF(‘minute’,[Start Time],[End Time]) * 60) + DATEDIFF(’second’,[Start Time],[End Time])

Now coming back to your calculated field (SLA_seconds) definition, I would modify it to look something like:

IF [Priority]= "High" then 2*3600
ELSEIF [Priority]= "Medium" then 2*3600
ELSE 4*3600
END

Then finally create your flag as another calculated field i.e. SLA_met

IF time_diff_seconds <= SLA_seconds THEN “Y”
ELSE “N”
END

Hope this helps! Pls don't forget to mention if it solves your problem :)


问:
Send Mail using PHP failing
I am using the same php code I have always used to try and send a form via email and I am getting this message:

Warning: mail() [function.mail]:
  Failed to connect to mailserver at
  "localhost" port 25, verify your
  "SMTP" and "smtp_port" setting in
  php.ini or use ini_set() in
  sendMailSuscribete.php on line 44

this are lines 40 - 54:

```<code>$header .= "From: $email" . "\r\n";
$header .= "Reply-To: $email" . "\r\n";
$header .= "Return-Path: $email" . "\r\n";

if(mail($to, $subject, $msg, $header)){
    //Message sent!
    redirect("http://www.domain.com/suscribete.html");
}else{
    // Display error message if the message failed to send
    echo "
    <div class=\"MsgError\">
        <h1>Error…</h1>
        <p>Disculpa <b><?=$name;?></b>, tu mensaje falló en ser enviado. Por favor vuelve a intentar.</p>
</div>";
}
</code>```

I already checked using phpinfo() and I know that the smtp is set to localhost and the port it uses is 25 so I really have no idea what the error may be.

Update
I forgot to say it is running on a Windows server and this php file is the one I've always used for Unix servers, should it contain something different?

答:
Can you try using an external SMTP mail server, for example, Gmail's? If you have a Gmail account, you can try adding this before your mail command:

```<code>ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
ini_set("username","<myaccount.gmail.com>"); # You need to change this
ini_set("password","YOUR_PASSWORD"); # You need to change this
</code>```

I haven't tested these settings, but it should send you in the right direction.

ContentLicense: CC BY-SA 2.5

Title: Send Mail using PHP failing

Body:
I am using the same php code I have always used to try and send a form via email and I am getting this message:

Warning: mail() [function.mail]:
  Failed to connect to mailserver at
  "localhost" port 25, verify your
  "SMTP" and "smtp_port" setting in
  php.ini or use ini_set() in
  sendMailSuscribete.php on line 44

this are lines 40 - 54:

$header .= "From: $email" . "\r\n";
$header .= "Reply-To: $email" . "\r\n";
$header .= "Return-Path: $email" . "\r\n";

if(mail($to, $subject, $msg, $header)){
    //Message sent!
    redirect("http://www.domain.com/suscribete.html");
}else{
    // Display error message if the message failed to send
    echo "

Error…

Disculpa <?=$name;?>, tu mensaje falló en ser enviado. Por favor vuelve a intentar.

";
}

I already checked using phpinfo() and I know that the smtp is set to localhost and the port it uses is 25 so I really have no idea what the error may be.

Update
I forgot to say it is running on a Windows server and this php file is the one I've always used for Unix servers, should it contain something different?

Body:
Can you try using an external SMTP mail server, for example, Gmail's? If you have a Gmail account, you can try adding this before your mail command:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
ini_set("username","<myaccount.gmail.com>"); # You need to change this
ini_set("password","YOUR_PASSWORD"); # You need to change this

I haven't tested these settings, but it should send you in the right direction.


问:
Is there any performance difference between `if let` and `if` for a boolean?
For example:

```<code>let mut v = vec![2, 3, 4];
if let false = v.is_empty() {
    v.push(5);
}
</code>```

vs:

```<code>let mut v = vec![2, 3, 4];
if !v.is_empty() {
    v.push(5);
}
</code>```

My gut feeling is that it's trivial and doesn't matter.

答:
For any performance question, you need to profile to be sure. Anything but that is essentially guessing.

As a first-level guess however, you can look at the generated assembly:

```<code>#![crate_type="lib"]

pub fn one() {
    let mut v = vec![2, 3, 4];
    if let false = v.is_empty() {
        v.push(5);
    }
}

pub fn two() {
    let mut v = vec![2, 3, 4];
    if !v.is_empty() {
        v.push(5);
    }
}
</code>```

Compiling the above code to assembly using Rust 1.18 and diffing the two functions shows minimal differences, mostly around constant and label names:

--- a.asm   2017-07-06 13:53:29.000000000 -0400
+++ b.asm   2017-07-06 13:53:48.000000000 -0400
@@ -1,2 +1,2 @@
-_ZN10playground3one17hbd49bc1da7229962E:
-.Lfunc_begin0:
+_ZN10playground3two17h3228f5d5d04f0491E:
+.Lfunc_begin1:
@@ -5 +5 @@
-   .cfi_lsda 27, .Lexception0
+   .cfi_lsda 27, .Lexception1
@@ -7 +7 @@
-.Ltmp8:
+.Ltmp14:
@@ -10 +10 @@
-.Ltmp9:
+.Ltmp15:
@@ -12 +12 @@
-.Ltmp10:
+.Ltmp16:
@@ -18 +18 @@
-   je  .LBB1_8
+   je  .LBB2_8
@@ -23 +23 @@
-   movaps  .LCPI1_0(%rip), %xmm0
+   movaps  .LCPI2_0(%rip), %xmm0
@@ -25 +25 @@
-.Ltmp5:
+.Ltmp11:
@@ -28 +28 @@
-.Ltmp6:
+.Ltmp12:
@@ -36 +36 @@
-   je  .LBB1_4
+   je  .LBB2_4
@@ -40 +40 @@
-.LBB1_4:
+.LBB2_4:
@@ -44 +44 @@
-.LBB1_8:
+.LBB2_8:
@@ -46,2 +46,2 @@
-.LBB1_5:
-.Ltmp7:
+.LBB2_5:
+.Ltmp13:
@@ -51 +51 @@
-   je  .LBB1_7
+   je  .LBB2_7
@@ -56 +56 @@
-.LBB1_7:
+.LBB2_7:
```

<p>To me, that's proof enough that they are the same. I'd still prefer the boolean form because it's easier to understand:</p>

```let mut v = vec![2, 3, 4];
if !v.is_empty() {
    v.push(5);
}
```

Body:
For example:

let mut v = vec![2, 3, 4];
if let false = v.is_empty() {
    v.push(5);
}

vs:

let mut v = vec![2, 3, 4];
if !v.is_empty() {
    v.push(5);
}

My gut feeling is that it's trivial and doesn't matter.

Body:
For any performance question, you need to profile to be sure. Anything but that is essentially guessing.

As a first-level guess however, you can look at the generated assembly:

#![crate_type="lib"]

pub fn one() {
    let mut v = vec![2, 3, 4];
    if let false = v.is_empty() {
        v.push(5);
    }
}

pub fn two() {
    let mut v = vec![2, 3, 4];
    if !v.is_empty() {
        v.push(5);
    }
}

Compiling the above code to assembly using Rust 1.18 and diffing the two functions shows minimal differences, mostly around constant and label names:

--- a.asm   2017-07-06 13:53:29.000000000 -0400
+++ b.asm   2017-07-06 13:53:48.000000000 -0400
@@ -1,2 +1,2 @@
-_ZN10playground3one17hbd49bc1da7229962E:
-.Lfunc_begin0:
+_ZN10playground3two17h3228f5d5d04f0491E:
+.Lfunc_begin1:
@@ -5 +5 @@
-   .cfi_lsda 27, .Lexception0
+   .cfi_lsda 27, .Lexception1
@@ -7 +7 @@
-.Ltmp8:
+.Ltmp14:
@@ -10 +10 @@
-.Ltmp9:
+.Ltmp15:
@@ -12 +12 @@
-.Ltmp10:
+.Ltmp16:
@@ -18 +18 @@
-   je  .LBB1_8
+   je  .LBB2_8
@@ -23 +23 @@
-   movaps  .LCPI1_0(%rip), %xmm0
+   movaps  .LCPI2_0(%rip), %xmm0
@@ -25 +25 @@
-.Ltmp5:
+.Ltmp11:
@@ -28 +28 @@
-.Ltmp6:
+.Ltmp12:
@@ -36 +36 @@
-   je  .LBB1_4
+   je  .LBB2_4
@@ -40 +40 @@
-.LBB1_4:
+.LBB2_4:
@@ -44 +44 @@
-.LBB1_8:
+.LBB2_8:
@@ -46,2 +46,2 @@
-.LBB1_5:
-.Ltmp7:
+.LBB2_5:
+.Ltmp13:
@@ -51 +51 @@
-   je  .LBB1_7
+   je  .LBB2_7
@@ -56 +56 @@
-.LBB1_7:
+.LBB2_7:

To me, that's proof enough that they are the same. I'd still prefer the boolean form because it's easier to understand:

let mut v = vec![2, 3, 4];
if !v.is_empty() {
    v.push(5);
}


问:
Adding manager attribute fails
I have a script that matches a contact based on an email in a csv, I can find the contact using a get-adobject -ldapfilter but when I try to add the contact as a manager the add fails stating it cannot find the contact.  The contact it states it cannot find is clearly present in the directory.

This line will find the contact:

```<code>$rmanager = Get-ADObject -SearchBase 'OU=workplace,OU=Contacts,DC=office,DC=com' -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))"
</code>```

An example of the contact in question being found...

```<code>PS C:\temp> Get-ADObject -SearchBase 'OU=workplace,OU=Contacts,DC=office,DC=com' -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))"

DistinguishedName Name ObjectClass ObjectGUID
----------------- ---- ----------- ----------
CN=Nick Hill,OU=workplace,OU=Contacts,DC=office,DC=com Nick Hill contact b649bd7e-aac9-4d4b-8203-b6a79f35b91
</code>```

However, this line with the set-aduser will fail stating it cannot find the contact that clearly exists...

```<code>get-aduser -f {mail -eq $username} |set-aduser -Manager "$rmanager"

set-aduser : Identity info provided in the extended attribute: 'Manager' could not be resolved. Reason: 'Cannot find an object with identity: 'CN=Nick Hill,OU=Workplace,OU=Contacts,DC=office,DC=com' under: 'DC=Office,DC=com'.'.
</code>```

答:
I just tested this and it worked:

a. Get distinguishedName of contact:

```<code>$contactDN = Get-ADObject -LDAPFilter "(&(objectClass=contact)(givenName=firstname)(sn=lastname))"
  | Select-Object -ExpandProperty DistinguishedName
</code>```

b. Get the user object and replace the manager attribute:

```<code>Get-ADUser username | Get-ADObject | Set-ADObject -Replace @{"manager" = $contactDN}
</code>```

Title: Adding manager attribute fails

Body:
I have a script that matches a contact based on an email in a csv, I can find the contact using a get-adobject -ldapfilter but when I try to add the contact as a manager the add fails stating it cannot find the contact.  The contact it states it cannot find is clearly present in the directory.

This line will find the contact:

$rmanager = Get-ADObject -SearchBase 'OU=workplace,OU=Contacts,DC=office,DC=com' -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))"

An example of the contact in question being found...

PS C:\temp> Get-ADObject -SearchBase 'OU=workplace,OU=Contacts,DC=office,DC=com' -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))"

DistinguishedName Name ObjectClass ObjectGUID
----------------- ---- ----------- ----------
CN=Nick Hill,OU=workplace,OU=Contacts,DC=office,DC=com Nick Hill contact b649bd7e-aac9-4d4b-8203-b6a79f35b91

However, this line with the set-aduser will fail stating it cannot find the contact that clearly exists...

get-aduser -f {mail -eq $username} |set-aduser -Manager "$rmanager"

set-aduser : Identity info provided in the extended attribute: 'Manager' could not be resolved. Reason: 'Cannot find an object with identity: 'CN=Nick Hill,OU=Workplace,OU=Contacts,DC=office,DC=com' under: 'DC=Office,DC=com'.'.

Body:
I just tested this and it worked:

a. Get distinguishedName of contact:

$contactDN = Get-ADObject -LDAPFilter "(&(objectClass=contact)(givenName=firstname)(sn=lastname))"
  | Select-Object -ExpandProperty DistinguishedName

b. Get the user object and replace the manager attribute:

Get-ADUser username | Get-ADObject | Set-ADObject -Replace @{"manager" = $contactDN}


问:
Server configuration is missing in Eclipse
Im using Eclipse Galileo, and have configured it for Apache Tomcat . I have added Apache Tomcat 6.0 to Windows->Server->Runtime Environments, with the following settings:

```<code>Tomcat Installation Directory - C:\apache-tomcat-6.0.24\apache-tomcat-6.0.24
JRE - Workbench Default JRE (This points to C:\Program Files\Java\jre6)
</code>```

Now, I create a Dynamic Web Project, and add a JSP file to it. But, when I run the project I get the following error:

```<code>The Tomcat server configuration at \Servers\Tomcat v6.0 Server at localhost-config is missing. Check the server for errors.
</code>```

Any way to fix this?

答: This happens when Eclipse shuts down incorrectly - delete the server and then re-create it again.</p>

Body:
Im using Eclipse Galileo, and have configured it for Apache Tomcat . I have added Apache Tomcat 6.0 to Windows->Server->Runtime Environments, with the following settings:

Tomcat Installation Directory - C:\apache-tomcat-6.0.24\apache-tomcat-6.0.24
JRE - Workbench Default JRE (This points to C:\Program Files\Java\jre6)

Now, I create a Dynamic Web Project, and add a JSP file to it. But, when I run the project I get the following error:

The Tomcat server configuration at \Servers\Tomcat v6.0 Server at localhost-config is missing. Check the server for errors.

Any way to fix this?


问:
Problems with graphing excel data off an internet source with dates
this is my first post on stackoveflow and I'm pretty new to programming especially python. I'm in engineering and am learning python to compliment that going forward, mostly at math and graphing applications.
Basically my question is how do I download csv excel data off a source (in my case stock data from google), and plot only certain rows against the date. For myself I want the date against the close value.
Right now the error message I'm getting is timedata '5-Jul-17' does not match '%d-%m-%Y'
previously I was also getting tuple data does not match
The description of the opened csv data in excel is
[7 columns (Date,Open,High,Low,Close,AdjClose,Volume, and the date is organized as 2017-05-30][1]
I'm sure there are other errors as well unfortunately
I would really be grateful for any help on this,
thank you in advance!
--edit--
Upon fiddling some more I don't think names and dtypes are necessary, when I check the matrix dimensions without those identifiers I get (250L, 6L) which seems right. Now my main problem is coverting the dates to something usable, My error now is strptime only accepts strings, so I'm not sure what to use. (see updated code below)</p>

```<code>import matplotlib.pyplot as plt
importnumpy as np
from datetime import datetime

def graph_data(stock):

    %getting the data off google finance
    data = np.genfromtxt('urlgoeshere'+stock+'forthecsvdata', delimiter=',',
                        skip_header=1)
    # checking format of matrix
    print data.shape (returns 250L,6L)

    time_format = '%d-%m-%Y'
    # I only want the 1st column (dates) and 5 column (close), all rows
    date = data[:,0][:,]
    close = data[:,4][:,]

    dates = [datetime.strptime(date, time_format)]

    %plotting section
    plt.plot_date(dates,close, '-')
    plt.legend()
    plt.show()

graph_data('stockhere')
</code>```

答:
Assuming the dates in the csv file are in the format '5-Jul-17', the proper format string to use is %d-%b-%y.

```<code>In [6]: datetime.strptime('5-Jul-17','%d-%m-%Y')

ValueError: time data '5-Jul-17' does not match format '%d-%m-%Y'

In [7]: datetime.strptime('5-Jul-17','%d-%b-%y')

Out[7]: datetime.datetime(2017, 7, 5, 0, 0)
</code>```

See the Python documentation on strptime() behavior.

Body:
this is my first post on stackoveflow and I'm pretty new to programming especially python. I'm in engineering and am learning python to compliment that going forward, mostly at math and graphing applications.
Basically my question is how do I download csv excel data off a source (in my case stock data from google), and plot only certain rows against the date. For myself I want the date against the close value.
Right now the error message I'm getting is timedata '5-Jul-17' does not match '%d-%m-%Y'
previously I was also getting tuple data does not match
The description of the opened csv data in excel is
[7 columns (Date,Open,High,Low,Close,AdjClose,Volume, and the date is organized as 2017-05-30][1]
I'm sure there are other errors as well unfortunately
I would really be grateful for any help on this,
thank you in advance!
--edit--
Upon fiddling some more I don't think names and dtypes are necessary, when I check the matrix dimensions without those identifiers I get (250L, 6L) which seems right. Now my main problem is coverting the dates to something usable, My error now is strptime only accepts strings, so I'm not sure what to use. (see updated code below)

import matplotlib.pyplot as plt
importnumpy as np
from datetime import datetime

def graph_data(stock):

    %getting the data off google finance
    data = np.genfromtxt('urlgoeshere'+stock+'forthecsvdata', delimiter=',',
                        skip_header=1)
    # checking format of matrix
    print data.shape (returns 250L,6L)

    time_format = '%d-%m-%Y'
    # I only want the 1st column (dates) and 5 column (close), all rows
    date = data[:,0][:,]
    close = data[:,4][:,]

    dates = [datetime.strptime(date, time_format)]

    %plotting section
    plt.plot_date(dates,close, '-')
    plt.legend()
    plt.show()

graph_data('stockhere')

Body:
Assuming the dates in the csv file are in the format '5-Jul-17', the proper format string to use is %d-%b-%y.

In [6]: datetime.strptime('5-Jul-17','%d-%m-%Y')

ValueError: time data '5-Jul-17' does not match format '%d-%m-%Y'

In [7]: datetime.strptime('5-Jul-17','%d-%b-%y')

Out[7]: datetime.datetime(2017, 7, 5, 0, 0)

See the Python documentation on strptime() behavior.


问:
Wrong result array_map function
this is my input array...

```<code>$var = Array ( [0] => 57;5;7;Hertha BSC - SV Werder Bremen [1] => Heim )
</code>```

I change it to another array with this function

```<code>$int_array = array_map("intval", explode(";", $var[0]));
</code>```

When I call this array I get this result

```<code>Array ( [0] => 57 [1] => 5 [2] => 7 [3] => 0 )
</code>```

But why is Array position [3] = 0. There must be "Hertha BSC..."?

答:
The description of the intval function, according to the PHP docs is:

Get the integer value of a variable

The integer value of Hertha BSC - SV Werder Bremen (the 4th element of the array created by exploding ; on "57;5;7;Hertha BSC - SV Werder Bremen") is not clear.

Throwing a string at it will not yield meaningful results in this context. So, I don't think it's the wrong result.

Here's something that might get you a little closer to what I think you're after, though

```<code>$var = [
    '57;5;7;Hertha BSC - SV Werder Bremen',
    'Heim'
];

$int_array = array_map(
    function($item) {
        // In cases where the exploded array item is not entirely made up of digits, return it as a string.
        if (0 === preg_match('/\d+/', $item)) {
            return $item;
        }

        // else, cast to int.
        return intval($item);
    },
    explode(";", $var[0])
);
</code>```

Title: Wrong result array_map function

Body:
this is my input array...

$var = Array ( [0] => 57;5;7;Hertha BSC - SV Werder Bremen [1] => Heim )

I change it to another array with this function

$int_array = array_map("intval", explode(";", $var[0]));

When I call this array I get this result

Array ( [0] => 57 [1] => 5 [2] => 7 [3] => 0 )

But why is Array position [3] = 0. There must be "Hertha BSC..."?

Body:
The description of the intval function, according to the PHP docs is:

Get the integer value of a variable

The integer value of Hertha BSC - SV Werder Bremen (the 4th element of the array created by exploding ; on "57;5;7;Hertha BSC - SV Werder Bremen") is not clear.

Throwing a string at it will not yield meaningful results in this context. So, I don't think it's the wrong result.

Here's something that might get you a little closer to what I think you're after, though

$var = [
    '57;5;7;Hertha BSC - SV Werder Bremen',
    'Heim'
];

$int_array = array_map(
    function($item) {
        // In cases where the exploded array item is not entirely made up of digits, return it as a string.
        if (0 === preg_match('/\d+/', $item)) {
            return $item;
        }

        // else, cast to int.
        return intval($item);
    },
    explode(";", $var[0])
);


问:
Ruby case statement not returning when condition evaluates to true
Ruby newbie here. I've written a case statement to check whether a string parameter ends with "?", and I don't understand the result. Here's my code:

```<code>class Bob
  def self.hey(phrase)
    case phrase
    when phrase.chars.last == "?"
      'Sure.'
    else
      'Whatever.'
    end
  end
end
</code>```

When I call Bob.hey("Does this cryogenic chamber make me look fat?") I get back Whatever., despite "Does this cryogenic chamber make me look fat?".chars.last == "?" evaluating to true in IRB. I can't figure out what I'm missing. Any help would be appreciated.

答:
If there are only two cases, an if/else is more than enough:

```<code>if phrase.chars.last == "?"
  ...
else
  ...
end
</code>```

Note that you could use end_with? :

```<code>if phrase.end_with?('?')
   ...
</code>```

Body:
Ruby newbie here. I've written a case statement to check whether a string parameter ends with "?", and I don't understand the result. Here's my code:

class Bob
  def self.hey(phrase)
    case phrase
    when phrase.chars.last == "?"
      'Sure.'
    else
      'Whatever.'
    end
  end
end

When I call Bob.hey("Does this cryogenic chamber make me look fat?") I get back Whatever., despite "Does this cryogenic chamber make me look fat?".chars.last == "?" evaluating to true in IRB. I can't figure out what I'm missing. Any help would be appreciated.

Body:
If there are only two cases, an if/else is more than enough:

if phrase.chars.last == "?"
  ...
else
  ...
end

Note that you could use end_with? :

if phrase.end_with?('?')
   ...


问:
What is the best way to update two tables at the same time in SQL?
I have two tables. one is "Data" and another one is "AnalyzedData"

Two tables are for, first table "Data" is used to store basic data and another table to store details about analyzed data.

In "Data" table we have 3 columns - "DataID","DataName","AnalyzedDataID" (foreign key to "AnalyzedData")
in AnalyzedData table we have 3 columns. "AnalyzedDataID","AnalyzedataName"

Initially we have data in DataID and DataName colums. Later, after analyzing the data, We are inserting data into AnalyzedData table. So we need to update the AnalyzedDataID in Data table after inserting data into AnalyzedData table.

What's the best way to do this?

答:
Assuming that you are using SQL Server 2008 or later, OUTPUT clause can be pretty helpful in your scenario. You can insert data in your "Analyzed Data" table, which will generate an ID, which can be captured with the help of OUTPUT. Then that ID can be used to update your "Data" table.

Refer Implementing the OUTPUT Clause in SQL Server 2008 for more details on how to use the OUTPUT clause.


问:
Why is this Haskell function inferred to this type?
I'm a Haskell beginner working through an exercise in Chapter 2 of Real World Haskell, where you write a function that returns the second-to-last element of a list.

I've written the following function to attempt to solve this:

```<code>-- file: \Learn Haskell\lastButOne.hs
lastButOne xs = if length xs == 2
                then head xs
                else lastButOne tail xs
</code>```

What I don't understand is this error the compiler throws:

```<code>lastButOne.hs:2:1: error:
    • Couldn't match type ‘[a] -> [a]’ with ‘[t]’
      Expected type: ([a] -> [a]) -> [t] -> t
        Actual type: [t] -> t
    • Relevant bindings include
        lastButOne :: ([a] -> [a]) -> [t] -> t (bound at lastButOne.hs:2:1)
</code>```

From what I understand, ghci thinks my function ought to have a different type than it does, but I don't understand why that's happening, or how I can fix it.

Edit: Thanks for the answers! I've updated my code to:

```<code>-- file: \Learn Haskell\lastButOne.hs
lastButOne xs = if length xs == 2
                then head xs
                else if length xs < 2
                     then error "This list does not have a second-to-last element."
                     else lastButOne (tail xs)
</code>```

This eliminates the error where tail xs is being interpreted as two arguments, rather than a single expression. I also added some code that ensures the list isn't too short. Willem Van Onsem's solution is nicer, but as an exercise I thought I'd come up with a solution that only used the concepts introduced so far in the book.

答:
The problem is with the line:

```<code>        else lastButOne tail xs
</code>```

It should be:

```<code>        else lastButOne (tail xs)
</code>```

Otherwise ghci things that you give lastButOne two arguments: tail and xs.

You can however make the code more elegant:

```<code>lastButOne [x,_] = x
lastButOne xs = lastButOne $ tail xs
</code>```

Furthermore you will have to find a way to resolve lists with one element, and the empty list. Right now the function will start looping. An idea could be to to error on these lists, like:

```<code>lastButOne [x,_] = x
lastButOne (_:xs) = lastButOne xs
lastButOne [] = error "The list has no last but one element."
</code>```

Body:
I'm a Haskell beginner working through an exercise in Chapter 2 of Real World Haskell, where you write a function that returns the second-to-last element of a list.

I've written the following function to attempt to solve this:

-- file: \Learn Haskell\lastButOne.hs
lastButOne xs = if length xs == 2
                then head xs
                else lastButOne tail xs

What I don't understand is this error the compiler throws:

lastButOne.hs:2:1: error:
    • Couldn't match type ‘[a] -> [a]’ with ‘[t]’
      Expected type: ([a] -> [a]) -> [t] -> t
        Actual type: [t] -> t
    • Relevant bindings include
        lastButOne :: ([a] -> [a]) -> [t] -> t (bound at lastButOne.hs:2:1)

From what I understand, ghci thinks my function ought to have a different type than it does, but I don't understand why that's happening, or how I can fix it.

Edit: Thanks for the answers! I've updated my code to:

-- file: \Learn Haskell\lastButOne.hs
lastButOne xs = if length xs == 2
                then head xs
                else if length xs < 2
                     then error "This list does not have a second-to-last element."
                     else lastButOne (tail xs)

This eliminates the error where tail xs is being interpreted as two arguments, rather than a single expression. I also added some code that ensures the list isn't too short. Willem Van Onsem's solution is nicer, but as an exercise I thought I'd come up with a solution that only used the concepts introduced so far in the book.

Body:
The problem is with the line:

        else lastButOne tail xs

It should be:

        else lastButOne (tail xs)

Otherwise ghci things that you give lastButOne two arguments: tail and xs.

You can however make the code more elegant:

lastButOne [x,_] = x
lastButOne xs = lastButOne $ tail xs

Furthermore you will have to find a way to resolve lists with one element, and the empty list. Right now the function will start looping. An idea could be to to error on these lists, like:

lastButOne [x,_] = x
lastButOne (_:xs) = lastButOne xs
lastButOne [] = error "The list has no last but one element."


问:
Where are the SNS/SMS logs? Cloudwatch empty
Context: I use Amazon AWS, SNS service, to manually send SMS as a trial before I do any integration by code.

I want to log the SMS reponses (the JSONs that appear here: http://docs.aws.amazon.com/sns/latest/dg/sms_stats_cloudwatch.html ) at some place.

Investigation done:

It seems I had to create an IAM role. I did it following the steps in the page, in the section "Viewing CloudWatch Logs". The role has been created. The policy for the role contains the following actions:

```<code>"Action": [
    "logs:CreateLogGroup",
    "logs:CreateLogStream",
    "logs:PutLogEvents",
    "logs:PutMetricFilter",
    "logs:PutRetentionPolicy"
],
</code>```

I have set the "Default percentage of success to sample" to the 100% so it should log all errors and successes...

And now what? I have sent a couple of SMSs, I go to the Cloudwatch / Logs and all is empty.

Questions:

Where are the logs?

Do I have to do anything else with the IAM to get that logged?

Do I have to do anything in the Cloudwatch section?

Where is it supposed I should be able to see the logs?

I've spent 6+ hours with this and I want to think it is some silly point I'm missing. It can't be so complicated.

The overall question is Where are the SNS/SMS logs and how do I activate them?

答:
I don't know if your AIM configuration is good or wrong, I would need to check your configuration in order to tell you that, but if you want to know where the SNS logs are, in my case I can find them doing:

Go to CloudWatch

From the left menu, select Logs

You will see the list of your logs, search for the name of your SNS, in my case is something like sns/us-west-2/<account-id>/app/APNS/<endpoint-name>

After you click on that name, you will find all your logs

Image attached:

Body:
Context: I use Amazon AWS, SNS service, to manually send SMS as a trial before I do any integration by code.

I want to log the SMS reponses (the JSONs that appear here: http://docs.aws.amazon.com/sns/latest/dg/sms_stats_cloudwatch.html ) at some place.

Investigation done:

It seems I had to create an IAM role. I did it following the steps in the page, in the section "Viewing CloudWatch Logs". The role has been created. The policy for the role contains the following actions:

"Action": [
    "logs:CreateLogGroup",
    "logs:CreateLogStream",
    "logs:PutLogEvents",
    "logs:PutMetricFilter",
    "logs:PutRetentionPolicy"
],

I have set the "Default percentage of success to sample" to the 100% so it should log all errors and successes...

And now what? I have sent a couple of SMSs, I go to the Cloudwatch / Logs and all is empty.

Questions:

Where are the logs?

Do I have to do anything else with the IAM to get that logged?

Do I have to do anything in the Cloudwatch section?

Where is it supposed I should be able to see the logs?

I've spent 6+ hours with this and I want to think it is some silly point I'm missing. It can't be so complicated.

The overall question is Where are the SNS/SMS logs and how do I activate them?


问:
C# switch statement limitations - why?
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

```<code>  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }
</code>```

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

答:
I have virtually no knowledge of C#, but I suspect that either switch was simply taken as it occurs in other languages without thinking about making it more general or the developer decided that extending it was not worth it.

Strictly speaking you are absolutely right that there is no reason to put these restrictions on it. One might suspect that the reason is that for the allowed cases the implementation is very efficient (as suggested by Brian Ensink (44921)), but I doubt the implementation is very efficient (w.r.t. if-statements) if I use integers and some random cases (e.g. 345, -4574 and 1234203). And in any case, what is the harm in allowing it for everything (or at least more) and saying that it is only efficient for specific cases (such as (almost) consecutive numbers).

I can, however, imagine that one might want to exclude types because of reasons such as the one given by lomaxx (44918).

Edit: @Henk (44970): If Strings are maximally shared, strings with equal content will be pointers to the same memory location as well. Then, if you can make sure that the strings used in the cases are stored consecutively in memory, you can very efficiently implement the switch (i.e. with execution in the order of 2 compares, an addition and two jumps).

OwnerDisplayName: kronoz

Title: C# switch statement limitations - why?

Body:
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

LastEditorDisplayName: ecleel

OwnerDisplayName: mweerden

LastEditorDisplayName: mweerden


问:
Why does this JavaScript freeze IE6?
When you click, "Add to Bag" on this page, it freezes IE6 every time. How can I figure out why it is freezing? Does anyone have a more direct answer?

totallytrollbeads {dot} com {slash} Safety0.html

```<code>function update() {
    $.ajax({
        dataType: 'json',
        type: 'POST',
        url: '/cgi-bin/ajax_cart_count.cgi',
        timeout: 2000,
        success: function (data) {
            // If bag is empty, it's see through.
            if (data.cart_count == 0) {
                $(".shopping_bag").css("opacity", ".2");
            }
            // If bag is not empty, it's not see through.
            else {
                $(".shopping_bag").css("opacity", "1");
            }
            $("#bag_total").html(data.grand_total);
            $("#bag_count").html(data.cart_count);
            window.setTimeout(update, 15000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $("#bag_total").html('Timeout contacting server..');
            window.setTimeout(update, 60000);
        }
    })
}
$(document).ready(update);
</code>```

```<code>// preparethe form when the DOM is ready
$(document).ready(function () {
    // bind form using ajaxForm
    $('.add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
});
// preparethe form when the DOM is ready
$(document).ready(function () {
    // bind form using ajaxForm
    $('.add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
});
// $(".add_to_cart_form").click(function () {
// $('.bypass_add_to_cart_form').ajaxForm({ success: myBox });
// });

function loading() {
    $("#loadingContent").show();
}
function myBox(resptext, statustext) {
    $("#loadingContent").hide();
    Boxy.ask(resptext, ["View Bag", "Continue Shopping"], function (val) {
        if (val == "View Bag") {
            document.location.href = "/cgi-bin/store.cgi?action=view_cart";
        }
        if (val == "Continue Shopping" && product_detail == 1) {
            history.go(-1);
        }
    }, {
        title: "Add to Bag"
    });
    $('.bypass_add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
    update();
    return false;
}
/*
 This tells the ajax-style add to cart that
 it's on a product detail page so if the
 user clicks "Continue Shopping" it takes
 them back on step in their history.
 */
$('.search_view').click(function () {
    product_detail = 0;
});
$('.product_view').click(function () {
    product_detail = 1;
});
</code>```

答:
It's not easy to debug a thing that freezes immediately from the outside. But it's always a good idea to cleanup the whole, remove things that are not essential, check the functionality and then do the next step.

For example this:

```<code>// preparethe form when the DOM is ready
$(document).ready(function () {
    // bind form using ajaxForm
    $('.add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
});
// preparethe form when the DOM is ready
$(document).ready(function () {
    // bind form using ajaxForm
    $('.add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
});
</code>```

It's not hard to see that have this part twice there.

Put a little more accuracy into your application instead of copy&paste.

Title: Why does this JavaScript freeze IE6?

Body:
When you click, "Add to Bag" on this page, it freezes IE6 every time. How can I figure out why it is freezing? Does anyone have a more direct answer?

totallytrollbeads {dot} com {slash} Safety0.html

function update() {
    $.ajax({
        dataType: 'json',
        type: 'POST',
        url: '/cgi-bin/ajax_cart_count.cgi',
        timeout: 2000,
        success: function (data) {
            // If bag is empty, it's see through.
            if (data.cart_count == 0) {
                $(".shopping_bag").css("opacity", ".2");
            }
            // If bag is not empty, it's not see through.
            else {
                $(".shopping_bag").css("opacity", "1");
            }
            $("#bag_total").html(data.grand_total);
            $("#bag_count").html(data.cart_count);
            window.setTimeout(update, 15000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $("#bag_total").html('Timeout contacting server..');
            window.setTimeout(update, 60000);
        }
    })
}
$(document).ready(update);

// preparethe form when the DOM is ready
$(document).ready(function () {
    // bind form using ajaxForm
    $('.add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
});
// preparethe form when the DOM is ready
$(document).ready(function () {
    // bind form using ajaxForm
    $('.add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
});
// $(".add_to_cart_form").click(function () {
// $('.bypass_add_to_cart_form').ajaxForm({ success: myBox });
// });

function loading() {
    $("#loadingContent").show();
}
function myBox(resptext, statustext) {
    $("#loadingContent").hide();
    Boxy.ask(resptext, ["View Bag", "Continue Shopping"], function (val) {
        if (val == "View Bag") {
            document.location.href = "/cgi-bin/store.cgi?action=view_cart";
        }
        if (val == "Continue Shopping" && product_detail == 1) {
            history.go(-1);
        }
    }, {
        title: "Add to Bag"
    });
    $('.bypass_add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
    update();
    return false;
}
/*
 This tells the ajax-style add to cart that
 it's on a product detail page so if the
 user clicks "Continue Shopping" it takes
 them back on step in their history.
 */
$('.search_view').click(function () {
    product_detail = 0;
});
$('.product_view').click(function () {
    product_detail = 1;
});

Body:
It's not easy to debug a thing that freezes immediately from the outside. But it's always a good idea to cleanup the whole, remove things that are not essential, check the functionality and then do the next step.

For example this:

// preparethe form when the DOM is ready
$(document).ready(function () {
    // bind form using ajaxForm
    $('.add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
});
// preparethe form when the DOM is ready
$(document).ready(function () {
    // bind form using ajaxForm
    $('.add_to_cart_form').ajaxForm({
        beforeSubmit: loading,
        success: myBox
    });
});

It's not hard to see that have this part twice there.

Put a little more accuracy into your application instead of copy&paste.


问:
Time Complexity of smallest range of elements containing at least 1 element from each of the k lists
Can someone please elaborate how is the time complexity of this function  O(n^2 * k)? I understand the for loop within the while loop will execute atmost k times.But what I don't understand is the n^2 term.</p>

```<code>void findSmallestRange(int arr[][N], int n, int k)
{
  int i,minval,maxval,minrange,minel,maxel,flag,minind;

  //initializing to 0 index;
  for(i = 0;i <= k;i++)
    ptr[i] = 0;

  minrange = INT_MAX;

  while(1)
  {
      // for mainting the index of list containing the minimum element
      minind = -1;
      minval = INT_MAX;
      maxval = INT_MIN;
      flag = 0;

      //iterating over all the list
      for(i = 0;i < k;i++)
      {
          // if every element of list[i] is traversed then break the loop
          if(ptr[i] == n)
          {
            flag = 1;
            break;
          }
          // find minimum value among all the list elements pointing by the ptr[] array
          if(ptr[i] < n && arr[i][ptr[i]] < minval)
          {
              minind=i;  // update the index of the list
              minval=arr[i][ptr[i]];
          }
          // find maximum value among all the list elements pointing by the ptr[] array
          if(ptr[i] < n && arr[i][ptr[i]] > maxval)
          {
              maxval = arr[i][ptr[i]];
          }
      }

      //if any list exhaust we will not get any better answer ,so break the while loop
      if(flag)
        break;

      ptr[minind]++;

      //updating the minrange
      if((maxval-minval) < minrange)
      {
          minel = minval;
          maxel = maxval;
          minrange = maxel - minel;
      }
  }

  printf("The smallest range is [%d , %d]\n",minel,maxel);
}
</code>```

答:
Disclaimer: This actually proves a complexity of O(n * k^2) - I am not (yet) deleting this because maybe someone will find a flaw in my reasoning, or maybe this is the real complexity...

The inner loop is O(k) as you already noticed, the question is how much times will the outer loop be executed?

The outer loop will stop being executed as soon as one of the value in ptr is n.

Your start with ptr[i] = 0 for i = 1 .. k, and for each execution of the outer loop, you increment a single value in ptr.

The worst-possible case is when all the value in ptr are increment successively, i.e. when you get:

```<code>ptr = 0 0 0 ... 0
ptr = 1 0 0 ... 0
ptr = 1 1 0 ... 0
...
ptr = 1 1 1 ... 1
ptr = 2 1 1 ... 1
</code>```

With this scenario, the loop will stop at the following iteration:

```<code>ptr = n (n-1) (n-1) ... (n-1)
</code>```

How much time does it require to go from 0 0 0 ... 0 to n (n-1) (n-1) ... (n-1)? O(n * k) because it require O(n) for one cell to go from 1 to n, and you have k cells in ptr.

So the total complexity seems to be O(n * k^2), and not O(n^2 * k)...

Body:
Can someone please elaborate how is the time complexity of this function  O(n^2 * k)? I understand the for loop within the while loop will execute atmost k times.But what I don't understand is the n^2 term.

void findSmallestRange(int arr[][N], int n, int k)
{
  int i,minval,maxval,minrange,minel,maxel,flag,minind;

  //initializing to 0 index;
  for(i = 0;i <= k;i++)
    ptr[i] = 0;

  minrange = INT_MAX;

  while(1)
  {
      // for mainting the index of list containing the minimum element
      minind = -1;
      minval = INT_MAX;
      maxval = INT_MIN;
      flag = 0;

      //iterating over all the list
      for(i = 0;i < k;i++)
      {
          // if every element of list[i] is traversed then break the loop
          if(ptr[i] == n)
          {
            flag = 1;
            break;
          }
          // find minimum value among all the list elements pointing by the ptr[] array
          if(ptr[i] < n && arr[i][ptr[i]] < minval)
          {
              minind=i;  // update the index of the list
              minval=arr[i][ptr[i]];
          }
          // find maximum value among all the list elements pointing by the ptr[] array
          if(ptr[i] < n && arr[i][ptr[i]] > maxval)
          {
              maxval = arr[i][ptr[i]];
          }
      }

      //if any list exhaust we will not get any better answer ,so break the while loop
      if(flag)
        break;

      ptr[minind]++;

      //updating the minrange
      if((maxval-minval) < minrange)
      {
          minel = minval;
          maxel = maxval;
          minrange = maxel - minel;
      }
  }

  printf("The smallest range is [%d , %d]\n",minel,maxel);
}

Body:
Disclaimer: This actually proves a complexity of O(n * k^2) - I am not (yet) deleting this because maybe someone will find a flaw in my reasoning, or maybe this is the real complexity...

The inner loop is O(k) as you already noticed, the question is how much times will the outer loop be executed?

The outer loop will stop being executed as soon as one of the value in ptr is n.

Your start with ptr[i] = 0 for i = 1 .. k, and for each execution of the outer loop, you increment a single value in ptr.

The worst-possible case is when all the value in ptr are increment successively, i.e. when you get:

ptr = 0 0 0 ... 0
ptr = 1 0 0 ... 0
ptr = 1 1 0 ... 0
...
ptr = 1 1 1 ... 1
ptr = 2 1 1 ... 1

With this scenario, the loop will stop at the following iteration:

ptr = n (n-1) (n-1) ... (n-1)

How much time does it require to go from 0 0 0 ... 0 to n (n-1) (n-1) ... (n-1)? O(n * k) because it require O(n) for one cell to go from 1 to n, and you have k cells in ptr.

So the total complexity seems to be O(n * k^2), and not O(n^2 * k)...


问:
How to write a file to a directory?
I am trying to write a file to a specific directory in Java. I have looked at many of the already answered questions relating to this in the Stack Overflow forums. Yet, every method I try just ends up with this error:

```<code>java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at mainFiles.fileManagers.NewCSV.nJSON(NewCSV.java:40)
at mainFiles.appWindows.UserDashboard$1.run(UserDashboard.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Code:

```<code>public static void nJSON(String username) {

    File file = new File("src/jsonFiles/" +  username + ".json");

    try {
        if (file.exists() && file.isDirectory()) {
            System.out.println(username + ".json exist.");
        } else {
            json.put("Username", username);
            json.put("Password", mainFiles.windowsSrc.UserInfo.password);

            file.createNewFile();
            FileWriter writer = new FileWriter(file);
            FileOutputStream os = new FileOutputStream(file);

            writer.write(json.toJSONString());
            writer.flush();
            os.close();
            writer.close();

            System.out.println(username + ".json created.");

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Any suggestions on how I can write my file to a certain directory?

答:
Some remarks about your code:

Create the parent directory before the file. You cannot create a file in a non existent directory.

file.getParentFile().mkdirs();

Remove the FileOutputStream code. You are using both a FileWriter and FileOutputStream at the same time for the same file. This is a mistake as one may overwrite the other, causing the file to be immediately cleared after being written to.

createNewFile() is not necessary. The FileWriter or FileOutputStream can create it's own file as long as the directory exists (see #1).

Close the writer in a finally block so that you are guaranteed the underlying stream is closed even if an exception occurs during writing.

I'm not sure what the isDirectory check is for. If it exists, surely it would be a file and not a directory. Either way, file.exists() && file.isDirectory() is unnecessary as isDirectory already checks for existence.

Updated code:

```<code>public static void nJSON(String username ) {

    File file = new File("src/jsonFiles/" +  username + ".json");

    if (file.isDirectory()) {
        System.err.println(username + ".json exist and is a directory.");
        return;
    }

    if(!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        System.err.println("Failed to create directory " + file.getParent());
        return;
    }

    FileWriter writer = null;
    try{
        json.put("Username", username);
        json.put("Password", mainFiles.windowsSrc.UserInfo.password);

        writer = new FileWriter(file);
        writer.write(json.toJSONString());
        writer.close();

        System.out.println(username + ".json created.");

    } catch(IOException e){
        e.printStackTrace();
    } finally {
        if(writer != null) {
            try {
                writer.close();
            } catch(IOException ignore) { }
        }
    }
}
</code>```

Title: How to write a file to a directory?

Body:
I am trying to write a file to a specific directory in Java. I have looked at many of the already answered questions relating to this in the Stack Overflow forums. Yet, every method I try just ends up with this error:

java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at mainFiles.fileManagers.NewCSV.nJSON(NewCSV.java:40)
at mainFiles.appWindows.UserDashboard$1.run(UserDashboard.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Code:

public static void nJSON(String username) {

    File file = new File("src/jsonFiles/" +  username + ".json");

    try {
        if (file.exists() && file.isDirectory()) {
            System.out.println(username + ".json exist.");
        } else {
            json.put("Username", username);
            json.put("Password", mainFiles.windowsSrc.UserInfo.password);

            file.createNewFile();
            FileWriter writer = new FileWriter(file);
            FileOutputStream os = new FileOutputStream(file);

            writer.write(json.toJSONString());
            writer.flush();
            os.close();
            writer.close();

            System.out.println(username + ".json created.");

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Any suggestions on how I can write my file to a certain directory?

Body:
Some remarks about your code:

Create the parent directory before the file. You cannot create a file in a non existent directory.

file.getParentFile().mkdirs();

Remove the FileOutputStream code. You are using both a FileWriter and FileOutputStream at the same time for the same file. This is a mistake as one may overwrite the other, causing the file to be immediately cleared after being written to.

createNewFile() is not necessary. The FileWriter or FileOutputStream can create it's own file as long as the directory exists (see #1).

Close the writer in a finally block so that you are guaranteed the underlying stream is closed even if an exception occurs during writing.

I'm not sure what the isDirectory check is for. If it exists, surely it would be a file and not a directory. Either way, file.exists() && file.isDirectory() is unnecessary as isDirectory already checks for existence.

Updated code:

public static void nJSON(String username ) {

    File file = new File("src/jsonFiles/" +  username + ".json");

    if (file.isDirectory()) {
        System.err.println(username + ".json exist and is a directory.");
        return;
    }

    if(!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        System.err.println("Failed to create directory " + file.getParent());
        return;
    }

    FileWriter writer = null;
    try{
        json.put("Username", username);
        json.put("Password", mainFiles.windowsSrc.UserInfo.password);

        writer = new FileWriter(file);
        writer.write(json.toJSONString());
        writer.close();

        System.out.println(username + ".json created.");

    } catch(IOException e){
        e.printStackTrace();
    } finally {
        if(writer != null) {
            try {
                writer.close();
            } catch(IOException ignore) { }
        }
    }
}


问:
Access object key with a string value
I have a hand-typed database with an object that has categories and a list of words for each category, as below:

```<code>var words =
{
    sports: [
        'baseball', 'football', 'volleyball', 'basketball', 'soccer'],

    animals: [
        'dog', 'cat', 'elephant', 'crocodile', 'bird'],

    entertainment: [
        'netflix', 'movies', 'music', 'concert', 'band', 'computer']
}
</code>```

My HTML has a bootstrap dropdown that will display all categories based on that list. I have the code working to give me the value of the category clicked as a string: as below:

```<code>$(document).on('click', '.dropdown-menu li a', function () {
    var selectedCategory;

    selectedCategory = $(this).text();
    //setting value of category to global variable
    categorySelected = selectedCategory;
});
</code>```

I need to be able to find the key in my database from that value.
The problem is that I can't access words."animals"
I need to take the quotation marks off my string to get the list of words like this:
words.animals

How do I do this? I've tried replace() but it doesn't work.

答:
It seems like you're trying to access the list of values corresponding to the category in your words object. Keys can be strings, so words['animals'] would be an example of getting your list of animals.

JavaScript allows variables to be used as keys as well, so you can access it as follows:

```<code>words[categorySelected]
</code>```

Title: Access object key with a string value

Body:
I have a hand-typed database with an object that has categories and a list of words for each category, as below:

var words =
{
    sports: [
        'baseball', 'football', 'volleyball', 'basketball', 'soccer'],

    animals: [
        'dog', 'cat', 'elephant', 'crocodile', 'bird'],

    entertainment: [
        'netflix', 'movies', 'music', 'concert', 'band', 'computer']
}

My HTML has a bootstrap dropdown that will display all categories based on that list. I have the code working to give me the value of the category clicked as a string: as below:

$(document).on('click', '.dropdown-menu li a', function () {
    var selectedCategory;

    selectedCategory = $(this).text();
    //setting value of category to global variable
    categorySelected = selectedCategory;
});

I need to be able to find the key in my database from that value.
The problem is that I can't access words."animals"
I need to take the quotation marks off my string to get the list of words like this:
words.animals

How do I do this? I've tried replace() but it doesn't work.

Body:
It seems like you're trying to access the list of values corresponding to the category in your words object. Keys can be strings, so words['animals'] would be an example of getting your list of animals.

JavaScript allows variables to be used as keys as well, so you can access it as follows:

words[categorySelected]


问:
Laravel Testing - How to validate each fields in JSON response
I want to test my endpoint with valid format. For example, I have /api/token (POST) which will return api token.

In my case, this endpoint will return "token" string and "message" fields. Thus, I want to check if this two fields are exist with valid format. Currently I am using Laravel Validator.

Example json output:

```<code>{
"message": "login successful",
"token": "d4zmendnd69u6h..."
}
</code>```

Test class (ApiTokenTest.php).

```<code>class ApiTokenTest extends TestCase
{

    protected $validFormBody = [
        'os_type' => 'android',
        'device_id' => '0000-AAAA-CCCC-XXXX',
        'os_version' => '5.1',
        'apps_version' => '1.0',
    ];

    public function testSucessResponseFormat()
    {
        $response = $this->json('post', '/api/token', $this->validFormBody);

        $validator = Validator::make(json_decode($response->getContent(), true), [
            'token' => 'required|size:100', // token length should be 100 chars
            'message' => 'required',
        ]);

        if ($validator->fails()) {
            $this->assertTrue(false);
        }
        else {
            $this->assertTrue(true);
        }
    }

}
</code>```

The issue here is the failure message is not really helps, especially if I have more than 1 fields that are not in valid format, should i assert one-by-one?. (see below phpunit output on failure case). What should I use in order to validate format for each fields?
Thanks in advance.

```<code>There was 1 failure:

1) Tests\Feature\ApiTokenTest::testSucessResponseFormat
Failed asserting that false is true.
</code>```

答:
It looks like you are not displaying anything in the terminal if there is in fact any validation errors, what you can do is a var_dump into the terminal if the validator fails, like so:

```<code>    if ($validator->fails()) {
        var_dump($validator->errors()->all());
        $this->assertTrue(false);
    }
    else {
        $this->assertTrue(true);
    }
</code>```

Body:
I want to test my endpoint with valid format. For example, I have /api/token (POST) which will return api token.

In my case, this endpoint will return "token" string and "message" fields. Thus, I want to check if this two fields are exist with valid format. Currently I am using Laravel Validator.

Example json output:

{
"message": "login successful",
"token": "d4zmendnd69u6h..."
}

Test class (ApiTokenTest.php).

class ApiTokenTest extends TestCase
{

    protected $validFormBody = [
        'os_type' => 'android',
        'device_id' => '0000-AAAA-CCCC-XXXX',
        'os_version' => '5.1',
        'apps_version' => '1.0',
    ];

    public function testSucessResponseFormat()
    {
        $response = $this->json('post', '/api/token', $this->validFormBody);

        $validator = Validator::make(json_decode($response->getContent(), true), [
            'token' => 'required|size:100', // token length should be 100 chars
            'message' => 'required',
        ]);

        if ($validator->fails()) {
            $this->assertTrue(false);
        }
        else {
            $this->assertTrue(true);
        }
    }

}

The issue here is the failure message is not really helps, especially if I have more than 1 fields that are not in valid format, should i assert one-by-one?. (see below phpunit output on failure case). What should I use in order to validate format for each fields?
Thanks in advance.

There was 1 failure:

1) Tests\Feature\ApiTokenTest::testSucessResponseFormat
Failed asserting that false is true.

Body:
It looks like you are not displaying anything in the terminal if there is in fact any validation errors, what you can do is a var_dump into the terminal if the validator fails, like so:

    if ($validator->fails()) {
        var_dump($validator->errors()->all());
        $this->assertTrue(false);
    }
    else {
        $this->assertTrue(true);
    }