问:
java.io.NotSerializableException: groovy.util.slurpersupport.NodeChild
I am newbie to groovy script. I have jenkins job which has groovy being used for pipeline.

I'm trying to read the XML file using XmlSlurper class and capture the required information within it so that I can supply those to the next command.

I was able to capture the information, however when I try to input captured values to the next command which run based on the values it being supplied, it throwing an error. Below is the details,

My groovy script:

```<code>env.WORKSPACE = pwd()
def setting = readFile "${env.WORKSPACE}/settings.xml"
def pkgXml = new XmlSlurper().parseText(setting)
def hostUrl = pkgXml.profiles.profile[0].properties['sonar.host.url']
sh("node_modules/sonar-scanner/bin/sonar-scanner scan -e -Dsonar.host.url="+hostUrl+" -Dsonar.language=js '-Dsonar.projectName=Test angular project analyzed with the SonarQube Runner' -Dsonar.projectVersion=1.0 -Dsonar.sourceEncoding=UTF-8 -Dsonar.projectKey=testpipeline_02 -Dsonar.sources=src -Dsonar.projectBaseDir=/base/dir/ -Dsonar.buildbreaker.skip=true")
</code>```

Error message:

```<code>[BFA] Done. 0s
an exception which occurred:
    in field locals
    in field caller
    in field e
    in field program
    in field threads
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2ff2da03
Caused: java.io.NotSerializableException: groovy.util.slurpersupport.NodeChild
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
</code>```

Im expecting to pass the values captured from XmlSlurper, to the sonar scanner command.

Thanks in advance and in anticipation with resolution.

答:
I am guessing pkgXml.profiles.profile[0].properties['sonar.host.url'] is not returning the property value, but an object that cannot be serialized.  Have you tried the following:

```<code>def hostUrl = pkgXml.profiles.profile[0].getProperty('sonar.host.url')
</code>```

Body:
I am newbie to groovy script. I have jenkins job which has groovy being used for pipeline.

I'm trying to read the XML file using XmlSlurper class and capture the required information within it so that I can supply those to the next command.

I was able to capture the information, however when I try to input captured values to the next command which run based on the values it being supplied, it throwing an error. Below is the details,

My groovy script:

env.WORKSPACE = pwd()
def setting = readFile "${env.WORKSPACE}/settings.xml"
def pkgXml = new XmlSlurper().parseText(setting)
def hostUrl = pkgXml.profiles.profile[0].properties['sonar.host.url']
sh("node_modules/sonar-scanner/bin/sonar-scanner scan -e -Dsonar.host.url="+hostUrl+" -Dsonar.language=js '-Dsonar.projectName=Test angular project analyzed with the SonarQube Runner' -Dsonar.projectVersion=1.0 -Dsonar.sourceEncoding=UTF-8 -Dsonar.projectKey=testpipeline_02 -Dsonar.sources=src -Dsonar.projectBaseDir=/base/dir/ -Dsonar.buildbreaker.skip=true")

Error message:

[BFA] Done. 0s
an exception which occurred:
    in field locals
    in field caller
    in field e
    in field program
    in field threads
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@2ff2da03
Caused: java.io.NotSerializableException: groovy.util.slurpersupport.NodeChild
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)

Im expecting to pass the values captured from XmlSlurper, to the sonar scanner command.

Thanks in advance and in anticipation with resolution.

Body:
I am guessing pkgXml.profiles.profile[0].properties['sonar.host.url'] is not returning the property value, but an object that cannot be serialized.  Have you tried the following:

def hostUrl = pkgXml.profiles.profile[0].getProperty('sonar.host.url')


来源: stackexchange

问:
Remote Desktop Services error on WS 2012
I have Remote Desktop Services running on Windows Server 2012 R2. This feature is still working just fine. I can log into the RD Web page, and access all of my remote applications that I have published.

However, I can no longer manage the deployment. When I launch server manager, and navigate to Remote Desktop Services, I see a message "A Remote Desktop Services deployment does not exist in the server pool. To create a deployment, run the Add Roles and Features Wizard and select the Remote Desktop Services installation option."

When I click manage > Add Roles and Features. The RD Web components are showing as installed. This just started happening recently. Does anyone know why?

答: I fixed it! I'm not sure why this fixed it, but disabling the options for IPv6 worked. Basically, go into your NIC adapter properties, and uncheck the box next to IPv6.</p>

ContentLicense: CC BY-SA 3.0


问:
How to pass the data with AJAX to Controller in Laravel?
I am really stuck with AJAX request/response in Laravel and would be glad if someone could help me.

This is my JS Ajax:

```<code>$('#manufacturer_id').change(function(){
  var manuf_id = $(this).val();
  console.log("1:"+manuf_id);

  var dataString = '{manufacturer_id:'+ manuf_id+'}';
  console.log("2:"+dataString);

  // Ajax
  $.ajax({
    url: "/laravel/public/posts/create",
    type: 'GET',
    data: dataString,
    cache: false,
    success: function(data) {
      console.log(dataString);
    },
  });
});
</code>```

And this is the PostsController, where I need to change just one ID:

```<code>public function create(Request $manuf_id)
    {
        $title = 'Add post';

        $categories = Category::all();
        $manufacturers = Manufacturer::all();
        $fuels = Fuel::all();

        $sendedID = \Response::json($manuf_id);
        $cars = Car::where('manufacturer_id', $sendedID)->get();

        return view('posts.create',
            compact(
                'title',
                'categories',
                'fuels',
                'cars',
                'manufacturers'
            )
        );
    }
</code>```

What I really want to achieve: When user select manufacturer from select box in my form, the ID of manufacturer will change the ID which is written here:

```<code>$cars = Car::where('manufacturer_id', $sendedID)->get();
</code>```

Basically when I hardcode the number (ID) instead of variable $sendedID, I get everything I need (I already have releationships between the tables in my database).

All I need to do is to send the value (onchange) of manufacturer and pass it to variable $sendedID in my PostsController. I probably need to change the code in my PostController, just don't know how and I've already researched a lot, but could not find the answer. Thank anybody who has an idea how to repair this.

答:
In your JS you're trying to make a JSON string to send through to the server. There is no need to do this as jQuery will convert everything for you, so just send a normal Javascript object with your required params.

This also means you can clean up your server code as you no longer need to try decode the data sent.

For your JS:

```<code>$('#manufacturer_id').change(function(){
  $.ajax({
    url: "/laravel/public/posts/create",
    type: 'GET',
    data: { manufacturer_id: $(this).val() },
    cache: false,
    success: function(data) {
      console.log(dataString);
    },
  });
});
</code>```

Then in your controller:

```<code>public function create(Request $manuf_id)
{
    $title = 'Add post';

    $categories = Category::all();
    $manufacturers = Manufacturer::all();
    $fuels = Fuel::all();

    $cars = Car::where('manufacturer_id', request('manufacturer_id'))->get();

    return view('posts.create',
        compact(
            'title',
            'categories',
            'fuels',
            'cars',
            'manufacturers'
        )
    );
}
</code>```

Body:
I am really stuck with AJAX request/response in Laravel and would be glad if someone could help me.

This is my JS Ajax:

$('#manufacturer_id').change(function(){
  var manuf_id = $(this).val();
  console.log("1:"+manuf_id);

  var dataString = '{manufacturer_id:'+ manuf_id+'}';
  console.log("2:"+dataString);

  // Ajax
  $.ajax({
    url: "/laravel/public/posts/create",
    type: 'GET',
    data: dataString,
    cache: false,
    success: function(data) {
      console.log(dataString);
    },
  });
});

And this is the PostsController, where I need to change just one ID:

public function create(Request $manuf_id)
    {
        $title = 'Add post';

        $categories = Category::all();
        $manufacturers = Manufacturer::all();
        $fuels = Fuel::all();

        $sendedID = \Response::json($manuf_id);
        $cars = Car::where('manufacturer_id', $sendedID)->get();

        return view('posts.create',
            compact(
                'title',
                'categories',
                'fuels',
                'cars',
                'manufacturers'
            )
        );
    }

What I really want to achieve: When user select manufacturer from select box in my form, the ID of manufacturer will change the ID which is written here:

$cars = Car::where('manufacturer_id', $sendedID)->get();

Basically when I hardcode the number (ID) instead of variable $sendedID, I get everything I need (I already have releationships between the tables in my database).

All I need to do is to send the value (onchange) of manufacturer and pass it to variable $sendedID in my PostsController. I probably need to change the code in my PostController, just don't know how and I've already researched a lot, but could not find the answer. Thank anybody who has an idea how to repair this.

Body:
In your JS you're trying to make a JSON string to send through to the server. There is no need to do this as jQuery will convert everything for you, so just send a normal Javascript object with your required params.

This also means you can clean up your server code as you no longer need to try decode the data sent.

For your JS:

$('#manufacturer_id').change(function(){
  $.ajax({
    url: "/laravel/public/posts/create",
    type: 'GET',
    data: { manufacturer_id: $(this).val() },
    cache: false,
    success: function(data) {
      console.log(dataString);
    },
  });
});

Then in your controller:

public function create(Request $manuf_id)
{
    $title = 'Add post';

    $categories = Category::all();
    $manufacturers = Manufacturer::all();
    $fuels = Fuel::all();

    $cars = Car::where('manufacturer_id', request('manufacturer_id'))->get();

    return view('posts.create',
        compact(
            'title',
            'categories',
            'fuels',
            'cars',
            'manufacturers'
        )
    );
}


问:
Exception in thread "main" java.lang.NumberFormatException: empty String
my program is meant to read from a txt and print certain parts of it. when i try to set Double d4 it gives me an error saying that string is
empty although it's not. and it's also not an issue of formatting since d1-5 worked fine when i removed the line. i also printed data[5] and that showed the proper line from the txt.</p>

```<code>import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class AAAAAA {
    public static void main (String[] args)throws IOException {

    final String fileName = "classQuizzes.txt";
//1)
    Scanner sc = new Scanner(new File(fileName));

    //declarations
    String input;
    double total = 0.0;
    double num = 0;
    double count = 0;
    double average = 0;
    String lastName;
    String firstName;
    double minimum;
    double max;

//2) process rows
    input = sc.nextLine();
    System.out.println(input);
    while (sc.hasNextLine()) {

       String line = sc.nextLine();
       System.out.println(line);

    // split the line into pieces of data separated by the spaces
       String[] data = line.split(" ");

    // get the name from data[]
       System.out.println("d5 " +data[4]);
       firstName = data[0];
       lastName = data[1];
       Double d1 = Double.valueOf(data[2]);
       Double d2 = Double.valueOf(data[3]);
       Double d3 = Double.valueOf(data[4]);
       Double d4 = Double.valueOf(data[5]);
       Double d5 = Double.valueOf(data[6]);

    // do the same...
    System.out.println("data " + d3);
         total += d1 + d2 + d3  + d5;
         count++;

   //find average (decimal 2 points)
               System.out.println(count);
               average = total / count;
               System.out.println("Total = " + total);
               System.out.println("Average = " + average);

//3) class statistics

    //while
       }
         System.out.println("Program created by");
     }
}
</code>```

答:
The line might not be empty, but when you split it at spaces, if there are two spaces in a row, you will get empty strings in the split. To prevent this, change

```<code>String[] data = line.split(" ");
</code>```

to

```<code>String[] data = line.split(" *");
</code>```

or, perhaps better, since it will deal with tabs and other white space:

```<code>String[] data = line.split("\\s*");
</code>```

To track down these kinds of problems yourself (and to verify that I've diagnosed the problem correctly), you should print out each element of the split array, as well as verify the array length is what you expect.

Body:
my program is meant to read from a txt and print certain parts of it. when i try to set Double d4 it gives me an error saying that string is
empty although it's not. and it's also not an issue of formatting since d1-5 worked fine when i removed the line. i also printed data[5] and that showed the proper line from the txt.

import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class AAAAAA {
    public static void main (String[] args)throws IOException {

    final String fileName = "classQuizzes.txt";
//1)
    Scanner sc = new Scanner(new File(fileName));

    //declarations
    String input;
    double total = 0.0;
    double num = 0;
    double count = 0;
    double average = 0;
    String lastName;
    String firstName;
    double minimum;
    double max;

//2) process rows
    input = sc.nextLine();
    System.out.println(input);
    while (sc.hasNextLine()) {

       String line = sc.nextLine();
       System.out.println(line);

    // split the line into pieces of data separated by the spaces
       String[] data = line.split(" ");

    // get the name from data[]
       System.out.println("d5 " +data[4]);
       firstName = data[0];
       lastName = data[1];
       Double d1 = Double.valueOf(data[2]);
       Double d2 = Double.valueOf(data[3]);
       Double d3 = Double.valueOf(data[4]);
       Double d4 = Double.valueOf(data[5]);
       Double d5 = Double.valueOf(data[6]);

    // do the same...
    System.out.println("data " + d3);
         total += d1 + d2 + d3  + d5;
         count++;

   //find average (decimal 2 points)
               System.out.println(count);
               average = total / count;
               System.out.println("Total = " + total);
               System.out.println("Average = " + average);

//3) class statistics

    //while
       }
         System.out.println("Program created by");
     }
}

Body:
The line might not be empty, but when you split it at spaces, if there are two spaces in a row, you will get empty strings in the split. To prevent this, change

String[] data = line.split(" ");

to

String[] data = line.split(" *");

or, perhaps better, since it will deal with tabs and other white space:

String[] data = line.split("\\s*");

To track down these kinds of problems yourself (and to verify that I've diagnosed the problem correctly), you should print out each element of the split array, as well as verify the array length is what you expect.


问:
Which WordPress hook fires after save all post data and post meta?
I have a custom post type crm, and i need to send a mail after each crm saved or updated. i user cmb2 for some custom meta like subject, to users etc. I know the save_post hook fires after post save (according to WordPress codex) in my case when i call save_post with two parameters (id and post) the post does not contains update values. here is my code :

```<code>function send_mail_to_user($id, $post){
    $crm = $post;
    $user_email = array();
    if($crm->vc_all_vc == 'on'){
        $args = array('orderby' => 'display_name');
        $wp_user_query = new WP_User_Query($args);
        $authors = $wp_user_query->get_results();
        if (!empty($authors)) {
            foreach ($authors as $author) {
                array_push($user_email , $author->user_email );
            }
        }
    }
    else{
        $to_users = $crm->vc_users;
        $to_program = $crm->vc_program;
        $to_group = $crm->vc_group;
        $to_excode = $crm->vc_ex_code;
        foreach ($to_users as $key => $value) {
            $user_data = get_userdata($value);
            array_push($user_email, $user_data->user_email);
        }
        foreach ($to_program as $key => $value) {
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
        foreach($to_group as $group) {
            $term = get_term_by('slug', esc_attr($group), 'user-group');
            $user_ids = get_objects_in_term($term->term_id, 'user-group');
            foreach($user_ids as $user_id){
                $fc_user = get_userdata($user_id);
                if(! in_array($fc_user->user_email, $user_email)  )
                {
                    array_push($user_email, $fc_user->user_email);
                }
            }
        }
        foreach($to_excode as $codes) {
            $value = explode('*',$codes)[1];
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
    }
    foreach($user_email as $index => $email){
        $to      = $email;
        $subject = $crm->vc_subject;
        $body    = $crm->post_content;
        $headers = array(
        'Content-Type: text/html; charset=UTF-8'
        );
        wp_mail($to, $subject, $body, $headers);
    }
}

add_action( 'save_post', 'send_mail_to_user', 10, 2 );
</code>```

And i also try publish_post hook , that works fine when new post created but when updated it works same. I have tried edit_post and post_updated hook also, but i never be able to retrieve my update data.

So how can i solve it? which action hook will give me all the new data?
thanks in advance.

答:
You can use something like this, </p>

```<code>function your_custom_function($meta_id, $post_id, $meta_key='', $meta_value='') {
    if($meta_key=='_edit_lock') {
        // if post meta is updated
    }
}
add_action('updated_post_meta', 'your_custom_function', 10, 4);
</code>```

Body:
I have a custom post type crm, and i need to send a mail after each crm saved or updated. i user cmb2 for some custom meta like subject, to users etc. I know the save_post hook fires after post save (according to WordPress codex) in my case when i call save_post with two parameters (id and post) the post does not contains update values. here is my code :

function send_mail_to_user($id, $post){
    $crm = $post;
    $user_email = array();
    if($crm->vc_all_vc == 'on'){
        $args = array('orderby' => 'display_name');
        $wp_user_query = new WP_User_Query($args);
        $authors = $wp_user_query->get_results();
        if (!empty($authors)) {
            foreach ($authors as $author) {
                array_push($user_email , $author->user_email );
            }
        }
    }
    else{
        $to_users = $crm->vc_users;
        $to_program = $crm->vc_program;
        $to_group = $crm->vc_group;
        $to_excode = $crm->vc_ex_code;
        foreach ($to_users as $key => $value) {
            $user_data = get_userdata($value);
            array_push($user_email, $user_data->user_email);
        }
        foreach ($to_program as $key => $value) {
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
        foreach($to_group as $group) {
            $term = get_term_by('slug', esc_attr($group), 'user-group');
            $user_ids = get_objects_in_term($term->term_id, 'user-group');
            foreach($user_ids as $user_id){
                $fc_user = get_userdata($user_id);
                if(! in_array($fc_user->user_email, $user_email)  )
                {
                    array_push($user_email, $fc_user->user_email);
                }
            }
        }
        foreach($to_excode as $codes) {
            $value = explode('*',$codes)[1];
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
    }
    foreach($user_email as $index => $email){
        $to      = $email;
        $subject = $crm->vc_subject;
        $body    = $crm->post_content;
        $headers = array(
        'Content-Type: text/html; charset=UTF-8'
        );
        wp_mail($to, $subject, $body, $headers);
    }
}

add_action( 'save_post', 'send_mail_to_user', 10, 2 );

And i also try publish_post hook , that works fine when new post created but when updated it works same. I have tried edit_post and post_updated hook also, but i never be able to retrieve my update data.

So how can i solve it? which action hook will give me all the new data?
thanks in advance.

Body:
You can use something like this,

function your_custom_function($meta_id, $post_id, $meta_key='', $meta_value='') {
    if($meta_key=='_edit_lock') {
        // if post meta is updated
    }
}
add_action('updated_post_meta', 'your_custom_function', 10, 4);


问:
zip files using powershell
This is what I am trying to do with powershell for zipping files.

Sort out files older than xxx days

Add those files in a zip file.

Delete the source files.

I have Powershell_Community_Extensions installed so I use Write-zip to do the job.

```<code>$Source = "\\network\share"
$files = Get-ChildItem -Path $Source | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-62)}

$files | Write-Zip -OutputPath $Source\Archive.zip -EntryPathRoot $Source -Append -Quiet

Remove-Item $files -Force
</code>```

Issues:

I have to use -EntryPathRoot with Write-zip, otherwise it wont pick up network share

Remove-item also wont pickup files from network share, it says "Remove-Item : Cannot find path 'C:\Windows\system32\feb03.txt' because it does not exist.", why it deleting file from C:\Windows\system32\ instead of \\network\share

Write-zip -append did add files into the zip file, but it did not just add files in the root of that zip file, it actually created entire folder structure in the root of the zip and added newer filtered files in the end of that folder structure. I just want to add the newer filtered files into root of that zip file.

Any idea please?

答:
Utilizing the v5 *Archive cmdlets:</p>

```<code>$Source = '\\network\share'
$Files = Get-ChildItem -Path $Source |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-62) }
Compress-Archive -Path $Files.FullName -DestinationPath $Source\Archive.zip -CompressionLevel Optimal -Update

$Files | Remove-Item -Force
</code>```

Title: zip files using powershell

Body:
This is what I am trying to do with powershell for zipping files.

Sort out files older than xxx days

Add those files in a zip file.

Delete the source files.

I have Powershell_Community_Extensions installed so I use Write-zip to do the job.

$Source = "\\network\share"
$files = Get-ChildItem -Path $Source | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-62)}

$files | Write-Zip -OutputPath $Source\Archive.zip -EntryPathRoot $Source -Append -Quiet

Remove-Item $files -Force

Issues:

I have to use -EntryPathRoot with Write-zip, otherwise it wont pick up network share

Remove-item also wont pickup files from network share, it says "Remove-Item : Cannot find path 'C:\Windows\system32\feb03.txt' because it does not exist.", why it deleting file from C:\Windows\system32\ instead of \\network\share

Write-zip -append did add files into the zip file, but it did not just add files in the root of that zip file, it actually created entire folder structure in the root of the zip and added newer filtered files in the end of that folder structure. I just want to add the newer filtered files into root of that zip file.

Any idea please?

Body:
Utilizing the v5 *Archive cmdlets:

$Source = '\\network\share'
$Files = Get-ChildItem -Path $Source |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-62) }
Compress-Archive -Path $Files.FullName -DestinationPath $Source\Archive.zip -CompressionLevel Optimal -Update

$Files | Remove-Item -Force


问:
How to use ASP.NET Web pages on Cordova Project
I looked into Apache Cordova and I figured it would be a great place to start mobile development for Android/iOS phones. According to the Cordova website, it allows developers to develop mobile apps using HTML, CSS,and JavaScript. My plan is to add ASP.NET web pages onto the Cordova project so I can use C# for backened development. I've been google searching ways to add ASP files to Cordova but I didn't find it helpful. So here are my questions.

Is there a way to add ASP files to a Cordova project, or to convert an ASP project into Cordova? Any answer for this question is greatly appreciated. Thanks.

答: No, I don't think this is possible without heavily extending Cordova itself. Out-of-the-box, Apache doesn't even support ASP.Net.</p>


问:
AngularJS, need help creating a simple function
I would like to understand how to do the following, they asked me to try and create a function in the controller instead of writing the code in the view.

The code is:

```<code> <div class="row">
                <div class="col-xs-12 max300"
                     uib-dropdown is-open="vm.descriptionDropdownOpen">
                    <textarea name="description" class="form-control"
                              ng-model="vm.presence.description"
                              ng-click="vm.toggleDescriptionDropdown()"
                              autofocus>
                    </textarea>
                    <ul id="descriptionDropdown" uib-dropdown-menu>
                        <li ng-repeat="descr in vm.loadedDescriptions"
                            ng-click="vm.presence.description = descr.text;
                                      vm.descriptionDropdownOpen = false;">
                            {{descr.text}}
                        </li>
                    </ul>
                </div>
            </div>
</code>```

so basically this creates a text box, and when you click on it, a dropdown menu will appear, and if you click on a string of the dropdown menu, that string will be put in the text box.

What I need to do is to create a function that will be put in the controller, so we can just call that function in the view and keep the code nicer.

This function just needs to do the last part of the code I posted above, take the string I click on from the dropdown menu and put it in the text box!

It's really simple but as I'm learning I'm not that sure on how I should write it

```<code>setDescription(text: string) {
        // code should go here.
}
</code>```

Sorry for this stupid question, just wanna be sure to understand correctly what I am doing! thank you

答:
html

```<code> ng-click="vm.submitString(descr.text)"
</code>```

controller

```<code>vm.submitString = function(text){
    return vm.presence.description = text;
}
</code>```

Body:
I would like to understand how to do the following, they asked me to try and create a function in the controller instead of writing the code in the view.

The code is:

                    <textarea name="description" class="form-control"
                              ng-model="vm.presence.description"
                              ng-click="vm.toggleDescriptionDropdown()"
                              autofocus>
                    </textarea>

                            {{descr.text}}

so basically this creates a text box, and when you click on it, a dropdown menu will appear, and if you click on a string of the dropdown menu, that string will be put in the text box.

What I need to do is to create a function that will be put in the controller, so we can just call that function in the view and keep the code nicer.

This function just needs to do the last part of the code I posted above, take the string I click on from the dropdown menu and put it in the text box!

It's really simple but as I'm learning I'm not that sure on how I should write it

setDescription(text: string) {
        // code should go here.
}

Sorry for this stupid question, just wanna be sure to understand correctly what I am doing! thank you

Body:
html

 ng-click="vm.submitString(descr.text)"

controller

vm.submitString = function(text){
    return vm.presence.description = text;
}


问:
Creating border using box shadow?
I'm trying to create a border for my elements using CSS box shadow.
However, I can't seem to get this to work.

This is my code:

.vid_img{
display:inline-block;
width:25%;
vertical-align: top;
 box-shadow: inset 0 0 0 -1px red;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"></code>```

答:
You can do it like this:

.vid_img {
  display: inline-block;
  width: 25%;
  vertical-align: top;
  box-shadow: 0 0 0 1px red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"></code>```

Title: Creating border using box shadow?

Body:
You can do it like this:

.vid_img {
  display: inline-block;
  width: 25%;
  vertical-align: top;
  box-shadow: 0 0 0 1px red;
}

<img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img"><img src="https://static.pexels.com/photos/204611/pexels-photo-204611.jpeg" class="vid_img">


问:
I want to create a program that returns a list that contains only the elements that are common between the lists (without duplicates)
Below is the code:

```<code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)
</code>```

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

答:
```<code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

c = list( set(a).intersection(set(b)) )
print (c)
</code>```

The code is self explanatory given that you have basic knowledge of sets.

Body:
Below is the code:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

Body:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

c = list( set(a).intersection(set(b)) )
print (c)

The code is self explanatory given that you have basic knowledge of sets.


问:
jQuery How do set text in a input field then press enter?
jQuery How do set text in a input field then press enter?  I have input field if I manually enter text then submit button will get enabled but if I use jQuery to enter text, then the button won't enabled. How can I make the button enabled?  I am using jQuery with Selenium

Here is what I am looking for verizonwireless.com/support/contact-us on this page, if you enter something in search field, "X" will show up but if you enter using JQuery it won't. So how will I make the "X" show up when I use jquery to enter the text? $('#vgn_q').val('iphone').change(); I tried this but no luck

答:
I was able to do it with following code.</p>

```<code>var e = jQuery.Event( "keypress" );
$('#vgn_q').val('iPhone').trigger(e);
</code>```

Body:
I was able to do it with following code.

var e = jQuery.Event( "keypress" );
$('#vgn_q').val('iPhone').trigger(e);


问:
The dreaded Lazy Initialization Exception when using JAX-WS and JEE6
I am getting a LIE when using the JAX-WS @Path and the @Stateless (or @RequestScoped) annotation. The code:

```<code>@Path("/users")
@Stateless
@Produces(MediaType.APPLICATION_XML)
public class UserResourceRESTService {
  @Inject
  @UserRepository
  @PersistenceContext
  private EntityManager em;

  @GET
  @Path("/{id:[1-9][0-9]*}")
  public User lookupUserById(@PathParam("id") long id) {
      return em.find(User.class, id);
  }
}
</code>```

The actual exception I am getting:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

The user object has an address, which has a country. If I change this to a stateful bean and use an extended context it works, but this really shouldn't be a SFSB should it? I am at a bit of a loss as to why the "em" wouldn't be able to open a session when using a stateless bean?

答:
When you are operating in extended persistence context your returned User entity remains in managed state and when you are using transaction persistence context transaction ends once lookupUserById() method returns and result of that method is an entity which is already detached from persistence context. As a result all properties of that entity which are marked as LAZY are not accessible anymore.

If you want to access these lazy properties after entity became detached from persistence context invoke specific getter methods on that entity prior returning from lookupUserById method.

i.e.

```<code> public User lookupUserById(@PathParam("id") long id) {
  User user =  em.find(User.class, id);
  user.getAddress().getCountry();
  return user;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am getting a LIE when using the JAX-WS @Path and the @Stateless (or @RequestScoped) annotation. The code:

@Path("/users")
@Stateless
@Produces(MediaType.APPLICATION_XML)
public class UserResourceRESTService {
  @Inject
  @UserRepository
  @PersistenceContext
  private EntityManager em;

  @GET
  @Path("/{id:[1-9][0-9]*}")
  public User lookupUserById(@PathParam("id") long id) {
      return em.find(User.class, id);
  }
}

The actual exception I am getting:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

The user object has an address, which has a country. If I change this to a stateful bean and use an extended context it works, but this really shouldn't be a SFSB should it? I am at a bit of a loss as to why the "em" wouldn't be able to open a session when using a stateless bean?

Body:
When you are operating in extended persistence context your returned User entity remains in managed state and when you are using transaction persistence context transaction ends once lookupUserById() method returns and result of that method is an entity which is already detached from persistence context. As a result all properties of that entity which are marked as LAZY are not accessible anymore.

If you want to access these lazy properties after entity became detached from persistence context invoke specific getter methods on that entity prior returning from lookupUserById method.

i.e.

 public User lookupUserById(@PathParam("id") long id) {
  User user =  em.find(User.class, id);
  user.getAddress().getCountry();
  return user;
}


问:
Dialogflow V2 Messenger Integration with Multiple Messages
I am trying to send to multiple messages within one Webhook call to Dialogflow, which shall be passed to Messenger. Right now my Webhook responds with a malfunctioning JSON body:

```<code>{
    'fulfillmentText': "Text",
    'fulfillmentMessages': [{
        "platform": "facebook",
        "text": [{
            "text": "Text"
        }]
    }],
    'source': "facebook"
}
</code>```

When I test the Webhook via Messenger I see the is typing symbol, but never receive the Text message. While testing the same Webhook from the Dialogflow Console I get

Webhook execution successful

returned. I guess I am missing some JSON fields to tell Dialogflow in which format it has to send the JSON two the Messenger API. Anybody having any clues on how to solve this issue?

Edit:
My latest not working trial...

```<code>{
  "fulfillmentText": "Hola!",
  "fulfillmentMessages": [
    {
      "text": {
        "text": [
          "Title: this is a title"
        ]
      },
      "platform": "FACEBOOK"
    },
    {
      "text": {
        "text": [
          "Title: this is a title"
        ]
      },
      "platform": "FACEBOOK"
    }
  ]
}
</code>```

答:
If you're only sending text you only need to provide a string to the fulfillmentText and don't have to provide the fulfillmentMessages attribute.

If you do provide a fulfillmentMessages attribute with the target platform Dialogflow will send your payload to Facebook.  In this case, where the payload is invalid, no message will actually be surfaced in Facebook.  remove the fulfillmentMessages attribute of the response JSON and your bot should respond.

If you'd like to add a card to your response you can send the following response:

```<code>{
  "fulfillmentMessages": [
    {
      "platform": "FACEBOOK",
      "card": {
        "title": "Title: this is a title",
        "subtitle": "This is an subtitle.  Text can include unicode characters including emoji .",
        "imageUri": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
        "buttons": [
          {
            "text": "This is a button",
            "postback": "https://assistant.google.com/"
          }
        ]
      }
    }
  ]
}
</code>```

EDIT: If you want to send multiple messages you can do so by sending a response like this (this JSON will send two identical cards but you can change the message type (card/text/etc) based on this documentation):

```<code>{
  "fulfillmentMessages": [
    {
      "platform": "FACEBOOK",
      "card": {
        "title": "Title: this is a title",
        "subtitle": "This is an subtitle.  Text can include unicode characters including emoji .",
        "imageUri": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
        "buttons": [
          {
            "text": "This is a button",
            "postback": "https://assistant.google.com/"
          }
        ]
      }
    },
    {
      "platform": "FACEBOOK",
      "card": {
        "title": "Title: this is a title",
        "subtitle": "This is an subtitle.  Text can include unicode characters including emoji .",
        "imageUri": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
        "buttons": [
          {
            "text": "This is a button",
            "postback": "https://assistant.google.com/"
          }
        ]
      }
    }
  ]
}
</code>```

Body:
I am trying to send to multiple messages within one Webhook call to Dialogflow, which shall be passed to Messenger. Right now my Webhook responds with a malfunctioning JSON body:

{
    'fulfillmentText': "Text",
    'fulfillmentMessages': [{
        "platform": "facebook",
        "text": [{
            "text": "Text"
        }]
    }],
    'source': "facebook"
}

When I test the Webhook via Messenger I see the is typing symbol, but never receive the Text message. While testing the same Webhook from the Dialogflow Console I get

Webhook execution successful

returned. I guess I am missing some JSON fields to tell Dialogflow in which format it has to send the JSON two the Messenger API. Anybody having any clues on how to solve this issue?

Edit:
My latest not working trial...

{
  "fulfillmentText": "Hola!",
  "fulfillmentMessages": [
    {
      "text": {
        "text": [
          "Title: this is a title"
        ]
      },
      "platform": "FACEBOOK"
    },
    {
      "text": {
        "text": [
          "Title: this is a title"
        ]
      },
      "platform": "FACEBOOK"
    }
  ]
}

Body:
If you're only sending text you only need to provide a string to the fulfillmentText and don't have to provide the fulfillmentMessages attribute.

If you do provide a fulfillmentMessages attribute with the target platform Dialogflow will send your payload to Facebook.  In this case, where the payload is invalid, no message will actually be surfaced in Facebook.  remove the fulfillmentMessages attribute of the response JSON and your bot should respond.

If you'd like to add a card to your response you can send the following response:

{
  "fulfillmentMessages": [
    {
      "platform": "FACEBOOK",
      "card": {
        "title": "Title: this is a title",
        "subtitle": "This is an subtitle.  Text can include unicode characters including emoji .",
        "imageUri": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
        "buttons": [
          {
            "text": "This is a button",
            "postback": "https://assistant.google.com/"
          }
        ]
      }
    }
  ]
}

EDIT: If you want to send multiple messages you can do so by sending a response like this (this JSON will send two identical cards but you can change the message type (card/text/etc) based on this documentation):

{
  "fulfillmentMessages": [
    {
      "platform": "FACEBOOK",
      "card": {
        "title": "Title: this is a title",
        "subtitle": "This is an subtitle.  Text can include unicode characters including emoji .",
        "imageUri": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
        "buttons": [
          {
            "text": "This is a button",
            "postback": "https://assistant.google.com/"
          }
        ]
      }
    },
    {
      "platform": "FACEBOOK",
      "card": {
        "title": "Title: this is a title",
        "subtitle": "This is an subtitle.  Text can include unicode characters including emoji .",
        "imageUri": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
        "buttons": [
          {
            "text": "This is a button",
            "postback": "https://assistant.google.com/"
          }
        ]
      }
    }
  ]
}


问:
Apache ambari installation
I'm trying to install ambari server + agents.

I have a doubt regarding ambari.

I tried to install ambari.

It always gets link with hortonwork

My doubt is that I have hadoop cluster of my own in Ubunu 16.0.
Will ambari only work with HDP or is it possible to also make it work with custom built clusters?

Or if possible please share me detailed descriptive documentation

答:
It's not clear where you downloaded Ambari from, but it sounds like you used the Hortonworks version of it. Not directly from https://ambari.apache.org

Ambari works with the concept of stacks. Each stack has a set of services and components. HDP is such a stack, but there are others, or you can even define your own, so yes, you can manage your own Hadoop installation components, but that really would be not much different from what Hortonworks already provides.

Besides, the HDP services and components have been tested to work together more throughly than off the shelf Hadoop installation.

If you don't want HDP components, there is also the Apache Bigtop project that provides installation packs for many Hadoop related services

Ambari expects Java and Hadoop to be installed in a certain way. I'm not sure how easy it is to setup for an existing Hadoop install.

Title: Apache ambari installation


答:
what you are doing is to compare list a with the elements of list b.

only if an element of list a is also in list b, you put it into the list c.

list c will contain all matching numbers of list a and b, which is obviously the case.

About the comparison which seam to confusing you:

you have to loop 11 times because the len of list a is 11. if you want to compare every element of list a with list b you have to do this.

```<code>for d in range(cal):
</code>```

means you get a range of numbers from 0 to the value of cal (which is the len of your list a), in this case 0,1,2,...10.

```<code>a[d]
</code>```

then means

```<code>a[0]
a[1]
...
a[10]
</code>```

so you finally iterate over every element of your list.

hope that helps your understanding.

Best,

me

Title: I want to create a program that returns a list that contains only the elements that are common between the lists (without duplicates)

Body:
what you are doing is to compare list a with the elements of list b.

only if an element of list a is also in list b, you put it into the list c.

list c will contain all matching numbers of list a and b, which is obviously the case.

About the comparison which seam to confusing you:

you have to loop 11 times because the len of list a is 11. if you want to compare every element of list a with list b you have to do this.

for d in range(cal):

means you get a range of numbers from 0 to the value of cal (which is the len of your list a), in this case 0,1,2,...10.

a[d]

then means

a[0]
a[1]
...
a[10]

so you finally iterate over every element of your list.

hope that helps your understanding.

Best,

me


问:
Does Firebase support overwritten setter methods?
Can you use overwritten setter methods in your Java object (e.g. one that takes a String object and one that takes an int)? if you are going to load and read your object from the Firebase database? Does Firebase know which to use or is it all treated as int/String?

e.g:

```<code>public void setAppointStartTime(String appointStartTime) {
    this.appointStartTime = appointStartTime;
}

public void setAppointStartTime(int minutes) {
    this.appointStartTime = String.format("%02d",((minutes - (minutes % 60)) / 60)) + ":" + (String.format("%02d",(minutes%60)));
}
</code>```

答:
The Firebase SDK follows a JavaBean pattern for determining the properties in a class. JavaBeans properties are of a single type, since their getter method will have a single return type.

As far as I recall, your example setters will lead to the client generating an error about not knowing the type of the appointStartTime property.

Body:
Can you use overwritten setter methods in your Java object (e.g. one that takes a String object and one that takes an int)? if you are going to load and read your object from the Firebase database? Does Firebase know which to use or is it all treated as int/String?

e.g:

public void setAppointStartTime(String appointStartTime) {
    this.appointStartTime = appointStartTime;
}

public void setAppointStartTime(int minutes) {
    this.appointStartTime = String.format("%02d",((minutes - (minutes % 60)) / 60)) + ":" + (String.format("%02d",(minutes%60)));
}


问:
Python Scrapy - service_identity(opentype) not working and cannot install
Python and linux beginner trying to get scrapy up and running. Following the instructions and code from https://doc.scrapy.org/en/latest/intro/tutorial.html. Getting user warning You do not have a working installation of the service_identity module: 'cannot import name 'opentype'

downloaded and tried to install service_identity but got Requirement already satisfied on the different parts of the install. Tried both pip3 and download and install from .whl file downloaded from the pypi-URL below.

python 3.5.3 on lubuntu 17.04 on virtualbox

```<code>mat@mat-VirtualBox:~$ scrapy startproject tutorial2
:0: UserWarning: You do not have a working installation of the service_identity module: 'cannot import name 'opentype''.  Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied.  Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification.  Many valid certificate/hostname mappings may be rejected.
New Scrapy project 'tutorial2', using template directory '/usr/local/lib/python3.5/dist-packages/scrapy/templates/project', created in:
    /home/mat/tutorial2

You can start your first spider with:
    cd tutorial2
    scrapy genspider example example.com
mat@mat-VirtualBox:~$ pip3 install Downloads/
geckodriver-v0.19.1-linux64.tar.gz
NOOBS_lite_v2_4.zip
npm-debug.log
phantomjs-2.1.1-linux-x86_64/
phantomjs-2.1.1-linux-x86_64.tar.bz2
reveal.js-master.zip
service_identity/
service_identity-17.0.0.dist-info/
service_identity-17.0.0-py2.py3-none-any.whl
mat@mat-VirtualBox:~$ pip3 install Downloads/service_identity-17.0.0
Invalid requirement: 'Downloads/service_identity-17.0.0'
It looks like a path. Does it exist ?
mat@mat-VirtualBox:~$ pip3 install Downloads/service_identity-17.0.0-py2.py3-none-any.whl
Requirement already satisfied: service-identity==17.0.0 from file:///home/mat/Downloads/service_identity-17.0.0-py2.py3-none-any.whl in /usr/local/lib/python3.5/dist-packages
Requirement already satisfied: pyopenssl>=0.12 in /usr/local/lib/python3.5/dist-packages (from service-identity==17.0.0)
Requirement already satisfied: attrs in /usr/local/lib/python3.5/dist-packages (from service-identity==17.0.0)
Requirement already satisfied: pyasn1-modules in /usr/local/lib/python3.5/dist-packages (from service-identity==17.0.0)
Requirement already satisfied: pyasn1 in /usr/lib/python3/dist-packages (from service-identity==17.0.0)
Requirement already satisfied: six>=1.5.2 in /usr/lib/python3/dist-packages (from pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: cryptography>=2.1.4 in /usr/local/lib/python3.5/dist-packages (from pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: asn1crypto>=0.21.0 in /usr/local/lib/python3.5/dist-packages (from cryptography>=2.1.4->pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: cffi>=1.7; platform_python_implementation != "PyPy" in /usr/local/lib/python3.5/dist-packages (from cryptography>=2.1.4->pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: idna>=2.1 in /usr/lib/python3/dist-packages (from cryptography>=2.1.4->pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: pycparser in /usr/local/lib/python3.5/dist-packages (from cffi>=1.7; platform_python_implementation != "PyPy"->cryptography>=2.1.4->pyopenssl>=0.12->service-identity==17.0.0)
mat@mat-VirtualBox:~$
</code>```

trying anyway to see what happes

```<code>mat@mat-VirtualBox:~/tutorial2$ scrapy crawl qoutes
:0: UserWarning: You do not have a working installation of the service_identity module: 'cannot import name 'opentype''.  Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied.  Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification.  Many valid certificate/hostname mappings may be rejected.
2017-12-06 19:35:52 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: tutorial2)
2017-12-06 19:35:52 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'tutorial2', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['tutorial2.spiders'], 'NEWSPIDER_MODULE': 'tutorial2.spiders'}
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/scrapy/spiderloader.py", line 69, in load
    return self._spiders[spider_name]
KeyError: 'qoutes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/scrapy", line 11, in <module>
    sys.exit(execute())
  File "/usr/local/lib/python3.5/dist-packages/scrapy/cmdline.py", line 149, in execute
    _run_print_help(parser, _run_command, cmd, args, opts)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/cmdline.py", line 89, in _run_print_help
    func(*a, **kw)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/cmdline.py", line 156, in _run_command
    cmd.run(args, opts)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/commands/crawl.py", line 57, in run
    self.crawler_process.crawl(spname, **opts.spargs)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/crawler.py", line 167, in crawl
    crawler = self.create_crawler(crawler_or_spidercls)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/crawler.py", line 195, in create_crawler
    return self._create_crawler(crawler_or_spidercls)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/crawler.py", line 199, in _create_crawler
    spidercls = self.spider_loader.load(spidercls)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/spiderloader.py", line 71, in load
    raise KeyError("Spider not found: {}".format(spider_name))
KeyError: 'Spider not found: qoutes'
mat@mat-VirtualBox:~/tutorial2$
</code>```

code in my /home/mat/tutorial2/tutorial2/spiders/qoutes_spider.py

```<code>import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        urls = [
            'http://quotes.toscrape.com/page/1/',
            'http://quotes.toscrape.com/page/2/',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'quotes-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)
</code>```

答:
Your issue seems to be a typo. You are using qoutes and quotes. Swapping o and u. Also for service_identity is a warning as such. If you want to install it try using

```<code>pip3 install service_identity --force --upgrade
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Python and linux beginner trying to get scrapy up and running. Following the instructions and code from https://doc.scrapy.org/en/latest/intro/tutorial.html. Getting user warning You do not have a working installation of the service_identity module: 'cannot import name 'opentype'

downloaded and tried to install service_identity but got Requirement already satisfied on the different parts of the install. Tried both pip3 and download and install from .whl file downloaded from the pypi-URL below.

python 3.5.3 on lubuntu 17.04 on virtualbox

mat@mat-VirtualBox:~$ scrapy startproject tutorial2
:0: UserWarning: You do not have a working installation of the service_identity module: 'cannot import name 'opentype''.  Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied.  Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification.  Many valid certificate/hostname mappings may be rejected.
New Scrapy project 'tutorial2', using template directory '/usr/local/lib/python3.5/dist-packages/scrapy/templates/project', created in:
    /home/mat/tutorial2

You can start your first spider with:
    cd tutorial2
    scrapy genspider example example.com
mat@mat-VirtualBox:~$ pip3 install Downloads/
geckodriver-v0.19.1-linux64.tar.gz
NOOBS_lite_v2_4.zip
npm-debug.log
phantomjs-2.1.1-linux-x86_64/
phantomjs-2.1.1-linux-x86_64.tar.bz2
reveal.js-master.zip
service_identity/
service_identity-17.0.0.dist-info/
service_identity-17.0.0-py2.py3-none-any.whl
mat@mat-VirtualBox:~$ pip3 install Downloads/service_identity-17.0.0
Invalid requirement: 'Downloads/service_identity-17.0.0'
It looks like a path. Does it exist ?
mat@mat-VirtualBox:~$ pip3 install Downloads/service_identity-17.0.0-py2.py3-none-any.whl
Requirement already satisfied: service-identity==17.0.0 from file:///home/mat/Downloads/service_identity-17.0.0-py2.py3-none-any.whl in /usr/local/lib/python3.5/dist-packages
Requirement already satisfied: pyopenssl>=0.12 in /usr/local/lib/python3.5/dist-packages (from service-identity==17.0.0)
Requirement already satisfied: attrs in /usr/local/lib/python3.5/dist-packages (from service-identity==17.0.0)
Requirement already satisfied: pyasn1-modules in /usr/local/lib/python3.5/dist-packages (from service-identity==17.0.0)
Requirement already satisfied: pyasn1 in /usr/lib/python3/dist-packages (from service-identity==17.0.0)
Requirement already satisfied: six>=1.5.2 in /usr/lib/python3/dist-packages (from pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: cryptography>=2.1.4 in /usr/local/lib/python3.5/dist-packages (from pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: asn1crypto>=0.21.0 in /usr/local/lib/python3.5/dist-packages (from cryptography>=2.1.4->pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: cffi>=1.7; platform_python_implementation != "PyPy" in /usr/local/lib/python3.5/dist-packages (from cryptography>=2.1.4->pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: idna>=2.1 in /usr/lib/python3/dist-packages (from cryptography>=2.1.4->pyopenssl>=0.12->service-identity==17.0.0)
Requirement already satisfied: pycparser in /usr/local/lib/python3.5/dist-packages (from cffi>=1.7; platform_python_implementation != "PyPy"->cryptography>=2.1.4->pyopenssl>=0.12->service-identity==17.0.0)
mat@mat-VirtualBox:~$

trying anyway to see what happes

mat@mat-VirtualBox:~/tutorial2$ scrapy crawl qoutes
:0: UserWarning: You do not have a working installation of the service_identity module: 'cannot import name 'opentype''.  Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied.  Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification.  Many valid certificate/hostname mappings may be rejected.
2017-12-06 19:35:52 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: tutorial2)
2017-12-06 19:35:52 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'tutorial2', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['tutorial2.spiders'], 'NEWSPIDER_MODULE': 'tutorial2.spiders'}
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/scrapy/spiderloader.py", line 69, in load
    return self._spiders[spider_name]
KeyError: 'qoutes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/scrapy", line 11, in <module>
    sys.exit(execute())
  File "/usr/local/lib/python3.5/dist-packages/scrapy/cmdline.py", line 149, in execute
    _run_print_help(parser, _run_command, cmd, args, opts)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/cmdline.py", line 89, in _run_print_help
    func(*a, **kw)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/cmdline.py", line 156, in _run_command
    cmd.run(args, opts)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/commands/crawl.py", line 57, in run
    self.crawler_process.crawl(spname, **opts.spargs)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/crawler.py", line 167, in crawl
    crawler = self.create_crawler(crawler_or_spidercls)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/crawler.py", line 195, in create_crawler
    return self._create_crawler(crawler_or_spidercls)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/crawler.py", line 199, in _create_crawler
    spidercls = self.spider_loader.load(spidercls)
  File "/usr/local/lib/python3.5/dist-packages/scrapy/spiderloader.py", line 71, in load
    raise KeyError("Spider not found: {}".format(spider_name))
KeyError: 'Spider not found: qoutes'
mat@mat-VirtualBox:~/tutorial2$

code in my /home/mat/tutorial2/tutorial2/spiders/qoutes_spider.py

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        urls = [
            'http://quotes.toscrape.com/page/1/',
            'http://quotes.toscrape.com/page/2/',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'quotes-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)

Body:
Your issue seems to be a typo. You are using qoutes and quotes. Swapping o and u. Also for service_identity is a warning as such. If you want to install it try using

pip3 install service_identity --force --upgrade


问:
SQL Server 2008 - False error for "Msg 8120"?
I am writing a query in SQL Server 2008 (Express I believe?). I am currently getting this error:

Msg 8120, Level 16, State 1, Line 16

  Column 'AIM.dbo.AggTicket.TotDirectHrs' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I am trying to do a historical analysis of our production WIP (Work In Process).
I have created a standalone calendar table (actually located in a separate database called BAS on the same server to not interfere with the ERP that operates the AIM database). I've been overwhelmed for days with some of the examples for creating running total queries/views/tables, so for now I'll just plan on taking care of that part inside of Crystal Reports 2016. My thinking was that I wanted to return records for each order each day of my calendar table (to be narrowed down in the future to only days that match records in the AIM database). The values I think I will need are:

Record Date (not unique)

Order Number (unique for each day)

Estimated hours for the job

The total number of hours worked on the job current as of today's date (in case the estimated hours were drastically underbudgeted)

The SUM of the direct labor hours charged to the job on said record date

The COUNT of the number of employees in attendance on said record date.

The SUM of the hours attended by employees on said record date.

The tables I use are as follows:

BAS Database:

dbo.DateDimension - Used for complete calendar of dates from 1/1/1987 to 12/31/2036

AIM Database:

dbo.AggAttend - Contains one or more records for each employee's attendance duration on a given date (i.e. One record for each punch-in / punch-out. Should be equal to indirect + direct labor)

dbo.AggTicket - Contains one or more records for each employee's direct labor duration charged to a particular order number

dbo.ModOrders - Contains one record for each order including the estimated hours, start date, and end date (I will worry about using the start and end dates later for figuring out how many available hours there were on each date)

Here is the code I'm using in my query:

```<code>;WITH OrderTots AS
(
    SELECT
        AggTicket.OrderNo,
        SUM(AggTicket.TotDirectHrs) AS TotActHrs
    FROM
        AIM.dbo.AggTicket
    GROUP BY
        AggTicket.OrderNo
)
SELECT
    d.Date,
    t.OrderNo,
    o.EstHrs,
    OrderTots.TotActHrs,
    SUM(t.TotDirectHrs) OVER (PARTITION BY t.TicketDate) AS DaysDirectHrs,
    COUNT(a.EmplCode) AS NumEmployees,
    SUM(a.TotHrs) AS DaysAttendHrs
FROM
    BAS.dbo.DateDimension d
INNER JOIN
    AIM.dbo.AggAttend a ON d.Date = a.TicketDate
LEFT OUTER JOIN
    AIM.dbo.AggTicket t ON d.Date = t.TicketDate
LEFT OUTER JOIN
    AIM.dbo.ModOrders o ON t.OrderNo = o.OrderNo
LEFT OUTER JOIN
    OrderTots ON t.OrderNo = OrderTots.OrderNo
GROUP BY
    d.Date, t.TicketDate, t.OrderNo, o.EstHrs,
    OrderTots.TotActHrs
ORDER BY
    d.Date
</code>```

When I run that query in SQL Server Management Studio 2017, I get the above error.

These are my questions for the community:

Does this error message correctly describe an error in my code?

If so, why is that error an error? (To the best of my knowledge, everything is already contained in either an aggregate function or in the GROUP BY clause...smh)

What is a better way to write this query so that it will function?

Much appreciation to everyone in advance!

答:
I am writing a query in SQL Server 2008 (Express I believe?).

SELECT @@VERSION Will let you know what version you are on.

Column 'AIM.dbo.AggTicket.TotDirectHrs' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause.

The problem is with your SUM OVER() statement:

```<code>SUM(t.TotDirectHrs) OVER (PARTITION BY t.TicketDate) AS DaysDirectHrs
</code>```

Here, since you are using the OVER clause, you must include it in the GROUP BY. The OVER clause is used to determine the partitioning and order of a row-set for a window function. So, while you are using an aggregate with SUM you are doing this in a window function. Window functions belong to a type of function known as a 'set function', which means a function that applies to a set of rows. The word 'window' is used to refer to the set of rows that the function works on.

Thus, add t.TotDirectHrs to the GROUP BY

```<code>GROUP BY
    d.Date, t.TicketDate, t.OrderNo, o.EstHrs,
    OrderTots.TotActHrs, t.TotDirectHrs
</code>```

If this narrows your results into a grouping that you don't want, then you can wrap it in another CTE or use a correlated sub-query. Potentially like the below:

```<code>(SELECT SUM(t2.TotDirectHrs) OVER (PARTITION BY t2.TicketDate) AS DaysDirectHrs FROM  AIM.dbo.AggTicket t2 WHERE t2.TicketDate = t.TicketDate) as DaysDirectHrs,
</code>```

EXAMPLE

```<code>if object_id('tempdb..#test') is not null
drop table #test

create table #test(id int identity(1,1), letter char(1))
insert into #test
values
('a'),
('b'),
('b'),
('c'),
('c'),
('c')
</code>```

Given the data set above, suppose we wanted to get a count of all rows. That's simple right?

```<code>select
    TheCount = count(*)
from
    #test

+----------+
| TheCount |
+----------+
|        6 |
+----------+
</code>```

Here, no GROUP BY is needed because it's implied to group over all columns since no columns are specified in the SELECT list. Remember, GROUP BY groups the SELECT statement results according to the values in a list of one or more column expressions. If aggregate functions are included in the SELECT list, GROUP BY calculates a summary value for each group. These are known as vector aggregates.[MSDN].

Now, suppose we wanted to count each letter in the table. We could do that at least two ways. Using COUNT(*) with the letter column in the select list--or using COUNT(letter) with the letter column in the select list. However, in order for us to attribute the count with the letter, we need to return the letter column. Thus, we must include letter in the GROUP BY to tell SQL Server what to apply the summary table to.

```<code>select
    letter
    ,TheCount = count(*)
from
    #test
group by
    letter

+--------+----------+
| letter | TheCount |
+--------+----------+
| a      |        1 |
| b      |        2 |
| c      |        3 |
+--------+----------+
</code>```

Now, what if we wanted to return this same count, but we wanted to return all rows as well? This is where window functions come in. The window function works similar to GROUP BY in this case by telling SQL Server the set of rows to apply the aggregate to. Then, it's value is returned for for every row in this window / partition. Thus, it returns a column which is applied to every row making it just like any column or calculated column which is returned form the select list.

```<code>select
    letter
    ,TheCountOfTheLetter = count(*) over (partition by letter)
from
    #test

+--------+---------------------+
| letter | TheCountOfTheLetter |
+--------+---------------------+
| a      |                   1 |
| b      |                   2 |
| b      |                   2 |
| c      |                   3 |
| c      |                   3 |
| c      |                   3 |
+--------+---------------------+
</code>```

Now we get to your case where you want to use an aggregate and an aggregate in a window function. Remember that the return of the window function is treated like any other column, thus must be applied in the GROUP BY. Pseudo would look something like this, but window functions aren't allowed in the GROUP BY clause.

```<code>select
    letter
    ,TheCount = count(*)
    ,TheCountOfTheLetter = count(*) over (partition by letter)
from
    #test
group by
    letter
    ,count(*) over (partition by letter)

--returns an error
</code>```

Thus, we must a correlated sub-query or a cte or some other method.

```<code>select
    t.letter
    ,TheCount = count(*)
    ,TheCountOfTheLetter = (select distinct count(*) over (partition by letter) from #test t2 where t2.letter = t.letter)
from
    #test t
group by
    t.letter

+--------+----------+---------------------+
| letter | TheCount | TheCountOfTheLetter |
+--------+----------+---------------------+
| a      |        1 |                   1 |
| b      |        2 |                   2 |
| c      |        3 |                   3 |
+--------+----------+---------------------+
</code>```

Body:
I am writing a query in SQL Server 2008 (Express I believe?). I am currently getting this error:

Msg 8120, Level 16, State 1, Line 16

  Column 'AIM.dbo.AggTicket.TotDirectHrs' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I am trying to do a historical analysis of our production WIP (Work In Process).
I have created a standalone calendar table (actually located in a separate database called BAS on the same server to not interfere with the ERP that operates the AIM database). I've been overwhelmed for days with some of the examples for creating running total queries/views/tables, so for now I'll just plan on taking care of that part inside of Crystal Reports 2016. My thinking was that I wanted to return records for each order each day of my calendar table (to be narrowed down in the future to only days that match records in the AIM database). The values I think I will need are:

Record Date (not unique)

Order Number (unique for each day)

Estimated hours for the job

The total number of hours worked on the job current as of today's date (in case the estimated hours were drastically underbudgeted)

The SUM of the direct labor hours charged to the job on said record date

The COUNT of the number of employees in attendance on said record date.

The SUM of the hours attended by employees on said record date.

The tables I use are as follows:

BAS Database:

dbo.DateDimension - Used for complete calendar of dates from 1/1/1987 to 12/31/2036

AIM Database:

dbo.AggAttend - Contains one or more records for each employee's attendance duration on a given date (i.e. One record for each punch-in / punch-out. Should be equal to indirect + direct labor)

dbo.AggTicket - Contains one or more records for each employee's direct labor duration charged to a particular order number

dbo.ModOrders - Contains one record for each order including the estimated hours, start date, and end date (I will worry about using the start and end dates later for figuring out how many available hours there were on each date)

Here is the code I'm using in my query:

;WITH OrderTots AS
(
    SELECT
        AggTicket.OrderNo,
        SUM(AggTicket.TotDirectHrs) AS TotActHrs
    FROM
        AIM.dbo.AggTicket
    GROUP BY
        AggTicket.OrderNo
)
SELECT
    d.Date,
    t.OrderNo,
    o.EstHrs,
    OrderTots.TotActHrs,
    SUM(t.TotDirectHrs) OVER (PARTITION BY t.TicketDate) AS DaysDirectHrs,
    COUNT(a.EmplCode) AS NumEmployees,
    SUM(a.TotHrs) AS DaysAttendHrs
FROM
    BAS.dbo.DateDimension d
INNER JOIN
    AIM.dbo.AggAttend a ON d.Date = a.TicketDate
LEFT OUTER JOIN
    AIM.dbo.AggTicket t ON d.Date = t.TicketDate
LEFT OUTER JOIN
    AIM.dbo.ModOrders o ON t.OrderNo = o.OrderNo
LEFT OUTER JOIN
    OrderTots ON t.OrderNo = OrderTots.OrderNo
GROUP BY
    d.Date, t.TicketDate, t.OrderNo, o.EstHrs,
    OrderTots.TotActHrs
ORDER BY
    d.Date

When I run that query in SQL Server Management Studio 2017, I get the above error.

These are my questions for the community:

Does this error message correctly describe an error in my code?

If so, why is that error an error? (To the best of my knowledge, everything is already contained in either an aggregate function or in the GROUP BY clause...smh)

What is a better way to write this query so that it will function?

Much appreciation to everyone in advance!

Body:
I am writing a query in SQL Server 2008 (Express I believe?).

SELECT @@VERSION Will let you know what version you are on.

Column 'AIM.dbo.AggTicket.TotDirectHrs' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause.

The problem is with your SUM OVER() statement:

SUM(t.TotDirectHrs) OVER (PARTITION BY t.TicketDate) AS DaysDirectHrs

Here, since you are using the OVER clause, you must include it in the GROUP BY. The OVER clause is used to determine the partitioning and order of a row-set for a window function. So, while you are using an aggregate with SUM you are doing this in a window function. Window functions belong to a type of function known as a 'set function', which means a function that applies to a set of rows. The word 'window' is used to refer to the set of rows that the function works on.

Thus, add t.TotDirectHrs to the GROUP BY

GROUP BY
    d.Date, t.TicketDate, t.OrderNo, o.EstHrs,
    OrderTots.TotActHrs, t.TotDirectHrs

If this narrows your results into a grouping that you don't want, then you can wrap it in another CTE or use a correlated sub-query. Potentially like the below:

(SELECT SUM(t2.TotDirectHrs) OVER (PARTITION BY t2.TicketDate) AS DaysDirectHrs FROM  AIM.dbo.AggTicket t2 WHERE t2.TicketDate = t.TicketDate) as DaysDirectHrs,

EXAMPLE

if object_id('tempdb..#test') is not null
drop table #test

create table #test(id int identity(1,1), letter char(1))
insert into #test
values
('a'),
('b'),
('b'),
('c'),
('c'),
('c')

Given the data set above, suppose we wanted to get a count of all rows. That's simple right?

select
    TheCount = count(*)
from
    #test

+----------+
| TheCount |
+----------+
|        6 |
+----------+

Here, no GROUP BY is needed because it's implied to group over all columns since no columns are specified in the SELECT list. Remember, GROUP BY groups the SELECT statement results according to the values in a list of one or more column expressions. If aggregate functions are included in the SELECT list, GROUP BY calculates a summary value for each group. These are known as vector aggregates.[MSDN].

Now, suppose we wanted to count each letter in the table. We could do that at least two ways. Using COUNT(*) with the letter column in the select list--or using COUNT(letter) with the letter column in the select list. However, in order for us to attribute the count with the letter, we need to return the letter column. Thus, we must include letter in the GROUP BY to tell SQL Server what to apply the summary table to.

select
    letter
    ,TheCount = count(*)
from
    #test
group by
    letter

+--------+----------+
| letter | TheCount |
+--------+----------+
| a      |        1 |
| b      |        2 |
| c      |        3 |
+--------+----------+

Now, what if we wanted to return this same count, but we wanted to return all rows as well? This is where window functions come in. The window function works similar to GROUP BY in this case by telling SQL Server the set of rows to apply the aggregate to. Then, it's value is returned for for every row in this window / partition. Thus, it returns a column which is applied to every row making it just like any column or calculated column which is returned form the select list.

select
    letter
    ,TheCountOfTheLetter = count(*) over (partition by letter)
from
    #test

+--------+---------------------+
| letter | TheCountOfTheLetter |
+--------+---------------------+
| a      |                   1 |
| b      |                   2 |
| b      |                   2 |
| c      |                   3 |
| c      |                   3 |
| c      |                   3 |
+--------+---------------------+

Now we get to your case where you want to use an aggregate and an aggregate in a window function. Remember that the return of the window function is treated like any other column, thus must be applied in the GROUP BY. Pseudo would look something like this, but window functions aren't allowed in the GROUP BY clause.

select
    letter
    ,TheCount = count(*)
    ,TheCountOfTheLetter = count(*) over (partition by letter)
from
    #test
group by
    letter
    ,count(*) over (partition by letter)

--returns an error

Thus, we must a correlated sub-query or a cte or some other method.

select
    t.letter
    ,TheCount = count(*)
    ,TheCountOfTheLetter = (select distinct count(*) over (partition by letter) from #test t2 where t2.letter = t.letter)
from
    #test t
group by
    t.letter

+--------+----------+---------------------+
| letter | TheCount | TheCountOfTheLetter |
+--------+----------+---------------------+
| a      |        1 |                   1 |
| b      |        2 |                   2 |
| c      |        3 |                   3 |
+--------+----------+---------------------+


问:
Rand Implementation
I would like to go through how rand() and srand() functions are implemented and would like to tweak the code to modify it to my requirements. Where can i find the source code of rand() and srand(). </p>

答:
rand and srand are usually implemented as a simple LCG, you can easily write your own (it's few lines of code) without looking for the sources of rand and srand. Notice that, if you need random numbers for "serious" purposes (e.g. cryptography), there are much better RNGs than LCG.

By the way, the C standard itself includes a sample implementation of rand and srand:

```<code>static unsigned long int next = 1;

int rand(void) // RAND_MAX assumed to be 32767
{
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}

void srand(unsigned int seed)
{
    next = seed;
}
</code>```

Title: Rand Implementation

Body:
rand and srand are usually implemented as a simple LCG, you can easily write your own (it's few lines of code) without looking for the sources of rand and srand. Notice that, if you need random numbers for "serious" purposes (e.g. cryptography), there are much better RNGs than LCG.

By the way, the C standard itself includes a sample implementation of rand and srand:

static unsigned long int next = 1;

int rand(void) // RAND_MAX assumed to be 32767
{
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}

void srand(unsigned int seed)
{
    next = seed;
}


问:
Match exact phrase within a string in Python
I'm trying to determine whether a substring is in a string.
The issue I'm running into is that I don't want my function to return True if the substring is found within another word in the string.

For example: if the substring is; "Purple cow"
and the string is; "Purple cows make the best pets."
This should return False. Since cow isn't plural in the substring.

And if the substring was; "Purple cow"
and the string was; "Your purple cow trampled my hedge!"
would return True

My code looks something like this:

```<code>def is_phrase_in(phrase, text):
    phrase = phrase.lower()
    text = text.lower()

    return phrase in text

text = "Purple cows make the best pets!"
phrase = "Purple cow"
print(is_phrase_in(phrase, text)
</code>```

In my actual code I clean up unnecessary punctuation and spaces in 'text' before comparing it to phrase, but otherwise this is the same.
I've tried using re.search, but I don't understand regular expressions very well yet and have only gotten the same functionality from them as in my example.

Thanks for any help you can provide!

答:
One can do this very literally with a loop

```<code>phrase = phrase.lower()
text = text.lower()

answer = False
j = 0
for i in range(len(text)):
    if j == len(phrase):
        return text[i] == " "
    if phrase[j] == text[i]:
        answer = True
        j+=1
    else:
        j = 0
        answer = False
return answer
</code>```

Or by splitting

```<code>phrase_words = phrase.lower().split()
text_words = text.lower().split()

return phrase_words in text_words
</code>```

or using regular expressions

```<code>import re
pattern = re.compile("[^\w]" + text + ""[^\w]")
pattern.match(phrase.lower())
</code>```

to say that we want no characters preceding or following our text, but whitespace is okay.

Body:
I'm trying to determine whether a substring is in a string.
The issue I'm running into is that I don't want my function to return True if the substring is found within another word in the string.

For example: if the substring is; "Purple cow"
and the string is; "Purple cows make the best pets."
This should return False. Since cow isn't plural in the substring.

And if the substring was; "Purple cow"
and the string was; "Your purple cow trampled my hedge!"
would return True

My code looks something like this:

def is_phrase_in(phrase, text):
    phrase = phrase.lower()
    text = text.lower()

    return phrase in text

text = "Purple cows make the best pets!"
phrase = "Purple cow"
print(is_phrase_in(phrase, text)

In my actual code I clean up unnecessary punctuation and spaces in 'text' before comparing it to phrase, but otherwise this is the same.
I've tried using re.search, but I don't understand regular expressions very well yet and have only gotten the same functionality from them as in my example.

Thanks for any help you can provide!

Body:
One can do this very literally with a loop

phrase = phrase.lower()
text = text.lower()

answer = False
j = 0
for i in range(len(text)):
    if j == len(phrase):
        return text[i] == " "
    if phrase[j] == text[i]:
        answer = True
        j+=1
    else:
        j = 0
        answer = False
return answer

Or by splitting

phrase_words = phrase.lower().split()
text_words = text.lower().split()

return phrase_words in text_words

or using regular expressions

import re
pattern = re.compile("[^\w]" + text + ""[^\w]")
pattern.match(phrase.lower())

to say that we want no characters preceding or following our text, but whitespace is okay.


问:
Swift Alamofire response status code
How can I get status code from the Alamofire response?

In the latest version I can use validate but I need to check what the status code is.

Code:

```<code>Alamofire.request(.GET, "http://example.com/url")
         .responseJSON { response in

         }
</code>```

答:
While the above methods will work, there is a more efficient way to do this. response.response.statusCode returns a status code that could very in large amounts. Alamofire includes two functions that are useful for this case, isSuccess and isFailure.

```<code>Alamofire.request(.get, "http://example.com/url").responseJSON { response in
    let responseErrorCode = response.response!.statusCode

    if response.result.isSuccess {
         print("Successful HTTP code: \(responseErrorCode)")

         // Run code if request is successful

    } else if response.result.isFailure {
         print("Failure HTTP code: \(responseErrorCode)")

         // Run code if request isn't successful

    }
}
</code>```

By using the code above you can easily know whether the HTTP code is good or bad.

Title: Swift Alamofire response status code

Body:
How can I get status code from the Alamofire response?

In the latest version I can use validate but I need to check what the status code is.

Code:

Alamofire.request(.GET, "http://example.com/url")
         .responseJSON { response in

         }

Body:
While the above methods will work, there is a more efficient way to do this. response.response.statusCode returns a status code that could very in large amounts. Alamofire includes two functions that are useful for this case, isSuccess and isFailure.

Alamofire.request(.get, "http://example.com/url").responseJSON { response in
    let responseErrorCode = response.response!.statusCode

    if response.result.isSuccess {
         print("Successful HTTP code: \(responseErrorCode)")

         // Run code if request is successful

    } else if response.result.isFailure {
         print("Failure HTTP code: \(responseErrorCode)")

         // Run code if request isn't successful

    }
}

By using the code above you can easily know whether the HTTP code is good or bad.


问:
Visual Studio: How to break on handled exceptions?
I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception).

e.g. I want the debugger to break at the exception:

```<code>try
{
   System.IO.File.Delete(someFilename);
}
catch (Exception)
{
   //we really don't care at runtime if the file couldn't be deleted
}
</code>```

I came across these notes for Visual Studio.NET:

1) In VS.NET go to the Debug Menu >>
  "Exceptions..." >> "Common Language
  Runtime Exceptions" >> "System" and
  select "System.NullReferenceException"

2) In the bottom of that dialog there
  is a "When the exception is thrown:"
  group box, select "Break into the
  debugger"

3) Run your scenario. When the
  exception is thrown, the debugger will
  stop and notify you with a dialog that
  says something like:
            "An exception of type "System.NullReferenceException" has
  been thrown.
            [Break] [Continue]"

Hit [Break]. This will put you on the
  line of code that's causing the
  problem.

But they do not apply to Visual Studio 2005 (there is no Exceptions option on the Debug menu).

Does anyone know where the find this options dialog in Visual Studio that the "When the exception is thrown" group box, with the option to "Break into the debugger"?

Update: The problem was that my Debug menu didn't have an Exceptions item. I customized the menu to manually add it.

答:
From Visual Studio 2015 and onward, you need to go to the "Exception Settings" dialog (Ctrl+Alt+E) and check off the "Common Language Runtime Exceptions" (or a specific one you want i.e. ArgumentNullException) to make it break on handled exceptions.

Step 1

Step 2

Body:
I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception).

e.g. I want the debugger to break at the exception:

try
{
   System.IO.File.Delete(someFilename);
}
catch (Exception)
{
   //we really don't care at runtime if the file couldn't be deleted
}

I came across these notes for Visual Studio.NET:

1) In VS.NET go to the Debug Menu >>
  "Exceptions..." >> "Common Language
  Runtime Exceptions" >> "System" and
  select "System.NullReferenceException"

2) In the bottom of that dialog there
  is a "When the exception is thrown:"
  group box, select "Break into the
  debugger"

3) Run your scenario. When the
  exception is thrown, the debugger will
  stop and notify you with a dialog that
  says something like:
            "An exception of type "System.NullReferenceException" has
  been thrown.
            [Break] [Continue]"

Hit [Break]. This will put you on the
  line of code that's causing the
  problem.

But they do not apply to Visual Studio 2005 (there is no Exceptions option on the Debug menu).

Does anyone know where the find this options dialog in Visual Studio that the "When the exception is thrown" group box, with the option to "Break into the debugger"?

Update: The problem was that my Debug menu didn't have an Exceptions item. I customized the menu to manually add it.


问:
Replacing requirejs with systemjs -- variables not visible in local scope
I'm trying to convert our requirejs calls to use SystemJS, but I'm not exactly sure what I'm doing wrong.

Our original calls look like this:

```<code>return function(callback) {
    requirejs(["/app/shared.js"], function(result){
        callbackFunction = callback;
        callback(dashboard);
        main();
    })
}
</code>```

And what I'm trying instead is:

```<code>return function(callback) {
    console.log(callback.toString())
    SystemJS.import('app/shared.js').then(function(result){
        callbackFunction = callback;
        callback(dashboard);
        main();
    });
}
</code>```

I've had to remove some leading / to get things to load properly, which is fine, but I've now ran into an issue where variables that were defined at the top of shared.js aren't visible in my local main.js file. In my browser console I get:

Potentially unhandled rejection [1] ReferenceError: dashboard is not defined

shared.js defines dashboard:

```<code>var dashboard = { rows: [], }
// Other definitions...

define(["/app/custom-config.js", /* etc */]);
</code>```

I guess I have two questions:

is this the correct way to replace requirejs calls?

if so, why aren't my variables from shared.js accessible?

For a fuller picture, main() just sets up the dashboard object, and then calls callbackFunction(dashboard) on it.

答:
Your problem can be reduced to the following case where you have two AMD modules, with one that leaks into the global space, and the 2nd one that tries to use what the first one leaked. Like the two following modules.

src/a.js requires the module that leaks and depends on what that module leaks:

```<code>define(["./b"], function () {
    console.log("a loaded");
    callback();
});
</code>```

src/b.js leaks into the global space:

```<code>// This leaks `callback` into the global space.
var callback = function () {
  console.log("callback called");
}
define(["./b"], function () {
    console.log("b loaded");
});
</code>```

With RequireJS, the code above will work. Oh, it is badly designed because b.js should not leak into the global space, but it will work. You'll see callback called on the console.

With SystemJS, the code above won't work. Why? RequireJS loads modules by adding a script element to the header and lets script execute the module's code so callback does end up in the global space in exactly the same way it would if you had written your own script element with an src attribute that points to your script. (You'd get an "Mismatched anonymous define" error, but that's a separate issue that need not detain us here.) SystemJS, by default, uses eval rather than create script elements, and this changes how the code is evaluated. Usually, it does not matter, but sometimes it does. In the case at hand here callback does not end up in the global space, and module a fails.

Ultimately, your AMD modules should be written so that they don't use the global space to pass information from one another.

However, there is another solution which may be useful as a stepping-stone towards a final solution. You can use scriptLoad: true to tell SystemJS to use script elements like RequirejS does. (See the documentation on meta for details and caveats.) Here is a configuration that does that:

```<code>System.config({
    baseURL: "src",
    meta: {
        "*": {
            scriptLoad: true, // This is what fixes the issue.
        }
    },
    packages: {
        // Yes, this empty package does something. It makes `.js` the
        // default extension for modules.
        "": {}
    },
});

// We have to put `define` in the global space to
// so that our modules can find it.
window.define = System.amdDefine;
</code>```

If I run the example code I've given here without scriptLoad: true, then module a cannot call the callback. With scriptLoad: true, it can call the callback and I get on the console:

```<code>b loaded
a loaded
callback called
</code>```

Body:
I'm trying to convert our requirejs calls to use SystemJS, but I'm not exactly sure what I'm doing wrong.

Our original calls look like this:

return function(callback) {
    requirejs(["/app/shared.js"], function(result){
        callbackFunction = callback;
        callback(dashboard);
        main();
    })
}

And what I'm trying instead is:

return function(callback) {
    console.log(callback.toString())
    SystemJS.import('app/shared.js').then(function(result){
        callbackFunction = callback;
        callback(dashboard);
        main();
    });
}

I've had to remove some leading / to get things to load properly, which is fine, but I've now ran into an issue where variables that were defined at the top of shared.js aren't visible in my local main.js file. In my browser console I get:

Potentially unhandled rejection [1] ReferenceError: dashboard is not defined

shared.js defines dashboard:

var dashboard = { rows: [], }
// Other definitions...

define(["/app/custom-config.js", /* etc */]);

I guess I have two questions:

is this the correct way to replace requirejs calls?

if so, why aren't my variables from shared.js accessible?

For a fuller picture, main() just sets up the dashboard object, and then calls callbackFunction(dashboard) on it.

Body:
Your problem can be reduced to the following case where you have two AMD modules, with one that leaks into the global space, and the 2nd one that tries to use what the first one leaked. Like the two following modules.

src/a.js requires the module that leaks and depends on what that module leaks:

define(["./b"], function () {
    console.log("a loaded");
    callback();
});

src/b.js leaks into the global space:

// This leaks `callback` into the global space.
var callback = function () {
  console.log("callback called");
}
define(["./b"], function () {
    console.log("b loaded");
});

With RequireJS, the code above will work. Oh, it is badly designed because b.js should not leak into the global space, but it will work. You'll see callback called on the console.

With SystemJS, the code above won't work. Why? RequireJS loads modules by adding a script element to the header and lets script execute the module's code so callback does end up in the global space in exactly the same way it would if you had written your own script element with an src attribute that points to your script. (You'd get an "Mismatched anonymous define" error, but that's a separate issue that need not detain us here.) SystemJS, by default, uses eval rather than create script elements, and this changes how the code is evaluated. Usually, it does not matter, but sometimes it does. In the case at hand here callback does not end up in the global space, and module a fails.

Ultimately, your AMD modules should be written so that they don't use the global space to pass information from one another.

However, there is another solution which may be useful as a stepping-stone towards a final solution. You can use scriptLoad: true to tell SystemJS to use script elements like RequirejS does. (See the documentation on meta for details and caveats.) Here is a configuration that does that:

System.config({
    baseURL: "src",
    meta: {
        "*": {
            scriptLoad: true, // This is what fixes the issue.
        }
    },
    packages: {
        // Yes, this empty package does something. It makes `.js` the
        // default extension for modules.
        "": {}
    },
});

// We have to put `define` in the global space to
// so that our modules can find it.
window.define = System.amdDefine;

If I run the example code I've given here without scriptLoad: true, then module a cannot call the callback. With scriptLoad: true, it can call the callback and I get on the console:

b loaded
a loaded
callback called