问:
How to add and get Header values in WebApi
I need to create a POST method in WebApi so I can send data from application to WebApi method. I'm not able to get header value.

Here I have added header values in the application:

```<code>using (var client = new WebClient())
{
    // Set the header so it knows we are sending JSON.
    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    client.Headers.Add("Custom", "sample");
    // Make the request
    var response = client.UploadString(url, jsonObj);
}
</code>```

Following the WebApi post method:

```<code>public string Postsam([FromBody]object jsonData)
{
    HttpRequestMessage re = new HttpRequestMessage();
    var headers = re.Headers;

    if (headers.Contains("Custom"))
    {
       string token = headers.GetValues("Custom").First();
    }
}
</code>```

What is the correct method for getting header values?

Thanks.

答:
For WEB API 2.0:

I had to use Request.Content.Headers instead of  Request.Headers

and then i declared an extestion as below

```<code>  /// <summary>
    /// Returns an individual HTTP Header value
    /// </summary>
    /// <param name="headers"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetHeader(this HttpContentHeaders headers, string key, string defaultValue)
    {
        IEnumerable<string> keys = null;
        if (!headers.TryGetValues(key, out keys))
            return defaultValue;

        return keys.First();
    }
</code>```

And then i invoked it by this way.

```<code>  var headerValue = Request.Content.Headers.GetHeader("custom-header-key", "default-value");
</code>```

I hope it might be helpful

Body:
I need to create a POST method in WebApi so I can send data from application to WebApi method. I'm not able to get header value.

Here I have added header values in the application:

using (var client = new WebClient())
{
    // Set the header so it knows we are sending JSON.
    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    client.Headers.Add("Custom", "sample");
    // Make the request
    var response = client.UploadString(url, jsonObj);
}

Following the WebApi post method:

public string Postsam([FromBody]object jsonData)
{
    HttpRequestMessage re = new HttpRequestMessage();
    var headers = re.Headers;

    if (headers.Contains("Custom"))
    {
       string token = headers.GetValues("Custom").First();
    }
}

What is the correct method for getting header values?

Thanks.

Body:
For WEB API 2.0:

I had to use Request.Content.Headers instead of  Request.Headers

and then i declared an extestion as below

  /// <summary>
    /// Returns an individual HTTP Header value
    /// </summary>
    /// <param name="headers"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetHeader(this HttpContentHeaders headers, string key, string defaultValue)
    {
        IEnumerable<string> keys = null;
        if (!headers.TryGetValues(key, out keys))
            return defaultValue;

        return keys.First();
    }

And then i invoked it by this way.

  var headerValue = Request.Content.Headers.GetHeader("custom-header-key", "default-value");

I hope it might be helpful


来源: stackexchange

问:
Creating another column in R
This is my current data set

I want to take the numbers after "narrow" (e.g. 20) and make another vector. Any idea how I can do that?

答:
You want separate from the tidyr package.</p>

```<code>library(dplyr)
df <- data.frame(x = c(NA, "a.b", "a.d", "b.c"))
df %>% separate(x, c("A", "B"))
#>      A    B
#> 1 <NA> <NA>
#> 2    a    b
#> 3    a    d
#> 4    b    c
</code>```

ContentLicense: CC BY-SA 4.0

Title: Creating another column in R

Body:
You want separate from the tidyr package.

library(dplyr)
df <- data.frame(x = c(NA, "a.b", "a.d", "b.c"))
df %>% separate(x, c("A", "B"))
#>      A    B
#> 1 <NA> <NA>
#> 2    a    b
#> 3    a    d
#> 4    b    c


问:
Git fetch not pulling changes when using URL
I'm trying to set up a service that will update my repository automatically when it detects changes on the remote branch. Before anyone mentions it, I'm aware that embedding the password in the URL is bad practice. I'm currently using:

```<code>git fetch https://<user>:<pass>@github.com/<org>/<repo>
</code>```

Which gives an output of:

```<code>From https://github.com/<org>/<repo>
 * branch            development -> FETCH_HEAD
</code>```

When I run git status after doing the fetch, it doesn't detect the most recent changes.

If I run a normal git fetch without the URL and supply the username and password manually, I get a different output:

```<code>From https://github.com/<org>/<repo>
   96353f7..e88782c  development -> origin/development
</code>```

And then running git status works as predicted and detects that there are changes on the remote branch.

I'm not very experienced with Git and I feel like I'm missing something very obvious. Where is my error?

Edit

So it looks like the missing piece was for me to specify the local and remote branch after the URL:

```<code>git fetch https://<user>:<pass>@github.com/<org>/<repo> development:origin/development
</code>```

As the accepted answer points out: if you don't specify the remote name, git puts the remote changes in the default FETCH_HEAD. This is resolved by specifying the local and remote branches explicitly.

I'm still a little confused as to why git fetch knows to grab from the origin remote by default, but specifying the URL changes this default. But it's working now in any case

答:
Git remotes are a name associated with a URL. The default name is origin and the URL is usually whatever you cloned from.

Git stores a snapshot of remote repositories in "remote tracking branches". These are of the form <remote-name>/<branch>. When you git fetch origin Git goes and fetches changes from the URL associated with origin and puts them into remote branches. development -> origin/development is telling you that it put the remote's development branch into your origin/development remote branch.

When you run git fetch https://<user>:<pass>@github.com/<org>/<repo> and give it just the URL, no remote name, Git doesn't have a name for its remote tracking branches. So it just sticks them in an ephemeral FETCH_HEAD which records your last git fetch. That's what development -> FETCH_HEAD is telling you.

Regardless of any of this, git status will show no change. git fetch never changes your local branches nor your index nor your checkout. It will only update your remote tracking branches. This makes it safe to habitually run git fetch to update your snapshot of the remote repository.

What you're looking for to update your local copy of a remote branch is git pull.

Finally, to avoid having to type in your username and password every time, or worse hard coding them into the URL, set up a Git credential helper to securely store your username and password.

Body:
I'm trying to set up a service that will update my repository automatically when it detects changes on the remote branch. Before anyone mentions it, I'm aware that embedding the password in the URL is bad practice. I'm currently using:

git fetch https://<user>:<pass>@github.com/<org>/<repo>

Which gives an output of:

From https://github.com/<org>/<repo>
 * branch            development -> FETCH_HEAD

When I run git status after doing the fetch, it doesn't detect the most recent changes.

If I run a normal git fetch without the URL and supply the username and password manually, I get a different output:

From https://github.com/<org>/<repo>
   96353f7..e88782c  development -> origin/development

And then running git status works as predicted and detects that there are changes on the remote branch.

I'm not very experienced with Git and I feel like I'm missing something very obvious. Where is my error?

Edit

So it looks like the missing piece was for me to specify the local and remote branch after the URL:

git fetch https://<user>:<pass>@github.com/<org>/<repo> development:origin/development

As the accepted answer points out: if you don't specify the remote name, git puts the remote changes in the default FETCH_HEAD. This is resolved by specifying the local and remote branches explicitly.

I'm still a little confused as to why git fetch knows to grab from the origin remote by default, but specifying the URL changes this default. But it's working now in any case


问:
Ansible : appending data of file using template module
Is there a way to append data using a template module in ansible. There are options for lineinfile and blockinfile in ansible. But I have to append data to the host's file. I want to preserve original hosts and add new hosts to the existing file.</p>

答:
You can use blockinfile to accomplish above as below:</p>

```<code>- name: Add the below DNS records
  blockinfile:
   path: /etc/hosts
   marker: "------"
   insertafter: '^yourlinepattern'
   state: present
   block: |
      lines to append
</code>```

Body:
You can use blockinfile to accomplish above as below:

- name: Add the below DNS records
  blockinfile:
   path: /etc/hosts
   marker: "------"
   insertafter: '^yourlinepattern'
   state: present
   block: |
      lines to append


问:
Having trouble with undefined output from this code below
```<code>var output = [];
var count = 1;

function fizzbuzz() {
  while (count <= 100) {
    if (count % 3 === 0 && count % 5 === 0) {
      output.push("FizzBuzz");
    } else if (count % 5 === 0) {
      output.push("Buzz");
    } else if (count % 3 === 0) {
      output.push("Fizz");
    } else {
      output.push(count);
    }
    count++;
  }

  console.log(output);
}
</code>```

the output from the google chrome and Mozilla Firefox inspector page, says output is  not defined.

Seriously, don't know why.

答:
```<code>var output = [];
var count = 1;

function fizzbuzz() {
while (count <= 100) {
  if (count % 3 === 0 && count % 5 === 0) {
    output.push("FizzBuzz");
  } else if (count % 5 === 0) {
    output.push("Buzz");
  } else if (count % 3 === 0) {
    output.push("Fizz");
  } else {
    output.push(count);
  }
  count++;
}
console.log(output);
}
// just need to add the below line
fizzbuzz();
</code>```

Body:
var output = [];
var count = 1;

function fizzbuzz() {
  while (count <= 100) {
    if (count % 3 === 0 && count % 5 === 0) {
      output.push("FizzBuzz");
    } else if (count % 5 === 0) {
      output.push("Buzz");
    } else if (count % 3 === 0) {
      output.push("Fizz");
    } else {
      output.push(count);
    }
    count++;
  }

  console.log(output);
}

the output from the google chrome and Mozilla Firefox inspector page, says output is  not defined.

Seriously, don't know why.


问:
Dynamically Add tabPanel content which is list of cards to tabView in PrimeNg
I have to add tab content (primeng cards with content) dynamically into tabview using primeng in Angular 8. am trying with ComponentFactoryResolver to generate component dynamically . Please suggest best way to do.
i have attached image for reference.

    //
Content
 tab content which is list of cards with content.here i have to add components dynamically

```

答:
You can use an *ngFor inside the p-tabContent to render all the cards. This would be standardAngular and not related to primeNG

```<code><div *ngFor="let mortgage of mortgages">
... render the content
</div>
</code>```

What am I missing?

Body:
You can use an *ngFor inside the p-tabContent to render all the cards. This would be standardAngular and not related to primeNG

<div *ngFor="let mortgage of mortgages">
... render the content
</div>

What am I missing?


问:
Parallel prime number checker using threads in Java
I have a java program that checks if numbers are prime. I tried to make it parallel by checking different numbers using separate threads.

I ran the programs and compared their execution times, but I am not seeing an improvement...

Here is my sequential program, primeSeq.java:

import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class primeSeq {

    static boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {
                long single_startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                boolean isPrime = isPrime(Long.parseLong(args[i]));
                long single_endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                System.out.println(args[i] + ": " + isPrime + "\tStart time: " + single_startTime + "\tEnd time: " + single_endTime + "\tElapsed time: " + (single_endTime - single_startTime));

                // boolean isPrime = isPrime(Long.parseLong(args[i]));
                // System.out.println(args[i] + ": " + isPrime);
            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}
```

<p>And here is my attempt at parallelizing it, primePar.java:</p>

<pre class="lang-java prettyprint-override"><code>import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class MyThread extends Thread
{
    boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    String threadName;
    public MyThread(String threadName)
    {
        super(threadName);
        this.threadName = threadName;
    }

    @Override
    public void run()
    {
        long startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        boolean isPrime = isPrime(Long.parseLong(threadName));
        long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        System.out.println(threadName + ": " + isPrime + "\tStart time: " + startTime + "\tEnd time: " + endTime + "\tElapsed time: " + (endTime - startTime));
    }
}

class primePar {
    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {
                try
                {
                    Thread newThread = new MyThread(args[i]);
                    newThread.start();
                    newThread.join();
                }
                catch (InterruptedException exc)
                {
                    System.out.println(exc);
                }
            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}
</code>```

Here is the output of these:

PrimeSeq:

```<code>$ java primeSeq 1000000000000037 1000000000000091 1000000000000159 1000000000000187
1000000000000037: true  Start time: 143773080   End time: 143773182 Elapsed time: 102
1000000000000091: true  Start time: 143773183   End time: 143773284 Elapsed time: 101
1000000000000159: true  Start time: 143773284   End time: 143773400 Elapsed time: 116
1000000000000187: true  Start time: 143773400   End time: 143773510 Elapsed time: 110
Total time: 430 milliseconds
</code>```

PrimePar:

```<code>$ java primePar 1000000000000037 1000000000000091 1000000000000159 1000000000000187
1000000000000037: true  Start time: 143746202   End time: 143746309 Elapsed time: 107
1000000000000091: true  Start time: 143746310   End time: 143746415 Elapsed time: 105
1000000000000159: true  Start time: 143746415   End time: 143746519 Elapsed time: 104
1000000000000187: true  Start time: 143746520   End time: 143746619 Elapsed time: 99
Total time: 418 milliseconds
</code>```

It doesn't seem that my parallel program is actually running in parallel. How can I fix this?

答:
As pointed out by user "Dawood says reinstate Monica" in the comments, newThread.join() was the problematic command.

Removing this helps, as all the threads start at the same time:

Updated primePar.java program:

import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class MyThread extends Thread
{
    boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    String threadName;
    public MyThread(String threadName)
    {
        super(threadName);
        this.threadName = threadName;
    }

    @Override
    public void run()
    {
        long startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        boolean isPrime = isPrime(Long.parseLong(threadName));
        long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        System.out.println(threadName + ": " + isPrime + "\tStart time: " + startTime + "\tEnd time: " + endTime + "\tElapsed time: " + (endTime - startTime));
    }
}

class primePar {
    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {
                // try
                // {
                    Thread newThread = new MyThread(args[i]);
                    newThread.start();
                    // newThread.join();
                // }
                // catch (InterruptedException exc)
                // {
                //  System.out.println(exc);
                // }
            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}
```

<p>New output:</p>

```$ java primePar 1000000000000037 1000000000000091 1000000000000159 1000000000000187
Total time: 0 milliseconds
1000000000000091: true  Start time: 144449191   End time: 144449354 Elapsed time: 163
1000000000000159: true  Start time: 144449191   End time: 144449355 Elapsed time: 164
1000000000000187: true  Start time: 144449191   End time: 144449357 Elapsed time: 166
1000000000000037: true  Start time: 144449191   End time: 144449370 Elapsed time: 179
```

Body:
I have a java program that checks if numbers are prime. I tried to make it parallel by checking different numbers using separate threads.

I ran the programs and compared their execution times, but I am not seeing an improvement...

Here is my sequential program, primeSeq.java:

import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class primeSeq {

    static boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {
                long single_startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                boolean isPrime = isPrime(Long.parseLong(args[i]));
                long single_endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                System.out.println(args[i] + ": " + isPrime + "\tStart time: " + single_startTime + "\tEnd time: " + single_endTime + "\tElapsed time: " + (single_endTime - single_startTime));

                // boolean isPrime = isPrime(Long.parseLong(args[i]));
                // System.out.println(args[i] + ": " + isPrime);
            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}

And here is my attempt at parallelizing it, primePar.java:

import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class MyThread extends Thread
{
    boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    String threadName;
    public MyThread(String threadName)
    {
        super(threadName);
        this.threadName = threadName;
    }

    @Override
    public void run()
    {
        long startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        boolean isPrime = isPrime(Long.parseLong(threadName));
        long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        System.out.println(threadName + ": " + isPrime + "\tStart time: " + startTime + "\tEnd time: " + endTime + "\tElapsed time: " + (endTime - startTime));
    }
}

class primePar {
    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {
                try
                {
                    Thread newThread = new MyThread(args[i]);
                    newThread.start();
                    newThread.join();
                }
                catch (InterruptedException exc)
                {
                    System.out.println(exc);
                }
            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}

Here is the output of these:

PrimeSeq:

$ java primeSeq 1000000000000037 1000000000000091 1000000000000159 1000000000000187
1000000000000037: true  Start time: 143773080   End time: 143773182 Elapsed time: 102
1000000000000091: true  Start time: 143773183   End time: 143773284 Elapsed time: 101
1000000000000159: true  Start time: 143773284   End time: 143773400 Elapsed time: 116
1000000000000187: true  Start time: 143773400   End time: 143773510 Elapsed time: 110
Total time: 430 milliseconds

PrimePar:

$ java primePar 1000000000000037 1000000000000091 1000000000000159 1000000000000187
1000000000000037: true  Start time: 143746202   End time: 143746309 Elapsed time: 107
1000000000000091: true  Start time: 143746310   End time: 143746415 Elapsed time: 105
1000000000000159: true  Start time: 143746415   End time: 143746519 Elapsed time: 104
1000000000000187: true  Start time: 143746520   End time: 143746619 Elapsed time: 99
Total time: 418 milliseconds

It doesn't seem that my parallel program is actually running in parallel. How can I fix this?

Body:
As pointed out by user "Dawood says reinstate Monica" in the comments, newThread.join() was the problematic command.

Removing this helps, as all the threads start at the same time:

Updated primePar.java program:

import java.io.*;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

class MyThread extends Thread
{
    boolean isPrime(long n) {
        // Check base cases:
        // n < 2, n is 2 or 3, n is divisible by 2 or 3
        if(n < 2) return false;
        if(n == 2 || n == 3) return true;
        if(n%2 == 0 || n%3 == 0) return false;

        // Check if divisible by all numbers 6k +-1 up to sqrt(n)
        long sqrtN = (long)Math.sqrt(n)+1;
        for(long i = 6L; i <= sqrtN; i += 6) {
            if(n%(i-1) == 0 || n%(i+1) == 0) return false;
        }
        return true;
    }

    String threadName;
    public MyThread(String threadName)
    {
        super(threadName);
        this.threadName = threadName;
    }

    @Override
    public void run()
    {
        long startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        boolean isPrime = isPrime(Long.parseLong(threadName));
        long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        System.out.println(threadName + ": " + isPrime + "\tStart time: " + startTime + "\tEnd time: " + endTime + "\tElapsed time: " + (endTime - startTime));
    }
}

class primePar {
    public static void main(String args[]) throws ParseException
    {
        if (args.length == 0){
            System.out.println("No args provided.");
        }
        else
        {
            long startTime = System.nanoTime();

            for(int i=0;i< args.length;i++)
            {
                // try
                // {
                    Thread newThread = new MyThread(args[i]);
                    newThread.start();
                    // newThread.join();
                // }
                // catch (InterruptedException exc)
                // {
                //  System.out.println(exc);
                // }
            }

            long endTime = System.nanoTime();
            System.out.println("Total time: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds");
        }
    }
}

New output:

$ java primePar 1000000000000037 1000000000000091 1000000000000159 1000000000000187
Total time: 0 milliseconds
1000000000000091: true  Start time: 144449191   End time: 144449354 Elapsed time: 163
1000000000000159: true  Start time: 144449191   End time: 144449355 Elapsed time: 164
1000000000000187: true  Start time: 144449191   End time: 144449357 Elapsed time: 166
1000000000000037: true  Start time: 144449191   End time: 144449370 Elapsed time: 179


问:
Javascript/html undefined input
For some reason, no matter what I do, my variables are returning undefined for this javascript assignment for homework. I wasn't getting the output i wanted so I used alert to see if I was at least getting a value, but no matter what, the value of op1 is always undefined no matter what is entered into the first operand box, and no matter which way i tried selecting the value of what was in that input box. if someone could help me out here i would appreciate that.    </p>

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Multiply and Divide</title>
<style>
  body {margin-left:100px;}
</style>

<script>
// code two functions multiply and divide functions here
    //hints:
    //when you get a value out of an input, you are getting a string.  To get a number, use
    //parseInt()
    //When you want to output something into the HTML you can use .innerHTML - like
    //document.getElementById("result").innerHTML= "fred";
    var op1 = document.forms["test"]["firstoperand"].value;

    var op2 = document.getElementById("secondoperand").value;

    var ans = "";

    function divide() {
        alert(op1);
    }
    function multiply() {

    }

</script>

</head>
<body>
  <div>
    <h2>JavaScript Exercise 5d </h2>
  </div>
  <form id="test">
    <input type="text" id="firstoperand" placeholder="First Operand"/><br>
    <input type="text" id="secondoperand" placeholder="Second Operand"/><br>
    <input type="button" onclick="divide()" value="Divide" />
    <input type="button" onclick="multiply()" value="Multiply" />
    <p>The answer: <span id="result"></span></p>
  </form>
</body>
</html>
</code>```

答:
I recommend putting all the script tags just before the closing  tag.
Then when you create the variable of the form element op1 you have to do it without the value check for the value when you have the function running. I also recommend to do use document.querySelector() and document.querySelectorAll()

// this
var op1 = document.querySelector("#firstoperand");
// will work exactly the same as your
// var op1 = document.forms["test"]["firstoperand"];

function divide() {
  alert(op1.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="test">
    <input type="text" id="firstoperand" placeholder="First Operand"/><br>
    <input type="button" onclick="divide()" value="Divide" />
</form>
<!--
in real life you might have here more HTML elements
and you will have somewhere here a closing body tag like:</body>

now the trick is to add your script tags
before the closing </body> so something like

<script src="/path/to/some/js-file.js"></script>

<script>
// some javascript code here
</script>

</body>

--></code>```

Title: Javascript/html undefined input

Body:
For some reason, no matter what I do, my variables are returning undefined for this javascript assignment for homework. I wasn't getting the output i wanted so I used alert to see if I was at least getting a value, but no matter what, the value of op1 is always undefined no matter what is entered into the first operand box, and no matter which way i tried selecting the value of what was in that input box. if someone could help me out here i would appreciate that.

<!DOCTYPE html>

<meta charset="utf-8"/>
<title>Multiply and Divide</title>

JavaScript Exercise 5d

  <form id="test">
    <input type="text" id="firstoperand" placeholder="First Operand"/>

    <input type="text" id="secondoperand" placeholder="Second Operand"/>

    <input type="button" onclick="divide()" value="Divide" />
    <input type="button" onclick="multiply()" value="Multiply" />

The answer:

  </form>

Body:
I recommend putting all the script tags just before the closing </body> tag.
Then when you create the variable of the form element op1 you have to do it without the value check for the value when you have the function running. I also recommend to do use document.querySelector() and document.querySelectorAll()

// this
var op1 = document.querySelector("#firstoperand");
// will work exactly the same as your
// var op1 = document.forms["test"]["firstoperand"];

function divide() {
  alert(op1.value);
}

<form id="test">
    <input type="text" id="firstoperand" placeholder="First Operand"/><br>
    <input type="button" onclick="divide()" value="Divide" />
</form>
<!--
in real life you might have here more HTML elements
and you will have somewhere here a closing body tag like:</body>

now the trick is to add your script tags
before the closing </body> so something like

<script src="/path/to/some/js-file.js"></script>

<script>
// some javascript code here
</script>

</body>

-->


答:
Below is a modified snippet of your function:
1) i moved your var declarations into the function scope instead of being global so that other functions cant influence their values
    a) consider a for loop instead of a while loop. a for loop is more aligned to the purpose of doing something for a predetermined count such as count < 100
2) changed your console.log to a return statement so that when this function is called it will perform its calcs and send back the data. thus it doesnt require the caller to have access to a console (ie called from an alert, document.write, etc)
3) called your function from inside a console.log statement so that the return value will be logged as was your original desire

function fizzbuzz() {
  var output = [];
  var count = 1;
  while (count <= 100) {
    if (count % 3 === 0 && count % 5 === 0) {
      output.push("FizzBuzz");
    } else if (count % 5 === 0) {
      output.push("Buzz");
    } else if (count % 3 === 0) {
      output.push("Fizz");
    } else {
      output.push(count);
    }
    count++;
  }
  return output;
}
console.log(fizzbuzz());```

Title: Having trouble with undefined output from this code below


问:
jpcap error sending packets cooked mode
I want to send a UDP packet using jpcap.

My code is:

```<code>    PcapNetworkInterface nif = Pcaps.getDevByName(args[0]);
    int snapLen = 65536;
    PromiscuousMode mode = PromiscuousMode.NONPROMISCUOUS;
    int timeout = 10000;
    PcapHandle handle = nif.openLive(snapLen, mode, timeout);

    UdpPort srcPort = new UdpPort((short)1002,"");
    UdpPort dstPort = new UdpPort((short)2001, "");;
    short length = (short)12;
    short checksum = (short)0xABCD;

    UnknownPacket.Builder unknownb = new UnknownPacket.Builder();
    unknownb.rawData(new byte[] { (byte)0, (byte)1, (byte)2, (byte)3 });

    UdpPacket.Builder b = new UdpPacket.Builder();
    b.dstPort(dstPort)
     .srcPort(srcPort)
     .length(length)
     .checksum(checksum)
     .correctChecksumAtBuild(false)
     .correctLengthAtBuild(false)
     .payloadBuilder(unknownb);

    EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
    etherBuilder.dstAddr(MacAddress.getByName("FF:FF:FF:FF:FF:FF"))
                .srcAddr(MacAddress.getByName("FF:FF:FF:FF:FF:FF"))
                .type( EtherType.IPV4) //
                .payloadBuilder(b)
                .paddingAtBuild(true);

    Packet p = etherBuilder.build();

    int i=1;
    while(true) {

        handle.sendPacket(p);
        System.out.println("send "+i);i++;
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {

        }
    }
</code>```

After executing that ,i get :

org.pcap4j.core.PcapNativeException: Error occured in pcap_sendpacket():
Sending packets isn't supported in cooked mode
 at org.pcap4j.core.PcapHandle.sendPacket(PcapHandle.java:1242)
 at org.pcap4j.core.PcapHandle.sendPacket(PcapHandle.java:1212)

And this is the link to c implementation:

https://github.com/frgtn/rpcapd-linux/blob/master/libpcap/pcap-linux.c#L1091

答:
I am definitely late to answer but I hope this code helps other people.</p>

```<code>import org.pcap4j.core.PcapHandle;
import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.packet.*;
import org.pcap4j.packet.namednumber.EtherType;
import org.pcap4j.packet.namednumber.IpNumber;
import org.pcap4j.packet.namednumber.IpVersion;
import org.pcap4j.packet.namednumber.UdpPort;
import org.pcap4j.util.MacAddress;
import org.pcap4j.util.NifSelector;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;

public class RAWUDP {

    public static void main(String[] args) throws Exception {
        byte[] pck = "Meow".getBytes();

        UnknownPacket unknownPacket = UnknownPacket.newPacket(pck, 0, pck.length);

        UdpPacket udpPacket = new UdpPacket.Builder()
                .srcAddr(InetAddress.getByName("192.168.1.6"))
                .dstAddr(InetAddress.getByName("192.168.1.6"))
                .srcPort(UdpPort.getInstance((short) 54163))
                .dstPort(UdpPort.getInstance((short) 9110))
                .correctLengthAtBuild(true)
                .correctChecksumAtBuild(true)
                .payloadBuilder(unknownPacket.getBuilder())
                .build();

        IpV4Packet.Builder ipV4Builder = new IpV4Packet.Builder();

        ipV4Builder.version(IpVersion.IPV4)
                .tos(IpV4Rfc791Tos.newInstance((byte) 0))
                .ttl((byte) 100)
                .protocol(IpNumber.UDP)
                .srcAddr((Inet4Address) InetAddress.getByName("192.168.1.6"))
                .dstAddr((Inet4Address) InetAddress.getByName("192.168.1.6"))
                .payloadBuilder(udpPacket.getBuilder())
                .correctChecksumAtBuild(true)
                .correctLengthAtBuild(true);

        PcapNetworkInterface nif;
        try {
            nif = new NifSelector().selectNetworkInterface();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        if (nif == null) {
            return;
        }

        System.out.println(nif.getName() + "(" + nif.getDescription() + ")");

        final PcapHandle handle4send = nif.openLive(65536, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 10);

        EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
        etherBuilder.dstAddr(MacAddress.getByName("00:A0:C9:14:C8:29", ":"))
                .srcAddr(MacAddress.getByName("00:A0:C9:14:C8:29", ":"))
                .type(EtherType.IPV4)
                .payloadBuilder(ipV4Builder.build().getBuilder())
                .paddingAtBuild(true);

        Packet p = etherBuilder.build();

        handle4send.sendPacket(p);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: jpcap error sending packets cooked mode

Body:
I want to send a UDP packet using jpcap.

My code is:

    PcapNetworkInterface nif = Pcaps.getDevByName(args[0]);
    int snapLen = 65536;
    PromiscuousMode mode = PromiscuousMode.NONPROMISCUOUS;
    int timeout = 10000;
    PcapHandle handle = nif.openLive(snapLen, mode, timeout);

    UdpPort srcPort = new UdpPort((short)1002,"");
    UdpPort dstPort = new UdpPort((short)2001, "");;
    short length = (short)12;
    short checksum = (short)0xABCD;

    UnknownPacket.Builder unknownb = new UnknownPacket.Builder();
    unknownb.rawData(new byte[] { (byte)0, (byte)1, (byte)2, (byte)3 });

    UdpPacket.Builder b = new UdpPacket.Builder();
    b.dstPort(dstPort)
     .srcPort(srcPort)
     .length(length)
     .checksum(checksum)
     .correctChecksumAtBuild(false)
     .correctLengthAtBuild(false)
     .payloadBuilder(unknownb);

    EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
    etherBuilder.dstAddr(MacAddress.getByName("FF:FF:FF:FF:FF:FF"))
                .srcAddr(MacAddress.getByName("FF:FF:FF:FF:FF:FF"))
                .type( EtherType.IPV4) //
                .payloadBuilder(b)
                .paddingAtBuild(true);

    Packet p = etherBuilder.build();

    int i=1;
    while(true) {

        handle.sendPacket(p);
        System.out.println("send "+i);i++;
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {

        }
    }

After executing that ,i get :

org.pcap4j.core.PcapNativeException: Error occured in pcap_sendpacket():
Sending packets isn't supported in cooked mode
 at org.pcap4j.core.PcapHandle.sendPacket(PcapHandle.java:1242)
 at org.pcap4j.core.PcapHandle.sendPacket(PcapHandle.java:1212)

And this is the link to c implementation:

https://github.com/frgtn/rpcapd-linux/blob/master/libpcap/pcap-linux.c#L1091

Body:
I am definitely late to answer but I hope this code helps other people.

import org.pcap4j.core.PcapHandle;
import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.packet.*;
import org.pcap4j.packet.namednumber.EtherType;
import org.pcap4j.packet.namednumber.IpNumber;
import org.pcap4j.packet.namednumber.IpVersion;
import org.pcap4j.packet.namednumber.UdpPort;
import org.pcap4j.util.MacAddress;
import org.pcap4j.util.NifSelector;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;

public class RAWUDP {

    public static void main(String[] args) throws Exception {
        byte[] pck = "Meow".getBytes();

        UnknownPacket unknownPacket = UnknownPacket.newPacket(pck, 0, pck.length);

        UdpPacket udpPacket = new UdpPacket.Builder()
                .srcAddr(InetAddress.getByName("192.168.1.6"))
                .dstAddr(InetAddress.getByName("192.168.1.6"))
                .srcPort(UdpPort.getInstance((short) 54163))
                .dstPort(UdpPort.getInstance((short) 9110))
                .correctLengthAtBuild(true)
                .correctChecksumAtBuild(true)
                .payloadBuilder(unknownPacket.getBuilder())
                .build();

        IpV4Packet.Builder ipV4Builder = new IpV4Packet.Builder();

        ipV4Builder.version(IpVersion.IPV4)
                .tos(IpV4Rfc791Tos.newInstance((byte) 0))
                .ttl((byte) 100)
                .protocol(IpNumber.UDP)
                .srcAddr((Inet4Address) InetAddress.getByName("192.168.1.6"))
                .dstAddr((Inet4Address) InetAddress.getByName("192.168.1.6"))
                .payloadBuilder(udpPacket.getBuilder())
                .correctChecksumAtBuild(true)
                .correctLengthAtBuild(true);

        PcapNetworkInterface nif;
        try {
            nif = new NifSelector().selectNetworkInterface();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        if (nif == null) {
            return;
        }

        System.out.println(nif.getName() + "(" + nif.getDescription() + ")");

        final PcapHandle handle4send = nif.openLive(65536, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 10);

        EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
        etherBuilder.dstAddr(MacAddress.getByName("00:A0:C9:14:C8:29", ":"))
                .srcAddr(MacAddress.getByName("00:A0:C9:14:C8:29", ":"))
                .type(EtherType.IPV4)
                .payloadBuilder(ipV4Builder.build().getBuilder())
                .paddingAtBuild(true);

        Packet p = etherBuilder.build();

        handle4send.sendPacket(p);
    }
}


答:
You could use separate to separate the stimulus column into two vectors.

```<code>library(tidyr)
df %>%
  separate(col = stimulus,
           sep = ", ",
           into = c("Text","Number"))
</code>```

Title: Creating another column in R

Body:
This is my current data set

I want to take the numbers after "narrow" (e.g. 20) and make another vector. Any idea how I can do that?

Body:
You could use separate to separate the stimulus column into two vectors.

library(tidyr)
df %>%
  separate(col = stimulus,
           sep = ", ",
           into = c("Text","Number"))


问:
Scala Spark Task not serializable error in code
Not sure whats wrong with the code below , but its throwing

```<code>org.apache.spark.SparkException: Task not serializable
</code>```

error. Googled about the error, but couldn't resolve.

Below is the code: (Can be copy pasted and executed on community.cloud.databricks.com by creating new Scala notebook)

```<code>    import com.google.gson._
     object TweetUtils {
          case class Tweet(
               id : String,
               user : String,
               userName : String,
               text : String,
               place : String,
               country : String,
               lang : String
          )

       def parseFromJson(lines:Iterator[String]):Iterator[Tweet] = {
            val gson = new Gson
            lines.map( line => gson.fromJson(line, classOf[Tweet]))
       }

       def loadData(): RDD[Tweet] = {
           val pathToFile = "/FileStore/tables/reduced_tweets-57570.json"
           sc.textFile(pathToFile).mapPartitions(parseFromJson(_))
       }

       def tweetsByUser(): RDD[(String, Iterable[Tweet])] = {
           val tweets = loadData
           tweets.groupBy(_.user)
       }
   }

   val res = TweetUtils.tweetsByUser()
   res.collect().take(5).foreach(println)
</code>```

Below is the detailed error Message:

```<code>at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:393)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2548)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:827)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:392)
    at org.apache.spark.rdd.RDD.mapPartitions(RDD.scala:826)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$TweetUtils$.loadData(command-3696793732897971:22)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$TweetUtils$.tweetsByUser(command-3696793732897971:25)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:30)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:84)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:86)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:88)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:90)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw.<init>(command-3696793732897971:92)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw.<init>(command-3696793732897971:94)
</code>```

Thanks in advance,

Sri

答:
Make your TweetUtils object as Serializable and it should work:

object TweetUtils extends Serializable

Body:
Not sure whats wrong with the code below , but its throwing

org.apache.spark.SparkException: Task not serializable

error. Googled about the error, but couldn't resolve.

Below is the code: (Can be copy pasted and executed on community.cloud.databricks.com by creating new Scala notebook)

    import com.google.gson._
     object TweetUtils {
          case class Tweet(
               id : String,
               user : String,
               userName : String,
               text : String,
               place : String,
               country : String,
               lang : String
          )

       def parseFromJson(lines:Iterator[String]):Iterator[Tweet] = {
            val gson = new Gson
            lines.map( line => gson.fromJson(line, classOf[Tweet]))
       }

       def loadData(): RDD[Tweet] = {
           val pathToFile = "/FileStore/tables/reduced_tweets-57570.json"
           sc.textFile(pathToFile).mapPartitions(parseFromJson(_))
       }

       def tweetsByUser(): RDD[(String, Iterable[Tweet])] = {
           val tweets = loadData
           tweets.groupBy(_.user)
       }
   }

   val res = TweetUtils.tweetsByUser()
   res.collect().take(5).foreach(println)

Below is the detailed error Message:

at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:393)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2548)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:827)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:392)
    at org.apache.spark.rdd.RDD.mapPartitions(RDD.scala:826)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$TweetUtils$.loadData(command-3696793732897971:22)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$TweetUtils$.tweetsByUser(command-3696793732897971:25)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:30)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:84)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:86)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:88)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:90)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw.<init>(command-3696793732897971:92)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw.<init>(command-3696793732897971:94)

Thanks in advance,

Sri


问:
Unit Testing React HashRouter with Jest
I am desperately trying to Unit Test my HashRouter routes but cannot get my head around how. I managed to get a solution using Enzyme but am forced to use ReactTestingLibrary by tech lead.

Can anyone help out pointing me in the right direction?

App Component

```<code>import React, { Component } from 'react';
import { HashRouter } from 'react-router-dom'
import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/styles';

import './App.css';
import Routes from './Routes';

class App extends Component {

  render() {
    return (
      <HashRouter>
        <Routes />
      </HashRouter>
    );
  }
}

export default App;
</code>```

Routes Component

```<code>import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import { withRouter } from 'react-router';

import NetworksList from './pages/NetworksList';
import DealsList from './pages/DealsList';

class Routes extends Component {

  render() {
    return (
      <div>
        <Route path="/networks" component={NetworksList} />
        <Route path="/deals" component={DealsList} />
      </div>
    );
  }
}

export default withRouter(Routes);
</code>```

App Component Test

```<code>import React from 'react';
import App from './App';
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history'
import { Router } from 'react-router-dom'

import Routes from './Routes';

beforeEach(() => {
  jest.resetAllMocks();
});

it.only('should render networks list page at #/networks', () => {

  const history = createMemoryHistory()
  history.push('networks');

  const { container, getByText } = render(
    <Router history={history}>
      <Routes />
    </Router>
  )

});
</code>```

答:
Idea is to use hash based history 'createHashHistory', for testing Hash based router. I have put together a working example for this Hash Router React Testing Library navigation example. https://codesandbox.io/s/hashrouter-react-router-react-testing-library-njmj5

For example, your App.jsx is:

```<code>import Routes from "./Routes";
import { HashRouter as Router } from "react-router-dom";

export default function App() {
  return (
    <div className="App">
      <h1>HashRouter Testing</h1>
      <Router>
        <ul className="nav justify-content-center">
          <li className="nav-item">
            <a class="nav-link active" href="#">
              CompOne
            </a>
          </li>
          <li className="nav-item">
            <a class="nav-link active" href="#/comp-two">
              CompTwo
            </a>
          </li>
        </ul>
        <Routes />
      </Router>
    </div>
  );
}
</code>```

And Routes.jsx is:

```<code>import { Route, Switch } from "react-router-dom";

const CompOne = () => <div>Component One</div>;
const CompTwo = () => <div>Component Two</div>;

export default function Routes(props) {
  return (
    <Switch>
      <Route exact path="/">
        <CompOne />
      </Route>
      <Route exact path="/comp-two">
        <CompTwo />
      </Route>
    </Switch>
  );
}
</code>```

Then, here is how you can test hash based navigation :

```<code>import React from "react";
import { render, wait, waitForElement } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { createHashHistory } from "history";
import App from "./App";

describe("AppRouter component", () => {
  afterEach(jest.resetAllMocks);

  it("navigates correctly", async () => {
    const history = createHashHistory({ initialEntries: ["/"] });
    history.push("/comp-two");
    const { container, getByText, debug } = render(<App />);
    await waitForElement(() => getByText(/Component Two/i));
    debug();
  });
});
</code>```

Hope that helps!

Title: Unit Testing React HashRouter with Jest

Body:
I am desperately trying to Unit Test my HashRouter routes but cannot get my head around how. I managed to get a solution using Enzyme but am forced to use ReactTestingLibrary by tech lead.

Can anyone help out pointing me in the right direction?

App Component

import React, { Component } from 'react';
import { HashRouter } from 'react-router-dom'
import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/styles';

import './App.css';
import Routes from './Routes';

class App extends Component {

  render() {
    return (
      <HashRouter>
        <Routes />
      </HashRouter>
    );
  }
}

export default App;

Routes Component

import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import { withRouter } from 'react-router';

import NetworksList from './pages/NetworksList';
import DealsList from './pages/DealsList';

class Routes extends Component {

  render() {
    return (

        <Route path="/networks" component={NetworksList} />
        <Route path="/deals" component={DealsList} />

    );
  }
}

export default withRouter(Routes);

App Component Test

import React from 'react';
import App from './App';
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history'
import { Router } from 'react-router-dom'

import Routes from './Routes';

beforeEach(() => {
  jest.resetAllMocks();
});

it.only('should render networks list page at #/networks', () => {

  const history = createMemoryHistory()
  history.push('networks');

  const { container, getByText } = render(
    <Router history={history}>
      <Routes />
    </Router>
  )

});

Body:
Idea is to use hash based history 'createHashHistory', for testing Hash based router. I have put together a working example for this Hash Router React Testing Library navigation example. https://codesandbox.io/s/hashrouter-react-router-react-testing-library-njmj5

For example, your App.jsx is:

import Routes from "./Routes";
import { HashRouter as Router } from "react-router-dom";

export default function App() {
  return (
    <div className="App">
      <h1>HashRouter Testing</h1>
      <Router>
        <ul className="nav justify-content-center">
          <li className="nav-item">
            <a class="nav-link active" href="#">
              CompOne
            </a>
          </li>
          <li className="nav-item">
            <a class="nav-link active" href="#/comp-two">
              CompTwo
            </a>
          </li>
        </ul>
        <Routes />
      </Router>
    </div>
  );
}

And Routes.jsx is:

import { Route, Switch } from "react-router-dom";

const CompOne = () => <div>Component One</div>;
const CompTwo = () => <div>Component Two</div>;

export default function Routes(props) {
  return (
    <Switch>
      <Route exact path="/">
        <CompOne />
      </Route>
      <Route exact path="/comp-two">
        <CompTwo />
      </Route>
    </Switch>
  );
}

Then, here is how you can test hash based navigation :

import React from "react";
import { render, wait, waitForElement } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { createHashHistory } from "history";
import App from "./App";

describe("AppRouter component", () => {
  afterEach(jest.resetAllMocks);

  it("navigates correctly", async () => {
    const history = createHashHistory({ initialEntries: ["/"] });
    history.push("/comp-two");
    const { container, getByText, debug } = render(<App />);
    await waitForElement(() => getByText(/Component Two/i));
    debug();
  });
});

Hope that helps!


问:
how to get the font src url via webfont loader
i use webfont-loader dynamic load fonts via css files,code like this

```<code>WebFont.load({
    custom: {
        families: 'Lobster',
        urls:'mydomain.com/lobster.css'
    }
}
</code>```

and in the css file,it like this

```<code>@font-face {
    font-family: 'Lobster';
    src: url('Lobster_1.3-webfont.woff') format('woff'),
         url('Lobster_1.3-webfont.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
</code>```

i wonder as if there is a way to get the font face url,like "Lobster_1.3-webfont.ttf" and "Lobster_1.3-webfont.woff" which defined in css.

in webfont-loader,there is no such api,if there is no directly way,i have to load the css as text file first,but i relly don't want do such things

do you guys have any clue?

PS:the reason why i need the font's url,is because i use fabric.js to create svg file and render it to PDF by phantom.js in node side,but looks that phantom.js did not support svg with @import url('xxx.css'). so i have to use @font-face with src.

答:
First get font name with URL's.

```<code>var fontArray = [];
$.get("https://www.googleapis.com/webfonts/v1/webfonts?key={your key}&sort=popularity", {}, function (data) {
    var count = 0;
    $.each(data.items, function (index, value) {
        count++
        fontArray.push(value);
    });
});
</code>```

and then add to fabric.fontPaths.

```<code>    $.each(fontArray, function (i, item) {
     if (fontName == item.family) {
     var ttfFile  = item.files.regular;
     var dataFile = [];
    fabric.fontPaths[fontName] = "data:font/opentype;charset=utf-8;base64," + ttfFile;
      }
})
</code>```

Body:
i use webfont-loader dynamic load fonts via css files,code like this

WebFont.load({
    custom: {
        families: 'Lobster',
        urls:'mydomain.com/lobster.css'
    }
}

and in the css file,it like this

@font-face {
    font-family: 'Lobster';
    src: url('Lobster_1.3-webfont.woff') format('woff'),
         url('Lobster_1.3-webfont.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

i wonder as if there is a way to get the font face url,like "Lobster_1.3-webfont.ttf" and "Lobster_1.3-webfont.woff" which defined in css.

in webfont-loader,there is no such api,if there is no directly way,i have to load the css as text file first,but i relly don't want do such things

do you guys have any clue?

PS:the reason why i need the font's url,is because i use fabric.js to create svg file and render it to PDF by phantom.js in node side,but looks that phantom.js did not support svg with @import url('xxx.css'). so i have to use @font-face with src.

Body:
First get font name with URL's.

var fontArray = [];
$.get("https://www.googleapis.com/webfonts/v1/webfonts?key={your key}&sort=popularity", {}, function (data) {
    var count = 0;
    $.each(data.items, function (index, value) {
        count++
        fontArray.push(value);
    });
});

and then add to fabric.fontPaths.

    $.each(fontArray, function (i, item) {
     if (fontName == item.family) {
     var ttfFile  = item.files.regular;
     var dataFile = [];
    fabric.fontPaths[fontName] = "data:font/opentype;charset=utf-8;base64," + ttfFile;
      }
})


问:
Can I pull Max and Min values in SQL without using group by for non aggregate values?
I have a table of user data for when they enroll in a program.  The fields include a user ID, start date, end date, entry reason, exit reason and program type.  For each year the user is enrolled in a specific program they will have an entry and exit date for that year along with an entry reason.  They only get an exit reason when they are exited from the program completely.  Here is an example of the data in the table.

Data Table
Desired Result

I need to pull one line for each user that has their original start date in the program, most recent start date, and most recent end date.  I also need to pull the exit reason if one exists and entry reason associated with the most recent start date and this is what is getting me hung up.  I’m assuming the problem is related to having to group by the entry reason.  Is there any way around using an aggregate function to get the min/max dates?
  My query is:

```<code>Select
    Table1.userID,
    CAST(Min(table2.startdate) as date) as Originalstartdate,
    CAST(Max(table2.startdate) as date) as Maxstartdate,
    CAST(Max(table2.enddate) as date) as ExitDate,
    CASE
        WHEN table2.exitreason = NULL then ‘’
        ELSE table2.exitreason
    END as Exitcode,
    Table2.entryreason
From
    Table1 left outer join
    Table2 on Table1.userID = Table2.userID
Where
    Table1.status = ‘active’ and Table2.programID = ‘Program1’ and (Table2.exitreason <> ‘NULL’ or Table2.entryreason <> ‘NULL’)
Group By
    Table1.userID, Table2.exitreason, Table2.entryreason
</code>```

答:
I used the below sample code in order to generate this.

The idea here is to utilize the userID as the anchor (you want one row per user, right?), aggregating the rest of the information but with the situation you requested.

CREATE TABLE SCRIPT:

```<code>
CREATE TABLE table1
(
  userID INT IDENTITY(1, 1) PRIMARY KEY,
  name   VARCHAR(200),
  stat   CHAR(1) NOT NULL
                 DEFAULT 'A');

CREATE TABLE table2
(
  t2ID        INT IDENTITY(1, 1),
  StartDate   DATE,
  UserID      INT FOREIGN KEY REFERENCES table1(userID),
  ProgramID   VARCHAR(150) DEFAULT 'Program1',
  EndDate     DATE,
  EntryReason VARCHAR(2000),
  ExitReason  VARCHAR(2000));

INSERT INTO Table1
(name)
       SELECT *
       FROM(VALUES
       (
         'First name'),
       (
         'Second name'),
       (
         'Third name')) x("name");

INSERT INTO Table2
       SELECT *
       FROM(VALUES
       (
         '20180101', 1, 'Program1', '20181231', 11, NULL),
       (
         '20190101', 1, 'Program1', '20191231', 12, NULL),
       (
         '20200101', 1, 'Program1', NULL, 11, NULL),
       (
         '20170101', 2, 'Program1', '20171231', 11, NULL),
       (
         '20180101', 2, 'Program1', '20171231', 14, 2),
       (
         '20200101', 3, 'Program1', NULL, 11, NULL)
) x(StartDate, UserID, ProgramID, EndDate, EntryReason, ExitReason);
</code>```

QUERY:

```<code>SELECT t1.userID,
       CAST(MIN(t2.StartDate) AS DATE)
AS OriginalStartDate, -- This uses your logic to grab the earliest date
       CAST(MAX(t2.StartDate) AS DATE)
AS RecentStartDate, -- This utilizes your logic to grab the last start date
       CAST(MAX(t2.enddate) AS DATE)
AS ExitDate,
-- This works because we know an ExitDate must be populated due to the where
-- criteria (which prevents people who haven't exited yet from showing up)
       ISNULL(MAX(t2.exitreason), '')
AS ExitCode, -- This is just a cleaner way to handle nulls.
       STUFF(
(
  SELECT CONCAT(',', EntryReason)
  FROM Table2
  WHERE Table2.UserID=t1.UserID FOR XML PATH('')
), 1, 1, '')
AS EntryReasonList
-- this solution creates a list of entry reasons; we could pick a best winner
-- (e.g. first entry code, last entry code..) but I created a list because
-- I didn't understand your intent.
FROM Table1
AS t1
LEFT JOIN
Table2
AS t2
ON T1.userID=T2.userID
WHERE t1.stat='A' -- you would use status= 'active'
      AND t2.programID='Program1' -- same as before
      AND NOT EXISTS
      -- a not exists clause will do what you want to filter graduates out
(
  SELECT 1
  FROM Table2
  AS t2self
  WHERE t2.userID=t2self.userID
        AND t2self.exitreason IS NOT NULL
)
GROUP BY t1.userID;
</code>```

Body:
I have a table of user data for when they enroll in a program.  The fields include a user ID, start date, end date, entry reason, exit reason and program type.  For each year the user is enrolled in a specific program they will have an entry and exit date for that year along with an entry reason.  They only get an exit reason when they are exited from the program completely.  Here is an example of the data in the table.

Data Table
Desired Result

I need to pull one line for each user that has their original start date in the program, most recent start date, and most recent end date.  I also need to pull the exit reason if one exists and entry reason associated with the most recent start date and this is what is getting me hung up.  I’m assuming the problem is related to having to group by the entry reason.  Is there any way around using an aggregate function to get the min/max dates?
  My query is:

Select
    Table1.userID,
    CAST(Min(table2.startdate) as date) as Originalstartdate,
    CAST(Max(table2.startdate) as date) as Maxstartdate,
    CAST(Max(table2.enddate) as date) as ExitDate,
    CASE
        WHEN table2.exitreason = NULL then ‘’
        ELSE table2.exitreason
    END as Exitcode,
    Table2.entryreason
From
    Table1 left outer join
    Table2 on Table1.userID = Table2.userID
Where
    Table1.status = ‘active’ and Table2.programID = ‘Program1’ and (Table2.exitreason <> ‘NULL’ or Table2.entryreason <> ‘NULL’)
Group By
    Table1.userID, Table2.exitreason, Table2.entryreason

Body:
I used the below sample code in order to generate this.

The idea here is to utilize the userID as the anchor (you want one row per user, right?), aggregating the rest of the information but with the situation you requested.

CREATE TABLE SCRIPT:

CREATE TABLE table1
(
  userID INT IDENTITY(1, 1) PRIMARY KEY,
  name   VARCHAR(200),
  stat   CHAR(1) NOT NULL
                 DEFAULT 'A');

CREATE TABLE table2
(
  t2ID        INT IDENTITY(1, 1),
  StartDate   DATE,
  UserID      INT FOREIGN KEY REFERENCES table1(userID),
  ProgramID   VARCHAR(150) DEFAULT 'Program1',
  EndDate     DATE,
  EntryReason VARCHAR(2000),
  ExitReason  VARCHAR(2000));

INSERT INTO Table1
(name)
       SELECT *
       FROM(VALUES
       (
         'First name'),
       (
         'Second name'),
       (
         'Third name')) x("name");

INSERT INTO Table2
       SELECT *
       FROM(VALUES
       (
         '20180101', 1, 'Program1', '20181231', 11, NULL),
       (
         '20190101', 1, 'Program1', '20191231', 12, NULL),
       (
         '20200101', 1, 'Program1', NULL, 11, NULL),
       (
         '20170101', 2, 'Program1', '20171231', 11, NULL),
       (
         '20180101', 2, 'Program1', '20171231', 14, 2),
       (
         '20200101', 3, 'Program1', NULL, 11, NULL)
) x(StartDate, UserID, ProgramID, EndDate, EntryReason, ExitReason);

QUERY:

SELECT t1.userID,
       CAST(MIN(t2.StartDate) AS DATE)
AS OriginalStartDate, -- This uses your logic to grab the earliest date
       CAST(MAX(t2.StartDate) AS DATE)
AS RecentStartDate, -- This utilizes your logic to grab the last start date
       CAST(MAX(t2.enddate) AS DATE)
AS ExitDate,
-- This works because we know an ExitDate must be populated due to the where
-- criteria (which prevents people who haven't exited yet from showing up)
       ISNULL(MAX(t2.exitreason), '')
AS ExitCode, -- This is just a cleaner way to handle nulls.
       STUFF(
(
  SELECT CONCAT(',', EntryReason)
  FROM Table2
  WHERE Table2.UserID=t1.UserID FOR XML PATH('')
), 1, 1, '')
AS EntryReasonList
-- this solution creates a list of entry reasons; we could pick a best winner
-- (e.g. first entry code, last entry code..) but I created a list because
-- I didn't understand your intent.
FROM Table1
AS t1
LEFT JOIN
Table2
AS t2
ON T1.userID=T2.userID
WHERE t1.stat='A' -- you would use status= 'active'
      AND t2.programID='Program1' -- same as before
      AND NOT EXISTS
      -- a not exists clause will do what you want to filter graduates out
(
  SELECT 1
  FROM Table2
  AS t2self
  WHERE t2.userID=t2self.userID
        AND t2self.exitreason IS NOT NULL
)
GROUP BY t1.userID;


问:
kubectl cannot connect GKE, failing with x509: certificate signed by unknown authority
I can't connect from my machine to any GKE cluster. From remote machine, it's working, but not from mine and I can't figure out why. If some of you have any idea...

I have installed kubectl from within gcloud (gcloud components install kubectl)

I'm running gcloud init, then on existing cluster or on newly created one with gcloud container clusters create my-cluster  --preemptible --cluster-version 1.12.7-gke.10 --machine-type n1-standard-1 --disk-size 20 --num-nodes 1

I'm retrieving my credentials with gcloud container clusters get-credentials my-cluster --zone europe-west1-b --project my-project-123456 which creates a new context for my kubectl. Switching to it (with kubectx).

But when I'm trying to contact my cluster (e.g. kubectl get pods) it fails with with the following message:

Unable to connect to the server: x509: certificate signed by unknown authority

I just can't figure out why my local kubectl can't validate Google CA.
I followed all resources I found, tried with other clusters, in other zone/region, with a different version of python (2.7 & 3.6), re-init gcloud, used another Google account, another version of kubectl (1.11, 1.12 & 1.14), update my CA (sudo update-ca-certificates) in Linux (Mint 19.1 Tessa).

Has anyone already face this and found a solution?

答:
If anyone runs into this after they are able to log in, this solution worked for me

```<code>gcloud container clusters get-credentials YOURCLUSTERHERE --zone YOURCLUSTERZONEHERE
</code>```

After you fill in your info and run it, you should be able to move forward.

Body:
If anyone runs into this after they are able to log in, this solution worked for me

gcloud container clusters get-credentials YOURCLUSTERHERE --zone YOURCLUSTERZONEHERE

After you fill in your info and run it, you should be able to move forward.


问:
Return not killing recursive function
I have the bit of code that searches the entire computer for a file and once found, should return that file. The problem is in the second function, the recursive one. Once the file is found, it should return, which it does, but for some reason, even after returning the value, it continues the recursive search.

I don't get it. I'd still consider myself new to programming so please explain in detail if you see what I'm doing wrong.

```<code>public string SearchDirectory(string dir, string fileName)
{
    string foundDir = "";
    bool fileFound = false;
    // Gets all files from directory and creates list of matches to fileName
    try
    {
        foreach (string match in Directory.GetFiles(dir, fileName))
        {
            // Returns the first found match as a path and breaks loop
            Console.WriteLine("Checked path: " + dir + ".");
            if (File.Exists(dir + @"\" + fileName))
            {
                Console.WriteLine("FOUND!!");
                fileFound = true;
                foundDir = dir;
                break;
            }
            if (fileFound == true)
            {
                break;
            }
        }
    }
    catch
    {
        Console.WriteLine("Access to path: " + dir + " denied.");
    }

    // If fileName isn't found in directory, it searches each new directory
    // The last directory it will check is the last one in the original directory
    if (fileFound == false)
    {
        try
        {
            foreach (string newDirectory in Directory.GetDirectories(dir))
            {
                Console.WriteLine("Checked path: " + dir + ".");
                SearchDirectory(newDirectory, fileName);
            }
        }
        catch
        {
            Console.WriteLine("Access to path: " + dir + " denied.");
        }
        // fileName does not exist in starting directory
    }
    else
    {
        return foundDir;
    }
    return "";
}
</code>```

答:
You could just do this instead:</p>

```<code>public string SearchDirectory(string dir, string fileName)
{
  return Directory
    .EnumerateFiles(dir, fileName, SearchOption.AllDirectories)
    .FirstOrDefault() ?? "";
}
</code>```

Title: Return not killing recursive function

Body:
I have the bit of code that searches the entire computer for a file and once found, should return that file. The problem is in the second function, the recursive one. Once the file is found, it should return, which it does, but for some reason, even after returning the value, it continues the recursive search.

I don't get it. I'd still consider myself new to programming so please explain in detail if you see what I'm doing wrong.

public string SearchDirectory(string dir, string fileName)
{
    string foundDir = "";
    bool fileFound = false;
    // Gets all files from directory and creates list of matches to fileName
    try
    {
        foreach (string match in Directory.GetFiles(dir, fileName))
        {
            // Returns the first found match as a path and breaks loop
            Console.WriteLine("Checked path: " + dir + ".");
            if (File.Exists(dir + @"\" + fileName))
            {
                Console.WriteLine("FOUND!!");
                fileFound = true;
                foundDir = dir;
                break;
            }
            if (fileFound == true)
            {
                break;
            }
        }
    }
    catch
    {
        Console.WriteLine("Access to path: " + dir + " denied.");
    }

    // If fileName isn't found in directory, it searches each new directory
    // The last directory it will check is the last one in the original directory
    if (fileFound == false)
    {
        try
        {
            foreach (string newDirectory in Directory.GetDirectories(dir))
            {
                Console.WriteLine("Checked path: " + dir + ".");
                SearchDirectory(newDirectory, fileName);
            }
        }
        catch
        {
            Console.WriteLine("Access to path: " + dir + " denied.");
        }
        // fileName does not exist in starting directory
    }
    else
    {
        return foundDir;
    }
    return "";
}

Body:
You could just do this instead:

public string SearchDirectory(string dir, string fileName)
{
  return Directory
    .EnumerateFiles(dir, fileName, SearchOption.AllDirectories)
    .FirstOrDefault() ?? "";
}


问:
"If" conditions in Jenkinsfile pipeline (windows)
please see below my Jenkinsfile.

Currently I am stopping and deleting windows service, then recreating and restarting.
However I only want to stop service if its already started.....and I only want to delete if it exists.

Can anyone help?

```<code>node {
      stage('Scm-Checkout'){
          git credentialsId: 'git-creds', url: 'https://jamurphy@bitbucketdev.ca.bestbuy.com/scm/mot/mpx_spring_react.git'
      }
      stage('Build') {
          bat 'mvn clean package'
      }
  stage('Create Windows Service'){
          bat 'copy C:\\Jenkins\\workspace\\Build_Mpx_Spring_React\\target\\mpx_spring_react.jar C:\\Jenkins\\workspace\\Build_Mpx_Spring_React\\win_svc'
          bat 'net stop mpxsvc'
          bat 'sc delete mpxsvc'
          bat 'C:\\Jenkins\\workspace\\Build_Mpx_Spring_React\\win_svc\\WinSW.NET4.exe install'
          bat 'net start mpxsvc'
      }
}
</code>```

答:
You can use the when statement as shown below, regarding mpxsvcisrunning you can capture the output of the status command and verify it.

```<code>node{
        stage("stop mpxsvc"){
            when { expression { mpxsvcisrunning() } }
            steps {
            }
        }
}

def mpxsvcisrunning(){
   // check if the applicaion is runnning
}
</code>```

Body:
please see below my Jenkinsfile.

Currently I am stopping and deleting windows service, then recreating and restarting.
However I only want to stop service if its already started.....and I only want to delete if it exists.

Can anyone help?

node {
      stage('Scm-Checkout'){
          git credentialsId: 'git-creds', url: 'https://jamurphy@bitbucketdev.ca.bestbuy.com/scm/mot/mpx_spring_react.git'
      }
      stage('Build') {
          bat 'mvn clean package'
      }
  stage('Create Windows Service'){
          bat 'copy C:\\Jenkins\\workspace\\Build_Mpx_Spring_React\\target\\mpx_spring_react.jar C:\\Jenkins\\workspace\\Build_Mpx_Spring_React\\win_svc'
          bat 'net stop mpxsvc'
          bat 'sc delete mpxsvc'
          bat 'C:\\Jenkins\\workspace\\Build_Mpx_Spring_React\\win_svc\\WinSW.NET4.exe install'
          bat 'net start mpxsvc'
      }
}

Body:
You can use the when statement as shown below, regarding mpxsvcisrunning you can capture the output of the status command and verify it.

node{
        stage("stop mpxsvc"){
            when { expression { mpxsvcisrunning() } }
            steps {
            }
        }
}

def mpxsvcisrunning(){
   // check if the applicaion is runnning
}


问:
Making API calls to Skype for Business / Lync without registering application
I was looking to develop a service that interacts with my Skype for Business account. The UCWA API look to be almost perfect (language agnostic HTTP API) unfortunately it seems that using the UCWA API requires registering a persistent(?) application with the Lync server which Id rather not do. I just want to auth, make a few API calls and be done? IS there anyway to do this with Skype for Business / Lync wthout regiersting an application on the server?</p>

答:
I think you are confused, you don't been to register a application to use UCWA.
You need to register a azure application if you want to communicate with SfB online with UCWA but on-prem UCWA access you don't have to.

I think you are getting confused with Trusted Application API which is ONLY for SfB online (it's kind-of like a replacement for UCMA trusted server applications) and only works on SfB online only. You can think of Trusted Application API as a extension of the UCWA api to provide more high-privilege capabilities.  If you don't need the extra capabilities then you don't need to use the Trusted Application API.


问:
SQL query to check if a select operation returns rows
I need to check if the select operation I am performing is returning any rows or not.

Can someone please help me with this.

I am working on a shell script so I cannot save it in a variable and check. I need to check on the fly. I know I can use the count switch. But can someone help me with the syntax?

For example, I need to check:

```<code>--Now this query should return some data
select * from error_repository_BKP partition(part_maxval);
</code>```

答:
```<code>If exists (Select 1 from error_repository_BKP partition(part_maxval))
  Begin
      print 'returns Row'
  End
Else
  Begin
      Print 'No Rows'
  End
</code>```

<p>??</p>

Body:
I need to check if the select operation I am performing is returning any rows or not.

Can someone please help me with this.

I am working on a shell script so I cannot save it in a variable and check. I need to check on the fly. I know I can use the count switch. But can someone help me with the syntax?

For example, I need to check:

--Now this query should return some data
select * from error_repository_BKP partition(part_maxval);

Body:
If exists (Select 1 from error_repository_BKP partition(part_maxval))
  Begin
      print 'returns Row'
  End
Else
  Begin
      Print 'No Rows'
  End

??


问:
get(int index) method in java
I am trying to do a get(int index) method that returns the element at the specified index in a list but I can't see what to return. What shall I have after tempNode in the end?

```<code>public E get(int index) throws IndexOutOfBoundsException {
    Node tempNode = head;
    if (index < 0 || index >= size) {
        throw new IllegalArgumentException("index was out of bounds");
    }
    for (int i = 0; i < index; i++) {
        tempNode = tempNode.getmNextNode();
    }
    return tempNode.;
}
</code>```

I am using the Node class:

```<code>public class Node<E> {
    private E mElement;
    private Node<E> mNextNode;

    Node(E data) {
        this.setmElement(data);
    }
    public E getmElement() {
        return this.mElement;
    }
    public void setmElement(E element) {
        this.mElement = element;
    }
    public Node<E> getmNextNode() {
        return this.mNextNode;
    }
    public void setmNextNode(Node<E> node) {
        this.mNextNode = node;
    }
}
</code>```

答:
You'd return mElement of type E. That the list is build out of nodes is an implementation detail. So return return tempNode.eElement or rather tempNode.getmElement() if you cannot access it directly due to the access modifiers of the field.

Don't know what you were expecting to return otherwise.

Note that because of the m in there, Java will probably not recognize it as a get method. That's not a good idea, in Java you don't use identifiers like that, remove the ms from your identifiers!

Title: get(int index) method in java

Body:
I am trying to do a get(int index) method that returns the element at the specified index in a list but I can't see what to return. What shall I have after tempNode in the end?

public E get(int index) throws IndexOutOfBoundsException {
    Node tempNode = head;
    if (index < 0 || index >= size) {
        throw new IllegalArgumentException("index was out of bounds");
    }
    for (int i = 0; i < index; i++) {
        tempNode = tempNode.getmNextNode();
    }
    return tempNode.;
}

I am using the Node class:

public class Node<E> {
    private E mElement;
    private Node<E> mNextNode;

    Node(E data) {
        this.setmElement(data);
    }
    public E getmElement() {
        return this.mElement;
    }
    public void setmElement(E element) {
        this.mElement = element;
    }
    public Node<E> getmNextNode() {
        return this.mNextNode;
    }
    public void setmNextNode(Node<E> node) {
        this.mNextNode = node;
    }
}


问:
If value in one cell, then modify row which consists that cell
I am totally new to VBA and I am struggling a little bit with one thing. I want to make a macro, which checks values in "M" column. If value is higher than 5, then print "hello". If not then print "x". Unfortunately, I only gets "x" back in selected cells.

```<code>Private Sub costam()
Dim i As Integer
Dim a As Integer
a = 13

For i = 1 To Range("M" & Rows.Count).End(xlUp).Row
    If Cells(a, i).Value > 5 Then
     Range(Cells(1, i), Cells(10, i)).Value = "hello"
    Else
     Range(Cells(1, i), Cells(10, i)).Value = "x"
    End If
Next i

End Sub
</code>```

I know this problem is silly and takes like 1 minute to solve, but I am trying to apply some alike problems but without any progress.

答:
You could create a custom function for this workbook.

```<code>Public Function CustomFunction(myVal As Integer)
Dim myResult As String

If myVal > 5 Then
    myResult = "Hello"
Else
    myResult = "X"
End If

    CustomFunction = myResult
End Function
</code>```

Then, you would write a formula in the cell where you want the value to be returned.
=CustomFunction(A2)

Your custom function will need to be placed into a module.

Excel VBA User-Defined Functions Tutorial

Body:
I am totally new to VBA and I am struggling a little bit with one thing. I want to make a macro, which checks values in "M" column. If value is higher than 5, then print "hello". If not then print "x". Unfortunately, I only gets "x" back in selected cells.

Private Sub costam()
Dim i As Integer
Dim a As Integer
a = 13

For i = 1 To Range("M" & Rows.Count).End(xlUp).Row
    If Cells(a, i).Value > 5 Then
     Range(Cells(1, i), Cells(10, i)).Value = "hello"
    Else
     Range(Cells(1, i), Cells(10, i)).Value = "x"
    End If
Next i

End Sub

I know this problem is silly and takes like 1 minute to solve, but I am trying to apply some alike problems but without any progress.

Body:
You could create a custom function for this workbook.

Public Function CustomFunction(myVal As Integer)
Dim myResult As String

If myVal > 5 Then
    myResult = "Hello"
Else
    myResult = "X"
End If

    CustomFunction = myResult
End Function

Then, you would write a formula in the cell where you want the value to be returned.
=CustomFunction(A2)

Your custom function will need to be placed into a module.

Excel VBA User-Defined Functions Tutorial


问:
java.lang.Object cannot be converted to the class i created
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code

```<code>public class Test1
{
  public static void main(String args[])
  {
    Thing whipersnaper = new Thing(30, "whipersnaper");
    List storage = new List();

    storage.insert(whipersnaper);

    Thing x = storage.getItem(0);

    x.doubleWeight();

    System.out.println(x.getWeight());
  }
}
</code>```

here is the "Thing" class

```<code>public class Thing
{
  private int weight;
  private String name;

  public Thing(int weight,String name){
    this.weight = weight;
    this.name = name;
  }

  public void doubleWeight(){
    this.weight *= 2;
  }

  public int getWeight(){
    return this.weight;
  }
}
</code>```

finally here is the List class

```<code>public class List
{
  private Object[] itemList;
  private int size;

  public List()
  {
    this.itemList = new Object[10];
    this.size = 0;
  }

  public void insert(Object item){
    itemList[size] = item;
    size++;
  }

  public Object getItem(int index){
    return itemList[index];
  }
}
</code>```

i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.

答:
```<code>Thing x = (Thing) storage.getItem(0);
</code>```

Body:
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code

public class Test1
{
  public static void main(String args[])
  {
    Thing whipersnaper = new Thing(30, "whipersnaper");
    List storage = new List();

    storage.insert(whipersnaper);

    Thing x = storage.getItem(0);

    x.doubleWeight();

    System.out.println(x.getWeight());
  }
}

here is the "Thing" class

public class Thing
{
  private int weight;
  private String name;

  public Thing(int weight,String name){
    this.weight = weight;
    this.name = name;
  }

  public void doubleWeight(){
    this.weight *= 2;
  }

  public int getWeight(){
    return this.weight;
  }
}

finally here is the List class

public class List
{
  private Object[] itemList;
  private int size;

  public List()
  {
    this.itemList = new Object[10];
    this.size = 0;
  }

  public void insert(Object item){
    itemList[size] = item;
    size++;
  }

  public Object getItem(int index){
    return itemList[index];
  }
}

i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.

Body: Thing x = (Thing) storage.getItem(0);


问:
How to print out a list of tuple?
This is my code:

```<code>def points_per_game(master_list):
container1= []
for line in master_list:
    container1.append((float(line[18]),line[0],line[2]))
container1.sort(reverse=True)
container1 = container1[:10]
return container1
</code>```

And the output of my code is a list of tuples:

```<code>[(1.92, 'Wayne Gretzky', 'C'), (1.88, 'Mario Lemieux', 'C'), (1.5, 'Mike Bossy', 'R'), (1.4, 'Joe Malone', 'C'), (1.39, 'Bobby Orr', 'D'), (1.33, 'Connor McDavid', 'C'), (1.31, 'Marcel Dionne', 'C'), (1.28, 'Sidney Crosby', 'C'), (1.27, 'Peter Stastny', 'C'), (1.25, 'Peter Forsberg', 'C')]
</code>```

How to turn the list into the picture below, changing the order of the floating point number, the name, and the letter, with format "{:<20s}{:>8s}{:>16s}" in main()?

答:
Just loop over the list elements and format it. You can use tuple unpacking to reorder the elements.

```<code>for score, player, letter in points_per_game(master_list):
    print("{:<20s}{:>8s}{:>16.2f}".format(player, letter, score))
</code>```

You need to use f formatting for the float scores, and you can use .2 to specify 2 digits after the decimal.

Title: How to print out a list of tuple?

Body:
This is my code:

def points_per_game(master_list):
container1= []
for line in master_list:
    container1.append((float(line[18]),line[0],line[2]))
container1.sort(reverse=True)
container1 = container1[:10]
return container1

And the output of my code is a list of tuples:

[(1.92, 'Wayne Gretzky', 'C'), (1.88, 'Mario Lemieux', 'C'), (1.5, 'Mike Bossy', 'R'), (1.4, 'Joe Malone', 'C'), (1.39, 'Bobby Orr', 'D'), (1.33, 'Connor McDavid', 'C'), (1.31, 'Marcel Dionne', 'C'), (1.28, 'Sidney Crosby', 'C'), (1.27, 'Peter Stastny', 'C'), (1.25, 'Peter Forsberg', 'C')]

How to turn the list into the picture below, changing the order of the floating point number, the name, and the letter, with format "{:<20s}{:>8s}{:>16s}" in main()?

Body:
Just loop over the list elements and format it. You can use tuple unpacking to reorder the elements.

for score, player, letter in points_per_game(master_list):
    print("{:<20s}{:>8s}{:>16.2f}".format(player, letter, score))

You need to use f formatting for the float scores, and you can use .2 to specify 2 digits after the decimal.


问:
Can't understand python variable scopes for callbacks and with blocks
While writing a function that will show a progress bar while downloading a list of files from an ftp server I ended up with some strange script:

with ftplib.FTP(...) as ftp:
  files = list(ftp.mlsd(path=remote_dir_path))
  total_size = sum(int(f[1]['size']) for f in files)
  total_done = 0
  current_done = 0
  current_size = 0

  def callback(chunk):
    global current_done
    global total_done
    global current_size
    global total_size
    trg_file.write(chunk) # how? why it knows what is `trg_file`?
    current_done += len(chunk)
    total_done += len(chunk)
    print_progressbar(current_done,total_done,...)

  for file in files:
    current_done = 0
    current_size = int(file[1]['size'])
    with open(file[0],'wb') as trg_file:
      ftp.retrbinary('RETR %s/%s'%(remote_dir_path,file[0]),callback)
```

<p>I had to write <code>global</code> in <code>callback</code> function so that python does not complain about it. BUT it knew what is <code>trg_file</code> no problem?!?!?!
Trying to understand I wrote a small test:</p>

<pre class="lang-py prettyprint-override"><code>def callback():
  print(foo)

def main():
  foo = 'FOOOO'
  callback()

main()
</code>```

It failed as expected.

I get why the second script does not work. Intuition says that the first should not work too. But it works. Can somebody please explain why?
EDIT:
The question is not about global itself, but about with ... as ... block and scope (scope of ... as variable variable)

答:
When you do something like this:

```<code>def abc():
    x = 5
</code>```

The x variable is local, same applies to

```<code>def abc():
    x += 5
</code>```

Because it basically is x = x + 5, assign operator again.
Consider this one:

```<code>x = 1
def abc():
    print(x)
</code>```

What will hapen here? x will be printed because x is available in the abc function scope.

Now consider this one:

```<code>x = 1
def abc():
    print(x)
    x = 5
    print(x)

abc()
</code>```

What will happen? Will the first print print 1? The answer is no because later on in the function definition there is x = 5, so  x will be treated as a local variable in whole the function, the first print included - it won't look to global scope, because there is an x variable in local scope. It wasn't assign yet when first print is executed, that's why there will be an error.

Now with statement doesn't create a scope. That's why you need global keyword if you want to assign to (global) variables: total_size, total_done, current_done, current_size.

To ilustrate why some variables doesn't need global keyword consider this snippet:

```<code>some_list = [1, 2, 3]
def abc():
    some_list = ['a', 'b', 'c']  # assignment to variable some_list, it is
                                 # a local variable, it has nothing to do
                                 # with global some_list (it references a different object)
    print(some_list)

abc()
print(some_list)
>>> ['a', 'b', 'c']
>>> [1, 2, 3]

def cba():
    some_list.append(4)  # now there is no assignment so some_list is a global variable and references the same object in memory from the beginning

cba()
print(some_list)
>>> [1, 2, 3, 4]
</code>```

If it's still confusing, there is this nice website when you can visualize which variable references which object in memory here: http://pythontutor.com/visualize.html.

Body:
While writing a function that will show a progress bar while downloading a list of files from an ftp server I ended up with some strange script:

with ftplib.FTP(...) as ftp:
  files = list(ftp.mlsd(path=remote_dir_path))
  total_size = sum(int(f[1]['size']) for f in files)
  total_done = 0
  current_done = 0
  current_size = 0

  def callback(chunk):
    global current_done
    global total_done
    global current_size
    global total_size
    trg_file.write(chunk) # how? why it knows what is `trg_file`?
    current_done += len(chunk)
    total_done += len(chunk)
    print_progressbar(current_done,total_done,...)

  for file in files:
    current_done = 0
    current_size = int(file[1]['size'])
    with open(file[0],'wb') as trg_file:
      ftp.retrbinary('RETR %s/%s'%(remote_dir_path,file[0]),callback)

I had to write global in callback function so that python does not complain about it. BUT it knew what is trg_file no problem?!?!?!
Trying to understand I wrote a small test:

def callback():
  print(foo)

def main():
  foo = 'FOOOO'
  callback()

main()

It failed as expected.

I get why the second script does not work. Intuition says that the first should not work too. But it works. Can somebody please explain why?
EDIT:
The question is not about global itself, but about with ... as ... block and scope (scope of ... as variable variable)

Body:
When you do something like this:

def abc():
    x = 5

The x variable is local, same applies to

def abc():
    x += 5

Because it basically is x = x + 5, assign operator again.
Consider this one:

x = 1
def abc():
    print(x)

What will hapen here? x will be printed because x is available in the abc function scope.

Now consider this one:

x = 1
def abc():
    print(x)
    x = 5
    print(x)

abc()

What will happen? Will the first print print 1? The answer is no because later on in the function definition there is x = 5, so  x will be treated as a local variable in whole the function, the first print included - it won't look to global scope, because there is an x variable in local scope. It wasn't assign yet when first print is executed, that's why there will be an error.

Now with statement doesn't create a scope. That's why you need global keyword if you want to assign to (global) variables: total_size, total_done, current_done, current_size.

To ilustrate why some variables doesn't need global keyword consider this snippet:

some_list = [1, 2, 3]
def abc():
    some_list = ['a', 'b', 'c']  # assignment to variable some_list, it is
                                 # a local variable, it has nothing to do
                                 # with global some_list (it references a different object)
    print(some_list)

abc()
print(some_list)
>>> ['a', 'b', 'c']
>>> [1, 2, 3]

def cba():
    some_list.append(4)  # now there is no assignment so some_list is a global variable and references the same object in memory from the beginning

cba()
print(some_list)
>>> [1, 2, 3, 4]

If it's still confusing, there is this nice website when you can visualize which variable references which object in memory here: http://pythontutor.com/visualize.html.


问:
Python requirements conflict with PyPi
I have a project that needs some DevOps TLC, so I am finally building my installation script. This will eventually be a package that will be install-able by pip locally, but may not end up in PyPI.

It has a dependency for a module called u2py. It is this package, created for U2 Database operations, not this package, for... something else. The one I want is only ever installed by a 3rd party vendor (Rocket), the one I don't want is in PyPI.

What should be the expected behavior of my package in this case? I will include a blurb about this in my readme doc, but is that sufficient?

I've thought about throwing an exception to identify when the wrong package is present, but that makes me feel weird. It seems that maybe the most pythonic thing is to NOT add this to my install script, and blindly assume import u2py results in a module I can use. If it quacks like a duck, parses DynArrays like a duck, and call()s SUBROUTINEs like a duck, then it's a duck, right? Otherwise, if there is an error the user will just go and actually read the docs.

I've looked a classifiers, but not sure if they apply here.

答:
You can specify the url to the package in install_requires using setuptools (requires pip version 18.1 or greater).

Requirement specifiers

Example

setup.py

```<code>import setuptools

setuptools.setup(
    name='MyPackage',
    version='1.0.0',
    # ...
    install_requires=[
        'requests @ https://github.com/psf/requests/archive/v2.22.0.zip'
    ]
    # ...
)
</code>```

and do python setup.py install

Also

Since version 19.1, pip also supports direct references like so:

SomeProject @ file:///somewhere/...

Ref

https://www.python.org/dev/peps/pep-0508/

https://github.com/pypa/pip/pull/4175

Title: Python requirements conflict with PyPi

Body:
You can specify the url to the package in install_requires using setuptools (requires pip version 18.1 or greater).

Requirement specifiers

Example

setup.py

import setuptools

setuptools.setup(
    name='MyPackage',
    version='1.0.0',
    # ...
    install_requires=[
        'requests @ https://github.com/psf/requests/archive/v2.22.0.zip'
    ]
    # ...
)

and do python setup.py install

Also

Since version 19.1, pip also supports direct references like so:

SomeProject @ file:///somewhere/...

Ref

https://www.python.org/dev/peps/pep-0508/

https://github.com/pypa/pip/pull/4175