问:
@async in spring behaviour is synchronous
i have written a piece of code for checking the @Async annotation behavior in Spring framework.

```<code>@RequestMapping( value="/async" , method = RequestMethod.GET)
  public ModelAndView AsyncCall(HttpServletRequest request)
  {
        async1();
        async2();
    return new ModelAndView("firstpage");
  }

  @Async
  private void async1(){
      System.out.println("Thread 1 enter");
      try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      System.out.println("Thread 1 exit");
  }

  @Async
  private void async2(){
      System.out.println("Thread 2 enter");
      try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      System.out.println("Thread 2 exit");
  }
</code>```

output of this code is as follows.

```<code>Thread 1 enter
Thread 1 exit
Thread 2 enter
Thread 2 exit
</code>```

By looking at this output it seems like that these two @Async function call are synchronous itself.

As of i know these two are different threads and should run asynchronously itself.

After changing the code according to spring proxy call logs which are printing are like.

Main Thread name: http-apr-8080-exec-8

```<code>Thread 1 enter
Async-1 Thread Name: neutrinoThreadPoolExecutor-1
Thread 1 exit
Thread 2 enter
Async-2 Thread Name: neutrinoThreadPoolExecutor-1
Thread 2 exit
</code>```

name of the thread for both async calls are same and still it seems that asynchronous behavior is not presented.

答:
Spring's @Async annotation has two rules that you need to follow.

It must be applied to public methods only

Self-invocation – Calling the async method from within the same class – won’t work

The reasons are simple – the method needs to be public so that it can be proxied.
And self-invocation doesn’t work because it bypasses the proxy and calls the underlying method directly.

Body:
i have written a piece of code for checking the @Async annotation behavior in Spring framework.

@RequestMapping( value="/async" , method = RequestMethod.GET)
  public ModelAndView AsyncCall(HttpServletRequest request)
  {
        async1();
        async2();
    return new ModelAndView("firstpage");
  }

  @Async
  private void async1(){
      System.out.println("Thread 1 enter");
      try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      System.out.println("Thread 1 exit");
  }

  @Async
  private void async2(){
      System.out.println("Thread 2 enter");
      try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      System.out.println("Thread 2 exit");
  }

output of this code is as follows.

Thread 1 enter
Thread 1 exit
Thread 2 enter
Thread 2 exit

By looking at this output it seems like that these two @Async function call are synchronous itself.

As of i know these two are different threads and should run asynchronously itself.

After changing the code according to spring proxy call logs which are printing are like.

Main Thread name: http-apr-8080-exec-8

Thread 1 enter
Async-1 Thread Name: neutrinoThreadPoolExecutor-1
Thread 1 exit
Thread 2 enter
Async-2 Thread Name: neutrinoThreadPoolExecutor-1
Thread 2 exit

name of the thread for both async calls are same and still it seems that asynchronous behavior is not presented.


来源: stackexchange

问:
How to get GA Tracking IDs from GTM code
Is there with javascript a way to retrieve the Google Analytics "Web Property ID" for a given GTM code?

I am including the snippet for GTM in the HEAD of my pages, and the Google Tag Assistant extension sees the tags properly, including the "Web Property Id" (UA-XXXXX-XX).
I am using ReactGA module to send GA Events, and I need the "Web Property Id" to initialise it.

If I copy it to initialize the module like this;

```<code>ReactGA.initialize('UA-XXXXX-XX');
</code>```

it is working properly, but I would prefer to retrieve it dynamically: i already map the GTM codes, i don't see any reason to do the same for the Web Property IDs if I can retrieve them from GTM codes.

答:
Google Analytics is storing information about ID in global variable gaData, you can receive GA ID information like that:

```<code>Object.keys(gaData)[0]
//it will return string UA-XXXXXXX
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there with javascript a way to retrieve the Google Analytics "Web Property ID" for a given GTM code?

I am including the snippet for GTM in the HEAD of my pages, and the Google Tag Assistant extension sees the tags properly, including the "Web Property Id" (UA-XXXXX-XX).
I am using ReactGA module to send GA Events, and I need the "Web Property Id" to initialise it.

If I copy it to initialize the module like this;

ReactGA.initialize('UA-XXXXX-XX');

it is working properly, but I would prefer to retrieve it dynamically: i already map the GTM codes, i don't see any reason to do the same for the Web Property IDs if I can retrieve them from GTM codes.

Body:
Google Analytics is storing information about ID in global variable gaData, you can receive GA ID information like that:

Object.keys(gaData)[0]
//it will return string UA-XXXXXXX


问:
Extracting only required details from the website using Selenium Python
I am trying to search a product 'Printer' in search bar automatically and retrieve only the MFR number of the products of company named EPSON. But the output which I am getting is more than what I want! It is the complete content of that class.

Here is my code

```<code>from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://shop.techdata.com/searchall?b=1&kw=printer')
items = driver.find_elements_by_class_name( 'productResult' )

for i, item in enumerate(items):
    if 'EPSON' in item.text:
       print(i, item.text)
</code>```

Expected output is

```<code>3

C11CF75201
</code>```

The example of (undesired) output of this code which I am getting is as shown :

```<code>3 EPSON WORKFORCE PRO WF-4740 - MULTIFUNCTION PRINTER (COLOR)
Multifunction printer - color - ink-jet - Legal (8.5 in x 14 in) (original)
 A4/Legal (media) - up to 22 ppm (copying) - up to 24 ppm (printing) - 500
 sheets
- 33.6 Kbps - USB 2.0, LAN, Wi-Fi(n), USB host, NFC

TD#: 12710297

MFR#: C11CF75201

Status: Active

MSRP:
$299.99
</code>```

答:
Try to replace line

```<code>print(i, item.text)
</code>```

with

```<code>print(i, item.find_element_by_xpath('.//div[@class="productCodes"]/div[2]/span').text)
</code>```

to get required output

Body:
I am trying to search a product 'Printer' in search bar automatically and retrieve only the MFR number of the products of company named EPSON. But the output which I am getting is more than what I want! It is the complete content of that class.

Here is my code

from selenium import webdriver
driver = webdriver.Chrome( "C:\All\chromedriver_win32\chromedriver.exe" )
driver.get('https://shop.techdata.com/searchall?b=1&kw=printer')
items = driver.find_elements_by_class_name( 'productResult' )

for i, item in enumerate(items):
    if 'EPSON' in item.text:
       print(i, item.text)

Expected output is

3

C11CF75201

The example of (undesired) output of this code which I am getting is as shown :

3 EPSON WORKFORCE PRO WF-4740 - MULTIFUNCTION PRINTER (COLOR)
Multifunction printer - color - ink-jet - Legal (8.5 in x 14 in) (original)
 A4/Legal (media) - up to 22 ppm (copying) - up to 24 ppm (printing) - 500
 sheets
- 33.6 Kbps - USB 2.0, LAN, Wi-Fi(n), USB host, NFC

TD#: 12710297

MFR#: C11CF75201

Status: Active

MSRP:
$299.99

Body:
Try to replace line

print(i, item.text)

with

print(i, item.find_element_by_xpath('.//div[@class="productCodes"]/div[2]/span').text)

to get required output


问:
ASP.net MVC 5 calling partial view thats in layout from Home controller
Hey all I am trying to find a way (or if its possible) to call this code:

```<code><nav>
    <ul class="nav navbar-nav">
        @if (Session["chosenAMT"] is bool == true)
        {
           @Html.Partial("_Menu")
        }
    </ul>
</nav>
</code>```

When it starts the page the value for chosenAMT is false so the navigation does not load up on the _Layout.cshtml page.

However, once the user selects a value from the dropdown I need to enable that partial view to be called so that it can show to the user the navigation now.

When the user selects a value from the dropdown list I call a POST to the HomeController.cs:

```<code>$.ajax({
  type: 'POST',
  url: 'Home/showNav',
  cache: false,
  dataType: 'json',
  data: {},
  success: function (response) {
     console.log('worked');
  },
  error: function (response) {
     console.log(response);
  }
});
</code>```

And this is the showNav code in the HomeController.cs:

```<code>[HttpPost]
public string showNav()
{
   Dictionary<string, string> resultsBack = new Dictionary<string, string>();

   Session["chosenAMT"] = true;

   resultsBack.Add("dback", "GOOD");
   resultsBack.Add("dhead", "worked");
   resultsBack.Add("dinfo", "called nav");

   return JsonConvert.SerializeObject(allData, Formatting.Indented);
}
</code>```

I'm pretty much stuck there as to how to go about making the call back to the _Layout.cshtml page in order to show the navigation now...

Any help would be great! Thanks!

UPDATE

Got it!

_Layout.cshtml:

```<code> <nav id="menuContainer" data-url="@Url.Action("Menu","Home")">
    @Html.Action("Menu")
 </nav>
</code>```

_Menu.cshtml:

```<code> @if (Session["chosenAMT"].ToString() == "True")
 {
    <ul class="nav navbar-nav">
    etc...etc....
    </ul>
 }
</code>```

index.js:

```<code> success: function (response) {
    var url = $("#menuContainer").data("url");

    $("#menuContainer").load(url);
 },
</code>```

HomeController:

```<code> public ActionResult Menu()
 {
    return PartialView("_Menu");
 }
</code>```

答:
You need to dynamically reload that part of the menu. To start, create an action method which returns the markup for the menu.

```<code>public ActionResult Menu()
{
   return PartialView("Menu");
}
</code>```

You may also move your if condition statement inside the partial view to conditionally render some markup. So your Menu.cshtml will be like

```<code>    <ul class="nav navbar-nav">
        @if (Session["chosenAMT"] is bool == true)
        {
           @Html.Partial("_Menu")
        }
    </ul>
</code>```

Now call this action method inside the outer container element.

```<code><nav id="menuContainer" data-url="@Url.Action("Menu","YourControllerName")">
   @Html.Action("Menu")
</nav>
</code>```

Now all you have to do is, reloading the content of this menu container div on the success event of your ajax call. You can use the jQuery load method

```<code>success: function (response) {
     var url = $("#menuContainer").data("url");
     $("#menuContainer").load(url);
},
</code>```

Body:
Hey all I am trying to find a way (or if its possible) to call this code:

        @if (Session["chosenAMT"] is bool == true)
        {
           @Html.Partial("_Menu")
        }

When it starts the page the value for chosenAMT is false so the navigation does not load up on the _Layout.cshtml page.

However, once the user selects a value from the dropdown I need to enable that partial view to be called so that it can show to the user the navigation now.

When the user selects a value from the dropdown list I call a POST to the HomeController.cs:

$.ajax({
  type: 'POST',
  url: 'Home/showNav',
  cache: false,
  dataType: 'json',
  data: {},
  success: function (response) {
     console.log('worked');
  },
  error: function (response) {
     console.log(response);
  }
});

And this is the showNav code in the HomeController.cs:

[HttpPost]
public string showNav()
{
   Dictionary<string, string> resultsBack = new Dictionary<string, string>();

   Session["chosenAMT"] = true;

   resultsBack.Add("dback", "GOOD");
   resultsBack.Add("dhead", "worked");
   resultsBack.Add("dinfo", "called nav");

   return JsonConvert.SerializeObject(allData, Formatting.Indented);
}

I'm pretty much stuck there as to how to go about making the call back to the _Layout.cshtml page in order to show the navigation now...

Any help would be great! Thanks!

UPDATE

Got it!

_Layout.cshtml:

    @Html.Action("Menu")

_Menu.cshtml:

 @if (Session["chosenAMT"].ToString() == "True")
 {

    etc...etc....

 }

index.js:

 success: function (response) {
    var url = $("#menuContainer").data("url");

    $("#menuContainer").load(url);
 },

HomeController:

 public ActionResult Menu()
 {
    return PartialView("_Menu");
 }

Body:
You need to dynamically reload that part of the menu. To start, create an action method which returns the markup for the menu.

public ActionResult Menu()
{
   return PartialView("Menu");
}

You may also move your if condition statement inside the partial view to conditionally render some markup. So your Menu.cshtml will be like

    <ul class="nav navbar-nav">
        @if (Session["chosenAMT"] is bool == true)
        {
           @Html.Partial("_Menu")
        }
    </ul>

Now call this action method inside the outer container element.

<nav id="menuContainer" data-url="@Url.Action("Menu","YourControllerName")">
   @Html.Action("Menu")
</nav>

Now all you have to do is, reloading the content of this menu container div on the success event of your ajax call. You can use the jQuery load method

success: function (response) {
     var url = $("#menuContainer").data("url");
     $("#menuContainer").load(url);
},


问:
Issue tracker for web agency workflow
We're looking into implementing an issue tracker for our web agency. The problem is that most issue trackers seem to revolve around the assumption that an issue is a bug, whereas in a web agency environment, a lot of the issues (request, or whatever you want to call them) are about changes and additions to a current web site.

It also seems to me that a lot of issue trackers assume that you're working on one main software project, and uses that project as the focus of the tracker. A good issue tracker for a web agency would be one which puts each separate client and their issues at the heart of the system, making it easy for them to track and report issues.

Does anyone know of a good issue tracker for the web agency workflow? What are other people using?

答: In my experience, issue trackers are so closely coupled to the workflow of the organisation that what works in one place may be a complete misfit in another. That said, could basecamp work for you?</p>

ContentLicense: CC BY-SA 2.5

Title: Issue tracker for web agency workflow


问:
Reusing UIViewController for two Tab bar items
I have 1 tab bar controller in storyboard and 1 UIViewController associated with it. I would like to re-use the same UIViewController in order to create second item in tab bar. When I am creating second relation from tab bar to view controller I need to specify 2 different items names. How can I re-use same view controller and set different items names from storyboard? If not possible to do it in storyboard, then do I have to rename each in tab bar controller class or there is better way?

I was going to provide different data to view controller in prepareforsegue.

UPDATE:

little more details and clarification

In above screenshot marked VC at the moment is reachable a) directly from tab, b) through 3 transitions. I want to add another DIRECT relation to initial tab bar, just like in case of "a".

答:
I've found much simpler solution using storyboard only.

Setup your storyboard like this:

Then in your Navigation Controller Identity Inspector set Restoration ID like this:

And in your ViewController class file put the following code:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationItem.title = parent?.restorationIdentifier
    label.text = parent?.restorationIdentifier
}
</code>```

or do what you like based on parent?.restorationIdentifier value

If you don't want the Navigation TopBar to appear on the ViewController just set it to None in Attributes Inspector of the desired Navigation Controller like this:

That's it! Hope it helps.

Body:
I've found much simpler solution using storyboard only.

Setup your storyboard like this:

Then in your Navigation Controller Identity Inspector set Restoration ID like this:

And in your ViewController class file put the following code:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationItem.title = parent?.restorationIdentifier
    label.text = parent?.restorationIdentifier
}

or do what you like based on parent?.restorationIdentifier value

If you don't want the Navigation TopBar to appear on the ViewController just set it to None in Attributes Inspector of the desired Navigation Controller like this:

That's it! Hope it helps.


问:
Perl unexpected result
Imagine I have this Perl script

```<code>my $name = "   foo    ";
my $sn   = "     foosu";

trim($name, \$sn);

print "name: [$name]\n";
print "sn: [$sn]\n";
exit 0;

sub trim{

   my $fref_trim = sub{
                          my ($ref_input) = @_;
                          ${$ref_input} =~ s/^\s+// ;
                          ${$ref_input} =~ s/\s+$// ;
    };

   foreach my $input (@_){
       if (ref($input) eq "SCALAR"){
            $fref_trim->($input);
       } else {
            $fref_trim->(\$input);
       }
   }
}
</code>```

Result:

```<code>name: [foo]
sn: [foosu]
</code>```

I would expect $name to be "[   foo    ]" when printing the value after calling trim, but the sub is setting $name as I would want it. Why is this working, when it really shouldn't?

I'm not passing $name by reference and the trim sub is not returning anything. I'd expect the trim sub to create a copy of the $name value, process the copy, but then the original $name would still have the leading and trailing white spaces when printed in the main code.

I assume it is because of the alias with @_, but shouldn't the foreach my $input (@_) force the sub to copy the value and only treat the value not the alias?

I know I can simplify this sub and I used it only as an example.

答:
Elements of @_ are aliases to the original variables. What you are observing is the difference between:

```<code>sub ltrim {
    $_[0] =~ s/^\s+//;
    return $_[0];
}
</code>```

and

```<code>sub ltrim {
    my ($s) = @_;
    $s =~ s/^\s+//;
    return $s;
}
</code>```

Compare your code to:

```<code>#!/usr/bin/env perl

my $name = "   foo    ";
my $sn   = "     foosu";

trim($name, \$sn);

print "name: [$name]\n";
print "sn: [$sn]\n";

sub trim {
    my @args = @_;

    my $fref_trim = sub{
        my ($ref_input) = @_;
        ${$ref_input} =~ s/^\s+//;
        ${$ref_input} =~ s/\s+\z//;
    };

   for my $input (@args) {
       if (ref($input) eq "SCALAR") {
           $fref_trim->($input);
       }
       else {
           $fref_trim->(\$input);
       }
   }
}
</code>```

Output:

$ ./zz.pl
name: [   foo    ]
sn: [foosu]
```
<p>Note also that the loop variable in <code>for my $input ( @array )</code> does not create a new copy for each element of the array. See <code>perldoc perlsyn</code>:</p>
<blockquote>
<p>The <code>foreach</code> loop iterates over a normal list value and sets the scalar variable <code>VAR</code> to be each element of the list in turn. ...</p>
<p>...</p>
<p>the <code>foreach</code> loop index variable is an implicit alias for each item in the list that you're looping over.</p>
</blockquote>
<p>In your case, this would mean that, at each iteration <code>$input</code> is an alias to the corresponding element of <code>@_</code> which itself is an alias to the variable that was passed in as an argument to the subroutine.</p>
<p>Making a copy of <code>@_</code> thus prevents the variables in the calling context from being modified. Of course, you could do something like:</p>
```sub trim {
    my $fref_trim = sub{
        my ($ref_input) = @_;
        ${$ref_input} =~ s/^\s+//;
        ${$ref_input} =~ s/\s+\z//;
    };

   for my $input (@_) {
       my $input_copy = $input;
       if (ref($input_copy) eq "SCALAR") {
           $fref_trim->($input_copy);
       }
       else {
           $fref_trim->(\$input_copy);
       }
   }
}
```

but I find making a wholesale copy of @_ once to be clearer and more efficient assuming you do not want to be selective.

Title: Perl unexpected result

Body:
Imagine I have this Perl script

my $name = "   foo    ";
my $sn   = "     foosu";

trim($name, \$sn);

print "name: [$name]\n";
print "sn: [$sn]\n";
exit 0;

sub trim{

   my $fref_trim = sub{
                          my ($ref_input) = @_;
                          ${$ref_input} =~ s/^\s+// ;
                          ${$ref_input} =~ s/\s+$// ;
    };

   foreach my $input (@_){
       if (ref($input) eq "SCALAR"){
            $fref_trim->($input);
       } else {
            $fref_trim->(\$input);
       }
   }
}

Result:

name: [foo]
sn: [foosu]

I would expect $name to be "[   foo    ]" when printing the value after calling trim, but the sub is setting $name as I would want it. Why is this working, when it really shouldn't?

I'm not passing $name by reference and the trim sub is not returning anything. I'd expect the trim sub to create a copy of the $name value, process the copy, but then the original $name would still have the leading and trailing white spaces when printed in the main code.

I assume it is because of the alias with @_, but shouldn't the foreach my $input (@_) force the sub to copy the value and only treat the value not the alias?

I know I can simplify this sub and I used it only as an example.

Body:
Elements of @_ are aliases to the original variables. What you are observing is the difference between:

sub ltrim {
    $_[0] =~ s/^\s+//;
    return $_[0];
}

and

sub ltrim {
    my ($s) = @_;
    $s =~ s/^\s+//;
    return $s;
}

Compare your code to:

#!/usr/bin/env perl

my $name = "   foo    ";
my $sn   = "     foosu";

trim($name, \$sn);

print "name: [$name]\n";
print "sn: [$sn]\n";

sub trim {
    my @args = @_;

    my $fref_trim = sub{
        my ($ref_input) = @_;
        ${$ref_input} =~ s/^\s+//;
        ${$ref_input} =~ s/\s+\z//;
    };

   for my $input (@args) {
       if (ref($input) eq "SCALAR") {
           $fref_trim->($input);
       }
       else {
           $fref_trim->(\$input);
       }
   }
}

Output:

$ ./zz.pl
name: [   foo    ]
sn: [foosu]

Note also that the loop variable in for my $input ( @array ) does not create a new copy for each element of the array. See perldoc perlsyn:

The foreach loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn. ...

...

the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

In your case, this would mean that, at each iteration $input is an alias to the corresponding element of @_ which itself is an alias to the variable that was passed in as an argument to the subroutine.

Making a copy of @_ thus prevents the variables in the calling context from being modified. Of course, you could do something like:

sub trim {
    my $fref_trim = sub{
        my ($ref_input) = @_;
        ${$ref_input} =~ s/^\s+//;
        ${$ref_input} =~ s/\s+\z//;
    };

   for my $input (@_) {
       my $input_copy = $input;
       if (ref($input_copy) eq "SCALAR") {
           $fref_trim->($input_copy);
       }
       else {
           $fref_trim->(\$input_copy);
       }
   }
}

but I find making a wholesale copy of @_ once to be clearer and more efficient assuming you do not want to be selective.


问:
How to change the size of a popover
I'm having trouble changing the size of my popover presentation. Here is what I have so far

```<code> override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) // func for popover
{
    if segue.identifier == "popoverView"
    {
        let vc = segue.destinationViewController

        let controller = vc.popoverPresentationController

        if controller != nil
        {
            controller?.delegate = self
            controller?.sourceView = self.view
            controller?.sourceRect = CGRect(x:CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds),width: 315,height: 230)
            controller?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
        }
    }
}
</code>```

So far all this does is center the popover and remove the arrow, which is good. but it doesn't resize the container.  any help would be greatly appreciated. thank you.

when I use preferredContentSize I get the error "Cannot assign to property: 'preferredContentSize' is immutable"

答:
I fixed it via storyboard :
Click on your controller
Click on Attribute inspector
ViewController>
Check Use Preferred Explicit size and input values.

Title: How to change the size of a popover

Body:
I'm having trouble changing the size of my popover presentation. Here is what I have so far

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) // func for popover
{
    if segue.identifier == "popoverView"
    {
        let vc = segue.destinationViewController

        let controller = vc.popoverPresentationController

        if controller != nil
        {
            controller?.delegate = self
            controller?.sourceView = self.view
            controller?.sourceRect = CGRect(x:CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds),width: 315,height: 230)
            controller?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
        }
    }
}

So far all this does is center the popover and remove the arrow, which is good. but it doesn't resize the container.  any help would be greatly appreciated. thank you.

when I use preferredContentSize I get the error "Cannot assign to property: 'preferredContentSize' is immutable"

ContentLicense: CC BY-SA 4.0


问:
While first index is an array?
I can tell I'm falling through my while loop, from frame 3 to 4.

Am I not checking the condition in my while loop correctly?

```<code>function steamrollArray(arr) {
  var R2 = [];
  while (arr[0].isArray) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}

steamrollArray([[["a"]], [["b"]]]); // should return ["a", "b"].
steamrollArray([1, [2], [3, [[4]]]]); // should return [1, 2, 3, 4].
steamrollArray([1, [], [3, [[4]]]]); // should return [1, 3, 4].
steamrollArray([1, {}, [3, [[4]]]]); // should return [1, {}, 3, 4].
</code>```

Step 3 to 4

答:
isArray is a method of Array - Array.isArray

```<code>function steamrollArray(arr) {
  var R2 = [];
  while (Array.isArray(arr[0])) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}
</code>```

Title: While first index is an array?

Body:
I can tell I'm falling through my while loop, from frame 3 to 4.

Am I not checking the condition in my while loop correctly?

function steamrollArray(arr) {
  var R2 = [];
  while (arr[0].isArray) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}

steamrollArray([[["a"]], [["b"]]]); // should return ["a", "b"].
steamrollArray([1, [2], [3, [[4]]]]); // should return [1, 2, 3, 4].
steamrollArray([1, [], [3, [[4]]]]); // should return [1, 3, 4].
steamrollArray([1, {}, [3, [[4]]]]); // should return [1, {}, 3, 4].

Step 3 to 4

Body:
isArray is a method of Array - Array.isArray

function steamrollArray(arr) {
  var R2 = [];
  while (Array.isArray(arr[0])) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}


问:
Remove Fancytree Dotted Border
I've got what I think is a basic question, but I can't seem to figure out/find the answer...

I'm looking to use the Fancytree plugin, and am wondering if someone can tell me how I can get rid of the dotted gray border line that shows up around the whole tree?

You can see what I mean in this Plunker

```<code><body>
<h1>Fancytree Demo</h1>
<button id="button1">Test</button>
<hr>
<div id="tree"></div>
</body>
</code>```

and for some reason it's NOT visible in this Fiddle

```<code><div id="tree"></div>
<div id="statusLine">-</div>
<p><button id="button1">Select item2</button></p>
</code>```

I've tried different things, but I can't seem to get rid of it. Anyone have an idea I can try, or point me at what I'm overlooking?

Thanks!

答:
You can modify the styling of the fancytree border by setting css properties of the ul.fancytree-container declaration:

```<code>ul.fancytree-container {
    border: none;
}
</code>```

This JSFiddle has an updated example without the dotted border.

Title: Remove Fancytree Dotted Border

Body:
I've got what I think is a basic question, but I can't seem to figure out/find the answer...

I'm looking to use the Fancytree plugin, and am wondering if someone can tell me how I can get rid of the dotted gray border line that shows up around the whole tree?

You can see what I mean in this Plunker

Fancytree Demo

<button id="button1">Test</button>

and for some reason it's NOT visible in this Fiddle

-

<button id="button1">Select item2</button>

I've tried different things, but I can't seem to get rid of it. Anyone have an idea I can try, or point me at what I'm overlooking?

Thanks!

Body:
You can modify the styling of the fancytree border by setting css properties of the ul.fancytree-container declaration:

ul.fancytree-container {
    border: none;
}

This JSFiddle has an updated example without the dotted border.


问:
UnicodeDecodeError When Opening a tar File in Python 3
I'm using Linux Mint 18.1 and Python 3.5.2.

I have a library that currently works using Python 2.7.  I need to use the library for a Python 3 project.  I'm updating it and have run into a unicode problem that I can't seem to fix.

First, a file is created via tar cvjf tarfile.tbz2 (on a Linux system) and is later opened in the Python library as open(tarfile).

If I run the code as is, using Python 3, I get the following error:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 11: invalid start byte
</code>```

My first attempt at a fix was to open it as open(tarfile, encoding='utf-8') as I was under the impression that tar would just use what the file system gave it.  When I do this, I get the same error (the byte value changes).

If I try with another encoding, say latin-1, I get the following error:

```<code>TypeError: Unicode-objects must be encoded before hashing
</code>```

Which leads me to believe that utf-8 is correct, but I might be misunderstanding.

Can anyone provide suggestions?

答:
I was going down the wrong path thinking this was some strange encoding problem.  When it was just a simple problem with that fact that open() defaults to read as text (r).  In Python 2 it's a no-op.

The fix is to open(tarfile, 'rb').

The head fake with unicode...should have seen this one coming.  :facepalm:

Body:
I'm using Linux Mint 18.1 and Python 3.5.2.

I have a library that currently works using Python 2.7.  I need to use the library for a Python 3 project.  I'm updating it and have run into a unicode problem that I can't seem to fix.

First, a file is created via tar cvjf tarfile.tbz2 (on a Linux system) and is later opened in the Python library as open(tarfile).

If I run the code as is, using Python 3, I get the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 11: invalid start byte

My first attempt at a fix was to open it as open(tarfile, encoding='utf-8') as I was under the impression that tar would just use what the file system gave it.  When I do this, I get the same error (the byte value changes).

If I try with another encoding, say latin-1, I get the following error:

TypeError: Unicode-objects must be encoded before hashing

Which leads me to believe that utf-8 is correct, but I might be misunderstanding.

Can anyone provide suggestions?


问:
How to limit class animations to clicked elements and their content
I know this question has been asked and answered, but here is a slightly more complicated situation. I have a list of cards, all set to animate once clicked. Of course the animation is created by using the toggleClass() command and the initial problem was that if i Clicked one card, all of them animated. This was easily fixed by using the $(this) statement. However, I then decided to add content to the cards, that would display only once the card is clicked. I thought this would be affected by the $(this) statement too, but it is not and now when I click a card, that card animates but the content of other cards is displayed too.

$(".card").click(function() {
  $(this).toggleClass("transform-active");
  $(".disappear").toggleClass("appear");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* CARDS SECTION */

.cards {
  display: block;
  position: absolute;
  width: 100%;
  top: 60px;
  list-style: none;
  text-decoration: none;
  z-index: -1;
}

.cards li {
  display: block;
  position: relative;
  width: 100%;
  padding-bottom: 10px;
}

.card {
  position: relative;
  background-color: #ffffff;
  height: 150px;
  width: 100%;
  left: -5%;
  border-radius: 8px;
  box-shadow: 2px 2px 2px #686868;
  cursor: pointer;
}

/* CARDS CONTENT SECTION */

#containText {
  position: absolute;
  width: 76%;
  color: #58a7dd;
  top: -2px;
  left: 90px;
  text-align: justify;
}

#containText p {
  position: absolute;
  top: 30px;
}

.face {
  position: relative;
  height: 70px;
  width: 70px;
  top: 10px;
  left: 10px;
  border: solid #58a7dd;
  background-color: white;
  border-radius: 50%;
  color: #58a7dd;
}

.face h2 {
  position: relative;
  left: 3px;
  top: 20px;
  transform: rotate(90deg);
}

.extra {
  position: relative;
  width: 90%;
  top: 7px;
  margin: auto;
  color: #2f4f4f;
}

.disappear {
  position: relative;
  width: 90%;
  height: 40%;
  top: 5px;
  margin: auto;
  color: #2f4f4f;
  opacity: 0;
}

.appear {
  animation: appear 1.2s ease;
  animation-fill-mode: forwards;
}

@keyframes appear {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.transform {
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -o-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

.transform-active {
  background-color: #ffffff;
  height: 300px;
  width: 100%;
  box-shadow: 6px 6px 6px #888888;
}</code>```

: )

HI! I am a card.

Click me to trigger the animation.

Here is some extra info about the items on this card, such as stuff, things and blah.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

TWO

THREE

FOUR

FIVE

SIX

```

CodePen with working example: https://codepen.io/BGGrieco/pen/PjOevR

答:
That is because you are asking all the .disappear elements to .appear.

```<code>$(".disappear").toggleClass("appear");
</code>```

You are not specifying in any way that you want the div.disappear within this to toggleClass('appear').

Try this instead:

```<code>$(this).children('.disappear').toggleClass('appear');
</code>```

Body:
I know this question has been asked and answered, but here is a slightly more complicated situation. I have a list of cards, all set to animate once clicked. Of course the animation is created by using the toggleClass() command and the initial problem was that if i Clicked one card, all of them animated. This was easily fixed by using the $(this) statement. However, I then decided to add content to the cards, that would display only once the card is clicked. I thought this would be affected by the $(this) statement too, but it is not and now when I click a card, that card animates but the content of other cards is displayed too.

$(".card").click(function() {
  $(this).toggleClass("transform-active");
  $(".disappear").toggleClass("appear");
});

/* CARDS SECTION */

.cards {
  display: block;
  position: absolute;
  width: 100%;
  top: 60px;
  list-style: none;
  text-decoration: none;
  z-index: -1;
}

.cards li {
  display: block;
  position: relative;
  width: 100%;
  padding-bottom: 10px;
}

.card {
  position: relative;
  background-color: #ffffff;
  height: 150px;
  width: 100%;
  left: -5%;
  border-radius: 8px;
  box-shadow: 2px 2px 2px #686868;
  cursor: pointer;
}

/* CARDS CONTENT SECTION */

#containText {
  position: absolute;
  width: 76%;
  color: #58a7dd;
  top: -2px;
  left: 90px;
  text-align: justify;
}

#containText p {
  position: absolute;
  top: 30px;
}

.face {
  position: relative;
  height: 70px;
  width: 70px;
  top: 10px;
  left: 10px;
  border: solid #58a7dd;
  background-color: white;
  border-radius: 50%;
  color: #58a7dd;
}

.face h2 {
  position: relative;
  left: 3px;
  top: 20px;
  transform: rotate(90deg);
}

.extra {
  position: relative;
  width: 90%;
  top: 7px;
  margin: auto;
  color: #2f4f4f;
}

.disappear {
  position: relative;
  width: 90%;
  height: 40%;
  top: 5px;
  margin: auto;
  color: #2f4f4f;
  opacity: 0;
}

.appear {
  animation: appear 1.2s ease;
  animation-fill-mode: forwards;
}

@keyframes appear {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.transform {
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -o-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

.transform-active {
  background-color: #ffffff;
  height: 300px;
  width: 100%;
  box-shadow: 6px 6px 6px #888888;
}

: )

HI! I am a card.

Click me to trigger the animation.

Here is some extra info about the items on this card, such as stuff, things and blah.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

TWO

THREE

FOUR

FIVE

SIX

CodePen with working example: https://codepen.io/BGGrieco/pen/PjOevR

Body:
That is because you are asking all the .disappear elements to .appear.

$(".disappear").toggleClass("appear");

You are not specifying in any way that you want the div.disappear within this to toggleClass('appear').

Try this instead:

$(this).children('.disappear').toggleClass('appear');


问:
What is the canonical way to control the closing of goroutine if one goroutine is complete?
I have a slice of struct that defines a task, each task is run in a goroutine, and I want all go goroutines to stop whenever the first one complete a task via the signal task.signalComplete

Currently I have the following.

```<code>for _, task := range taskList {
    go func(task *myTask, firstCompleteSignal chan<- bool) {
        for {
            select {
                // When the task completes, it emit signalComplete
                case <-task.signalComplete:
                    firstCompleteSignal<-true
                    return
            }
        }

    }(task, firstCompleteSignal)
}

for {
    select {
    case <-firstCompleteSignal:
        // manually stop all go thread
        return
    }
}
</code>```

Is this canonical?

Or is there library to do this for me like sync.WaitGroup for waiting all goroutine to be done?

答:
The common idiom is to have a Done channel shared between the calling code and the goroutines.

Then each goroutine would check that channel via a select each time they
send a new value to the calling code.

You can find a good example in Go's blog:

https://blog.golang.org/pipelines

(look for "Explicit Cancellation" there)

Later, they incorporated a context package to the standard library, and that is now the most "standard" way to manage cancellation of goroutines.

You can find a good example in the documentation for the package itself:

https://golang.org/pkg/context/#example_WithCancel

Body:
I have a slice of struct that defines a task, each task is run in a goroutine, and I want all go goroutines to stop whenever the first one complete a task via the signal task.signalComplete

Currently I have the following.

for _, task := range taskList {
    go func(task *myTask, firstCompleteSignal chan<- bool) {
        for {
            select {
                // When the task completes, it emit signalComplete
                case <-task.signalComplete:
                    firstCompleteSignal<-true
                    return
            }
        }

    }(task, firstCompleteSignal)
}

for {
    select {
    case <-firstCompleteSignal:
        // manually stop all go thread
        return
    }
}

Is this canonical?

Or is there library to do this for me like sync.WaitGroup for waiting all goroutine to be done?


问:
Select rows by partial string with query with pandas
I have a DataFrame. 1 column (name) has string values. I was wondering if there was a way to select rows based on a partial string match against a particular column, using the DataFrame.query() method.

I tried:

df.query('name.str.contains("lu")'). Error message: "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

df.query('"lu" in name'). Returns an empty DataFrame.

The code I use:

```<code>import pandas as pd

df = pd.DataFrame({
    'name':['blue','red','blue'],
    'X1':[96.32,96.01,96.05]
}, columns=['name','X1'])

print(df.query('"lu" in name').head())
print(df.query('name.str.contains("lu")').head())
</code>```

I know I could use df[df['name'].str.contains("lu")] but I prefer to use
query.

答:
This answer is out of date. Please check @petobens' answer.

As of version 0.20.2, query doesn't support partial string matching. There is an open future request about it and one of the core developers seems to agree that it would be a nice addition.

Body:
I have a DataFrame. 1 column (name) has string values. I was wondering if there was a way to select rows based on a partial string match against a particular column, using the DataFrame.query() method.

I tried:

df.query('name.str.contains("lu")'). Error message: "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

df.query('"lu" in name'). Returns an empty DataFrame.

The code I use:

import pandas as pd

df = pd.DataFrame({
    'name':['blue','red','blue'],
    'X1':[96.32,96.01,96.05]
}, columns=['name','X1'])

print(df.query('"lu" in name').head())
print(df.query('name.str.contains("lu")').head())

I know I could use df[df['name'].str.contains("lu")] but I prefer to use
query.


问:
YUI "Saved" notification
I'm trying to create a short term overlay notification for an app I'm working on. I also happen to be completely constrained to using YUI as my only script library. The goal is to make a YUI-styled notification appear over the page following a post wherein the form was saved. I would use the simpledialog, but the client doesn't want to have to interact with the notification, and they don't want any buttons or controls on it whatsoever, just a featureless, styled box that displays a message.

The effect I'm trying to pull off right now is to produce something similar to jQuery's showGlobalMessage function. So, are there any YUI controls capable of doing this? and if not, what would be the best way, using self-written js, to produce this effect?

Thanks for the help.

答: I ended up just writing in a javascript setTimeout function to hide a simpledialog. Not quite as elegant as I'd like...but it works.</p>

Title: YUI "Saved" notification


问:
Python - making a function library but says my functions are not defined in the secondary file
I want to make a user made function library filled with custom functions to use in other codes without having to write all the code and just importing the file, i have defined a function called hello() which prints hello, however when  i try to call it in my secondary file it say the hello() is not defined.

'python library.py'

```<code>def hello():
     print("Hello")
</code>```

'library test.py'

```<code>myfile = open('python library.py', 'a')

hello()
</code>```

答:
The open() command is for opening a file as text to read from or write to (principally). Your 'a' is saying you want to append text to the file `'python library.py'

One option to do what you want is to use import to get your functions from the file.

from file import function

in your case

```<code>from python library import hello
#NOTE the .py is left off
hello()
</code>```

If you have multiple functions to import, you can do import * instead of import function. Though I am not sure if this will work having a space in your filename, so if it gives an error, my first suggestion would be to rename your file using an underscore or something so that it's all one word.

More info: How to call a function from another file in Python?

Body:
I want to make a user made function library filled with custom functions to use in other codes without having to write all the code and just importing the file, i have defined a function called hello() which prints hello, however when  i try to call it in my secondary file it say the hello() is not defined.

'python library.py'

def hello():
     print("Hello")

'library test.py'

myfile = open('python library.py', 'a')

hello()

Body:
The open() command is for opening a file as text to read from or write to (principally). Your 'a' is saying you want to append text to the file `'python library.py'

One option to do what you want is to use import to get your functions from the file.

from file import function

in your case

from python library import hello
#NOTE the .py is left off
hello()

If you have multiple functions to import, you can do import * instead of import function. Though I am not sure if this will work having a space in your filename, so if it gives an error, my first suggestion would be to rename your file using an underscore or something so that it's all one word.

More info: How to call a function from another file in Python?


问:
How to configure Nginx with Passenger to process 500 requests/sec
I am hosting ruby application but it gives errors (some kind of error 500) while processing more than 400 requests per second. Test (loader.io) with lower amount of requests (below 400 request) finishes with good results.
I think I could have better results while processing 500 requests/second and more.

The app is using t2.2xlarge ec2 instance (with 32Gb of memory, 8 virtual cores). I guess it might give better performance. The machine is running on Ubuntu 14.04, Rails 4.0.12, Nginx with Passenger.

I tried to make some changes in Nginx configuration but without any big progress.
My current configuration:

```<code>passenger_max_pool_size 60;
#passenger_pool_idle_time 20;
server {
  listen 80;
  return 301 https://mydomain.eu$request_uri;
}

server {
  listen 443;
  server_name ~^(\w+)\.mydomain.eu$;
  return 301 https://mydomain.eu$request_uri;
}
server {
  listen 443 ssl spdy default;
  server_name mydomain.eu;
  passenger_enabled on;
  #passenger_max_pool_size 12;
  passenger_max_request_queue_size 2000;
  gzip on;

  root /home/ubuntu/application/cversion/public;

  ssl                  on;
  ssl_certificate      /home/ubuntu/fvhsdvhfd35/ssl-bundle1.crt;
  ssl_certificate_key  /home/ubuntu/fvhsdvhfd35/prvt.key;
  ssl_session_timeout  5m;
  ssl_protocols        TLSv1 TLSv1.1 TLSv1.2 SSLv3;
  ssl_ciphers          "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
  ssl_prefer_server_ciphers  on;

  location = /favicon.png {
    expires    max;
    add_header Cache-Control public;
  }

  location = /ZeroClipboard.swf {
    expires    max;
    add_header Cache-Control public;
  }

  location ~ ^/(assets)/  {
    gzip_static on;
    expires     max;
    add_header  Cache-Control public;
  }

  # disable gzip on all omniauth paths to prevent BREACH
  location ~ ^/auth/ {
    gzip off;
    passenger_enabled on;
  }
</code>```

Do you have any idea how to get more than 400 request per second?

here is a log of Nginx with Passenger while processing 500 requests(with passenger_max_pool_size 30; and passenger_max_request_queue_size 1200;)

```<code>2017/07/06 01:58:32 [error] 11749#11749: *56391 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.89.44.6, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11740#11740: *64104 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.87.219.148, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11749#11749: *64251 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.87.219.148, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11749#11749: *63289 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.89.44.6, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *67786 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *35057 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *35166 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11744#11744: *43208 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11744#11744: *69130 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.162.105.71, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
[ 2017-07-06 01:58:34.3865 11703/7fc703fff700 Ser/AcceptLoadBalancer.h:150 ]: Resuming accepting new clients
</code>```

UPDATE

I got a solution.
These changes of Nginx Configuration gave me 1000 request/second performance.

At first I put:

```<code>"65536" in /proc/sys/net/core/somaxconn
"65536" in /proc/sys/net/ipv4/tcp_max_syn_backlog
</code>```

/etc/nginx/conf.d/m.conf:

```<code>    passenger_max_pool_size 90;
    passenger_socket_backlog 16384;

    #in server block
    #was listen 443 ssl spdy default;
    listen 443 ssl spdy default backlog=16384;
    passenger_max_request_queue_size 2300;
    ssl_session_cache shared:SSL:10m;
</code>```

/etc/nginx/nginx.conf:

```<code>worker_rlimit_nofile 131072;

#in events block:
use epoll;
worker_connections 8192;
</code>```

Another question

Average response time is about 6seconds for 1000 requests per second during 1 minute of tests. Any ideas how to improve average response time for this amount of requests?

UPDATE2

I change my Nginx config to enable Nginx Microcashing according to this blog, but I've got no better performance. 500 req/second gave me 5.1sec as average response time. About 900 req/sec - 5.5sec. However without caching I have 2.5sec for 500 requests and 5.6 sec for 900 requests.

/etc/nginx/nginx.conf:

```<code>    ...
    http {
      ...
      proxy_cache_path /tmp/cache keys_zone=one:10m levels=1:2 inactive=600s max_size=100m;
      ...
    }
</code>```

/etc/nginx/conf.d/m.conf:

}

```<code>passenger_max_pool_size 90;
#passenger_pool_idle_time 20;
passenger_socket_backlog 16384;
server {
  listen 80;
  return 301 https://mydomain.eu$request_uri;
}

server {
  listen 443;
  server_name ~^(\w+)\.mydomain.eu$;
  return 301 https://mydomain.eu$request_uri;
}
server {
  listen 443 ssl spdy default backlog=16384;
  server_name mydomain.eu;

  ssl                  on;
  ssl_certificate      /home/ubuntu/fvhsdvhfd35/ssl-bundle1.crt;
  ssl_certificate_key  /home/ubuntu/fvhsdvhfd35/prvt.key;
  ssl_session_timeout  5m;
  ssl_protocols        TLSv1 TLSv1.1 TLSv1.2 SSLv3;
  ssl_ciphers          "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
  ssl_prefer_server_ciphers  on;

  ssl_session_cache shared:SSL:10m;

  location / {

    proxy_http_version 1.1; # Always upgrade to HTTP/1.1
    proxy_set_header Connection ""; # Enable keepalives
    proxy_set_header Accept-Encoding ""; # Optimize encoding
    proxy_pass http://127.0.0.1:81/;

    proxy_cache one;
    proxy_cache_lock on;
    proxy_cache_valid 200 1s;
    proxy_cache_use_stale updating;
  }
}
server {

  listen 81;
  server_name mydomain.eu;
  passenger_enabled on;

  passenger_max_request_queue_size 2300;
  gzip on;

  root /home/ubuntu/application/cversion/public;

  location = /favicon.png {
    expires    max;
    add_header Cache-Control public;
  }

  location = /ZeroClipboard.swf {
    expires    max;
    add_header Cache-Control public;
  }

  location ~ ^/(assets)/  {
    gzip_static on;
    expires     max;
    add_header  Cache-Control public;
  }

  # disable gzip on all omniauth paths to prevent BREACH
  location ~ ^/auth/ {
    gzip off;
    passenger_enabled on;
  }

}
</code>```

答: For making these optimizations make sure you refer the link nginx blog and do consider the response time for each request (minimise it as much as you can using rails techniques). Also consider your database optimizations i.e using the right indexes and maximum number of database connections concurrently. As it is a multi level problem and configurations must be made at each level for best performance. Good luck :)</p>

Body:
I am hosting ruby application but it gives errors (some kind of error 500) while processing more than 400 requests per second. Test (loader.io) with lower amount of requests (below 400 request) finishes with good results.
I think I could have better results while processing 500 requests/second and more.

The app is using t2.2xlarge ec2 instance (with 32Gb of memory, 8 virtual cores). I guess it might give better performance. The machine is running on Ubuntu 14.04, Rails 4.0.12, Nginx with Passenger.

I tried to make some changes in Nginx configuration but without any big progress.
My current configuration:

passenger_max_pool_size 60;
#passenger_pool_idle_time 20;
server {
  listen 80;
  return 301 https://mydomain.eu$request_uri;
}

server {
  listen 443;
  server_name ~^(\w+)\.mydomain.eu$;
  return 301 https://mydomain.eu$request_uri;
}
server {
  listen 443 ssl spdy default;
  server_name mydomain.eu;
  passenger_enabled on;
  #passenger_max_pool_size 12;
  passenger_max_request_queue_size 2000;
  gzip on;

  root /home/ubuntu/application/cversion/public;

  ssl                  on;
  ssl_certificate      /home/ubuntu/fvhsdvhfd35/ssl-bundle1.crt;
  ssl_certificate_key  /home/ubuntu/fvhsdvhfd35/prvt.key;
  ssl_session_timeout  5m;
  ssl_protocols        TLSv1 TLSv1.1 TLSv1.2 SSLv3;
  ssl_ciphers          "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
  ssl_prefer_server_ciphers  on;

  location = /favicon.png {
    expires    max;
    add_header Cache-Control public;
  }

  location = /ZeroClipboard.swf {
    expires    max;
    add_header Cache-Control public;
  }

  location ~ ^/(assets)/  {
    gzip_static on;
    expires     max;
    add_header  Cache-Control public;
  }

  # disable gzip on all omniauth paths to prevent BREACH
  location ~ ^/auth/ {
    gzip off;
    passenger_enabled on;
  }

Do you have any idea how to get more than 400 request per second?

here is a log of Nginx with Passenger while processing 500 requests(with passenger_max_pool_size 30; and passenger_max_request_queue_size 1200;)

2017/07/06 01:58:32 [error] 11749#11749: *56391 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.89.44.6, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11740#11740: *64104 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.87.219.148, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11749#11749: *64251 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.87.219.148, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11749#11749: *63289 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.89.44.6, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *67786 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *35057 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *35166 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11744#11744: *43208 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11744#11744: *69130 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.162.105.71, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
[ 2017-07-06 01:58:34.3865 11703/7fc703fff700 Ser/AcceptLoadBalancer.h:150 ]: Resuming accepting new clients

UPDATE

I got a solution.
These changes of Nginx Configuration gave me 1000 request/second performance.

At first I put:

"65536" in /proc/sys/net/core/somaxconn
"65536" in /proc/sys/net/ipv4/tcp_max_syn_backlog

/etc/nginx/conf.d/m.conf:

    passenger_max_pool_size 90;
    passenger_socket_backlog 16384;

    #in server block
    #was listen 443 ssl spdy default;
    listen 443 ssl spdy default backlog=16384;
    passenger_max_request_queue_size 2300;
    ssl_session_cache shared:SSL:10m;

/etc/nginx/nginx.conf:

worker_rlimit_nofile 131072;

#in events block:
use epoll;
worker_connections 8192;

Another question

Average response time is about 6seconds for 1000 requests per second during 1 minute of tests. Any ideas how to improve average response time for this amount of requests?

UPDATE2

I change my Nginx config to enable Nginx Microcashing according to this blog, but I've got no better performance. 500 req/second gave me 5.1sec as average response time. About 900 req/sec - 5.5sec. However without caching I have 2.5sec for 500 requests and 5.6 sec for 900 requests.

/etc/nginx/nginx.conf:

    ...
    http {
      ...
      proxy_cache_path /tmp/cache keys_zone=one:10m levels=1:2 inactive=600s max_size=100m;
      ...
    }

/etc/nginx/conf.d/m.conf:

}

passenger_max_pool_size 90;
#passenger_pool_idle_time 20;
passenger_socket_backlog 16384;
server {
  listen 80;
  return 301 https://mydomain.eu$request_uri;
}

server {
  listen 443;
  server_name ~^(\w+)\.mydomain.eu$;
  return 301 https://mydomain.eu$request_uri;
}
server {
  listen 443 ssl spdy default backlog=16384;
  server_name mydomain.eu;

  ssl                  on;
  ssl_certificate      /home/ubuntu/fvhsdvhfd35/ssl-bundle1.crt;
  ssl_certificate_key  /home/ubuntu/fvhsdvhfd35/prvt.key;
  ssl_session_timeout  5m;
  ssl_protocols        TLSv1 TLSv1.1 TLSv1.2 SSLv3;
  ssl_ciphers          "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
  ssl_prefer_server_ciphers  on;

  ssl_session_cache shared:SSL:10m;

  location / {

    proxy_http_version 1.1; # Always upgrade to HTTP/1.1
    proxy_set_header Connection ""; # Enable keepalives
    proxy_set_header Accept-Encoding ""; # Optimize encoding
    proxy_pass http://127.0.0.1:81/;

    proxy_cache one;
    proxy_cache_lock on;
    proxy_cache_valid 200 1s;
    proxy_cache_use_stale updating;
  }
}
server {

  listen 81;
  server_name mydomain.eu;
  passenger_enabled on;

  passenger_max_request_queue_size 2300;
  gzip on;

  root /home/ubuntu/application/cversion/public;

  location = /favicon.png {
    expires    max;
    add_header Cache-Control public;
  }

  location = /ZeroClipboard.swf {
    expires    max;
    add_header Cache-Control public;
  }

  location ~ ^/(assets)/  {
    gzip_static on;
    expires     max;
    add_header  Cache-Control public;
  }

  # disable gzip on all omniauth paths to prevent BREACH
  location ~ ^/auth/ {
    gzip off;
    passenger_enabled on;
  }

}


问:
Drawing graphics in ExtJs
First off I want to point out that I'm very new to the ExtJs library. I want to create an image through the use of some drawing/canvas API. The image I want to create is similar to the below image.

I'm wondering if this is possible through javascript/Extjs because I haven't been able to find anything online that makes this clear. If you can think of a different kind of approach I would appreciate that as well.

答:
I don't know of a canvas API for Ext. But you can easily use the canvas API with Ext. I fiddled it.

Markup:

```<code><canvas id="c1"></canvas>
</code>```

JavaScript:

```<code>Ext.onReady(function() {
    draw(document.getElementById('c1'));
});

function draw(el) {
    var canvas = el;
    var ctx = canvas.getContext("2d");
    ctx.strokeRect(0, 0, 50, 200);
    for(var y = 10; y < 200; y += 10){
        ctx.moveTo(0, y);
        ctx.lineTo(25, y);
    }
    ctx.stroke();
    ctx.closePath();
}
</code>```

Title: Drawing graphics in ExtJs

Body:
I don't know of a canvas API for Ext. But you can easily use the canvas API with Ext. I fiddled it.

Markup:

<canvas id="c1"></canvas>

JavaScript:

Ext.onReady(function() {
    draw(document.getElementById('c1'));
});

function draw(el) {
    var canvas = el;
    var ctx = canvas.getContext("2d");
    ctx.strokeRect(0, 0, 50, 200);
    for(var y = 10; y < 200; y += 10){
        ctx.moveTo(0, y);
        ctx.lineTo(25, y);
    }
    ctx.stroke();
    ctx.closePath();
}


问:
OneSignal ID for the same user on different platforms
First, thanks for baring with my question as well haha. Secondly.. I'm having a dilemma.

I have an app, based on Firebase, which runs on iOS / Android and Web. It basically is a chat like Facebook's messenger.

I am successfully using OneSignal for the iOS version... ( this was the first platform developed ). The issue arose when I started developing the web platform.. as per user, there is a OneSignalId generated upon registration. Issue with that is, how do I link the same account on different platforms, meaning, on iOS, say I have OneSignalId -- 1.

When I connect to the web version with an account that already exists, from a browser which is not known by OneSignal yet, I'm getting a new OneSignalId .. and that's not desired.

Is it possible to connect the OneSignalId that I already have, to the browser ?
Thanks for baring with me. I've also asked them on Intercom ( their live support ) but nobody replied as of yet.

I also don't seem to find anything inside SO or in their Docs.
Have a great evening!

答:
Each user that accesses your app or site from a different device or browser profile will get a new OneSignal playerID (unique across all OneSignal Apps).

To avoid sending notifications to the same user subscribed on multiple platforms with different Player IDs, you will need to tag the user with a unique identifier that you track in your own database and have it relate to that user's playerIDs.

https://documentation.onesignal.com/docs/internal-database-crm

So if I log into your site or app from multiple devices, you can tag me with the UUID that you use on your system and send notifications based on that tag.

If you are using user-to-user notifications within the app, you will also need to track the playerIDs of the users because you can only target users within the app with the "include_player_ids" parameter.

For further questions please email support@onesignal.com

Thanks


答:
you are using isArray wrong. It is a method, that takes an input and checks if it is an array.

```<code>function steamrollArray(arr) {
  var R2 = [];

  while (Array.isArray(arr[0])) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}
</code>```

Title: While first index is an array?

Body:
you are using isArray wrong. It is a method, that takes an input and checks if it is an array.

function steamrollArray(arr) {
  var R2 = [];

  while (Array.isArray(arr[0])) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}


问:
Replacement for collapseItemsRecursively and expandItemsRecursively in Vaadin 8.1 TreeGrid
Vaadin 8.1 introduced the TreeGrid component. It does not have the collapseItemsRecursively and expandItemsRecursively methods anymore (as available in the now legacy Tree component). Do i miss something or do you need to develop your own implementation? If so, what is a recommended way of doing this?

答:
From the docs for treegrid, you can use the methods, collapse and expand, by passing a list or array of the treegrid's data items to expand or collapse:

```<code>treeGrid.expand(someTreeGridItem1, someTreeGridItem2);
treeGrid.collapse(someTreeGridItem1);
</code>```

Also worthy of note, is a section showing the ability to prevent certain items from ever being collapsed

Body:
From the docs for treegrid, you can use the methods, collapse and expand, by passing a list or array of the treegrid's data items to expand or collapse:

treeGrid.expand(someTreeGridItem1, someTreeGridItem2);
treeGrid.collapse(someTreeGridItem1);

Also worthy of note, is a section showing the ability to prevent certain items from ever being collapsed


问:
fread() with dataset when there's missing column
I am using fread() to get data like this:

```<code>fread(data, select = c("col1", "col2", "missing", "col3"))
</code>```

where column with the name of "missing" doesn't exist. fread() will automatically drop "missing" column and return dataset like this:

```<code>col1   col2   col3
a      b      c
d      e      f
</code>```

...

I am wondering if there is a way to change the result to:

```<code>col1   col2   missing  col3
a      b      NA       c
d      e      NA       f
</code>```

答:
This question is tagged with data.table and fread but has attracted a base R answer. Therefore, I felt obliged to post a data.table solution.

The OP wants to add a particular column at a specific place inside a data.table where this column appears to be missing. The OP seems to expect that the select parameter to fread() could be used for that purpose but fread() does print a

Warning message:

In fread("col1   col2   col3 \na      b      c\nd    e      f",  :

Column name 'missing' not found in column name header (case sensitive), skipping.

So the missing column has to be added afterwards:

```<code>library(data.table)

# add column by reference
DT[, missing := NA][]
</code>```

```<code>   col1 col2 col3 missing
1:    a    b    c      NA
2:    d    e    f      NA
</code>```

```<code># rearrange column order
setcolorder(DT, c("col1", "col2", "missing", "col3"))[]
</code>```

```<code>   col1 col2 missing col3
1:    a    b      NA    c
2:    d    e      NA    f
</code>```

Note that data.table excutes both operations by reference, i.e., it is not required to copy the whole object in order to add a single column or to change an attribute.

Data

```<code>library(data.table)
DT <- fread(
"col1   col2   col3
a      b      c
d      e      f",
select = c("col1", "col2", "missing", "col3"))
</code>```

Body:
I am using fread() to get data like this:

fread(data, select = c("col1", "col2", "missing", "col3"))

where column with the name of "missing" doesn't exist. fread() will automatically drop "missing" column and return dataset like this:

col1   col2   col3
a      b      c
d      e      f

...

I am wondering if there is a way to change the result to:

col1   col2   missing  col3
a      b      NA       c
d      e      NA       f

Body:
This question is tagged with data.table and fread but has attracted a base R answer. Therefore, I felt obliged to post a data.table solution.

The OP wants to add a particular column at a specific place inside a data.table where this column appears to be missing. The OP seems to expect that the select parameter to fread() could be used for that purpose but fread() does print a

Warning message:

In fread("col1   col2   col3 \na      b      c\nd    e      f",  :

Column name 'missing' not found in column name header (case sensitive), skipping.

So the missing column has to be added afterwards:

library(data.table)

# add column by reference
DT[, missing := NA][]

   col1 col2 col3 missing
1:    a    b    c      NA
2:    d    e    f      NA

# rearrange column order
setcolorder(DT, c("col1", "col2", "missing", "col3"))[]

   col1 col2 missing col3
1:    a    b      NA    c
2:    d    e      NA    f

Note that data.table excutes both operations by reference, i.e., it is not required to copy the whole object in order to add a single column or to change an attribute.

Data

library(data.table)
DT <- fread(
"col1   col2   col3
a      b      c
d      e      f",
select = c("col1", "col2", "missing", "col3"))


问:
insert in url paratmeters using javascript
i have a url something like:

```<code>http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=abc123
</code>```

or

```<code>http://somewhere.com/dir/?parameter1=123123&parameter2=abcabc&parameter3=abc123
</code>```

and some variables including:

```<code>var alpha = aaa;
var num = 111;
var alphanum= aaa123;
</code>```

i want to add these variables by by one into url every url parameters using javascript (or jQuery) , so that i have:

```<code>http://somewhere.com/dir/parameter1=aaa&parameter2=abcabc&parameter3=abc123
http://somewhere.com/dir/parameter1=111&parameter2=abcabc&parameter3=abc123
http://somewhere.com/dir/parameter1=aaa123&parameter2=abcabc&parameter3=abc123
</code>```

and for next parameter:

```<code>http://somewhere.com/dir/parameter1=123123&parameter2=aaa&parameter3=abc123
http://somewhere.com/dir/parameter1=123123&parameter2=111&parameter3=abc123
http://somewhere.com/dir/parameter1=123123&parameter2=aaa123&parameter3=abc123
</code>```

and the last one

```<code>http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=aaa
http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=111
http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=aaa123
</code>```

how can i do it ?
thanks.

答:
To access a variable in jQuery we use $(YOUR_VARIABLE_NAME) for example $(alpha) will output aaa
So here's the code needed to set up this URL:

```<code>var alpha = aaa;
var num = 111;
var alphanum= aaa123;

var url = "http://somewhere.com/dir/?parameter1=" + $(alpha) + "&parameter2=" + $(num) + "&parameter3=" + $(alphanum);
</code>```

Now you could use the URL variable where you want to put the full URL such as:

```<code>alert($(url));
</code>```

And the output will be:

```<code>http://somewhere.com/dir/?parameter1=aaa&parameter2=111&parameter3=aaa123
</code>```

Body:
i have a url something like:

http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=abc123

or

http://somewhere.com/dir/?parameter1=123123&parameter2=abcabc&parameter3=abc123

and some variables including:

var alpha = aaa;
var num = 111;
var alphanum= aaa123;

i want to add these variables by by one into url every url parameters using javascript (or jQuery) , so that i have:

http://somewhere.com/dir/parameter1=aaa&parameter2=abcabc&parameter3=abc123
http://somewhere.com/dir/parameter1=111&parameter2=abcabc&parameter3=abc123
http://somewhere.com/dir/parameter1=aaa123&parameter2=abcabc&parameter3=abc123

and for next parameter:

http://somewhere.com/dir/parameter1=123123&parameter2=aaa&parameter3=abc123
http://somewhere.com/dir/parameter1=123123&parameter2=111&parameter3=abc123
http://somewhere.com/dir/parameter1=123123&parameter2=aaa123&parameter3=abc123

and the last one

http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=aaa
http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=111
http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=aaa123

how can i do it ?
thanks.

Body:
To access a variable in jQuery we use $(YOUR_VARIABLE_NAME) for example $(alpha) will output aaa
So here's the code needed to set up this URL:

var alpha = aaa;
var num = 111;
var alphanum= aaa123;

var url = "http://somewhere.com/dir/?parameter1=" + $(alpha) + "&parameter2=" + $(num) + "&parameter3=" + $(alphanum);

Now you could use the URL variable where you want to put the full URL such as:

alert($(url));

And the output will be:

http://somewhere.com/dir/?parameter1=aaa&parameter2=111&parameter3=aaa123


问:
Printing Out File Names that are Different
My code below works and the logic works. However, I want to print out the names of the actual files that are not the same in both folders, which are held in the arrays of fileNames1 and fileNames2. I have been searching for the answer with no solution. I am just getting back into the groove with Java after being away form it a while. Any help would be appreciated.

```<code>import java.io.File;
import java.util.ArrayList;

public class nameCompare {

    public static void main(String[] args) {

        String path1 = "C:/Users/hoflerj/Desktop/test";
        String path2 = "C:/Users/hoflerj/Desktop/test2";

        File folder1 = new File(path1);
        File folder2 = new File(path2);

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        ArrayList<String> fileNames1 = new ArrayList<String>();
        ArrayList<String> fileNames2 = new ArrayList<String>();

        for (int i = 0; i < listOfFiles1.length; i++)
        {

            if (listOfFiles1[i].isFile())
            {
                fileNames1.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {

            if (listOfFiles2[i].isFile())
            {
                fileNames2.add(listOfFiles2[i].getName());//seriously wow
            }
        }

        for ( int i = 0; i < 1; i++ )
        {
            if (fileNames1.equals(fileNames2) )
            {
                System.out.println("Files names are the same");
            }

            else if (fileNames1 != fileNames2 )
            {
                System.out.println("Files names are not equal");
            }
        }

    }

}
</code>```

答:
The simplest and elegant way to do this is:</p>

```<code>    List<String> commonFiles= new ArrayList<String>(fileNames1);
    commonFiles.retainAll(fileNames2);

    Set<String> uniqueFiles = new HashSet<String>(fileNames1);
    uniqueFiles.addAll(fileNames2);
    uniqueFiles.removeAll(commonFiles);
</code>```

Body:
My code below works and the logic works. However, I want to print out the names of the actual files that are not the same in both folders, which are held in the arrays of fileNames1 and fileNames2. I have been searching for the answer with no solution. I am just getting back into the groove with Java after being away form it a while. Any help would be appreciated.

import java.io.File;
import java.util.ArrayList;

public class nameCompare {

    public static void main(String[] args) {

        String path1 = "C:/Users/hoflerj/Desktop/test";
        String path2 = "C:/Users/hoflerj/Desktop/test2";

        File folder1 = new File(path1);
        File folder2 = new File(path2);

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        ArrayList<String> fileNames1 = new ArrayList<String>();
        ArrayList<String> fileNames2 = new ArrayList<String>();

        for (int i = 0; i < listOfFiles1.length; i++)
        {

            if (listOfFiles1[i].isFile())
            {
                fileNames1.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {

            if (listOfFiles2[i].isFile())
            {
                fileNames2.add(listOfFiles2[i].getName());//seriously wow
            }
        }

        for ( int i = 0; i < 1; i++ )
        {
            if (fileNames1.equals(fileNames2) )
            {
                System.out.println("Files names are the same");
            }

            else if (fileNames1 != fileNames2 )
            {
                System.out.println("Files names are not equal");
            }
        }

    }

}

Body:
The simplest and elegant way to do this is:

    List<String> commonFiles= new ArrayList<String>(fileNames1);
    commonFiles.retainAll(fileNames2);

    Set<String> uniqueFiles = new HashSet<String>(fileNames1);
    uniqueFiles.addAll(fileNames2);
    uniqueFiles.removeAll(commonFiles);


问:
CSS and JQuery not working?
So the CSS on my site doesn't seem to be working, at least the updates I made. I want to create a height transition effect with the css transition property and the JQuery.css property but my applied changes aren't working on my site.</p>

```<code>.blog{
    transition: 1500ms ease-in-out !important;
    width: 100%;
    height: 0% !important;
    background-color: #8394EB;
    margin: 0;
    padding: 10px 40px;
    color: white !important;
}

$('.blog').css('height','100%');
</code>```

答: try using “height” = “100%” in your jquery if that don’t work just do document.querySelector(“.blog”).style.height = “100%”</p>

Title: CSS and JQuery not working?

Body:
So the CSS on my site doesn't seem to be working, at least the updates I made. I want to create a height transition effect with the css transition property and the JQuery.css property but my applied changes aren't working on my site.

.blog{
    transition: 1500ms ease-in-out !important;
    width: 100%;
    height: 0% !important;
    background-color: #8394EB;
    margin: 0;
    padding: 10px 40px;
    color: white !important;
}

$('.blog').css('height','100%');


问:
Ruby I/O Existence Issues
I have a decent amount of knowledge about Ruby code, but I do have an issue with my current project. I use Gosu to make 2D games (and once I figure out how, simple 3D games), so I need a resolution.

And this is where my question comes in, why does Ruby keep giving me an error when seeing if the settings file exists? I've been trying to get it working with the file not existing, which keeps giving me the error, "'initialize': No such file or directory @ rb_sysopen - ./settings.set (Errno::ENOENT)" which has been annoying me for the last few days. The file gives no issues and actually works as intended when I leave the file created, but I want it to be where if the file gets deleted off of someone's computer, it rebuilds the file and creates a new one using default values.

Here's the area that it keeps crashing at:

```<code>settings = []

settings_file_existance = File.file?("settings.set")

if settings_file_existance == true

  File.open("settings.set").readlines.each do |line|
    settings.push line
  end

else

  settings_file = File.open("settings.set")
  settings_file.write "800"
  settings_file.write "\n"
  settings_file.write "600"
  settings_file.close

end
</code>```

I have tried looking for fixes on this site, along with many others, but no one so far has been able to help.

答:
You could try this:

```<code>settings = []

if File.file?("settings.set")
  settings = File.read("settings.set").split("\n")
else
  File.open("settings.set", "w") do |file|
    file.write "800\n600"
  end
end
</code>```

As a side note, consider that the above code will set settings only if settings.set file exits, otherwise it will remain in an empty array (i.e. []).

If you wish to avoid that, just define settings with the default values, for example:

```<code>settings = [800, 600]
</code>```

Now if settings.set file doesn't exist, then settings will be [800, 600], otherwise it will be overwritten with the values from settings.set.

To avoid writing 800 and 600 twice, you could use settings variable to get the values to be written in the new file, for example:

```<code>file.write(settings.join("\n"))
</code>```

Putting it all together, your code would look like this:

```<code>settings = [800, 600]

if File.file?("settings.set")
  settings = File.read("settings.set").split("\n")
else
  File.open("settings.set", "w") do |file|
    file.write(settings.join("\n"))
  end
end
</code>```

Title: Ruby I/O Existence Issues

Body:
I have a decent amount of knowledge about Ruby code, but I do have an issue with my current project. I use Gosu to make 2D games (and once I figure out how, simple 3D games), so I need a resolution.

And this is where my question comes in, why does Ruby keep giving me an error when seeing if the settings file exists? I've been trying to get it working with the file not existing, which keeps giving me the error, "'initialize': No such file or directory @ rb_sysopen - ./settings.set (Errno::ENOENT)" which has been annoying me for the last few days. The file gives no issues and actually works as intended when I leave the file created, but I want it to be where if the file gets deleted off of someone's computer, it rebuilds the file and creates a new one using default values.

Here's the area that it keeps crashing at:

settings = []

settings_file_existance = File.file?("settings.set")

if settings_file_existance == true

  File.open("settings.set").readlines.each do |line|
    settings.push line
  end

else

  settings_file = File.open("settings.set")
  settings_file.write "800"
  settings_file.write "\n"
  settings_file.write "600"
  settings_file.close

end

I have tried looking for fixes on this site, along with many others, but no one so far has been able to help.

Body:
You could try this:

settings = []

if File.file?("settings.set")
  settings = File.read("settings.set").split("\n")
else
  File.open("settings.set", "w") do |file|
    file.write "800\n600"
  end
end

As a side note, consider that the above code will set settings only if settings.set file exits, otherwise it will remain in an empty array (i.e. []).

If you wish to avoid that, just define settings with the default values, for example:

settings = [800, 600]

Now if settings.set file doesn't exist, then settings will be [800, 600], otherwise it will be overwritten with the values from settings.set.

To avoid writing 800 and 600 twice, you could use settings variable to get the values to be written in the new file, for example:

file.write(settings.join("\n"))

Putting it all together, your code would look like this:

settings = [800, 600]

if File.file?("settings.set")
  settings = File.read("settings.set").split("\n")
else
  File.open("settings.set", "w") do |file|
    file.write(settings.join("\n"))
  end
end


问:
Split to multiple lines in Spotfire
I have a dataset including the 3 years data from Google Analytics, I have a hard time to split the date into 3 different lines to display on Spotfire like the following pic.

答:
Well your X axis is a date, making this a linear visualization. It seems like you are trying to compare years by month. In that case, keep the color by year option that you have currently, but change the X axis from your date column to Month([DateColumn])

Another option would be to Trellis by year.

If you want to format the X as you have above, insert a calculated column and use this new column on the X axis:

```<code>Date(Year([DateColumn]),Month([DateColumn]),01) as [NewColumn]
</code>```

This builds a date column based off the YEAR and MONTHfrom your [DateColumn] and forces the DAY part to 01.

Title: Split to multiple lines in Spotfire

Body:
Well your X axis is a date, making this a linear visualization. It seems like you are trying to compare years by month. In that case, keep the color by year option that you have currently, but change the X axis from your date column to Month([DateColumn])

Another option would be to Trellis by year.

If you want to format the X as you have above, insert a calculated column and use this new column on the X axis:

Date(Year([DateColumn]),Month([DateColumn]),01) as [NewColumn]

This builds a date column based off the YEAR and MONTHfrom your [DateColumn] and forces the DAY part to 01.


问:
Add code into JS with button click
So I have these buttons that when pressed play a sound, and I wanted to make a button that when pressed would allow these sounds to loop. I dont know how to explain this correctly, so ill just show the code

```<code>function aud1play() {
  aud1.src = "aud1.mp3";
  aud1.play();
}
document.getElementById('aud1button').addEventListener('click', aud1play);

function aud2play() {
  aud2.src = "aud2.mp3";
  aud2.play();
}
document.getElementById('aud2button').addEventListener('click', aud2play);

function aud3play() {
  aud3.src = "aud3.mp3";
  aud3.play();
}
document.getElementById('aud3button').addEventListener('click', aud3play);
</code>```

is there a way to take the names (aud1, aud2, aud3) and put (name).loop; under each of the functions with a button press without having to actually write the (name).loop; for every one?

答:
You could do something like this:

```<code>// create an object containing all audio objects
var audios = (function () {
  var names = ['aud1.mp3', 'aud2.mp3', 'aud3.mp3'];
  var audios = {};

  for (var index in names) {
    var audio = audios[names[index]] = new Audio();
    audio.src = names[index];
  }

  return audios;
})();

function toggleAudioPlay () {
  // "this" refers to the button that was clicked
  var name = this.getAttribute('data-audio-src'); // read the button's "data-audio-src" attribute
  if (!audios.hasOwnProperty(name)) {
    // audio doesn't exist
    return;
  }
  var audio = audios[name];
  audio.src = name;
  // toggle the play state
  if (audio.paused) {
    audio.play();
  } else {
    audio.pause();
  }
}

function toggleAudioLoop () {
  var name = this.getAttribute('data-audio-src');
  if (!audios.hasOwnProperty(name)) {
    // audio doesn't exist
    return;
  }
  var audio = audios[name];
  audio.loop = !audio.loop;
}

document.querySelector('.audio-button-toggle-play').forEach(function (button) {
  button.addEventListener('click', toggleAudioPlay);
});

document.querySelector('.audio-button-toggle-loop').forEach(function (button) {
  button.addEventListener('click', toggleAudioLoop);
});
</code>```

Now, you could have the following HTML:

```<code><button class="audio-button-toggle-play" data-audio-src="aud1.mp3">Play/Pause the first audio</button>
<button class="audio-button-toggle-play" data-audio-src="aud2.mp3">Play/Pause the second audio</button>
<button class="audio-button-toggle-play" data-audio-src="aud3.mp3">Play/Pause the third audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud1.mp3">Enable/Disable looping of the first audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud2.mp3">Enable/Disable looping of the second audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud3.mp3">Enable/Disable looping of the third audio</button>
</code>```

That way, you don't have to create a new function for each audio. Just add a new audio file to the "names" array and add a button with a special class (audio-button-toggle-play in order to toggle the play state of an audio) and a data-audio-src attribute containing the location of the audio file.

Title: Add code into JS with button click

Body:
So I have these buttons that when pressed play a sound, and I wanted to make a button that when pressed would allow these sounds to loop. I dont know how to explain this correctly, so ill just show the code

function aud1play() {
  aud1.src = "aud1.mp3";
  aud1.play();
}
document.getElementById('aud1button').addEventListener('click', aud1play);

function aud2play() {
  aud2.src = "aud2.mp3";
  aud2.play();
}
document.getElementById('aud2button').addEventListener('click', aud2play);

function aud3play() {
  aud3.src = "aud3.mp3";
  aud3.play();
}
document.getElementById('aud3button').addEventListener('click', aud3play);

is there a way to take the names (aud1, aud2, aud3) and put (name).loop; under each of the functions with a button press without having to actually write the (name).loop; for every one?

Body:
You could do something like this:

// create an object containing all audio objects
var audios = (function () {
  var names = ['aud1.mp3', 'aud2.mp3', 'aud3.mp3'];
  var audios = {};

  for (var index in names) {
    var audio = audios[names[index]] = new Audio();
    audio.src = names[index];
  }

  return audios;
})();

function toggleAudioPlay () {
  // "this" refers to the button that was clicked
  var name = this.getAttribute('data-audio-src'); // read the button's "data-audio-src" attribute
  if (!audios.hasOwnProperty(name)) {
    // audio doesn't exist
    return;
  }
  var audio = audios[name];
  audio.src = name;
  // toggle the play state
  if (audio.paused) {
    audio.play();
  } else {
    audio.pause();
  }
}

function toggleAudioLoop () {
  var name = this.getAttribute('data-audio-src');
  if (!audios.hasOwnProperty(name)) {
    // audio doesn't exist
    return;
  }
  var audio = audios[name];
  audio.loop = !audio.loop;
}

document.querySelector('.audio-button-toggle-play').forEach(function (button) {
  button.addEventListener('click', toggleAudioPlay);
});

document.querySelector('.audio-button-toggle-loop').forEach(function (button) {
  button.addEventListener('click', toggleAudioLoop);
});

Now, you could have the following HTML:

<button class="audio-button-toggle-play" data-audio-src="aud1.mp3">Play/Pause the first audio</button>
<button class="audio-button-toggle-play" data-audio-src="aud2.mp3">Play/Pause the second audio</button>
<button class="audio-button-toggle-play" data-audio-src="aud3.mp3">Play/Pause the third audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud1.mp3">Enable/Disable looping of the first audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud2.mp3">Enable/Disable looping of the second audio</button>
<button class="audio-button-toggle-loop" data-audio-src="aud3.mp3">Enable/Disable looping of the third audio</button>

That way, you don't have to create a new function for each audio. Just add a new audio file to the "names" array and add a button with a special class (audio-button-toggle-play in order to toggle the play state of an audio) and a data-audio-src attribute containing the location of the audio file.


问:
Ice connection state , Completed vs Connected
Can someone please clarify the difference between iceConnectionstate:completed vs iceConnectionstate:connected.

When I connect to browsers with webrtc I am able to exchange data using datachannel but for some reason the the iceConnectionstate on browser that made the offer reaming completed wheres the browser that accepted the offers changes to connected.

Any idea if this is normal?

答:
In short:

connected: Found a working candidate pair, but still performing connectivity checks to find a better one.

completed: Found a working candidate pair and done performing connectivity checks.

For most purposes, you can probably treat the connected/completed states as the same thing.

Note that, as mentioned by Ajay, there are some notable difference between how the standard defines the states and how they're implemented in Chrome. The main ones that come to mind:

There's no "end-of-candidates" signaling, so none of those parts of the candidate state definitions are implemented. This means if a remote candidate arrives late, it's possible to go from  "completed" back to "connected" without an ICE restart. Though I assume this is rare in practice.

The ICE state is actually a combination ICE+DTLS state (see: https://bugs.chromium.org/p/webrtc/issues/detail?id=6145). This is because it was implemented before there was such thing as "RTCPeerConnectionState". This can lead to confusion if there's actually a DTLS-level issue, since the only way to really notice is to look in a native Chrome log.

We definitely plan on fixing all the discrepancies. But for a while we held off on it because the standard was still in flux. And right now our priority is more on implementing unified plan SDP and the RtpSender/RtpReceiver APIs.


问:
Mongodump getting blank folders
I am trying to run this command from a remote ssh

```<code>mongodump --host mongodb1.example.net --port 27017 --username user --password pass --out /opt/backup/mongodump-2013-10-24
</code>```

However, all I am getting is blank folders for each collections.

What am I doing wrong?

Info (if it matters):
Source Mongodb is on Windows Server
And SSH is of a remote Ubuntu Machine

Here is the terminal output:

```<code>connected to: ip.ip.ip.ip:27017
Thu Feb 18 00:46:01.757 all dbs
Thu Feb 18 00:46:01.809 DATABASE: admin  to     /opt/backup/mongodump-2013-10-24/admin
Thu Feb 18 00:46:01.903 DATABASE: anthony_data       to     /opt/backup/mongodump-2013-10-24/anthony_data
Thu Feb 18 00:46:02.004 DATABASE: temp_data  to     /opt/backup/mongodump-2013-10-24/temp_data
Thu Feb 18 00:46:02.104 DATABASE: zoomy   to     /opt/backup/mongodump-2013-10-24/zoomy
</code>```

So it creates empty folder for all collections. But there is no bson in it

答:
I was using the default mongodb-client deb package with Ubuntu. I removed those and installed the mongodb-org-tools package from mongodb.com https://docs.mongodb.com/master/tutorial/install-mongodb-on-ubuntu/?_ga=2.36209632.1945690590.1499275806-1594815486.1499275806

They have other install instructions for your specific OS if you are not on Ubuntu https://www.mongodb.com/download-center?jmp=nav#community

Title: Mongodump getting blank folders

Body:
I am trying to run this command from a remote ssh

mongodump --host mongodb1.example.net --port 27017 --username user --password pass --out /opt/backup/mongodump-2013-10-24

However, all I am getting is blank folders for each collections.

What am I doing wrong?

Info (if it matters):
Source Mongodb is on Windows Server
And SSH is of a remote Ubuntu Machine

Here is the terminal output:

connected to: ip.ip.ip.ip:27017
Thu Feb 18 00:46:01.757 all dbs
Thu Feb 18 00:46:01.809 DATABASE: admin  to     /opt/backup/mongodump-2013-10-24/admin
Thu Feb 18 00:46:01.903 DATABASE: anthony_data       to     /opt/backup/mongodump-2013-10-24/anthony_data
Thu Feb 18 00:46:02.004 DATABASE: temp_data  to     /opt/backup/mongodump-2013-10-24/temp_data
Thu Feb 18 00:46:02.104 DATABASE: zoomy   to     /opt/backup/mongodump-2013-10-24/zoomy

So it creates empty folder for all collections. But there is no bson in it