问:
formtastic - subset of values in accepts_nested_attributes_for
I have a model:

```<code>class Contact < ActiveRecord::Base
  has_many :phones
  accepts_nested_attributes_for :phones
end
</code>```

I want to build 50 phone #s that users can add (there may already be phones 1 or 5, but I always want 50 available)
In my controller:

```<code>while contact.phones.length < 50
  contact.phones.build({:phone_type_id => PhoneType['a_cool_type'].id})
end
</code>```

In my view, I want to have 2 columns of phone #s 25 rows each

```<code> <%= semantic_form_for contact do |form| %>
   <table width=50%>
   <%= form.inputs :for => :phones[0..25] do |phone_form| %>
      <td align="center"><%= phone_form.input :number, :label => false %></td>
       ....
   <% end %>
   </table>
   <table width=50%>
   <%= form.inputs :for => :phones[25..49] do |phone_form| %>
      <td align="center"><%= phone_form.input :number, :label => false %></td>
       ....
   <% end %>
   </table>
<%end %>
</code>```

Obviously the line:

```<code><%= form.inputs :for => :phones[25..49] do |phone_form| %>
</code>```

doesn't work, but it conveys my intention ( I hope).  I want to have more control over how formtastic grabs the underlying object association.

The following works, but I can't do two columns easily without fancy css.

```<code><%= form.inputs :for => :phones do |phone_form| %>
</code>```

Any suggestions?

---------- Update ----

I was able to get around this in a roundabout way:
I built up a separate list of phone #s not as contact.phones.build, but Phone.new(:contact_id => contact.id) and store those in a list called @new_phones

Then my form looks like this:

```<code><%= semantic_form_for @contact, :url => ..., do |f| %>
   <% @new_phones[0...25].each_with_index do |phone, i| %>
      <%= f.fields_for :phones, phone, :child_index => i do |phone_form| %>
         <%= render "phone_fields", {:phone_form => phone_form, :phone => phone} %>
      <%end%>
    <% end %>
   ....
   <% @new_phones[25...50].each_with_index do |phone, i| %>
        <%= f.fields_for :phones, phone, :child_index => i+25 do |phone_form| %>
        <%= render "phone_fields", {:phone_form => phone_form, :phone => phone} %>
    <%end%>
  <% end %>
<%end%>
</code>```

This allowed me to display 25 phones on one part of the page, and 25 on another, with nested_attributes_for :phones working as expected on form submit.

答:
I've always had problems with getting nested attributes working as I want but this may help resolve your issue.

Model:

```<code>class Contact < ActiveRecord::Base
  has_many :phones
  accepts_nested_attributes_for :phones
end
</code>```

Controller:
See we're looping @contract.phones.build 50 times, this creates 50 new instances.

```<code>class Contact < ApplicationController
  def new
    @contact = Contact.new
    25.times do
      @contact.phones.build
    end

  end
end
</code>```

View new.html.erb :

```<code>...
<%= p.semantic_fields_for :phones do |ec| %>
  <%= ec.input :number %>
<% end %>
...
</code>```

I did try a few attempts to intercept the loop, sadly with no definite clean avail.

Body:
I have a model:

class Contact < ActiveRecord::Base
  has_many :phones
  accepts_nested_attributes_for :phones
end

I want to build 50 phone #s that users can add (there may already be phones 1 or 5, but I always want 50 available)
In my controller:

while contact.phones.length < 50
  contact.phones.build({:phone_type_id => PhoneType['a_cool_type'].id})
end

In my view, I want to have 2 columns of phone #s 25 rows each

 <%= semantic_form_for contact do |form| %>

   <%= form.inputs :for => :phones[0..25] do |phone_form| %>
      <%= phone_form.input :number, :label => false %>
       ....
   <% end %>

   <%= form.inputs :for => :phones[25..49] do |phone_form| %>
      <%= phone_form.input :number, :label => false %>
       ....
   <% end %>

<%end %>

Obviously the line:

<%= form.inputs :for => :phones[25..49] do |phone_form| %>

doesn't work, but it conveys my intention ( I hope).  I want to have more control over how formtastic grabs the underlying object association.

The following works, but I can't do two columns easily without fancy css.

<%= form.inputs :for => :phones do |phone_form| %>

Any suggestions?

---------- Update ----

I was able to get around this in a roundabout way:
I built up a separate list of phone #s not as contact.phones.build, but Phone.new(:contact_id => contact.id) and store those in a list called @new_phones

Then my form looks like this:

<%= semantic_form_for @contact, :url => ..., do |f| %>
   <% @new_phones[0...25].each_with_index do |phone, i| %>
      <%= f.fields_for :phones, phone, :child_index => i do |phone_form| %>
         <%= render "phone_fields", {:phone_form => phone_form, :phone => phone} %>
      <%end%>
    <% end %>
   ....
   <% @new_phones[25...50].each_with_index do |phone, i| %>
        <%= f.fields_for :phones, phone, :child_index => i+25 do |phone_form| %>
        <%= render "phone_fields", {:phone_form => phone_form, :phone => phone} %>
    <%end%>
  <% end %>
<%end%>

This allowed me to display 25 phones on one part of the page, and 25 on another, with nested_attributes_for :phones working as expected on form submit.

Body:
I've always had problems with getting nested attributes working as I want but this may help resolve your issue.

Model:

class Contact < ActiveRecord::Base
  has_many :phones
  accepts_nested_attributes_for :phones
end

Controller:
See we're looping @contract.phones.build 50 times, this creates 50 new instances.

class Contact < ApplicationController
  def new
    @contact = Contact.new
    25.times do
      @contact.phones.build
    end

  end
end

View new.html.erb :

...
<%= p.semantic_fields_for :phones do |ec| %>
  <%= ec.input :number %>
<% end %>
...

I did try a few attempts to intercept the loop, sadly with no definite clean avail.


来源: stackexchange

问:
save array of object contain image in my iOS app
I want to save array of users , every user has name ,phone ,image and video , what is the best way to do that ?</p>

答:
I'd have a photo URL and a video URL instead of media. Those URLs can be references from your server or database. A Sample code could be:</p>

```<code>class User {

    var name: String?
    var phone: Int?
    var photoUrl: String?
    var videoUrl: String?

    init(name: String, phone: Int, photoUrl: String, videoUrl: String) {

        self.name = name
        self.phone = phone
        self.photoUrl = photoUrl
        self.videoUrl = videoUrl
    }
}

var users = [User]()

let user1 = User(name: "Something", phone: 123456, photoUrl: "SomeUrl", videoUrl: "SomeUrl")
let user2 = User(name: "Something", phone: 123456987, photoUrl: "SomeUrl", videoUrl: "SomeUrl")

users.append(user1)
users.append(user2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'd have a photo URL and a video URL instead of media. Those URLs can be references from your server or database. A Sample code could be:

class User {

    var name: String?
    var phone: Int?
    var photoUrl: String?
    var videoUrl: String?

    init(name: String, phone: Int, photoUrl: String, videoUrl: String) {

        self.name = name
        self.phone = phone
        self.photoUrl = photoUrl
        self.videoUrl = videoUrl
    }
}

var users = [User]()

let user1 = User(name: "Something", phone: 123456, photoUrl: "SomeUrl", videoUrl: "SomeUrl")
let user2 = User(name: "Something", phone: 123456987, photoUrl: "SomeUrl", videoUrl: "SomeUrl")

users.append(user1)
users.append(user2)


问:
Sort a list by a custom order
I have an array of some types

```<code>private string[] linkTypes = {
    "dog",
    "cat",
    // and so on ..
};
</code>```

Yes, I could use an enum but in this case it has to be an array of
  strings.

So now I have a List of objects called "LinkElement"

```<code>private List<LinkElement> links = new List<LinkElement>();
</code>```

and these objects have a string property called "Type"

```<code>string linkType = links[index].Type;
</code>```

If linkTypes contains the elements "dog" and "cat", my links can only have "dog" or "cat" as their type.

I want to sort the list "links" by the order of linkTypes.

Means the lists order contains the links with having the type "dog" first and after that the links with the type "cat" come up.

```<code>List<LinkElement> sortedLinks = ; // sort links

for (int i = 0; i < sortedLinks.Count; i++)
{
    LinkElement currentLink = sortedLinks[i];
    Console.WriteLine(currentLink.Type);
}

// Write down dogs first, cats after
</code>```

Can someone help me out?

答:
Comparisons such as "alphabetical order" (string) "bigger number" (numerical types) etc. are accomplished using the IComparable interface.  You can implement this interface in your custom class to make instances sort themselves any way you like.  Read up on the interface here:

https://msdn.microsoft.com/en-us/library/4d7sx9hd(v=vs.110).aspx

If you have a fixed number of types, then you could use a quick helper method to return an integer for each object depending on its type, and compare the returned integers from each object to determine which one "comes first."

Title: Sort a list by a custom order

Body:
I have an array of some types

private string[] linkTypes = {
    "dog",
    "cat",
    // and so on ..
};

Yes, I could use an enum but in this case it has to be an array of
  strings.

So now I have a List of objects called "LinkElement"

private List<LinkElement> links = new List<LinkElement>();

and these objects have a string property called "Type"

string linkType = links[index].Type;

If linkTypes contains the elements "dog" and "cat", my links can only have "dog" or "cat" as their type.

I want to sort the list "links" by the order of linkTypes.

Means the lists order contains the links with having the type "dog" first and after that the links with the type "cat" come up.

List<LinkElement> sortedLinks = ; // sort links

for (int i = 0; i < sortedLinks.Count; i++)
{
    LinkElement currentLink = sortedLinks[i];
    Console.WriteLine(currentLink.Type);
}

// Write down dogs first, cats after

Can someone help me out?


问:
In Jade, how to pass parameters in the onclick function call
```<code>a(id='myLinkTag' onclick='myFunction(' + user._id + ')' href='') Delete
</code>```

Here user._id is the variable and trying to pass that value to myFunction .

syntaxError: Invalid or unexpected token

答:
Use differing nested quotation marks so that you pass a string to your function.</p>

```<code>a(id='myLinkTag' onclick="myFunction(' + user._id + ')" href='') Delete
</code>```

Body:
a(id='myLinkTag' onclick='myFunction(' + user._id + ')' href='') Delete

Here user._id is the variable and trying to pass that value to myFunction .

syntaxError: Invalid or unexpected token

Body:
Use differing nested quotation marks so that you pass a string to your function.

a(id='myLinkTag' onclick="myFunction(' + user._id + ')" href='') Delete


问:
bootstrap collapse does not animate when opened programmatically
I have a site with a bootstrap collapse in it.  I am trying to make it open programatically when the user selects a certain radio button, its working but the collapse does not animate in it just pops in.

The code I'm using is:

```<code>$("#RadioBtn").on('change', function(){
    $("#RadioCollapse").addClass('in');
})
</code>```

I suspect I may have to do something involving the collapsing class, but I try applying that class to the element and it didn't animate either.

答:
Just found bootstrap has its own built in function <code>.collapse();</code> so all I had to do was </p>

```<code>$("#RadioCollapse").collapse();
</code>```

Body:
I have a site with a bootstrap collapse in it.  I am trying to make it open programatically when the user selects a certain radio button, its working but the collapse does not animate in it just pops in.

The code I'm using is:

$("#RadioBtn").on('change', function(){
    $("#RadioCollapse").addClass('in');
})

I suspect I may have to do something involving the collapsing class, but I try applying that class to the element and it didn't animate either.

Body:
Just found bootstrap has its own built in function .collapse(); so all I had to do was

$("#RadioCollapse").collapse();


问:
Favicon to PNG in PHP
I need a PHP script to convert favicons to PNGs while keeping their original dimensions.

I know Google has it's secret icon converter - http://www.google.com/s2/favicons?domain=http://facebook.com/ but this converts favicons to 16x16 even if they they were originally larger. So basically I need this, minus the shrinking effect.

I've also seen this - http://www.controlstyle.com/articles/programming/text/php-favicon/ but I couldn't get it to work after hours of messing around with it.

Basically I am trying to automatically grab the icon for a link that will be as large as possible - automatically 48x48 png based on a URL would be the perfect scenario, but I don't know of any humanly possible way to do this given that no websites happen to keep a 48x48 icon in a publicly accessible spot.

Does anybody know of a script/service or have a suggestion? Thanks!

答:
So I ended up using a class called FloIcon that could convert BMPs to ICO. I should note that it's always important to check the file type of an icon and not assume that .ico means bmp because some sites (like Facebook) were actually PNG).

@goker.cebeci Your service looks awesome! The main thing is that I needed my icons to be the maximum size when possible, so I just wrote my own script.

ContentLicense: CC BY-SA 2.5

Title: Favicon to PNG in PHP


问:
How to listen on <select> change events in materialize css
A simple jquery listener on change doesn't seem to work when use a materialize css select dropdown.

```<code> $("#somedropdown").change(function() {
         alert("Element Changed");
      });
</code>```

1) How can I add a listener to detect when a materialize select element has changed?

2) How do I get the select value in that case?

答:
Add change event listener when you initialize material select</p>

```<code>$(document).ready(function(){
          $('#somedropdown').material_select(someScope.someEvent.bind(someScope));
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
A simple jquery listener on change doesn't seem to work when use a materialize css select dropdown.

 $("#somedropdown").change(function() {
         alert("Element Changed");
      });

1) How can I add a listener to detect when a materialize select element has changed?

2) How do I get the select value in that case?

Body:
Add change event listener when you initialize material select

$(document).ready(function(){
          $('#somedropdown').material_select(someScope.someEvent.bind(someScope));
});


问:
Excel: Applying functions to a range of ranges using multi-cell array-formula

Can you apply a builtin function that takes a range (e.g. AVERAGE()), and have it apply to a multiple ranges?

I'm currently finishing up a pretty basic data-analysis unit with a small Excel segment and I had a past assignment that involved analysing some housing data.

One task involved averaging and rounding the residential housing prices of a few cities for each time period.

The target data is in the worksheet Residential_Houses, formatted such that cities are columns and time periods are rows spanning: C7:J30. With the goal to have the averages of each row in the worksheet Analysis spanning C7:C30.

My simple solution was to write the formula:

```<code>=ROUND(AVERAGE(Residential_Houses!C7:J7), 2)
</code>```

Into Analysis!C7 and then used Excel's "AutoFill" feature to generate the formulae for Analysis!C8:C30. This worked fine, and the results were correct but I lost marks for not explicitly using cell array formula.

Instead the sample answer I was given was this monolithic line:

```<code>{=ROUND((Residential_Property!C7:C30+Residential_Property!D7:D30+Residential_Property!E7:E30+Residential_Property!F7:F30+Residential_Property!G7:G30+Residential_Property!H7:H30+Residential_Property!I7:I30+Residential_Property!J7:J30)/8,2)}
</code>```

It seems clear that the intent of this code is to take the average of columns C-J for each row 7-30, but it avoids using the AVERAGE() builtin. This works, but it's cumbersome, and wouldn't scale if there were more than a few columns in this test data.

The crux of my question here is how can you combine functions that already operate on ranges, with cell array formula to process multiple ranges with a single formula?

My intuition tells me it might be something like this:

```<code>{=AVERAGE((C7:J7):(C30:J30))}
</code>```

Or something involving indirect addressing, but I can't seem to find any detailed information on the topic. All of the array formula resources I've found so far have been limited to basic arithmetic and single dimension ranges. Could someone point me in the right direction here, or is this just not possible with array formula?

EDIT: For anyone who stumbles upon this in the future. I chose Barry's solution because it helped me understand how to generalise this concept (replacing the range with a function that can slice a range). But as Scott notes, OFFSET() is volatile; so INDEX() is a better way to do this if you're working with large datasets.

答:
Similar to Scott's suggestion, SUBTOTAL can process an array of ranges created by an OFFSET function, so with the first argument of SUBTOTAL as 1 (for AVERAGE) this formula will give an array of rounded averages for each row

=ROUND(SUBTOTAL(1,OFFSET(C7:J30,ROW(C7:J30)-ROW(C7),0,1)),2)

entered in a vertical range and confirmed with CTRL+SHIFT+ENTER

or you can use the same OFFSET inside an AVERAGE function like this:

=ROUND(AVERAGE(OFFSET(C7:J30,ROW(C7:J30)-ROW(C7),0,1)),2)

Body:
Can you apply a builtin function that takes a range (e.g. AVERAGE()), and have it apply to a multiple ranges?

I'm currently finishing up a pretty basic data-analysis unit with a small Excel segment and I had a past assignment that involved analysing some housing data.

One task involved averaging and rounding the residential housing prices of a few cities for each time period.

The target data is in the worksheet Residential_Houses, formatted such that cities are columns and time periods are rows spanning: C7:J30. With the goal to have the averages of each row in the worksheet Analysis spanning C7:C30.

My simple solution was to write the formula:

=ROUND(AVERAGE(Residential_Houses!C7:J7), 2)

Into Analysis!C7 and then used Excel's "AutoFill" feature to generate the formulae for Analysis!C8:C30. This worked fine, and the results were correct but I lost marks for not explicitly using cell array formula.

Instead the sample answer I was given was this monolithic line:

{=ROUND((Residential_Property!C7:C30+Residential_Property!D7:D30+Residential_Property!E7:E30+Residential_Property!F7:F30+Residential_Property!G7:G30+Residential_Property!H7:H30+Residential_Property!I7:I30+Residential_Property!J7:J30)/8,2)}

It seems clear that the intent of this code is to take the average of columns C-J for each row 7-30, but it avoids using the AVERAGE() builtin. This works, but it's cumbersome, and wouldn't scale if there were more than a few columns in this test data.

The crux of my question here is how can you combine functions that already operate on ranges, with cell array formula to process multiple ranges with a single formula?

My intuition tells me it might be something like this:

{=AVERAGE((C7:J7):(C30:J30))}

Or something involving indirect addressing, but I can't seem to find any detailed information on the topic. All of the array formula resources I've found so far have been limited to basic arithmetic and single dimension ranges. Could someone point me in the right direction here, or is this just not possible with array formula?

EDIT: For anyone who stumbles upon this in the future. I chose Barry's solution because it helped me understand how to generalise this concept (replacing the range with a function that can slice a range). But as Scott notes, OFFSET() is volatile; so INDEX() is a better way to do this if you're working with large datasets.


答:
Assuming linkTypes (the private string array) is in the same class as links (the list of LinkElement), you can use LINQ's OrderBy with a simple lambda expression:

```<code>var sortedLinks = links.OrderBy(le => Array.IndexOf(linkTypes, le.linkType)).ToList()
</code>```

Title: Sort a list by a custom order

Body:
Assuming linkTypes (the private string array) is in the same class as links (the list of LinkElement), you can use LINQ's OrderBy with a simple lambda expression:

var sortedLinks = links.OrderBy(le => Array.IndexOf(linkTypes, le.linkType)).ToList()


问:
Load jquery asynchronously before other scripts
I've added the async attrib to my javascript inclusion HTML.

So now I've:

```<code><script async src="jquery.myscript.js"></script>
</code>```

And this works with all JS I load, all except jquery.

If I add async to jQuery  instead of including an external file.js, but this doesn't change the situation.

I'd like to run jQuery with async attrib and run other few external scripts asynchronously only after jquery is loaded.

It is possible?

答:
Using a recursive function

I have written a function to do this job very nice.

```<code>// scripts.js

function loadScripts(urls, length, success){
    if(length > 0){
        script = document.createElement("script");
        script.src = urls[length-1];
        console.log();
        script.onload = function() {
            console.log('%c Script: ' + urls[length-1] + ' loaded!', 'color: #4CAF50');
            loadScripts(urls, length-1, success);
        };
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    else{
        if(success){
            success();
        }
    }
}

/* Write links sorted from last one to first to load */
/* Here, jquery will be loaded first, then materialize and then wow libray. */
urls = [ '/js/wow.js', '/js/materialize.js',  '/js/jquery.js'];

loadScripts(urls, urls.length, function(){
    /* Codes inside of here will be executed after js files load */

});
</code>```

You can put these code in a file like scripts.js and load it with async attribute.

```<code><script async src="js/scripts.js"></script>
</code>```

For css async load, refer to edited versions of this answer.

Body:
I've added the async attrib to my javascript inclusion HTML.

So now I've:

And this works with all JS I load, all except jquery.

If I add async to jQuery  instead of including an external file.js, but this doesn't change the situation.

I'd like to run jQuery with async attrib and run other few external scripts asynchronously only after jquery is loaded.

It is possible?

Body:
Using a recursive function

I have written a function to do this job very nice.

// scripts.js

function loadScripts(urls, length, success){
    if(length > 0){
        script = document.createElement("script");
        script.src = urls[length-1];
        console.log();
        script.onload = function() {
            console.log('%c Script: ' + urls[length-1] + ' loaded!', 'color: #4CAF50');
            loadScripts(urls, length-1, success);
        };
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    else{
        if(success){
            success();
        }
    }
}

/* Write links sorted from last one to first to load */
/* Here, jquery will be loaded first, then materialize and then wow libray. */
urls = [ '/js/wow.js', '/js/materialize.js',  '/js/jquery.js'];

loadScripts(urls, urls.length, function(){
    /* Codes inside of here will be executed after js files load */

});

You can put these code in a file like scripts.js and load it with async attribute.

<script async src="js/scripts.js"></script>

For css async load, refer to edited versions of this answer.


问:
Stub external service requests for functional tests with symfony di container
question summary

Is it possible to inject stubs/mocks to the symfony di container in my test cases to simulate different external api responses?

test that my application sends an email if the api returns an error (i want to inject a stub for my http client class that returns a HTTP 500)

test that my application returns the correct result using 2 different APIs as source (i want to inject both HTTP Clients as stub with a specific result body)

details

i want to write functional tests for an silex application that uses the symfony di container. The application uses multiple API's as backend to fullfill the client reuquests.

The code injects an abstracted http client to the api client where i'm able to inject a http api client stub.

```<code>class AwesomeApiClient
   __construct(MyHttpClient $httpClient);

class MyApiHttpClient
</code>```

This does work pretty good with unit testing.

Now i want to write functional tests.
I extended the silex WebTestCase and implemented the application initialization.
The MyApiHttpClient is injected with the symfony di container.

Now i want to do something like this:

```<code># symfony di container does not allow this
$this->getDiContainer()->set('my_http_client', $myHttpClientStubInstance);
</code>```

i want to configure my stub in every test so i'm able to test different (e.g. error, success) responses for the same request.

things i've tried:

using setter injection at runtime

$his->getDiContainer()->get('MyApiClient')->setHttpClient($myMock);

The DiContainer returns a new instance for everytime i call the get method. That does make absolutely sense. So this does not work.

overriding the http client in the di container

$this->getDiContainer->set('MyHttpClient', $myHttpClientStub);

Does not work because symfony does not allow to change definitions at runtime. Also it seems to take a definition, not an instance.

PHP-VCR

Does work with a few changes in my production code because it messes up the HTTP Headers in my curl header callbacks. Does not work for other services (rabbitmq...)

答:
According to this, it should be possible to set mock in the DI container. </p>

```<code>$client = self::createClient();

$serviceA = $this->getMockBuilder('ServiceA')
    ->disableOriginalConstructor()
    ->getMock();

$client->getContainer()->set('my_bundle.service.a', $serviceA);
</code>```

Body:
question summary

Is it possible to inject stubs/mocks to the symfony di container in my test cases to simulate different external api responses?

test that my application sends an email if the api returns an error (i want to inject a stub for my http client class that returns a HTTP 500)

test that my application returns the correct result using 2 different APIs as source (i want to inject both HTTP Clients as stub with a specific result body)

details

i want to write functional tests for an silex application that uses the symfony di container. The application uses multiple API's as backend to fullfill the client reuquests.

The code injects an abstracted http client to the api client where i'm able to inject a http api client stub.

class AwesomeApiClient
   __construct(MyHttpClient $httpClient);

class MyApiHttpClient

This does work pretty good with unit testing.

Now i want to write functional tests.
I extended the silex WebTestCase and implemented the application initialization.
The MyApiHttpClient is injected with the symfony di container.

Now i want to do something like this:

# symfony di container does not allow this
$this->getDiContainer()->set('my_http_client', $myHttpClientStubInstance);

i want to configure my stub in every test so i'm able to test different (e.g. error, success) responses for the same request.

things i've tried:

using setter injection at runtime

$his->getDiContainer()->get('MyApiClient')->setHttpClient($myMock);

The DiContainer returns a new instance for everytime i call the get method. That does make absolutely sense. So this does not work.

overriding the http client in the di container

$this->getDiContainer->set('MyHttpClient', $myHttpClientStub);

Does not work because symfony does not allow to change definitions at runtime. Also it seems to take a definition, not an instance.

PHP-VCR

Does work with a few changes in my production code because it messes up the HTTP Headers in my curl header callbacks. Does not work for other services (rabbitmq...)

Body:
According to this, it should be possible to set mock in the DI container.

$client = self::createClient();

$serviceA = $this->getMockBuilder('ServiceA')
    ->disableOriginalConstructor()
    ->getMock();

$client->getContainer()->set('my_bundle.service.a', $serviceA);


问:
Joining two tables where id does not equal
I'm struggling getting this query to produce the results I want.

I have:

table1, columns=empid, alt_id

table2, columns=empid, alt_id

I want to get the empid, and alt_id from table 1 where the alt_id does not match the alt_id in table2. They will both have alt_id numbers I just want to get the ones that do not match.

Any ideas?

答:
```<code>SELECT * FROM table1
INNER JOIN table2 ON table2.empid = table1.empid AND table2.alt_id <> table1.alt_id
</code>```


问:
How to get user's location in a later screen for the MapKit?
I am building a navigation-based app for the iPhone, where I calculate the user's geolocation in the RootViewController (this is the code for my RootViewController.h) class:

```<code>#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "SecondViewController.h"
#import <sqlite3.h>

@interface RootViewController : UITableViewController <CLLocationManagerDelegate>{

    SecondViewController *secondViewController;
    NSUInteger numUpdates;

    CLLocationManager *lm;
    CLLocation *firstLocation;
    CLLocation *secondLocation;

}

@property (nonatomic, retain) SecondViewController *secondViewController;
@property (nonatomic, retain) NSMutableArray *restaurants;
@property (nonatomic, retain) NSArray *sortedRestaurants;
</code>```

here is the code for my RootViewController.m class:

```<code>- (void) locationManager:(CLLocationManager *)manager
 didUpdateToLocation:(CLLocation *)newLocation
        fromLocation:(CLLocation *)oldLocation {

CLLocationCoordinate2D location;

NSString *lat = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.latitude];
double lat1 = newLocation.coordinate.latitude;
location.latitude = newLocation.coordinate.latitude; //setting the latitude property of the location variable

NSString *lng = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.longitude];
double lon1 = newLocation.coordinate.longitude;
location.longitude = newLocation.coordinate.longitude; //setting the longitude property of the location variable

MapViewController *mController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:[NSBundle mainBundle]];
self.mapViewController = mController;
[mController release];

self.mapViewController.userCoord = [[[CLLocation alloc] initWithLatitude:location.latitude longitude:location.longitude] autorelease];
//in the above line I get the error, "incompatible type for argument 1 of 'setUserCoord' "
[lm stopUpdatingLocation];
</code>```

Because I am calculating the user's geolocation in the RootViewController class, I would like to re-use these value when I use the MapKit later on in the application in the MapViewController.m class:

```<code>- (void)viewDidLoad {

    [super viewDidLoad];
MKCoordinateRegion region;
MKCoordinateSpan span;
    region.center = userCoord;
/* userCoord is declared as an object of type CLLocationCoordinate2D
   in MapViewController.h, and is declared as a property, and then
   synthesized in the .m class.  Even though I am trying to center
   the map on the user's coordinates, the map is neither centering,
   nor zooming to my settings. */

    span.latitudeDelta = 0.2;
span.longitudeDelta = 0.2;
region.span = span;

[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
mapView.showsUserLocation = YES;
[mapView setRegion:region animated:YES];

    RestaurantAnnotation *rAnnotation = [[RestaurantAnnotation alloc] init];
rAnnotation.title = restaurantObj.name;
rAnnotation.subTitle = restaurantObj.address;

    CLLocationCoordinate2D newCoord = {restaurantObj.latitude, restaurantObj.longitude};
rAnnotation.coordinate = newCoord;
[mapView addAnnotation:rAnnotation];

}
</code>```

I would like the map to be centered on the user's location, and choose appropriate span values as well.

答:
There are a lot of ways to do this, the way I've done it is to store the location in NSUserDefaults and access that value later when I'm presenting my map. The benefit of doing it this way is that the user's location persists between runs, so if the next time they open the app they're having trouble getting a GPS signal, you still have a location to display.

This code may not be 100%, i'm writing it from memory:

```<code>#define latKey @"latKey"
#define lonKey @"lonKey"
#define locationKey @"locationKey"

- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

    NSNumber *lat = [NSNumber numberWithDouble:newLocation.coordinate.latitude];
    NSNumber *lon = [NSNumber numberWithDouble:newLocation.coordinate.longitude];

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:lat, latKey, lon, lonKey, nil];

    [[NSUserDefaults standardUserDefaults] addObjectForKey:locationKey];

}

- (void)viewDidLoad {

    NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictForKey:locationKey];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:[[dict objectForKey:lat] doubleValue] longitude:[[dict objectForKey:lon] doubleValue]];

}
</code>```

Body:
I am building a navigation-based app for the iPhone, where I calculate the user's geolocation in the RootViewController (this is the code for my RootViewController.h) class:

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "SecondViewController.h"
#import <sqlite3.h>

@interface RootViewController : UITableViewController <CLLocationManagerDelegate>{

    SecondViewController *secondViewController;
    NSUInteger numUpdates;

    CLLocationManager *lm;
    CLLocation *firstLocation;
    CLLocation *secondLocation;

}

@property (nonatomic, retain) SecondViewController *secondViewController;
@property (nonatomic, retain) NSMutableArray *restaurants;
@property (nonatomic, retain) NSArray *sortedRestaurants;

here is the code for my RootViewController.m class:

- (void) locationManager:(CLLocationManager *)manager
 didUpdateToLocation:(CLLocation *)newLocation
        fromLocation:(CLLocation *)oldLocation {

CLLocationCoordinate2D location;

NSString *lat = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.latitude];
double lat1 = newLocation.coordinate.latitude;
location.latitude = newLocation.coordinate.latitude; //setting the latitude property of the location variable

NSString *lng = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.longitude];
double lon1 = newLocation.coordinate.longitude;
location.longitude = newLocation.coordinate.longitude; //setting the longitude property of the location variable

MapViewController *mController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:[NSBundle mainBundle]];
self.mapViewController = mController;
[mController release];

self.mapViewController.userCoord = [[[CLLocation alloc] initWithLatitude:location.latitude longitude:location.longitude] autorelease];
//in the above line I get the error, "incompatible type for argument 1 of 'setUserCoord' "
[lm stopUpdatingLocation];

Because I am calculating the user's geolocation in the RootViewController class, I would like to re-use these value when I use the MapKit later on in the application in the MapViewController.m class:

- (void)viewDidLoad {

    [super viewDidLoad];
MKCoordinateRegion region;
MKCoordinateSpan span;
    region.center = userCoord;
/* userCoord is declared as an object of type CLLocationCoordinate2D
   in MapViewController.h, and is declared as a property, and then
   synthesized in the .m class.  Even though I am trying to center
   the map on the user's coordinates, the map is neither centering,
   nor zooming to my settings. */

    span.latitudeDelta = 0.2;
span.longitudeDelta = 0.2;
region.span = span;

[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
mapView.showsUserLocation = YES;
[mapView setRegion:region animated:YES];

    RestaurantAnnotation *rAnnotation = [[RestaurantAnnotation alloc] init];
rAnnotation.title = restaurantObj.name;
rAnnotation.subTitle = restaurantObj.address;

    CLLocationCoordinate2D newCoord = {restaurantObj.latitude, restaurantObj.longitude};
rAnnotation.coordinate = newCoord;
[mapView addAnnotation:rAnnotation];

}

I would like the map to be centered on the user's location, and choose appropriate span values as well.

Body:
There are a lot of ways to do this, the way I've done it is to store the location in NSUserDefaults and access that value later when I'm presenting my map. The benefit of doing it this way is that the user's location persists between runs, so if the next time they open the app they're having trouble getting a GPS signal, you still have a location to display.

This code may not be 100%, i'm writing it from memory:

#define latKey @"latKey"
#define lonKey @"lonKey"
#define locationKey @"locationKey"

- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

    NSNumber *lat = [NSNumber numberWithDouble:newLocation.coordinate.latitude];
    NSNumber *lon = [NSNumber numberWithDouble:newLocation.coordinate.longitude];

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:lat, latKey, lon, lonKey, nil];

    [[NSUserDefaults standardUserDefaults] addObjectForKey:locationKey];

}

- (void)viewDidLoad {

    NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictForKey:locationKey];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:[[dict objectForKey:lat] doubleValue] longitude:[[dict objectForKey:lon] doubleValue]];

}


问:
Get table names using SELECT statement in MySQL
In MySQL, I know I can list the tables in a database with:

```<code>SHOW TABLES
</code>```

However, I want to insert these table names into another table, for instance:

```<code>INSERT INTO metadata(table_name) SHOW TABLES /* does not work */
</code>```

Is there a way to get the table names using a standard SELECT statement, something like:

```<code>INSERT INTO metadata(table_name) SELECT name FROM table_names /* what should table_names be? */
</code>```

答:
I think it may be helpful to point out that if you want to select tables that contain specific words you can easily do it using the SELECT (instead of SHOW). Below query easily narrows down the search to tables that contain "keyword"

```<code>SELECT *
FROM information_schema.tables
WHERE table_name like "%keyword%"
</code>```

Body:
In MySQL, I know I can list the tables in a database with:

SHOW TABLES

However, I want to insert these table names into another table, for instance:

INSERT INTO metadata(table_name) SHOW TABLES /* does not work */

Is there a way to get the table names using a standard SELECT statement, something like:

INSERT INTO metadata(table_name) SELECT name FROM table_names /* what should table_names be? */

Body:
I think it may be helpful to point out that if you want to select tables that contain specific words you can easily do it using the SELECT (instead of SHOW). Below query easily narrows down the search to tables that contain "keyword"

SELECT *
FROM information_schema.tables
WHERE table_name like "%keyword%"


问:
Cython No Performance Increase with prange/parallel
I'm using Cython version 0.27.3 to compile the following source for a simple primality testing module that contains both python and cython implementations of the same algorithm. When I set the threads parameter to different values, I see no performance increase, despite the GIL being released. Is there something that's preventing this from running in parallel?

The function in question is the cdef void _getprimes which accepts a memoryview slice as a parameter and should set all non-prime values to 0 in that slice.

primes.pyx

```<code>#cython: boundscheck=False, wraparound=False, nonecheck=False
cimport cython
from cpython cimport array
from cython.parallel cimport parallel, prange
from libc.math cimport sqrt, ceil
from libc.stdlib cimport malloc, free
from libc.stdio cimport printf
import math

# =====================
# Python implementation
# =====================

def pyisprime(n):
    """Python implementation"""
    if n < 2 or n & 1 == 0:
        if n == 2:
            return True
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

def pygetprimes(nums):
    return [num for num in nums if pyisprime(num)]

# =====================
# Cython implementation
# =====================
cdef int _isprime(unsigned long long n) nogil:
    """Cython implementation of a simple primality check"""
    cdef unsigned long long upper
    cdef unsigned long long i = 3
    cdef int prime = 1
    if n < 2 or n & 1 == 0:
        if n == 2:
            return 1
        return 0
    upper = <unsigned long long>ceil(sqrt(<double>n))
    while i <= upper:
        if n % i == 0:
            prime = 0
            break
        i += 1
    return prime

def isprime(unsigned long long n):
    """Wrapper for _isprime"""
    cdef int result
    with nogil:
        result = _isprime(n)
    return result

cdef void _getprimes(unsigned long long[:] nums, int threads) nogil:
    cdef unsigned long num
    cdef int i = 0
    with parallel(num_threads=threads):
        for i in prange(nums.shape[0], schedule="dynamic"):
            if _isprime(nums[i]) == 0:
                nums[i] = 0

def getprimes(nums, int threads = 1):
    """Wrapper for _getprimes"""
    cdef unsigned long long num
    cdef unsigned long long[:] primes = array.array("Q", nums)

    with nogil:
        _getprimes(primes, threads)

    return [num for num in primes if num != 0]
</code>```

setup.py

```<code>#!/usr/bin/env python3
from distutils.core import setup
from Cython.Build import cythonize

setup(
    name="primes",
    ext_modules=cythonize('primes.pyx'),
)
</code>```

test.py

```<code>#!/usr/bin/env python3
import functools
import random
import time
import primes

def timed(func):
    def wrapped(*args, **kwargs):
        start = time.time()
        val = func(*args, **kwargs)
        end = time.time()
        print(func.__name__, end - start)
        return val
    return functools.wraps(func)(wrapped)

def main():
    nums = [random.randint(0, 0xffffff) for _ in range(500000)]

    pyfoo = timed(primes.pygetprimes)
    cyfoo = timed(primes.getprimes)

    x = pyfoo(nums)
    y = cyfoo(nums, 1)
    z = cyfoo(nums, 4)
    assert x == y == z

if __name__ == "__main__":
    main()
</code>```

When I run cyfoo, I expected that increasing the number of threads from 1 to 4 would show some type of speed increase, but this is not the case:

```<code>[aarcher@Arch]: ~/Programming/Cython/build/lib.linux-x86_64-3.6>$ ./test.py
pygetprimes 5.11554741859436
getprimes 1.1129701137542725
getprimes 1.1306445598602295
</code>```

答:
It seems you  need to enable compiler flags for OpenMP for the parallel statements to actually do anything.

See cython docs here
http://cython.readthedocs.io/en/latest/src/userguide/parallelism.html#compiling

```<code># setup.py
# ... omitted ...

ext_modules = [
    Extension(
        "hello",
        ["hello.pyx"],
        extra_compile_args=['-fopenmp'],
        extra_link_args=['-fopenmp'],
    )
]
</code>```

Body:
I'm using Cython version 0.27.3 to compile the following source for a simple primality testing module that contains both python and cython implementations of the same algorithm. When I set the threads parameter to different values, I see no performance increase, despite the GIL being released. Is there something that's preventing this from running in parallel?

The function in question is the cdef void _getprimes which accepts a memoryview slice as a parameter and should set all non-prime values to 0 in that slice.

primes.pyx

#cython: boundscheck=False, wraparound=False, nonecheck=False
cimport cython
from cpython cimport array
from cython.parallel cimport parallel, prange
from libc.math cimport sqrt, ceil
from libc.stdlib cimport malloc, free
from libc.stdio cimport printf
import math

# =====================
# Python implementation
# =====================

def pyisprime(n):
    """Python implementation"""
    if n < 2 or n & 1 == 0:
        if n == 2:
            return True
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

def pygetprimes(nums):
    return [num for num in nums if pyisprime(num)]

# =====================
# Cython implementation
# =====================
cdef int _isprime(unsigned long long n) nogil:
    """Cython implementation of a simple primality check"""
    cdef unsigned long long upper
    cdef unsigned long long i = 3
    cdef int prime = 1
    if n < 2 or n & 1 == 0:
        if n == 2:
            return 1
        return 0
    upper = <unsigned long long>ceil(sqrt(<double>n))
    while i <= upper:
        if n % i == 0:
            prime = 0
            break
        i += 1
    return prime

def isprime(unsigned long long n):
    """Wrapper for _isprime"""
    cdef int result
    with nogil:
        result = _isprime(n)
    return result

cdef void _getprimes(unsigned long long[:] nums, int threads) nogil:
    cdef unsigned long num
    cdef int i = 0
    with parallel(num_threads=threads):
        for i in prange(nums.shape[0], schedule="dynamic"):
            if _isprime(nums[i]) == 0:
                nums[i] = 0

def getprimes(nums, int threads = 1):
    """Wrapper for _getprimes"""
    cdef unsigned long long num
    cdef unsigned long long[:] primes = array.array("Q", nums)

    with nogil:
        _getprimes(primes, threads)

    return [num for num in primes if num != 0]

setup.py

#!/usr/bin/env python3
from distutils.core import setup
from Cython.Build import cythonize

setup(
    name="primes",
    ext_modules=cythonize('primes.pyx'),
)

test.py

#!/usr/bin/env python3
import functools
import random
import time
import primes

def timed(func):
    def wrapped(*args, **kwargs):
        start = time.time()
        val = func(*args, **kwargs)
        end = time.time()
        print(func.__name__, end - start)
        return val
    return functools.wraps(func)(wrapped)

def main():
    nums = [random.randint(0, 0xffffff) for _ in range(500000)]

    pyfoo = timed(primes.pygetprimes)
    cyfoo = timed(primes.getprimes)

    x = pyfoo(nums)
    y = cyfoo(nums, 1)
    z = cyfoo(nums, 4)
    assert x == y == z

if __name__ == "__main__":
    main()

When I run cyfoo, I expected that increasing the number of threads from 1 to 4 would show some type of speed increase, but this is not the case:

[aarcher@Arch]: ~/Programming/Cython/build/lib.linux-x86_64-3.6>$ ./test.py
pygetprimes 5.11554741859436
getprimes 1.1129701137542725
getprimes 1.1306445598602295

Body:
It seems you  need to enable compiler flags for OpenMP for the parallel statements to actually do anything.

See cython docs here
http://cython.readthedocs.io/en/latest/src/userguide/parallelism.html#compiling

# setup.py
# ... omitted ...

ext_modules = [
    Extension(
        "hello",
        ["hello.pyx"],
        extra_compile_args=['-fopenmp'],
        extra_link_args=['-fopenmp'],
    )
]


问:
C++ : How to ensure that a class member variable is modifiable only within a certain method
I am using C++ 14 with clang on MacOS Sierra. I want to enforce a rule by design. Following is the rule.

I have a member variable in my class say:

```<code>unsigned int m_important_num;
</code>```

There are 4 methods in my class.

```<code>fun1();
fun2();
fun3();
fun4();
</code>```

Objective:

I want only fun2() to be able to change the value of m_important_num.

Question:

Is it possible to make it compiler error if any method other than fun2() changes the variable?
One possible way is to declare it const somehow empower fun2() to change const variables? Is this a good solution? Or are their any better solutions?

Secondary question:

Is it a wrong design to try do such a thing?

答: Encapsulate it down. Put m_important_num in its own class. Aggregate it in your existing class. Have a getter for it. Then put fun2() as a member function of your inner class.

Body:
I am using C++ 14 with clang on MacOS Sierra. I want to enforce a rule by design. Following is the rule.

I have a member variable in my class say:

unsigned int m_important_num;

There are 4 methods in my class.

fun1();
fun2();
fun3();
fun4();

Objective:

I want only fun2() to be able to change the value of m_important_num.

Question:

Is it possible to make it compiler error if any method other than fun2() changes the variable?
One possible way is to declare it const somehow empower fun2() to change const variables? Is this a good solution? Or are their any better solutions?

Secondary question:

Is it a wrong design to try do such a thing?


问:
No suitable application records were found. Verify your bundle identifier 'com.swiftyjson.SwiftyJSON' is correct
It's really bothering. I have several apps on the App Store, some of them use SwiftyJSON, but this latter one is weird. I'm trying to upload it to the App Store but I get this strange error.

No suitable application records were found. Verify your bundle
  identifier 'com.swiftyjson.SwiftyJSON' is correct.

I have double checked project's bundle identifier it's correct, com.myname.appname. Also, it's correct on the iTunesConnect as well. I've read other similar questions, none of them helped. I'm using carthage and Xcode 9.

答: I don't know how these are related but I removed the Info.plis file, create a new project and replaced the app's plist file with this new one and the error is gone.


问:
pypi deployment error: invalid option "--password="
I am trying to setup the deployment to pypi but I get an error after the test is build.
My travis-ci file is here:

https://github.com/EnlightNS/enlightns-cli/blob/master/.travis.yml

I used the setup pypi command line which generated the section in my .travis.yml file.

travis setup pypi

The build failure is here:

https://travis-ci.org/EnlightNS/enlightns-cli/jobs/78112477

The error is this one here:

```<code>Fetching: dpl-1.7.21.gem (100%)
Successfully installed dpl-1.7.21
1 gem installed
invalid option "--password="
failed to deploy
</code>```

I can't figure out what I am doing wrong.

Regards

答:
From issue 327 (opened by the OP), that was because the password had special characters in it.

And the docs.travis-ci on encryption-key does mention the  need to escape special characters such as braces, parentheses, backslashes, and pipe symbols.

For example, when you want to assign the string 6&a(5!1Ab\ to FOO, you need to execute:

```<code>travis encrypt "FOO=6\\&a\\(5\\!1Ab\\\\"
</code>```

travis encrypts the string FOO=6\&a\(5\!1Ab\\, which then bash uses to evaluate in the build environment.

Equivalently, you can do:

```<code>travis encrypt 'FOO=6\&a\(5\!1AB\\'
</code>```

Body:
I am trying to setup the deployment to pypi but I get an error after the test is build.
My travis-ci file is here:

https://github.com/EnlightNS/enlightns-cli/blob/master/.travis.yml

I used the setup pypi command line which generated the section in my .travis.yml file.

travis setup pypi

The build failure is here:

https://travis-ci.org/EnlightNS/enlightns-cli/jobs/78112477

The error is this one here:

Fetching: dpl-1.7.21.gem (100%)
Successfully installed dpl-1.7.21
1 gem installed
invalid option "--password="
failed to deploy

I can't figure out what I am doing wrong.

Regards

Body:
From issue 327 (opened by the OP), that was because the password had special characters in it.

And the docs.travis-ci on encryption-key does mention the  need to escape special characters such as braces, parentheses, backslashes, and pipe symbols.

For example, when you want to assign the string 6&a(5!1Ab\ to FOO, you need to execute:

travis encrypt "FOO=6\\&a\\(5\\!1Ab\\\\"

travis encrypts the string FOO=6\&a\(5\!1Ab\\, which then bash uses to evaluate in the build environment.

Equivalently, you can do:

travis encrypt 'FOO=6\&a\(5\!1AB\\'


问:
understanding how custom metrics publisher work on hystrix
I am struggling a little bit to understand how to implement a Hystrix Metrics Publisher plugin.

Having read the documentation, it is still not clear how things are supposed to work together.

My goal is to write a plugin that will collect every metrics published by hystrix and write these metrics to a file on disk.
This file will later be collected and processed by an external tool giving us a good historical basis of the circuit’s behavior and problems.

The system where hystrix is running is a normal spring application. This said, I am also somewhat new on the java platform (although I am comfortable with the java language).

I thought that a first step towards understanding how the plugin could be implemented would be looking at the already implemented publishers. With this in mind, I looked at some of the implementations of hystrix-contrib directory.

I have chosen hystrix-codahale-metrics-publisher and hystrix-servo-metrics-publisher.

Both of them have a main class (servo is HystrixServoMetricsPublisher) which seems to register for receiving all possible kinds of metrics and some classes to deal with each kind of metric.

By looking at what I will call the main class, I see that, for example, there is a method called getMetricsPublisherForCommand that must return an implementation of the interface  HystrixMetricsPublisherCommand.

Now questions start:

Question 1 I am assuming that once a plugin is registered every execution of every command on the context where the plugin is registered, and by the word command we can understand every execution of the execute() method of every class which inherits from HistrixCommand on that context, will generate a call to the getMetricsPublisherForCommand() method of my plugin. Is it true?
If so, there are a lot of low level implementations in hystrix such as thread pools and other, Should my getMetricsPublisherForCommand() implementation be thread-safe or I am guaranteed to receive calls in a sequential order? On what thread will my getMetricsPublisherForCommand() be executed?

Question 2 By looking at the documentation I am still not sure about what exactly the implementation of HystrixMetricsPublisherCommand to be returned by getMetricsPublisherForCommand() has to do. This is due to the fact that the HystrixMetricsPublisherCommand interface only specifies a method called initialize (). if it specified a method called, say, publish() I would conclude that the hystrix engine would call  my custom getMetricsPublisherForCommand() method to get a metrics publisher on which it would call a publish() method to perform the custom publishing. But the initialize () method seens to be called only once when this given object is returned and I have found no other method the engine would call afterwards.

Also, by reading the documentation, I am under the impression that the implementation of HystrixMetricsPublisherCommand returned by getMetricsPublisherForCommand() will be somehow a singleton which completely breaks my understanding about how the thing is supposed to work.

The documentation say this:

The initialize() method will be called once-and-only-once to indicate when this instance can register with external services, start publishing metrics etc.

If you look at the servopublisher however you will notice that, unless I am completely and absolutely confused, the publishing stuff is performed right from the constructor. Now, if initialize() will be called to make some setup, how can I code my logic from the constructor where, unless the object is a singleton, it will be executed before any method including initialize () will have a chance to be called? In the other hand ,,, if this is a singleton, how can it run its constructor for every hystrix command?

May be I have missed something, I don't know ... but I need to understand conceptually what is going on here in order to implement my logic the right way. Thanks for your patience and I hope I have made myself clear enough in this long question.

答:
First, recommend staying within the one (concise) question format.

Second, recommend using an existing implementation such as the default CodaHale (formerly DropWizard) implementation (which publishes to Graphite repository for Grafana consumption for example) to get it working.

```<code>    HystrixPlugins.reset();

    final WebApplicationContext springContext =
            WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());

    HystrixPlugins plugins = HystrixPlugins.getInstance();

    plugins.registerCommandExecutionHook(...);

    // Good idea to use properties to enable/disable metrics generally...

    // Using Spring type example...

    if (hystrixMetricsEnabled.get()) {
        plugins.registerMetricsPublisher(new HystrixCodaHaleMetricsPublisher(
                getRegistry(springContext, sce.getServletContext())));
</code>```

...

Otherwise the Hystrix documentation and full source of classes involved are publicly available:

https://github.com/Netflix/Hystrix/wiki/Plugins#metricspublisher

Body:
First, recommend staying within the one (concise) question format.

Second, recommend using an existing implementation such as the default CodaHale (formerly DropWizard) implementation (which publishes to Graphite repository for Grafana consumption for example) to get it working.

    HystrixPlugins.reset();

    final WebApplicationContext springContext =
            WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());

    HystrixPlugins plugins = HystrixPlugins.getInstance();

    plugins.registerCommandExecutionHook(...);

    // Good idea to use properties to enable/disable metrics generally...

    // Using Spring type example...

    if (hystrixMetricsEnabled.get()) {
        plugins.registerMetricsPublisher(new HystrixCodaHaleMetricsPublisher(
                getRegistry(springContext, sce.getServletContext())));

...

Otherwise the Hystrix documentation and full source of classes involved are publicly available:

https://github.com/Netflix/Hystrix/wiki/Plugins#metricspublisher


答:
The problem here is that javascript is expecting quotes around functions. What jade is making is

This is not what javascript is expecting, Javascript expects a valid variable name to be given to its onclick functions. There are two choices:

If you are SURE that there is NO WAY for user._id to ever be anything other than a string ONLY CONTAINING alphanumeric characters (new RegExp(/^(A-Za-z0-9)+$/)) then put quotes in myFunction: a(id='myLinkTag' onclick='myFunction(\'' + user._id + '\')' href='') Delete

If user._id can be more than alphanumeric characters, you can instead use jade to set a class and a custom attribute like a(id='myLinkTag' class="myclass" userid=user._id href='') Delete then in javascript you can:

:

$(".myclass").click(function(e){
    var userid = $(e.target).attr("userid");
    console.log(userid);
    alert(userid);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Jade would be:

a(id='myLinkTag' class="myclass" userid=user._id href='#')
a(id='myLinkTag2' class="myclass" userid=user2._id href='#')
a(id='myLinkTag3' class="myclass" userid=user3._id href='#')</code>```

link
link2
class="myclass" userid="myuserid3" href="#">link3```

Title: In Jade, how to pass parameters in the onclick function call

Body:
a(id='myLinkTag' onclick='myFunction(' + user._id + ')' href='') Delete

Here user._id is the variable and trying to pass that value to myFunction .

syntaxError: Invalid or unexpected token

Body:
The problem here is that javascript is expecting quotes around functions. What jade is making is <a id='myLinkTag' onclick='myFunction(userid) href=''>

This is not what javascript is expecting, Javascript expects a valid variable name to be given to its onclick functions. There are two choices:

If you are SURE that there is NO WAY for user._id to ever be anything other than a string ONLY CONTAINING alphanumeric characters (new RegExp(/^(A-Za-z0-9)+$/)) then put quotes in myFunction: a(id='myLinkTag' onclick='myFunction(\'' + user._id + '\')' href='') Delete

If user._id can be more than alphanumeric characters, you can instead use jade to set a class and a custom attribute like a(id='myLinkTag' class="myclass" userid=user._id href='') Delete then in javascript you can:

:

$(".myclass").click(function(e){
    var userid = $(e.target).attr("userid");
    console.log(userid);
    alert(userid);
});

Jade would be:

a(id='myLinkTag' class="myclass" userid=user._id href='#')
a(id='myLinkTag2' class="myclass" userid=user2._id href='#')
a(id='myLinkTag3' class="myclass" userid=user3._id href='#')

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="myclass" userid="myuserid" href="#">link</a>
<a class="myclass" userid="myuserid2" href="#">link2</a>
<a class="myclass" userid="myuserid3" href="#">link3</a>


问:
How to visualize a Regression Tree in Python
I'm looking to visualize a regression tree built using any of the ensemble methods in scikit learn (gradientboosting regressor, random forest regressor,bagging regressor).
I've looked at this question which comes close, and this question
which deals with classifier trees. But these questions require the 'tree' method, which is not available to the regression models in SKLearn.

but it didn't seem to yield a result.
I'm running into issues because there is no .tree method for the regression versions of these trees (the method only exists for the classification versions).
I'd like an output resembling this but based on a sci kit learn-constructed tree.

I've explored the methods associated with the objects but just cannot produce an answer.

答:
As I commented, there is no functional difference between a classification and a regression decision tree plot. Adapting the regression toy example from the docs:

from sklearn import tree
X = [[0, 0], [2, 2]]
y = [0.5, 2.5]
clf = tree.DecisionTreeRegressor()
clf = clf.fit(X, y)
```

<p>and then, similarly, some code from the classification docs regarding <code>graphviz</code>:</p>

<pre class="lang-python prettyprint-override"><code>import graphviz
dot_data = tree.export_graphviz(clf, out_file='tree.dot')
</code>```

we end up with a file tree.dot, looking like that:

digraph Tree {
node [shape=box] ;
0 [label="X[0] <= 1.0\nmse = 1.0\nsamples = 2\nvalue = 1.5"] ;
1 [label="mse = 0.0\nsamples = 1\nvalue = 0.5"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
2 [label="mse = 0.0\nsamples = 1\nvalue = 2.5"] ;
0 -> 2 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
}
```

Now, you can proceed to visualize it as shown in the docs - but if for whatever reason you cannot render Graphviz objects, you can use the handy service WebGraphviz (+1 to the relevant answer in the linked question); the result looks like this:

Your own answer, i.e. going all the way to install graphlab just for the visualization, sounds like overkill...

Last remark: don't get deceived by the superficial differences in the tree layouts, which reflect only design choices of the respective visualization packages; the regression tree you have plotted (which, admittedly, does not look much like a tree) is structurally similar to the classification one taken from the docs - simply imagine a top-down tree, with your odor node at the top, followed by your green nodes and terminating to your blue & orange nodes (and replace "yes/no" with "True/False")...

Body:
As I commented, there is no functional difference between a classification and a regression decision tree plot. Adapting the regression toy example from the docs:

from sklearn import tree
X = [[0, 0], [2, 2]]
y = [0.5, 2.5]
clf = tree.DecisionTreeRegressor()
clf = clf.fit(X, y)

and then, similarly, some code from the classification docs regarding graphviz:

import graphviz
dot_data = tree.export_graphviz(clf, out_file='tree.dot')

we end up with a file tree.dot, looking like that:

digraph Tree {
node [shape=box] ;
0 [label="X[0] <= 1.0\nmse = 1.0\nsamples = 2\nvalue = 1.5"] ;
1 [label="mse = 0.0\nsamples = 1\nvalue = 0.5"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
2 [label="mse = 0.0\nsamples = 1\nvalue = 2.5"] ;
0 -> 2 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
}

Now, you can proceed to visualize it as shown in the docs - but if for whatever reason you cannot render Graphviz objects, you can use the handy service WebGraphviz (+1 to the relevant answer in the linked question); the result looks like this:

Your own answer, i.e. going all the way to install graphlab just for the visualization, sounds like overkill...

Last remark: don't get deceived by the superficial differences in the tree layouts, which reflect only design choices of the respective visualization packages; the regression tree you have plotted (which, admittedly, does not look much like a tree) is structurally similar to the classification one taken from the docs - simply imagine a top-down tree, with your odor node at the top, followed by your green nodes and terminating to your blue & orange nodes (and replace "yes/no" with "True/False")...


问:
How do I get cli curl (7.47.0) to output raw text from a page?
Long time reader first time questioner. So maybe my search fu is lacking, but I can't seem to find any reasonable help for this.

I have a little IoT device that has a small web server built into it. If I go to the page http://x.x.x.x/temp it will display the temp and humidity in plain text. I suspect this return is just raw unformatted text without HTML, and modern browsers add some needed html to display the results on their own. I believe this because if I view the source of the page there is just the text, but if I actually inspect the page I see some HTML. I am wanting to eventually grab this data and dump it into my database using curl in a perl script. I decided to make sure I could get the results I wanted from curl on the cli first. The trouble is curl returns nothing. I tried with wget too and also get nothing. Curl -v shows no return. Curl --trace-ascii - shows the response I am looking for, which I could probably deal with if I had to, but I would still like to know how to make it just dump what it receives as I would expect. Instead of having to parse/grep all that return from trace-ascii.

Browser output from the page:
Browser grab

CLI Output:

```<code>~$ curl http://192.168.11.7/temp -v
*   Trying 192.168.11.7...
* Connected to 192.168.11.7 (192.168.11.7) port 80 (#0)
> GET /temp HTTP/1.1
> Host: 192.168.11.7
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/html
< Connection: close
< Access-Control-Allow-Origin: *
<
* Closing connection 0
</code>```

curl with --trace-ascii:

```<code>~$ curl http://192.168.11.7/temp --trace-ascii -
== Info:   Trying 192.168.11.7...
== Info: Connected to 192.168.11.7 (192.168.11.7) port 80 (#0)
=> Send header, 80 bytes (0x50)
0000: GET /temp HTTP/1.1
0014: Host: 192.168.11.7
0028: User-Agent: curl/7.47.0
0041: Accept: */*
004e:
<= Recv header, 17 bytes (0x11)
0000: HTTP/1.1 200 OK
<= Recv header, 25 bytes (0x19)
0000: Content-Type: text/html
<= Recv header, 19 bytes (0x13)
0000: Connection: close
<= Recv header, 32 bytes (0x20)
0000: Access-Control-Allow-Origin: *
<= Recv header, 2 bytes (0x2)
0000:
<= Recv data, 21 bytes (0x15)
0000: DHT22,.80.60.,.64.30.   <----- Output I would expect
== Info: Closing connection 0
</code>```

Any help would be greatly appreciated!

答: So it looks like the return from the device is including some ^M carriage returns in it. This is apparently confusing several linux programs, probably because that is a Windows line ending. I've reach out the developer of the device and hopefully this will be addressed in a future upgrade. There is a newer firmware I will be trying to see if it resolves the issue. Until then I guess I'm just going to have to grab the output via --trace-ascii.</p>

Body:
Long time reader first time questioner. So maybe my search fu is lacking, but I can't seem to find any reasonable help for this.

I have a little IoT device that has a small web server built into it. If I go to the page http://x.x.x.x/temp it will display the temp and humidity in plain text. I suspect this return is just raw unformatted text without HTML, and modern browsers add some needed html to display the results on their own. I believe this because if I view the source of the page there is just the text, but if I actually inspect the page I see some HTML. I am wanting to eventually grab this data and dump it into my database using curl in a perl script. I decided to make sure I could get the results I wanted from curl on the cli first. The trouble is curl returns nothing. I tried with wget too and also get nothing. Curl -v shows no return. Curl --trace-ascii - shows the response I am looking for, which I could probably deal with if I had to, but I would still like to know how to make it just dump what it receives as I would expect. Instead of having to parse/grep all that return from trace-ascii.

Browser output from the page:
Browser grab

CLI Output:

~$ curl http://192.168.11.7/temp -v
*   Trying 192.168.11.7...
* Connected to 192.168.11.7 (192.168.11.7) port 80 (#0)
> GET /temp HTTP/1.1
> Host: 192.168.11.7
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/html
< Connection: close
< Access-Control-Allow-Origin: *
<
* Closing connection 0

curl with --trace-ascii:

~$ curl http://192.168.11.7/temp --trace-ascii -
== Info:   Trying 192.168.11.7...
== Info: Connected to 192.168.11.7 (192.168.11.7) port 80 (#0)
=> Send header, 80 bytes (0x50)
0000: GET /temp HTTP/1.1
0014: Host: 192.168.11.7
0028: User-Agent: curl/7.47.0
0041: Accept: */*
004e:
<= Recv header, 17 bytes (0x11)
0000: HTTP/1.1 200 OK
<= Recv header, 25 bytes (0x19)
0000: Content-Type: text/html
<= Recv header, 19 bytes (0x13)
0000: Connection: close
<= Recv header, 32 bytes (0x20)
0000: Access-Control-Allow-Origin: *
<= Recv header, 2 bytes (0x2)
0000:
<= Recv data, 21 bytes (0x15)
0000: DHT22,.80.60.,.64.30.   <----- Output I would expect
== Info: Closing connection 0

Any help would be greatly appreciated!


问:
Paging query with NodeJS and ObjectionJs
Hi I am relatively new to NodeJS and am using ObjectionJS as ORM.
I want to do a migration script for my users table, in order to change some field of each row.

I make something like this

```<code>export default class UserMigration {

  constructor(firstId, lastId = 9000000) {
    this.firstId = firstId;
    this.lastId  = lastId;
  }

  migrate() {
    let more = true;
    let page = 0;
    let batchSize = 100;
    while(more) {
      UserModel.query().where('id', '>=', this.firstId)
        .where('id', '<=', this.lastId)
        .page(page, batchSize)
        .then((result) => {
          let users = result.results;
          debug('Page: ', page);
          debug('PageSize: ', users.length)
          users.forEach((user) => {
            // Do something here
          });
          if(result.results.length < batchSize) {
            more = false
          } else {
            page++;
          }
        })
    }
  }

}
</code>```

But then I realize that the query is being executed asynchronously while the while block is being executed synchronously, is that correct?

How can I achieve the migration without making one big query that returns all the users at once?

Thanks in advance!!

答:
I have achieved that using async/await</p>

```<code>export default class UserMigration {

  constructor(firstId, lastId = 9000000) {
    this.firstId = firstId;
    this.lastId  = lastId;
  }

  run() {
    this.migrateV3().then((data) => {
      debug('All migrated');
      debug('data: ', data);
    }).catch((data) => {
      debug('Error');
      debug('data: ', data);
    });
  }

  async migrateV3() {
    let more = true;
    let page = 0;
    let batchSize = 100;
    while(more) {
      try {
        let result = await UserModel.query().where('id', '>=', this.firstId)
          .where('id', '<=', this.lastId)
          .page(page, batchSize);
        let users = result.results;
        debug('Page: ', page);
        debug('PageSize: ', users.length)
        for(let user of users) {
          debug(`User ${user.id} migration start`);
          // Do something
        };
        if(result.results.length < batchSize) {
          more = false
        } else {
          page++;
        }
      }
      catch (err) {
        throw err;
      }
    }
  }
}
</code>```

Body:
Hi I am relatively new to NodeJS and am using ObjectionJS as ORM.
I want to do a migration script for my users table, in order to change some field of each row.

I make something like this

export default class UserMigration {

  constructor(firstId, lastId = 9000000) {
    this.firstId = firstId;
    this.lastId  = lastId;
  }

  migrate() {
    let more = true;
    let page = 0;
    let batchSize = 100;
    while(more) {
      UserModel.query().where('id', '>=', this.firstId)
        .where('id', '<=', this.lastId)
        .page(page, batchSize)
        .then((result) => {
          let users = result.results;
          debug('Page: ', page);
          debug('PageSize: ', users.length)
          users.forEach((user) => {
            // Do something here
          });
          if(result.results.length < batchSize) {
            more = false
          } else {
            page++;
          }
        })
    }
  }

}

But then I realize that the query is being executed asynchronously while the while block is being executed synchronously, is that correct?

How can I achieve the migration without making one big query that returns all the users at once?

Thanks in advance!!

Body:
I have achieved that using async/await

export default class UserMigration {

  constructor(firstId, lastId = 9000000) {
    this.firstId = firstId;
    this.lastId  = lastId;
  }

  run() {
    this.migrateV3().then((data) => {
      debug('All migrated');
      debug('data: ', data);
    }).catch((data) => {
      debug('Error');
      debug('data: ', data);
    });
  }

  async migrateV3() {
    let more = true;
    let page = 0;
    let batchSize = 100;
    while(more) {
      try {
        let result = await UserModel.query().where('id', '>=', this.firstId)
          .where('id', '<=', this.lastId)
          .page(page, batchSize);
        let users = result.results;
        debug('Page: ', page);
        debug('PageSize: ', users.length)
        for(let user of users) {
          debug(`User ${user.id} migration start`);
          // Do something
        };
        if(result.results.length < batchSize) {
          more = false
        } else {
          page++;
        }
      }
      catch (err) {
        throw err;
      }
    }
  }
}


问:
Migration Webpack from version 1 to 2
I want to convert webpack 1 configuration file to webpack 2 version.
In addition, I want to exclude node modules from bundle.
I got following Exception

Using removed Babel 5 option: base.modules - Use the corresponding module transform plugin in the plugins option. Check out http://babeljs.io/docs/plugins/#modules

In addition, I get another error

ERROR in ./index.js
  Module parse failed: Unexpected token (9:16)
  You may need an appropriate loader to handle this file type.

The errors seem informative but I can't find what is wrong.

Do I miss something from migration guide?

Version 1

```<code>const config = {
    entry: './index.js',
    output: {
        path: '/',
        filename: 'bundle.js',
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};
module.exports = config;
</code>```

Version 2

```<code>const config = {
    entry: './index.js',
    output: {
        path:'/',
        filename: 'bundle.js',
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        rules:[
            {
                test:/\.jsx?$/,
                use:[
                    {
                        loader:'babel-loader',
                        options:{
                            only:['/node_modules/'],
                            presets:['es2015', 'react']
                        },
                    }
                ]
            }
        ]
    }
};

module.exports = config;
</code>```

答:
For the first error with Babel, you likely have a dependency that still uses Babel 5 and it contains a config that is no longer allowed in Babel 6. That probably happens because you're trying to transpile your node_modules, as you have removed the exclude option, which has not been changed in webpack 2. Babel always uses the closest config it can find.

For the second error, you are using some syntax that requires Babel, presumably JSX. But you have set the only option on babel-loader, which tells Babel to only transpile files that match the given path. Hence, it's only applied to the node_modules, not the rest of your project. That is exactly the opposite of what you wanted.

Your .jsx rule should be:

```<code>{
    test:/\.jsx?$/,
    exclude:/node_modules/,
    use:[
        {
            loader:'babel-loader',
            options:{
                presets:['es2015', 'react']
            },
        }
    ]
}
</code>```

You are also setting the output.path to /. That is the root of your file system, not the root of your project. To use the directory where the webpack config is, you can use Node's __dirname, which is the absolute path to the directory of the currently executed file (i.e. webpack.config.js).

```<code>output: {
    path: __dirname,
    filename: 'bundle.js',
},
</code>```

Title: Migration Webpack from version 1 to 2

Body:
I want to convert webpack 1 configuration file to webpack 2 version.
In addition, I want to exclude node modules from bundle.
I got following Exception

Using removed Babel 5 option: base.modules - Use the corresponding module transform plugin in the plugins option. Check out http://babeljs.io/docs/plugins/#modules

In addition, I get another error

ERROR in ./index.js
  Module parse failed: Unexpected token (9:16)
  You may need an appropriate loader to handle this file type.

The errors seem informative but I can't find what is wrong.

Do I miss something from migration guide?

Version 1

const config = {
    entry: './index.js',
    output: {
        path: '/',
        filename: 'bundle.js',
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};
module.exports = config;

Version 2

const config = {
    entry: './index.js',
    output: {
        path:'/',
        filename: 'bundle.js',
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        rules:[
            {
                test:/\.jsx?$/,
                use:[
                    {
                        loader:'babel-loader',
                        options:{
                            only:['/node_modules/'],
                            presets:['es2015', 'react']
                        },
                    }
                ]
            }
        ]
    }
};

module.exports = config;

Body:
For the first error with Babel, you likely have a dependency that still uses Babel 5 and it contains a config that is no longer allowed in Babel 6. That probably happens because you're trying to transpile your node_modules, as you have removed the exclude option, which has not been changed in webpack 2. Babel always uses the closest config it can find.

For the second error, you are using some syntax that requires Babel, presumably JSX. But you have set the only option on babel-loader, which tells Babel to only transpile files that match the given path. Hence, it's only applied to the node_modules, not the rest of your project. That is exactly the opposite of what you wanted.

Your .jsx rule should be:

{
    test:/\.jsx?$/,
    exclude:/node_modules/,
    use:[
        {
            loader:'babel-loader',
            options:{
                presets:['es2015', 'react']
            },
        }
    ]
}

You are also setting the output.path to /. That is the root of your file system, not the root of your project. To use the directory where the webpack config is, you can use Node's __dirname, which is the absolute path to the directory of the currently executed file (i.e. webpack.config.js).

output: {
    path: __dirname,
    filename: 'bundle.js',
},


问:
Batch script kill process
I have Process1,Process2,Process3 in tasklist       I want to write for loop or loop back to repeat the same task  to kill the ‘n' number process
Which I mention in batch script.
Below is sample script using to kill process</p>

```<code>@Echo Off

Tasklist | Findstr /I “Process1”
IF ERRORLEVEL 1 GOTO :Killprocess
GOTO:EOF

:Killprocess
Taskkill /IM “Process1”
</code>```

答:
Thanks everyone for suggestions....done with script </p>

```<code>   @echo off
 set len=3
 set obj[0]=chrome.exe
 set obj[1]=vlc.exe
 set obj[2]=MicrosoftEdge.exe

  set i=0
    :loop
    if %i% equ %len% goto :eof

          for /f "usebackq delims== tokens=2"            %%j in (`set obj[%i%]`) do (
          TASKLIST |FINDSTR /I "%%j"
           IF ERRORLEVEL 0 TASKKILL /IM "%%j" /F)

         set /a i=%i%+1
         goto loop
</code>```

Title: Batch script kill process

Body:
I have Process1,Process2,Process3 in tasklist       I want to write for loop or loop back to repeat the same task  to kill the ‘n' number process
Which I mention in batch script.
Below is sample script using to kill process

@Echo Off

Tasklist | Findstr /I “Process1”
IF ERRORLEVEL 1 GOTO :Killprocess
GOTO:EOF

:Killprocess
Taskkill /IM “Process1”

Body:
Thanks everyone for suggestions....done with script

   @echo off
 set len=3
 set obj[0]=chrome.exe
 set obj[1]=vlc.exe
 set obj[2]=MicrosoftEdge.exe

  set i=0
    :loop
    if %i% equ %len% goto :eof

          for /f "usebackq delims== tokens=2"            %%j in (`set obj[%i%]`) do (
          TASKLIST |FINDSTR /I "%%j"
           IF ERRORLEVEL 0 TASKKILL /IM "%%j" /F)

         set /a i=%i%+1
         goto loop


问:
Gradle Syncing error in android studio
I am new in android studio after installation I have a warning of

Error:(13, 0) Could not find method compile() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Anyone please Help me to solved out.

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar']) // <-- giving warning on that line
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.android.gms:play-services:6.5.+'
}
</code>```

答:
You probably don't have the libs directory.
I recommend removing that line.
This is used to drop JARs or AAR files directly into your project. This is poor practice other then when using some of the Google Maps services.

You should reference dependencies via url and maven or ivy, not local file tree if you can avoid it.

Secondly, if you really want, you can go make a directory libs.
Lastly, I would ask how you get this error? Gradle Sync, Android Studio Build, or terminal assembleRelease.

But the above should square you away.

Title: Gradle Syncing error in android studio

Body:
I am new in android studio after installation I have a warning of

Error:(13, 0) Could not find method compile() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Anyone please Help me to solved out.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar']) // <-- giving warning on that line
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.android.gms:play-services:6.5.+'
}


问:
Tuple that I append to a .txt file will not save to file
So I am making an atm program that keeps a record of deposits, withdrawals, and balance. Here is my deposit function

```<code>def deposite(bal):
    d=input("How much would you like to deposite? ")
    newbal = float(bal) + float(d)
    write = "deposit ", str(d), str(newbal)
    print(write)
    f1 = open('atmrecord', 'a')
    f1.write(str(write) + '\n')
    print(f1.closed)
    f1.close()
    print("Your new balance is", newbal)
    return newbal
</code>```

'write' is a tuple I know but I can't for the life of me figure out why it will not save to the .txt file. Earlier in my code I am able to read the file for getting the balance and I thought I had my write command right but it won't save. The code runs fine without any errors and it appears it closes the file when its done but when I open my .txt after running there is never the extra line of data. Any thoughts/tips would be appreciated.
Also 'write' = ('deposit ', '1', '10001.0') if d=1 for example

答:
You don't want to call str on write because it will return something like ('deposit ', '10', '20.0'). Simply do:

```<code>def deposite(bal):
    d = input("How much would you like to deposite? ")
    newbal = float(bal) + float(d)
    write = "deposit ", str(d), str(newbal)
    print(write)

    with open('atmrecord', 'a') as f:
        f.write(" ".join(write) + '\n')

    print("Your new balance is", newbal)
    return newbal
</code>```

Body:
So I am making an atm program that keeps a record of deposits, withdrawals, and balance. Here is my deposit function

def deposite(bal):
    d=input("How much would you like to deposite? ")
    newbal = float(bal) + float(d)
    write = "deposit ", str(d), str(newbal)
    print(write)
    f1 = open('atmrecord', 'a')
    f1.write(str(write) + '\n')
    print(f1.closed)
    f1.close()
    print("Your new balance is", newbal)
    return newbal

'write' is a tuple I know but I can't for the life of me figure out why it will not save to the .txt file. Earlier in my code I am able to read the file for getting the balance and I thought I had my write command right but it won't save. The code runs fine without any errors and it appears it closes the file when its done but when I open my .txt after running there is never the extra line of data. Any thoughts/tips would be appreciated.
Also 'write' = ('deposit ', '1', '10001.0') if d=1 for example

Body:
You don't want to call str on write because it will return something like ('deposit ', '10', '20.0'). Simply do:

def deposite(bal):
    d = input("How much would you like to deposite? ")
    newbal = float(bal) + float(d)
    write = "deposit ", str(d), str(newbal)
    print(write)

    with open('atmrecord', 'a') as f:
        f.write(" ".join(write) + '\n')

    print("Your new balance is", newbal)
    return newbal


问:
Retrieve Google Access Token after authenticated using Firebase Authentication
I am trying to retrieve Google Access Token to access Google REST API such as YouTube Data API from an authenticated user (using Firebase Authentication).

I have successfully integrated Google Sign-In in my app with the help of Firebase-UI for Android - Auth library. The token retrieved from FirebaseUser.getToken() method is not a valid Google Access Token for REST API.

```<code>user.getToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
    public void onComplete(@NonNull Task<GetTokenResult> task) {
        if (task.isSuccessful()) {
            String token = task.getResult().getToken();
            // 'token' is not a Google Access Token
        }
    }
});
</code>```

In Google Sign-In for Web guide, it's possible to get the access token by calling var token = result.credential.accessToken;, but I can't find the similar method in Android.

Any inputs? Please comment here if I do not provide enough information. Thank you :)

答:
I'm following the @vovkas solution, and want to let you know that with the last update 11.6.0 you can get the Account needed more easily, so you can have everything inside a handy dandy AsyncTask to be reused whenever you want to:

```<code>public class GetToken extends AsyncTask<Void, Void, String> {

    private final Context context;

    public GetToken(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(Void... voids) {
        try {
            String scope = "oauth2:" + Scopes.EMAIL + " " + Scopes.PROFILE;
            GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
            return GoogleAuthUtil.getToken(context, account.getAccount(), scope, new Bundle());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GoogleAuthException e) {
            e.printStackTrace();
        }
        return null;
    }
}
</code>```

The key is to use GoogleSignIn.getLastSignedInAccount(context).

Body:
I am trying to retrieve Google Access Token to access Google REST API such as YouTube Data API from an authenticated user (using Firebase Authentication).

I have successfully integrated Google Sign-In in my app with the help of Firebase-UI for Android - Auth library. The token retrieved from FirebaseUser.getToken() method is not a valid Google Access Token for REST API.

user.getToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
    public void onComplete(@NonNull Task<GetTokenResult> task) {
        if (task.isSuccessful()) {
            String token = task.getResult().getToken();
            // 'token' is not a Google Access Token
        }
    }
});

In Google Sign-In for Web guide, it's possible to get the access token by calling var token = result.credential.accessToken;, but I can't find the similar method in Android.

Any inputs? Please comment here if I do not provide enough information. Thank you :)

Body:
I'm following the @vovkas solution, and want to let you know that with the last update 11.6.0 you can get the Account needed more easily, so you can have everything inside a handy dandy AsyncTask to be reused whenever you want to:

public class GetToken extends AsyncTask<Void, Void, String> {

    private final Context context;

    public GetToken(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(Void... voids) {
        try {
            String scope = "oauth2:" + Scopes.EMAIL + " " + Scopes.PROFILE;
            GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
            return GoogleAuthUtil.getToken(context, account.getAccount(), scope, new Bundle());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GoogleAuthException e) {
            e.printStackTrace();
        }
        return null;
    }
}

The key is to use GoogleSignIn.getLastSignedInAccount(context).


问:
dynamic sql not parsing correctly
I am writing a dynamic sql statement that will check if the index exist and drop it. Getting compile error Could somebody tell what the problem is . I double checked the ticks but cant understand </p>

```<code>declare @startyear int = 2000
declare @startQuarter int = 1
declare @sql nvarchar(max)
declare @tableName varchar(50)

if @startYear is null
    set @startYear = 2000;
set @startQuarter = 1;
while @startYear <= year(getdate())
    begin
        set @startQuarter = 1;

        while @startQuarter < 5
        begin
            set @tableName = 'FinData' + cast(@startYear as varchar) + '_' + cast(@startQuarter as varchar);
            set @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(' + @tableName + ') AND NAME = ' + '.idx_' + @tableName
            drop  index' + @tableName + '.idx_' + @tableName

            print  @sql

            set @startQuarter += 1
        end
        set @startYear += 1;

    end
</code>```

答:
This does not answer your question, however, it is worth mentioning that if you want to do this without looping, you could create a virtual numbers table to join with.</p>

```<code>;WITH
A AS(SELECT 0 AS Q UNION ALL SELECT 0),
B AS(SELECT 0 AS Q FROM A AS A CROSS JOIN A AS B),
C AS(SELECT 0 AS Q FROM B AS A CROSS JOIN B AS B),
D AS(SELECT 0 AS Q FROM C AS A CROSS JOIN C AS B),
E AS(SELECT 0 AS Q FROM D AS A CROSS JOIN D AS B),
F AS(SELECT 0 AS Q FROM E AS A CROSS JOIN E AS B),
Numbers AS(SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Number FROM F)

SELECT
    Y.Number,Q.Number
FROM
    Numbers Y
    INNER JOIN Numbers Q ON Q.Number BETWEEN 1 AND 4
WHERE
    Y.Number BETWEEN 2000 AND YEAR(GETDATE())
ORDER BY
    Y.Number
</code>```

Title: dynamic sql not parsing correctly

Body:
I am writing a dynamic sql statement that will check if the index exist and drop it. Getting compile error Could somebody tell what the problem is . I double checked the ticks but cant understand

declare @startyear int = 2000
declare @startQuarter int = 1
declare @sql nvarchar(max)
declare @tableName varchar(50)

if @startYear is null
    set @startYear = 2000;
set @startQuarter = 1;
while @startYear <= year(getdate())
    begin
        set @startQuarter = 1;

        while @startQuarter < 5
        begin
            set @tableName = 'FinData' + cast(@startYear as varchar) + '_' + cast(@startQuarter as varchar);
            set @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(' + @tableName + ') AND NAME = ' + '.idx_' + @tableName
            drop  index' + @tableName + '.idx_' + @tableName

            print  @sql

            set @startQuarter += 1
        end
        set @startYear += 1;

    end

Body:
This does not answer your question, however, it is worth mentioning that if you want to do this without looping, you could create a virtual numbers table to join with.

;WITH
A AS(SELECT 0 AS Q UNION ALL SELECT 0),
B AS(SELECT 0 AS Q FROM A AS A CROSS JOIN A AS B),
C AS(SELECT 0 AS Q FROM B AS A CROSS JOIN B AS B),
D AS(SELECT 0 AS Q FROM C AS A CROSS JOIN C AS B),
E AS(SELECT 0 AS Q FROM D AS A CROSS JOIN D AS B),
F AS(SELECT 0 AS Q FROM E AS A CROSS JOIN E AS B),
Numbers AS(SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Number FROM F)

SELECT
    Y.Number,Q.Number
FROM
    Numbers Y
    INNER JOIN Numbers Q ON Q.Number BETWEEN 1 AND 4
WHERE
    Y.Number BETWEEN 2000 AND YEAR(GETDATE())
ORDER BY
    Y.Number