问:
Cannot get divs to stack horizontally and be 100% of screen, in mobile view, while staying as 3 side-by-side in desktop
I have tried several solutions offered on this forum and none have worked.
Here is my code (I want 3 separate divs next to each other in desktop view, but to stack and fill 100% wide in mobile, on top each other)

Mobile Layout: 480px and below:

```<code>.gridContainer {
    width: 100%;
    overflow: hidden;
    background-color: #FFF;
        }
#bnr1 {
    float: left;
    display: block;
    color: #FFF;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 32px;
    text-align: left;
    padding-top: 5px;
    padding-right: 15px;
    padding-bottom: 15px;
    padding-left: 20px;
    margin-right: 5px;
    margin-bottom: 0px;
    margin-left: 0px;
    visibility: visible;
    overflow: visible;
    height: auto;
    background-color: #9C0;
    clear: right;
    width: 100%;
    margin-top: 0px;
}

#maincontent {
    width: auto;
    margin: 0px;
    padding: 0px;
}

#footer {
    clear: none;
    float: left;
    width: 100%;
    display: block;
    background-color: #000;
    font-family: Verdana, Geneva, sans-serif;
    font-size: 10px;
    color: #FFF;
    text-decoration: none;
    padding-left: 5px;
    text-align: center;
    margin-top: 10px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    padding-top: 5px;
    padding-right: 5px;
    padding-bottom: 5px;
}
#bnrpic {
    width: 70%;
    display: block;
    padding: 0px;
    overflow: visible;
    -webkit-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -moz-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -ms-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -o-transition: border-top-width, opacity 2000s ease-in-out 2s;
    margin-bottom: 5px;
    height: 400px;
    margin-top: 0px;
    margin-right: 0px;
    margin-left: 0px;
}
#LayoutDiv1 {
    text-align: left;
        }
#LayoutDiv2 {
    text-align: left;
    }
#LayoutDiv3 {
       text-align: left;
}
</code>```

答:
give the divs a float: left and width: 33,3%, then a width: 100% under breakpoint

```<code>.class {
   width: 33.3%;
   float: left;
}

@media (max-width: 480px) {
   .class {
      width: 100%;
   }
 }
</code>```

fiddle here

Body:
I have tried several solutions offered on this forum and none have worked.
Here is my code (I want 3 separate divs next to each other in desktop view, but to stack and fill 100% wide in mobile, on top each other)

Mobile Layout: 480px and below:

.gridContainer {
    width: 100%;
    overflow: hidden;
    background-color: #FFF;
        }
#bnr1 {
    float: left;
    display: block;
    color: #FFF;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 32px;
    text-align: left;
    padding-top: 5px;
    padding-right: 15px;
    padding-bottom: 15px;
    padding-left: 20px;
    margin-right: 5px;
    margin-bottom: 0px;
    margin-left: 0px;
    visibility: visible;
    overflow: visible;
    height: auto;
    background-color: #9C0;
    clear: right;
    width: 100%;
    margin-top: 0px;
}

#maincontent {
    width: auto;
    margin: 0px;
    padding: 0px;
}

#footer {
    clear: none;
    float: left;
    width: 100%;
    display: block;
    background-color: #000;
    font-family: Verdana, Geneva, sans-serif;
    font-size: 10px;
    color: #FFF;
    text-decoration: none;
    padding-left: 5px;
    text-align: center;
    margin-top: 10px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    padding-top: 5px;
    padding-right: 5px;
    padding-bottom: 5px;
}
#bnrpic {
    width: 70%;
    display: block;
    padding: 0px;
    overflow: visible;
    -webkit-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -moz-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -ms-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -o-transition: border-top-width, opacity 2000s ease-in-out 2s;
    margin-bottom: 5px;
    height: 400px;
    margin-top: 0px;
    margin-right: 0px;
    margin-left: 0px;
}
#LayoutDiv1 {
    text-align: left;
        }
#LayoutDiv2 {
    text-align: left;
    }
#LayoutDiv3 {
       text-align: left;
}

Body:
give the divs a float: left and width: 33,3%, then a width: 100% under breakpoint

.class {
   width: 33.3%;
   float: left;
}

@media (max-width: 480px) {
   .class {
      width: 100%;
   }
 }

fiddle here


来源: stackexchange

问:
How to apply Spotify API authentication on my current code which uses Spotify Search API?
Earlier I was using Spotify's Search API
 without any kind of authentication. But just last week or so, they made their API usage with Authentication only.
So since the past 2-3 days I've not been able to figure how this authorization works for Search API where I as a developer can let users access responses from Search API without having them to login with their Spotify accounts.

Can someone help me with this authorization stuff(The docs from Spotify don't solve my problem :< )

So here's the python code that I was earlier using -

```<code>import requests
import json

def Spotify(keyword):

    url = "https://api.spotify.com/v1/search?q="+keyword+"&type=track&limit=1"
    headers = {
    'accept': "application/json",
    'access_token':''
    }

    r = requests.get(url=url,headers=headers).text
    jsonwa = json.loads(r)
    name = jsonwa["tracks"]["items"][0]["name"]
    artists = jsonwa["tracks"]["items"][0]["artists"][0]["name"]
    song_preview_url = jsonwa["tracks"]["items"][0]["preview_url"]
    image = jsonwa["tracks"]["items"][0]["album"]["images"][1]["url"]
    return_this = []
    return_this.append(name)
    return_this.append(artists)
    return_this.append(song_preview_url)
    return_this.append(image)
    print return_this
    return return_this

song = "hello"

Spotify(song)
</code>```

答:
Per the web authorization docs:

All requests to the Spotify Web API require authorization

You'll need your users to grant permission for your app in order to get an access token. The user must be logged in to gran permission.

Once your app is granted permission by the user, you can use the refresh_token from that point on, and the user shouldn't need to grant permission again unless they revoke permission for example. You'll need to manage the access_token expiration.

ContentLicense: CC BY-SA 3.0

Body:
Earlier I was using Spotify's Search API
 without any kind of authentication. But just last week or so, they made their API usage with Authentication only.
So since the past 2-3 days I've not been able to figure how this authorization works for Search API where I as a developer can let users access responses from Search API without having them to login with their Spotify accounts.

Can someone help me with this authorization stuff(The docs from Spotify don't solve my problem :< )

So here's the python code that I was earlier using -

import requests
import json

def Spotify(keyword):

    url = "https://api.spotify.com/v1/search?q="+keyword+"&type=track&limit=1"
    headers = {
    'accept': "application/json",
    'access_token':''
    }

    r = requests.get(url=url,headers=headers).text
    jsonwa = json.loads(r)
    name = jsonwa["tracks"]["items"][0]["name"]
    artists = jsonwa["tracks"]["items"][0]["artists"][0]["name"]
    song_preview_url = jsonwa["tracks"]["items"][0]["preview_url"]
    image = jsonwa["tracks"]["items"][0]["album"]["images"][1]["url"]
    return_this = []
    return_this.append(name)
    return_this.append(artists)
    return_this.append(song_preview_url)
    return_this.append(image)
    print return_this
    return return_this

song = "hello"

Spotify(song)


问:
Conditional summation in python
I have a numpy 2d array (8000x7200). I want to count the number of cells having a value greater than a specified threshold. I tried to do this using a double loop, but it takes a lot of time.
Is there a way to perform this calculation quickly?</p>

答:
Assume your variables are defined as

```<code>np.random.seed([3,1415])
a = np.random.rand(8000, 7200)
threshold = .5
</code>```

Then use sum

*(a > threshold) is a boolean array indicating every instance of a cell being greater than some threshold.  Since boolean values are a sub-class of int, with False as zero and True as one, we can easily sum them up.  numpys sum sums over the entire array by default.

```<code>(a > threshold).sum()
28798689
</code>```

Title: Conditional summation in python

Body:
Assume your variables are defined as

np.random.seed([3,1415])
a = np.random.rand(8000, 7200)
threshold = .5

Then use sum

*(a > threshold) is a boolean array indicating every instance of a cell being greater than some threshold.  Since boolean values are a sub-class of int, with False as zero and True as one, we can easily sum them up.  numpys sum sums over the entire array by default.

(a > threshold).sum()
28798689


问:
How to use bitwise operators in an elixir when guard clause?
I have the following function, that needs to match only with values of n being a power of 2 integers (1, 2, 4, 8, 16, 32, 64, ...):

```<code>defmodule MyModule do
  def my_func(n) when is_power_of_two(n) do
     ## Some expression
  end
  def is_power_of_two(x) do
    (x != 0)
        and (x &&& (x - 1)) == 0)
  end
end
</code>```

First, I tried defining is_power_of_two as a function in the module but it didn't work and I got this error:

cannot invoke local is_power_of_two/1 inside guard.

Following this blog post, I tried to define it as the following macro:

```<code>defmodule MyModule.Util do
  defmacro is_power_of_two(x) do
    quote do
      (unquote(x) != 0)
        and ((unquote(x) &&& (unquote(x) - 1)) == 0)
    end
  end
end
</code>```

Didn't work as well and I get the following error:

cannot invoke local &&&/2 inside guard

It seems that the bitwise &&& operator cannot be called from a when clause after the macro expansion.

How to perform matches that requires guards containing bitwise operators?

答:
The error message is misleading. You're just missing an import Bitwise in MyModule.Util. The code works if I add the import:

```<code>defmodule MyModule.Util do
  import Bitwise

  defmacro is_power_of_two(x) do
    quote do
      (unquote(x) != 0) and ((unquote(x) &&& (unquote(x) - 1)) == 0)
    end
  end
end

defmodule MyModule do
  import MyModule.Util

  def my_func(n) when is_power_of_two(n) do
    true
  end
  def my_func(_), do: false
end

IO.inspect MyModule.my_func(128)
IO.inspect MyModule.my_func(129)
</code>```

Output:

```<code>true
false
</code>```

Body:
I have the following function, that needs to match only with values of n being a power of 2 integers (1, 2, 4, 8, 16, 32, 64, ...):

defmodule MyModule do
  def my_func(n) when is_power_of_two(n) do
     ## Some expression
  end
  def is_power_of_two(x) do
    (x != 0)
        and (x &&& (x - 1)) == 0)
  end
end

First, I tried defining is_power_of_two as a function in the module but it didn't work and I got this error:

cannot invoke local is_power_of_two/1 inside guard.

Following this blog post, I tried to define it as the following macro:

defmodule MyModule.Util do
  defmacro is_power_of_two(x) do
    quote do
      (unquote(x) != 0)
        and ((unquote(x) &&& (unquote(x) - 1)) == 0)
    end
  end
end

Didn't work as well and I get the following error:

cannot invoke local &&&/2 inside guard

It seems that the bitwise &&& operator cannot be called from a when clause after the macro expansion.

How to perform matches that requires guards containing bitwise operators?

Body:
The error message is misleading. You're just missing an import Bitwise in MyModule.Util. The code works if I add the import:

defmodule MyModule.Util do
  import Bitwise

  defmacro is_power_of_two(x) do
    quote do
      (unquote(x) != 0) and ((unquote(x) &&& (unquote(x) - 1)) == 0)
    end
  end
end

defmodule MyModule do
  import MyModule.Util

  def my_func(n) when is_power_of_two(n) do
    true
  end
  def my_func(_), do: false
end

IO.inspect MyModule.my_func(128)
IO.inspect MyModule.my_func(129)

Output:

true
false


问:
Nested layouts in admin-on-rest
I've started investigating admin-on-rest. It works fine for 'flat' REST-endpoints, e.g.:

/posts/

/users/

etc.
But how do I implement nesting? I mean if I click on some post-entry in 'posts' table - I want not the actual post to be opened in a <Show> view, but a list of it's comments (fetched from URL /{postId}/comments)? And I need also to keep the navigation functionality (some back-arrow button or hierarchy in the header to return to previous page).

Is this even possible with admin-or-rest?

答:
If you want to show a list of comments for a post, use the <ReferenceField>. You can see an example in the demo: https://marmelab.com/admin-on-rest-demo/#/customers/77 (click on the "orders" and "reviews" tabs to see an embedded datagrid).

If you want to link to a filtered list of comments from the post list, you'll have to create a custom button component. Once again, you can find an example in the demo: https://github.com/marmelab/admin-on-rest-demo/blob/master/src/segments/LinkToRelatedCustomers.js

Title: Nested layouts in admin-on-rest


问:
Changing uri_protocol to PATH_INFO breaks my CodeIgniter app?
I'm setting up Haughin's Twitter OAuth Library for CodeIgniter, and one requirement is to change the uri_protocol in config.php to PATH_INFO, which seems to be breaking my app in the way that all requests load the home controller (ex. Navigating to http://dev.myapp.com/login would normally take my to the Login controller, but it's just showing the default controller.)

Any ideas what would be causing this, or maybe an Apache2 configuration that's messed up?

答:
Its to do with URL rewrites. Check your .htaccess files to see if you have the correct rewrite rules. Here is something that works for me when using PATH_INFO.

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>
</code>```

The above should work for you without any modification. If you're hosting in a folder lets say like http://myserver.com/my_app/ then change /index.php to /my_app/index.php in both places.

ContentLicense: CC BY-SA 2.5

Body:
Its to do with URL rewrites. Check your .htaccess files to see if you have the correct rewrite rules. Here is something that works for me when using PATH_INFO.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>

The above should work for you without any modification. If you're hosting in a folder lets say like http://myserver.com/my_app/ then change /index.php to /my_app/index.php in both places.


问:
How to mock method chaining using Mockito
I have a method which has below line of code.

```<code>getRequestedCapabilities(){
        ObjectMapper mapper = new ObjectMapper();

Capabilities capabilities = mapper.readValue(new
 File(getClass().getClassLoader().getResource(jsonFilePath).getFile()), Capabilities.class);

}
</code>```

In my test method I have prepared a DTO(capabilities) which  mapper.readValue() needs to return when it is invoked.

```<code>Mockito.when(mapper.readValue(Mockito.mock(File.class),Mockito.eq(Capabilities.class))).thenReturn(capabilities);
</code>```

But I am getting an exception saying invalid use of matchers.
Can you please suggest how can I do this? Here the issue is how should I mock the parameters that is passed to mapper.readValue method which has method invocation chaining.

答:
You could simply specify that if readValue receives any parameters then it will return capabilities object. Something like this:

```<code>ObjectMapper mapper = mock(ObjectMapper.class);
Mockito.when(mapper.readValue(any(), any())).thenReturn(capabilities);
</code>```

But if you want to be more specific with your mock recording, you could specify which type of parameters it should be called with. Like this:

```<code>ObjectMapper mapper = mock(ObjectMapper.class);
Mockito.when(mapper.readValue(any(File.class), any(Capabilities.class))).thenReturn(capabilities);
</code>```

UPDATE:
You can set the value of the file path manually. In the end, in unit tests you can and should declare any value in your test directly. Otherwise your test is not unit test anymore, given that you are interacting with other components.

Body:
I have a method which has below line of code.

getRequestedCapabilities(){
        ObjectMapper mapper = new ObjectMapper();

Capabilities capabilities = mapper.readValue(new
 File(getClass().getClassLoader().getResource(jsonFilePath).getFile()), Capabilities.class);

}

In my test method I have prepared a DTO(capabilities) which  mapper.readValue() needs to return when it is invoked.

Mockito.when(mapper.readValue(Mockito.mock(File.class),Mockito.eq(Capabilities.class))).thenReturn(capabilities);

But I am getting an exception saying invalid use of matchers.
Can you please suggest how can I do this? Here the issue is how should I mock the parameters that is passed to mapper.readValue method which has method invocation chaining.

Body:
You could simply specify that if readValue receives any parameters then it will return capabilities object. Something like this:

ObjectMapper mapper = mock(ObjectMapper.class);
Mockito.when(mapper.readValue(any(), any())).thenReturn(capabilities);

But if you want to be more specific with your mock recording, you could specify which type of parameters it should be called with. Like this:

ObjectMapper mapper = mock(ObjectMapper.class);
Mockito.when(mapper.readValue(any(File.class), any(Capabilities.class))).thenReturn(capabilities);

UPDATE:
You can set the value of the file path manually. In the end, in unit tests you can and should declare any value in your test directly. Otherwise your test is not unit test anymore, given that you are interacting with other components.


问:
Why is return used instead of console.log?
I'm trying to learn JS from Codecademy. I'm doing this excercise.

Can someone please tell me why return is used instead of console.log()?
I don't fully understand how return works.

答:
Return Is used to return a value from a function.

```<code>function foo(){
    return 1;
}

console.log(foo()); //1
</code>```

Useful when you have a function that does an operation that needs to return a value, and saves up space so you don't have to use a variable. It's generally just a more professional way of coding.

Body:
Return Is used to return a value from a function.

function foo(){
    return 1;
}

console.log(foo()); //1

Useful when you have a function that does an operation that needs to return a value, and saves up space so you don't have to use a variable. It's generally just a more professional way of coding.


问:
Why is there a NullPointerException in this method call?
When I call a method like this:

```<code>int value1;
Integer value2 = null;

setValue(value2);

private void setValue(int value) {
    value1 = value;
}
</code>```

Why is there a NullPointerException?

答:
Null Pointer Exception happens when you try to call a method on null reference. So when you are calling that method and any where you are using that argument to call some method you will get a Null Pointer Exception, otherwise if you are passing it into an API of JAVA or someone else and if the same thing happens inside then also you will jump into NPE. So debug your code properly to find the possible places where you might get Exception and give null checks.

```<code>void setValue(Object value) {

     // case : 1
     int i = (Integer) value;

     // case : 2
     int i = value.toString().length();

     // case : 3
     value.getSomethingElse();

}
</code>```

These are the possible cases where you will be getting NPE. But if you are just calling this method to simply set some derived attribute, its fine because null can be assigned to any derived attribute. But if you call any method on that attribute after setting it to null then the result will be the same.

```<code>class Foo {

     private String entity;
     public void setEntity(String entity) {
          this.entity = entity;
     }
     public String getEntity() {
          return entity;
     }
}
class FooManager {

      public static void main(String[] arg) {
            Foo foo = new Foo();
            foo.setEntity(null);
            System.out.println(foo.getEntity().length());   //NPE
      }
}
</code>```

Body:
When I call a method like this:

int value1;
Integer value2 = null;

setValue(value2);

private void setValue(int value) {
    value1 = value;
}

Why is there a NullPointerException?

Body:
Null Pointer Exception happens when you try to call a method on null reference. So when you are calling that method and any where you are using that argument to call some method you will get a Null Pointer Exception, otherwise if you are passing it into an API of JAVA or someone else and if the same thing happens inside then also you will jump into NPE. So debug your code properly to find the possible places where you might get Exception and give null checks.

void setValue(Object value) {

     // case : 1
     int i = (Integer) value;

     // case : 2
     int i = value.toString().length();

     // case : 3
     value.getSomethingElse();

}

These are the possible cases where you will be getting NPE. But if you are just calling this method to simply set some derived attribute, its fine because null can be assigned to any derived attribute. But if you call any method on that attribute after setting it to null then the result will be the same.

class Foo {

     private String entity;
     public void setEntity(String entity) {
          this.entity = entity;
     }
     public String getEntity() {
          return entity;
     }
}
class FooManager {

      public static void main(String[] arg) {
            Foo foo = new Foo();
            foo.setEntity(null);
            System.out.println(foo.getEntity().length());   //NPE
      }
}


答:
A NullPointerException is generally thrown when the JVM expected a valid object reference but got null instead. A very common specific case of this is when you set a reference to null and then try to call a method or access a field on that reference.

Given the information you have given, it is impossible tell if your code will throw an exception.

If the setter just assigns a reference, it will not throw anything immediately, because you can pretty much assign null to anything that is not a primitive. This is not to say that you will not get the exception later when you try to access the object you just set.

If the setter performs any type of actions directly on the reference you passed in, without checking if it is null first, you are likely to get an exception. Most likely, however, if the setter is well written, it will perform some checks and take appropriate action before blindly using the passed-in reference.

Title: Why is there a NullPointerException in this method call?


问:
Calling JObject.Value<string> throws InvalidCastException after upgrading JSON.NET to v10
What could be the reason for the following code to suddenly be throwing an error after upgrading the JSON.NET library to v10:

```<code>var name = json.Value<string>("Name"); // Error: Object must implement IConvertible
</code>```

The error goes away if I change the line to indexer syntax:

```<code>var name = (string)json["Name"];
</code>```

The puzzling bit is that the former line used to work perfectly fine with v6 of the library, but fails after upgrading to v10.

I'm also detecting a different behavior of null comparisons, which I also suspect is caused by the upgrade:

```<code>if (json["Name"] != null)
{
    // I find myself in here because JTokenType.Null was unexpectedly returned above.
    // This wasn't the case in v6!
}
</code>```

Was there a breaking change somewhere between v6 and v10 of Newtonsoft.Json library? If not, what else could be causing my problems (especially the first one)?

答:
It turns out that the problematic value was a JToken of type Guid. I can't currently verify if this indeed worked differently in JSON.NET v6, but it seems to me that JToken.Value<T>() method performs conversion to T differently than typecasting JToken instance directly to T does. I also can't tell at this time whether this is a bug in JSON.NET or simply a gotcha that needs to be remembered.

Sadly, I'm no closer to the explanation for my second problem, because I don't have a reproducible case, yet.

Body:
What could be the reason for the following code to suddenly be throwing an error after upgrading the JSON.NET library to v10:

var name = json.Value<string>("Name"); // Error: Object must implement IConvertible

The error goes away if I change the line to indexer syntax:

var name = (string)json["Name"];

The puzzling bit is that the former line used to work perfectly fine with v6 of the library, but fails after upgrading to v10.

I'm also detecting a different behavior of null comparisons, which I also suspect is caused by the upgrade:

if (json["Name"] != null)
{
    // I find myself in here because JTokenType.Null was unexpectedly returned above.
    // This wasn't the case in v6!
}

Was there a breaking change somewhere between v6 and v10 of Newtonsoft.Json library? If not, what else could be causing my problems (especially the first one)?


问:
Trying to implement something similar to jQuery
I'm trying to implement something similar to jQuery.

Basically, whenever I'd be doing something with DOM elements, I'd like to use a wrapper object's methods instead of manipulating the DOM directly.

This is what I have so far

HTML:

```<code><a href='#!'></a>
</code>```

JS:

```<code>var dd = function(selector)
{
    return new dd.prototype.constructor(selector);
}
dd.prototype =
{
    constructor: function(selector)
    {
        var nodes = document.querySelectorAll(selector);

        for(var i = 0; i < nodes.length; i++)
            this[i] = nodes[i];

        this.length = nodes.length;
        return Array.prototype.slice.call(this);
    },
    addClass: function(cl)
    {
        alert('a');
    }
};

var a = dd('[href="#!"]');
a.addClass('asd');
</code>```

The problems:

I get an error in the browser console saying that a.addClass is
not a function

dd('a') instanceof dd === false while $('a') instanceof $ === true, so I know that my logic is somehow wrong here.

Sadly, I don't quite get what I'm doing wrong.

答:
Not sure what you are trying to achieve but lets see what things are wrong right now.

1) You are calling new on constructor and then returning return Array.prototype.slice.call(this); so what you get in a is an array. Obviously array doesn't know about your function addClass.

2) If you comment out array slice part, you would be returning an object for which this is set to constructorbut again addClass is not added to prototype object of constructor. To do that you need to add addClass like below:

```<code>dd.prototype.constructor.prototype.addClass = function (cl) {
            alert('a');
        }
</code>```

With these changes you would get your alert and hopefully can proceed further.
So overall these changes:

var dd = function(selector) {
  return new dd.prototype.constructor(selector);
}
dd.prototype = {
  constructor: function(selector) {
    var nodes = document.querySelectorAll(selector);

    for (var i = 0; i < nodes.length; i++)
      this[i] = nodes[i];

    this.length = nodes.length;
    //return Array.prototype.slice.call(this);
  },
  //addClass: function (cl) {
  //    alert('a');
  //}
};
dd.prototype.constructor.prototype.addClass = function(cl) {
  alert('a');
}
var a = dd('[href="#!"]');
a.addClass('asd');```
<pre class="snippet-code-html lang-html prettyprint-override"><code></code>```

Body:
I'm trying to implement something similar to jQuery.

Basically, whenever I'd be doing something with DOM elements, I'd like to use a wrapper object's methods instead of manipulating the DOM directly.

This is what I have so far

HTML:

JS:

var dd = function(selector)
{
    return new dd.prototype.constructor(selector);
}
dd.prototype =
{
    constructor: function(selector)
    {
        var nodes = document.querySelectorAll(selector);

        for(var i = 0; i < nodes.length; i++)
            this[i] = nodes[i];

        this.length = nodes.length;
        return Array.prototype.slice.call(this);
    },
    addClass: function(cl)
    {
        alert('a');
    }
};

var a = dd('[href="#!"]');
a.addClass('asd');

The problems:

I get an error in the browser console saying that a.addClass is
not a function

dd('a') instanceof dd === false while $('a') instanceof $ === true, so I know that my logic is somehow wrong here.

Sadly, I don't quite get what I'm doing wrong.

Body:
Not sure what you are trying to achieve but lets see what things are wrong right now.

1) You are calling new on constructor and then returning return Array.prototype.slice.call(this); so what you get in a is an array. Obviously array doesn't know about your function addClass.

2) If you comment out array slice part, you would be returning an object for which this is set to constructorbut again addClass is not added to prototype object of constructor. To do that you need to add addClass like below:

dd.prototype.constructor.prototype.addClass = function (cl) {
            alert('a');
        }

With these changes you would get your alert and hopefully can proceed further.
So overall these changes:

var dd = function(selector) {
  return new dd.prototype.constructor(selector);
}
dd.prototype = {
  constructor: function(selector) {
    var nodes = document.querySelectorAll(selector);

    for (var i = 0; i < nodes.length; i++)
      this[i] = nodes[i];

    this.length = nodes.length;
    //return Array.prototype.slice.call(this);
  },
  //addClass: function (cl) {
  //    alert('a');
  //}
};
dd.prototype.constructor.prototype.addClass = function(cl) {
  alert('a');
}
var a = dd('[href="#!"]');
a.addClass('asd');

<a href='#!'></a>


问:
VBA Delete autofiltered rows in linked table
I have a linked table where I want to delete rows based on a date.
I get it to work out all the way to when I want to delete the rows where i get the error message "Delete method of Range Class failed".
What can be wrong here in the end?

```<code>Sheets("TimeSeries").Select
Range("TimeSeries[#Headers]").Select
Selection.AutoFilter
ActiveSheet.ListObjects("TimeSeries").Range.AutoFilter Field:=4, Operator:= _
    xlFilterValues, Criteria2:=Array(1, Format(Sheets("Start").Range("C2").Value, "mm/dd/yyyy"))
Range("A1").Select
Selection.End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.SpecialCells(xlCellTypeVisible).Offset(0, 0).Select
Selection.EntireRow.Delete
</code>```

Thanks!

答:
Assuming you autofilter statement works correctly, no need to use Select, try it this way:

```<code>With Sheets("TimeSeries").ListObjects("TimeSeries").Range
  .AutoFilter ......
  .Offset(1).Delete
  .AutoFilter
End With
</code>```

Body:
I have a linked table where I want to delete rows based on a date.
I get it to work out all the way to when I want to delete the rows where i get the error message "Delete method of Range Class failed".
What can be wrong here in the end?

Sheets("TimeSeries").Select
Range("TimeSeries[#Headers]").Select
Selection.AutoFilter
ActiveSheet.ListObjects("TimeSeries").Range.AutoFilter Field:=4, Operator:= _
    xlFilterValues, Criteria2:=Array(1, Format(Sheets("Start").Range("C2").Value, "mm/dd/yyyy"))
Range("A1").Select
Selection.End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.SpecialCells(xlCellTypeVisible).Offset(0, 0).Select
Selection.EntireRow.Delete

Thanks!

Body:
Assuming you autofilter statement works correctly, no need to use Select, try it this way:

With Sheets("TimeSeries").ListObjects("TimeSeries").Range
  .AutoFilter ......
  .Offset(1).Delete
  .AutoFilter
End With


问:
Will using a parallel stream on a single-core processor be slower than using a sequential stream?
I am applying an operation to every element in a very large LinkedList<LinkedList<Double>>:

```<code>list.stream().map(l -> l.stream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));
</code>```

On my computer (quad-core), parallel streams seem to be faster than using sequential streams:

```<code>list.parallelStream().map(l -> l.parallelStream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));
</code>```

However, not every computer is going to be multi-core. My question is, will using parallel streams on a single-processor computer be noticeably slower than using sequential streams?

答:
This is highly implementation specific, but usually, a parallel stream will go through a different code path for most operations, which implies performing additional work, but at the same time, the thread pool will be configured to the number of CPU cores.

E.g., if you run the following program

```<code>System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1");
System.out.println("Parallelism: "+ForkJoinPool.getCommonPoolParallelism());
Set<Thread> threads = ConcurrentHashMap.newKeySet();
for(int run=0; run<2; run++) {
    IntStream stream = IntStream.range(0, 100);
    if(run==1) {
        stream = stream.parallel();
        System.out.println("Parallel:");
    }
    int chunks = stream
        .mapToObj(i->Thread.currentThread())
        .collect(()->new int[]{1}, (a,t)->threads.add(t), (a,b)->a[0]+=b[0])[0];
    System.out.println("processed "+chunks+" chunk(s) with "+threads.size()+" thread(s)");
}
</code>```

it will print something like

Parallelism: 1
processed 1 chunk(s) with 1 thread(s)
Parallel:
processed 4 chunk(s) with 1 thread(s)
```

<p>You can see the effect of splitting the workload, whereas splitting to four times the configured parallelism is not a coincidence, but also that only one thread is involved, so there is no inter-thread communication happening here. Whether the JVM’s optimizer will detect the single-thread nature of this operation and elide synchronization costs in this case, is, like anything else, an implementation detail.</p>

<p>All in all, the overhead is not very big and doesn’t scale with the actual amount of work, so if the actual work is big enough to benefit from parallel processing on SMP machines, the fraction of the overhead will be negligible on single core machines.</p>

<hr>

<p>But if you care for performance, you should also look at the other aspects of your code.</p>

<p>By repeating an operation like <code>Collections.max(l)</code> for every element of <code>l</code>, you are combining two linear operations to an operation with quadratic time complexity. It’s easy to perform this operation only once instead:</p>

```List<List<Double>> result =
    list.parallelStream()
        .map(l -> {
                double limit = Collections.max(l)-5;
                return l.parallelStream()
                        .filter(d -> limit < d)
                        .collect(Collectors.toCollection(LinkedList::new));
            })
        .collect(Collectors.toCollection(LinkedList::new));
```

<p>Depending on the list sizes, the impact of this little change, turning a quadratic operation to linear, might be far bigger than dividing the processing time by just the number of cpu cores (in the best case).</p>

<p>The other consideration is whether you really need a <code>LinkedList</code>. For most practical purposes, a <code>LinkedList</code> performs worse than, e.g. an <code>ArrayList</code>, and if you don’t need mutability, you may just use the <code>toList()</code> collector and let the JRE return the best list it can offer…</p>

```List<List<Double>> result =
    list.parallelStream()
        .map(l -> {
                double limit = Collections.max(l)-5;
                return l.parallelStream()
                        .filter(d -> limit < d)
                        .collect(Collectors.toList());
            })
        .collect(Collectors.toList());
```

Keep in mind that after changing the performance characteristics, rechecking whether the parallelization still has any benefit is recommended. It should also be checked for both stream operations individually. Usually, if the outer stream has a decent parallelization, turning the inner stream to parallel does not improve the overall performance.

Also, the benefit of parallel streams will be much higher if the source lists are random access lists instead of LinkedLists.

Body:
I am applying an operation to every element in a very large LinkedList<LinkedList<Double>>:

list.stream().map(l -> l.stream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));

On my computer (quad-core), parallel streams seem to be faster than using sequential streams:

list.parallelStream().map(l -> l.parallelStream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));

However, not every computer is going to be multi-core. My question is, will using parallel streams on a single-processor computer be noticeably slower than using sequential streams?

Body:
This is highly implementation specific, but usually, a parallel stream will go through a different code path for most operations, which implies performing additional work, but at the same time, the thread pool will be configured to the number of CPU cores.

E.g., if you run the following program

System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1");
System.out.println("Parallelism: "+ForkJoinPool.getCommonPoolParallelism());
Set<Thread> threads = ConcurrentHashMap.newKeySet();
for(int run=0; run<2; run++) {
    IntStream stream = IntStream.range(0, 100);
    if(run==1) {
        stream = stream.parallel();
        System.out.println("Parallel:");
    }
    int chunks = stream
        .mapToObj(i->Thread.currentThread())
        .collect(()->new int[]{1}, (a,t)->threads.add(t), (a,b)->a[0]+=b[0])[0];
    System.out.println("processed "+chunks+" chunk(s) with "+threads.size()+" thread(s)");
}

it will print something like

Parallelism: 1
processed 1 chunk(s) with 1 thread(s)
Parallel:
processed 4 chunk(s) with 1 thread(s)

You can see the effect of splitting the workload, whereas splitting to four times the configured parallelism is not a coincidence, but also that only one thread is involved, so there is no inter-thread communication happening here. Whether the JVM’s optimizer will detect the single-thread nature of this operation and elide synchronization costs in this case, is, like anything else, an implementation detail.

All in all, the overhead is not very big and doesn’t scale with the actual amount of work, so if the actual work is big enough to benefit from parallel processing on SMP machines, the fraction of the overhead will be negligible on single core machines.

But if you care for performance, you should also look at the other aspects of your code.

By repeating an operation like Collections.max(l) for every element of l, you are combining two linear operations to an operation with quadratic time complexity. It’s easy to perform this operation only once instead:

List<List<Double>> result =
    list.parallelStream()
        .map(l -> {
                double limit = Collections.max(l)-5;
                return l.parallelStream()
                        .filter(d -> limit < d)
                        .collect(Collectors.toCollection(LinkedList::new));
            })
        .collect(Collectors.toCollection(LinkedList::new));

Depending on the list sizes, the impact of this little change, turning a quadratic operation to linear, might be far bigger than dividing the processing time by just the number of cpu cores (in the best case).

The other consideration is whether you really need a LinkedList. For most practical purposes, a LinkedList performs worse than, e.g. an ArrayList, and if you don’t need mutability, you may just use the toList() collector and let the JRE return the best list it can offer…

List<List<Double>> result =
    list.parallelStream()
        .map(l -> {
                double limit = Collections.max(l)-5;
                return l.parallelStream()
                        .filter(d -> limit < d)
                        .collect(Collectors.toList());
            })
        .collect(Collectors.toList());

Keep in mind that after changing the performance characteristics, rechecking whether the parallelization still has any benefit is recommended. It should also be checked for both stream operations individually. Usually, if the outer stream has a decent parallelization, turning the inner stream to parallel does not improve the overall performance.

Also, the benefit of parallel streams will be much higher if the source lists are random access lists instead of LinkedLists.


问:
How to add bookmark toolbar in visual studio 2012
I could not find in Google or I think I don't know how to search about it.

Any help would be appreciated

答:
This is late to the game, but I still have a viable copy of VS 2010 that I use sometimes.

For those who find this when searching for how to show the bookmark toolbar in Visual Studio 2010 like I did, here's how:

On the File menu, select: View > Toolbars > Text Editor.

That's it, easy once you know how, but difficult if you don't.


问:
Swap two blocks of text programatically
I have an XML file made up of multiple blocks that are very similar. Here are two:

```<code>    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-0
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-1
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
</code>```

Typically I have hundreds of similar <Grid> objects in a single file. Now, I want to programatically swap the positions of the <DataItem Name="r"> and <DataItem Name="z"> blocks in each <Grid> object such that the <DataItem>s are in the order z, theta, r. Also, for each Dimensions=" x y z " statement, each Dimensions attribute that contains three values, I want the attribute to be rewritten as Dimensions=" z y x ".

I don't really mind the programming language being used to do this. I'm on a Linux workstation with bash, python, perl... all the standard stuff.

EDIT: This answer uses sed to match blocks of text, but I'm not sure how to manipulate the selected block afterwards. This other answer swaps single lines up and down, but I'm not sure how to generalize to blocks of text, and to make it swap blocks.

答:
You can do that with replace, if you have your XML as a string :

```<code>#Swapping ( '\"' the slash escape the " to make it the string caracter)
XML_str = XML_str.replace("\"r","SomethingThatNeverAppearInTheXML")
XML_str = XML_str.replace("\"z","\r")
XML_str = XML_str.replace("SomethingThatNeverAppearInTheXML","\"z")
#Replacing
XML_str = XML_str.replace("x y z","z y x")
</code>```

input

```<code>XML_str = """
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-0
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-1
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
"""
</code>```

output

```<code><Grid Name="EMFieldMany" GridType="Uniform">
    <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
    <Attribute AttributeType="Scalar" Name="Er" Center="Node">
        <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/field/Er-0
        </DataItem>
    </Attribute>
    <Geometry GeometryType="VXVYVZ">
        <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/r
        </DataItem>
        <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/theta
        </DataItem>
        <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/z
        </DataItem>
    </Geometry>
</Grid>
<Grid Name="EMFieldMany" GridType="Uniform">
    <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
    <Attribute AttributeType="Scalar" Name="Er" Center="Node">
        <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/field/Er-1
        </DataItem>
    </Attribute>
    <Geometry GeometryType="VXVYVZ">
        <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/r
        </DataItem>
        <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/theta
        </DataItem>
        <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/z
        </DataItem>
    </Geometry>
</Grid>
</code>```

Title: Swap two blocks of text programatically

Body:
I have an XML file made up of multiple blocks that are very similar. Here are two:

    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-0
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-1
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>

Typically I have hundreds of similar <Grid> objects in a single file. Now, I want to programatically swap the positions of the <DataItem Name="r"> and <DataItem Name="z"> blocks in each <Grid> object such that the <DataItem>s are in the order z, theta, r. Also, for each Dimensions=" x y z " statement, each Dimensions attribute that contains three values, I want the attribute to be rewritten as Dimensions=" z y x ".

I don't really mind the programming language being used to do this. I'm on a Linux workstation with bash, python, perl... all the standard stuff.

EDIT: This answer uses sed to match blocks of text, but I'm not sure how to manipulate the selected block afterwards. This other answer swaps single lines up and down, but I'm not sure how to generalize to blocks of text, and to make it swap blocks.

Body:
You can do that with replace, if you have your XML as a string :

#Swapping ( '\"' the slash escape the " to make it the string caracter)
XML_str = XML_str.replace("\"r","SomethingThatNeverAppearInTheXML")
XML_str = XML_str.replace("\"z","\r")
XML_str = XML_str.replace("SomethingThatNeverAppearInTheXML","\"z")
#Replacing
XML_str = XML_str.replace("x y z","z y x")

input

XML_str = """
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-0
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-1
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
"""

output

<Grid Name="EMFieldMany" GridType="Uniform">
    <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
    <Attribute AttributeType="Scalar" Name="Er" Center="Node">
        <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/field/Er-0
        </DataItem>
    </Attribute>
    <Geometry GeometryType="VXVYVZ">
        <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/r
        </DataItem>
        <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/theta
        </DataItem>
        <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/z
        </DataItem>
    </Geometry>
</Grid>
<Grid Name="EMFieldMany" GridType="Uniform">
    <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
    <Attribute AttributeType="Scalar" Name="Er" Center="Node">
        <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/field/Er-1
        </DataItem>
    </Attribute>
    <Geometry GeometryType="VXVYVZ">
        <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/r
        </DataItem>
        <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/theta
        </DataItem>
        <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
            Field_reflected_time_3D.hdf5:/coordinates/z
        </DataItem>
    </Geometry>
</Grid>


问:
Git push won't do anything (everything up-to-date)
I'm trying to update a Git repository on GitHub. I made a bunch of changes, added them, committed then attempted to do a git push. The response tells me that everything is up to date, but clearly it's not.

```<code>git remote show origin
</code>```

responds with the repository I'd expect.

Why is Git telling me the repository is up to date when there are local commits that aren't visible on the repository?

```<code>  [searchgraph]  git status
# On branch develop
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       Capfile
#       config/deploy.rb
nothing added to commit but untracked files present (use "git add" to track)

  [searchgraph]  git add .

  [searchgraph]  git status
# On branch develop
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   Capfile
#       new file:   config/deploy.rb
#

  [searchgraph]  git commit -m "Added Capistrano deployment"
[develop 12e8af7] Added Capistrano deployment
 2 files changed, 26 insertions(+), 0 deletions(-)
 create mode 100644 Capfile
 create mode 100644 config/deploy.rb

  [searchgraph]  git push
Everything up-to-date

  [searchgraph]  git status
# On branch develop
nothing to commit (working directory clean)
</code>```

答:
For my case, none of other solutions worked. I had to do a backup of new modified files (shown with git status), and run a git reset --hard. This allowed me to realign with the remote server. Adding new modified files, and running

```<code>git add .
git commit -am "my comment"
git push
</code>```

Did the trick. I hope this helps someone, as a "last chance" solution.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to update a Git repository on GitHub. I made a bunch of changes, added them, committed then attempted to do a git push. The response tells me that everything is up to date, but clearly it's not.

git remote show origin

responds with the repository I'd expect.

Why is Git telling me the repository is up to date when there are local commits that aren't visible on the repository?

  [searchgraph]  git status
# On branch develop
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       Capfile
#       config/deploy.rb
nothing added to commit but untracked files present (use "git add" to track)

  [searchgraph]  git add .

  [searchgraph]  git status
# On branch develop
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   Capfile
#       new file:   config/deploy.rb
#

  [searchgraph]  git commit -m "Added Capistrano deployment"
[develop 12e8af7] Added Capistrano deployment
 2 files changed, 26 insertions(+), 0 deletions(-)
 create mode 100644 Capfile
 create mode 100644 config/deploy.rb

  [searchgraph]  git push
Everything up-to-date

  [searchgraph]  git status
# On branch develop
nothing to commit (working directory clean)

Body:
For my case, none of other solutions worked. I had to do a backup of new modified files (shown with git status), and run a git reset --hard. This allowed me to realign with the remote server. Adding new modified files, and running

git add .
git commit -am "my comment"
git push

Did the trick. I hope this helps someone, as a "last chance" solution.


问:
How to randomly select a certain percent of rows in Access with another condition?
I have a table with, let's say, boys, girls, number of purchases and price. I want to randomly select 10%  of girls with a condition that money they  spent should be 30% of a total amount of money spent from both groups. To select 10% of girls I use this code:

SELECT TOP 10 PERCENT from Students
Where StudentType='girl'
ORDER BY rnd(ID)

How should I place an additional condition?

答:
Since you are already selecting a random portion, the question is really just about selection criteria involving a "total".  The key here is that you need another query, an aggregate query.  The other query can be either another saved query, an embedded subquery, or a call to a function which performs the query.

Using a subquery to get the total:

```<code>SELECT TOP 10 PERCENT *
FROM Students
WHERE StudentType='girl'
    AND (Students.[Spent] / (SELECT SUM(S2.[Spent]) FROM Students As S2) = 0.30)
ORDER BY rnd(ID)
</code>```

Make sure to add a different alias to the same table, since Access can get confused if the subquery has a table with the same name as the main query.  The question did not mention the "amount spent" column so I just guessed.  This also assumes that "both groups" is essentially the same as "all student records".  If that's not the case then you could add to the subquery WHERE S2.StudentType In ('girl', 'boy').

Using a domain aggregate function:

```<code>SELECT TOP 10 PERCENT *
FROM Students
WHERE StudentType='girl'
    AND (Students.[Spent] / DSum("[Spent]", "Students", "") = 0.30)
ORDER BY rnd(ID)
</code>```

Using another saved query:

First create and save the separate aggregate query as [Summed]:

```<code>SELECT SUM(S2.[Spent]) As TotalSpent FROM Students As S2
</code>```

Now do a cross join so that each row is paired with the total:

```<code>SELECT TOP 10 PERCENT *
FROM Students, Summed
WHERE StudentType='girl'
    AND (Students.[Spent] / Summed.TotalSpent = 0.30)
ORDER BY rnd(ID)
</code>```

The efficiency of each solution may vary.  For a small table of students it might not matter. If it does become an issue, I have found that the Domain Aggregate functions are not very efficient even though they appear to be simpler to use. More powerful query engines (not Access) are often better at analyzing a query plan and automatically reducing redundant calculations, but with Access you have to plan that out yourself.

Last note: If you have more complicated grouping, any of the solutions will have additional join conditions.  For instance, if the aggregate query also had a GROUP BY clause on an ID, then instead of a cross join, you'd now want an INNER JOIN matching the ID in the main table.  In the case of the domain aggregate function, you'd want to specify a criteria parameter that refers to a table field value.  The point is that the above examples are not a precise template for all cases.

Body:
Since you are already selecting a random portion, the question is really just about selection criteria involving a "total".  The key here is that you need another query, an aggregate query.  The other query can be either another saved query, an embedded subquery, or a call to a function which performs the query.

Using a subquery to get the total:

SELECT TOP 10 PERCENT *
FROM Students
WHERE StudentType='girl'
    AND (Students.[Spent] / (SELECT SUM(S2.[Spent]) FROM Students As S2) = 0.30)
ORDER BY rnd(ID)

Make sure to add a different alias to the same table, since Access can get confused if the subquery has a table with the same name as the main query.  The question did not mention the "amount spent" column so I just guessed.  This also assumes that "both groups" is essentially the same as "all student records".  If that's not the case then you could add to the subquery WHERE S2.StudentType In ('girl', 'boy').

Using a domain aggregate function:

SELECT TOP 10 PERCENT *
FROM Students
WHERE StudentType='girl'
    AND (Students.[Spent] / DSum("[Spent]", "Students", "") = 0.30)
ORDER BY rnd(ID)

Using another saved query:

First create and save the separate aggregate query as [Summed]:

SELECT SUM(S2.[Spent]) As TotalSpent FROM Students As S2

Now do a cross join so that each row is paired with the total:

SELECT TOP 10 PERCENT *
FROM Students, Summed
WHERE StudentType='girl'
    AND (Students.[Spent] / Summed.TotalSpent = 0.30)
ORDER BY rnd(ID)

The efficiency of each solution may vary.  For a small table of students it might not matter. If it does become an issue, I have found that the Domain Aggregate functions are not very efficient even though they appear to be simpler to use. More powerful query engines (not Access) are often better at analyzing a query plan and automatically reducing redundant calculations, but with Access you have to plan that out yourself.

Last note: If you have more complicated grouping, any of the solutions will have additional join conditions.  For instance, if the aggregate query also had a GROUP BY clause on an ID, then instead of a cross join, you'd now want an INNER JOIN matching the ID in the main table.  In the case of the domain aggregate function, you'd want to specify a criteria parameter that refers to a table field value.  The point is that the above examples are not a precise template for all cases.


答:
You're mixing classes and object factories. You can't have it both ways.

Either you do (jQuery style):

```<code>function dd(selector) {
    return {
        addClass: function () {/**/}
    };
}

var a = dd('[href="#!"]');
a.addClass('asd');
</code>```

Or you do:

```<code>function dd(selector) {
    this.selector = selector;
}
dd.prototype.addClass = function () {/**/};

var a = new dd('[href="#!"]');
a.addClass('asd');
</code>```

Note that this doesn't automatically make a instanceof Array like jQuery does. You need some black magic to do that.

Title: Trying to implement something similar to jQuery

Body:
You're mixing classes and object factories. You can't have it both ways.

Either you do (jQuery style):

function dd(selector) {
    return {
        addClass: function () {/**/}
    };
}

var a = dd('[href="#!"]');
a.addClass('asd');

Or you do:

function dd(selector) {
    this.selector = selector;
}
dd.prototype.addClass = function () {/**/};

var a = new dd('[href="#!"]');
a.addClass('asd');

Note that this doesn't automatically make a instanceof Array like jQuery does. You need some black magic to do that.


问:
Nuxt generate command create an empty html
My application works with "npm run dev" command, but when i try to build for production with "npm run generate" in .nuxt/dist folder i have index.html with this content:

```<code><!DOCTYPE html>
<html {{ HTML_ATTRS }}>
  <head>
    {{ HEAD }}
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
</html>
</code>```

i miss some configuration?

答: The build result of nuxt generate is in the /dist folder, not in the .nuxt/dist folder.

Body:
My application works with "npm run dev" command, but when i try to build for production with "npm run generate" in .nuxt/dist folder i have index.html with this content:

<!DOCTYPE html>

    {{ HEAD }}

    {{ APP }}

i miss some configuration?


问:
Cygwin executable not found even if existing
I have recently been trying to install Blackbox on Cygwin, and as the docs say I did cp ./blackbox/bin/* /usr/bin.

Then I tried accessing it using blackbox_edit, and I get:

/bin/bash: /usr/bin/blackbox_edit: No file or directory

Same when I run /usr/bin/blackbox_edit. Running stat /usr/bin/blackbox_edit gives:

```<code>  File: /usr/bin/blackbox_edit
  Size: 958             Blocks: 4          IO Block: 65536  regular file
Device: 671faeah/108133098d     Inode: 2251799814041428  Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (197609/   adrie)   Gid: (197609/   adrie)
Access: 2017-06-07 15:34:50.353508600 +0200
Modify: 2017-06-07 15:54:58.823472200 +0200
Change: 2017-06-07 15:59:00.592320500 +0200
 Birth: 2017-06-07 15:34:50.353508600 +0200
</code>```

What am I missing?

Thanks in advance.

答:
Nevermind, it was a more obscure problem. To make it short, instead of running bash scripts with /usr/bin/bash.exe, cygwin was resolving C:\Windows\System32\bash.exe first (Ubuntu's bash).

Thanks anyways for your help!

Body:
I have recently been trying to install Blackbox on Cygwin, and as the docs say I did cp ./blackbox/bin/* /usr/bin.

Then I tried accessing it using blackbox_edit, and I get:

/bin/bash: /usr/bin/blackbox_edit: No file or directory

Same when I run /usr/bin/blackbox_edit. Running stat /usr/bin/blackbox_edit gives:

  File: /usr/bin/blackbox_edit
  Size: 958             Blocks: 4          IO Block: 65536  regular file
Device: 671faeah/108133098d     Inode: 2251799814041428  Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (197609/   adrie)   Gid: (197609/   adrie)
Access: 2017-06-07 15:34:50.353508600 +0200
Modify: 2017-06-07 15:54:58.823472200 +0200
Change: 2017-06-07 15:59:00.592320500 +0200
 Birth: 2017-06-07 15:34:50.353508600 +0200

What am I missing?

Thanks in advance.


问:
How can I reload .emacs after changing it?
How can I get Emacs to reload all my definitions that I have updated in .emacs without restarting Emacs?

答:
You can set a key binding for Emacs like this:</p>
```<code>;; Reload Emacs configuration
(defun reload-init-file ()
  (interactive)
  (load-file "~/.emacs"))

(global-set-key (kbd "C-c r") 'reload-init-file)
</code>```

Body:
You can set a key binding for Emacs like this:

;; Reload Emacs configuration
(defun reload-init-file ()
  (interactive)
  (load-file "~/.emacs"))

(global-set-key (kbd "C-c r") 'reload-init-file)