问:
Bing Maps - REST imagery API draw line limitations
Problem:

When using a POST to create pushpins and draw lines it only works if I draw up to 62 lines.

Why Post

Want to increase the limitation of 18 pushpins when using a GET request.

API Used:

```<code>URL:http://ecn.dev.virtualearth.net/REST/v1/Imagery/Map/AerialWithLabels?zoomLevel=20&format=Jpeg&mapSize=640,500&key=MYKEY

Body:
pp=Latitude,longitude;iconstyle
..
..
pp=latitude,longitude;iconstyle //I have 100 pushpins
dc=l,FF007EFF,3;latitude1,longitude1_latitude2,longitude_2.....//I have the corresponding lines for all the push pins.
</code>```

If I just draw the pushpins it works fine and I see the 100 push pins, but when I include the lines it fails with:

```<code>"errorDetails": [
        "Your request could not be completed because there was a problem with the service."
    ],
  "resourceSets": [],
    "statusCode": 500
</code>```

But if I delete enough coordinates in the "dc=l.." parameter to draw exactly 62 lines or less it works fine I see 100 pushpins but not all the lines.

Does anyone know if there is a limitation on how many lines can we draw on the static map? I looked at the documentation here it only says the limitation on pushpins but not on lines.

答:
For the request that fails, how long is the URL? GET URLs would potentially be long and browsers have a limit of 2083 characters for URL lengths. You could try encoding the line coordinates to make the URL shorter. I'm not sure about Bing Maps limitation on POS T, I don't see anything documented around this.

Another option is to take a look at Azure Maps, another Microsoft mapping platform. It also has a service for creating static map images. For large data sets you can create a GeoJSON file and upload that to the platform and have the static service render that data on the image. Here are some useful resources on this service: https://learn.microsoft.com/en-us/azure/azure-maps/how-to-render-custom-data

https://learn.microsoft.com/en-us/rest/api/maps/render/getmapimage

Body:
Problem:

When using a POST to create pushpins and draw lines it only works if I draw up to 62 lines.

Why Post

Want to increase the limitation of 18 pushpins when using a GET request.

API Used:

URL:http://ecn.dev.virtualearth.net/REST/v1/Imagery/Map/AerialWithLabels?zoomLevel=20&format=Jpeg&mapSize=640,500&key=MYKEY

Body:
pp=Latitude,longitude;iconstyle
..
..
pp=latitude,longitude;iconstyle //I have 100 pushpins
dc=l,FF007EFF,3;latitude1,longitude1_latitude2,longitude_2.....//I have the corresponding lines for all the push pins.

If I just draw the pushpins it works fine and I see the 100 push pins, but when I include the lines it fails with:

"errorDetails": [
        "Your request could not be completed because there was a problem with the service."
    ],
  "resourceSets": [],
    "statusCode": 500

But if I delete enough coordinates in the "dc=l.." parameter to draw exactly 62 lines or less it works fine I see 100 pushpins but not all the lines.

Does anyone know if there is a limitation on how many lines can we draw on the static map? I looked at the documentation here it only says the limitation on pushpins but not on lines.


来源: stackexchange

问:
Concatenate values returned from an array in Swift
I'm training on Swift, doing some exercises with arrays. I would like to pick up randomly 6 letters in an array containing the 26 letters of the alphabet, then concatenate them to generate a string.

I have no problem picking the values, but when it comes to concatenate them, I get error messages.

Here is my code :

```<code>var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

var a = alphabet.randomElement()
var b = alphabet.randomElement()
var c = alphabet.randomElement()
var d = alphabet.randomElement()
var e = alphabet.randomElement()
var f = alphabet.randomElement()

var password = a + b + c + d + e + f

print(password)
</code>```

What am I doing wrong ?

答:
Your alphabet is currently an [String] (a.k.a. Array<String>). You should probably change it to an [Character] instead.

Even better, since randomElement is defined on Collection, and Collection whose Element is Character would work. String is a Collection, and its Element is Character, so it fits the bill perfectly. The nicest way to do that is by breaking apart a string literal:

```<code>let alphabet = "abcdefghijklmnopqrstuvwxyz"
</code>```

randomElement() returns a T? (in this case, String?, a.k.a. Optional<String>), not just a T. Because if alphabet were to be empty (it's not, but if it was), then there would be no elements to return. The only sane thing to do is return nil instead.

Since in your case you can be certain that alphabet is non-empty, and that randomElement() will always return a valid non element, you're justified to force unwrap the result with the ! operator. Now don't make a bad habit of this. You have good reason to force unwrap here, but it's not to be used as a first-resort method of optional handling.

You're also repeating yourself a lot. You can improve this by using a loop of some kind or another.

In this case, you can use a neat little trick. Starting with a range like 0..<6, which has 6 elements, you can call map on it to transform its elements (which are 0, 1, ... 5). In this case, you woudl transform each element by ignoring it, and just replacing it with a random element frmo the alphabet:

```<code>(0..<6).map { _ in alphabet.randomElement()! }
</code>```

The result is an Array<Character>. All you need is to turn it into a string. Final code:

```<code>let alphabet = "abcdefghijklmnopqrstuvwxyz"
let password = String((0..<6).map { _ in alphabet.randomElement()! })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm training on Swift, doing some exercises with arrays. I would like to pick up randomly 6 letters in an array containing the 26 letters of the alphabet, then concatenate them to generate a string.

I have no problem picking the values, but when it comes to concatenate them, I get error messages.

Here is my code :

var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

var a = alphabet.randomElement()
var b = alphabet.randomElement()
var c = alphabet.randomElement()
var d = alphabet.randomElement()
var e = alphabet.randomElement()
var f = alphabet.randomElement()

var password = a + b + c + d + e + f

print(password)

What am I doing wrong ?

Body:
Your alphabet is currently an [String] (a.k.a. Array<String>). You should probably change it to an [Character] instead.

Even better, since randomElement is defined on Collection, and Collection whose Element is Character would work. String is a Collection, and its Element is Character, so it fits the bill perfectly. The nicest way to do that is by breaking apart a string literal:

let alphabet = "abcdefghijklmnopqrstuvwxyz"

randomElement() returns a T? (in this case, String?, a.k.a. Optional<String>), not just a T. Because if alphabet were to be empty (it's not, but if it was), then there would be no elements to return. The only sane thing to do is return nil instead.

Since in your case you can be certain that alphabet is non-empty, and that randomElement() will always return a valid non element, you're justified to force unwrap the result with the ! operator. Now don't make a bad habit of this. You have good reason to force unwrap here, but it's not to be used as a first-resort method of optional handling.

You're also repeating yourself a lot. You can improve this by using a loop of some kind or another.

In this case, you can use a neat little trick. Starting with a range like 0..<6, which has 6 elements, you can call map on it to transform its elements (which are 0, 1, ... 5). In this case, you woudl transform each element by ignoring it, and just replacing it with a random element frmo the alphabet:

(0..<6).map { _ in alphabet.randomElement()! }

The result is an Array<Character>. All you need is to turn it into a string. Final code:

let alphabet = "abcdefghijklmnopqrstuvwxyz"
let password = String((0..<6).map { _ in alphabet.randomElement()! })


问:
How can I configure the IDE code editor to save files as "UTF-8 without BOM"?
The Rad Studio has an editor option for the file encoding. By default it's configured as Ansi and can be UTF-8 among others.
If you want to change this default, for example, to UTF-8 this can be performed through the registry:

[HKEY_CURRENT_USER\Software\Embarcadero\BDS\20.0\Editor]
"DefaultFileFilter"="Borland.FileFilter.UTF8ToUTF8"

Then, the files are saved as UTF-8 but with the BOM mark.
The question is how can be saved as UTF-8 but without the BOM mark?

答: There is no option to do this.  The BOM is required by the IDE to distinguish ANSI encoded files from UTF-8.  If you remove the BOM the IDE will not properly identify the file as UTF-8 encoded.  </p>


问:
Implementing pattern matching in C#
In Scala, you can use pattern matching to produce a result depending on the type of the input. For instance:

```<code>val title = content match {
    case blogPost: BlogPost => blogPost.blog.title + ": " + blogPost.title
    case blog: Blog => blog.title
}
</code>```

In C#, I'd ideally like to be able to write:

```<code>var title = Visit(content,
    (BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title,
    (Blog blog) => blog.Title
);
</code>```

Is this possible? When I've tried writing it as a single method, I don't know how to specify the generics. The following implementation seems right, apart from getting the type checker to allow functions that accept subtypes of T:

```<code>    public TResult Visit<T, TResult>(T value, params Func<T, TResult>[] visitors)
    {
        foreach (var visitor in visitors)
        {
            if (visitor.Method.GetGenericArguments()[0].IsAssignableFrom(value.GetType()))
            {
                return visitor(value);
            }
        }
        throw new ApplicationException("No match");
    }
</code>```

The closest I've gotten is to add the functions to an object individually, and then call visit on a value:

```<code>    public class Visitor<T, TResult>
    {
        private class Result
        {
            public bool HasResult;
            public TResult ResultValue;
        }

        private readonly IList<Func<T, Result>> m_Visitors = new List<Func<T, Result>>();

        public TResult Visit(T value)
        {
            foreach (var visitor in m_Visitors)
            {
                var result = visitor(value);
                if (result.HasResult)
                {
                    return result.ResultValue;
                }
            }
            throw new ApplicationException("No match");
        }

        public Visitor<T, TResult> Add<TIn>(Func<TIn, TResult> visitor) where TIn : T
        {
            m_Visitors.Add(value =>
            {
                if (value is TIn)
                {
                    return new Result { HasResult = true, ResultValue = visitor((TIn)value) };
                }
                return new Result { HasResult = false };
            });
            return this;
        }
    }
</code>```

This can be used like so:

```<code>var title = new Visitor<IContent, string>()
    .Add((BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title)
    .Add((Blog blog) => blog.Title)
    .Visit(content);
</code>```

Any idea how to do this with a single method call?

答:
Using Functional C# (from @Alireza)</p>

```<code>var title = content.Match()
   .With<BlogPost>(blogPost => blogPost.Blog.Title + ": " + blogPost.Title)
   .With<Blog>(blog => blog.Title)
   .Result<string>();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Implementing pattern matching in C#

Body:
In Scala, you can use pattern matching to produce a result depending on the type of the input. For instance:

val title = content match {
    case blogPost: BlogPost => blogPost.blog.title + ": " + blogPost.title
    case blog: Blog => blog.title
}

In C#, I'd ideally like to be able to write:

var title = Visit(content,
    (BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title,
    (Blog blog) => blog.Title
);

Is this possible? When I've tried writing it as a single method, I don't know how to specify the generics. The following implementation seems right, apart from getting the type checker to allow functions that accept subtypes of T:

    public TResult Visit<T, TResult>(T value, params Func<T, TResult>[] visitors)
    {
        foreach (var visitor in visitors)
        {
            if (visitor.Method.GetGenericArguments()[0].IsAssignableFrom(value.GetType()))
            {
                return visitor(value);
            }
        }
        throw new ApplicationException("No match");
    }

The closest I've gotten is to add the functions to an object individually, and then call visit on a value:

    public class Visitor<T, TResult>
    {
        private class Result
        {
            public bool HasResult;
            public TResult ResultValue;
        }

        private readonly IList<Func<T, Result>> m_Visitors = new List<Func<T, Result>>();

        public TResult Visit(T value)
        {
            foreach (var visitor in m_Visitors)
            {
                var result = visitor(value);
                if (result.HasResult)
                {
                    return result.ResultValue;
                }
            }
            throw new ApplicationException("No match");
        }

        public Visitor<T, TResult> Add<TIn>(Func<TIn, TResult> visitor) where TIn : T
        {
            m_Visitors.Add(value =>
            {
                if (value is TIn)
                {
                    return new Result { HasResult = true, ResultValue = visitor((TIn)value) };
                }
                return new Result { HasResult = false };
            });
            return this;
        }
    }

This can be used like so:

var title = new Visitor<IContent, string>()
    .Add((BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title)
    .Add((Blog blog) => blog.Title)
    .Visit(content);

Any idea how to do this with a single method call?

Body:
Using Functional C# (from @Alireza)

var title = content.Match()
   .With<BlogPost>(blogPost => blogPost.Blog.Title + ": " + blogPost.Title)
   .With<Blog>(blog => blog.Title)
   .Result<string>();


问:
Javafx in jar can not open new scene
In my application from main controller i try to open new scene

```<code>public void runReportParserWindow() throws IOException {

    System.out.println("Open report parser window");
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("../views/reportWindow.fxml"));
    ControllerReportParser controller = new ControllerReportParser(getPrimaryStage(), getMainApp());
    controller.registerObserver(this);
    fxmlLoader.setController(controller);
    Scene scene = new Scene(fxmlLoader.load());
    Stage stage = new Stage();
    stage.setTitle("Get data for report");
    stage.setScene(scene); //scene
    stage.initModality(Modality.WINDOW_MODAL);
    stage.initOwner(getPrimaryStage());

    stage.show();
}
</code>```

If i run application in Intellij idea - all window open fine. When i create JAR file (artifacts) i can not open any window except main.  The main scene is shown, but other are not.
Settings for artifact

What am i doing wrong?

答:
Thanks a lot  James_D
I used relative paths for load fxml-files.
Now i replace views folder to controllers and change code from

```<code>fxmlLoader.setLocation(getClass().getResource("../views/reportWindow.fxml"));
</code>```

to

```<code>fxmlLoader.setLocation(getClass().getResource("views/reportWindow.fxml"));
</code>```

and all work fine.

Title: Javafx in jar can not open new scene

Body:
In my application from main controller i try to open new scene

public void runReportParserWindow() throws IOException {

    System.out.println("Open report parser window");
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("../views/reportWindow.fxml"));
    ControllerReportParser controller = new ControllerReportParser(getPrimaryStage(), getMainApp());
    controller.registerObserver(this);
    fxmlLoader.setController(controller);
    Scene scene = new Scene(fxmlLoader.load());
    Stage stage = new Stage();
    stage.setTitle("Get data for report");
    stage.setScene(scene); //scene
    stage.initModality(Modality.WINDOW_MODAL);
    stage.initOwner(getPrimaryStage());

    stage.show();
}

If i run application in Intellij idea - all window open fine. When i create JAR file (artifacts) i can not open any window except main.  The main scene is shown, but other are not.
Settings for artifact

What am i doing wrong?

Body:
Thanks a lot  James_D
I used relative paths for load fxml-files.
Now i replace views folder to controllers and change code from

fxmlLoader.setLocation(getClass().getResource("../views/reportWindow.fxml"));

to

fxmlLoader.setLocation(getClass().getResource("views/reportWindow.fxml"));

and all work fine.


问:
What is the difference between chain and chain.from_iterable in itertools?
I could not find any valid example on the internet where I can see the difference between them and why to choose one over the other.</p>

答:
Another way to look at it is to use chain.from_iterable

when you have an iterable of iterables like a nested iterable(or a compound iterbale) and use chain for simple iterables.


问:
How to sort this 3D data in python?
I have the following data:

Groups

inside every group there are widths

and every width has a meter

for example:

```<code> Group 1:
|Width|Meters|
--------------
|144  |500   |
--------------
|142  | 450  |

Group 2:
|Width|Meters|
--------------
|140  |500   |
--------------
|156  | 450  |
</code>```

Now i need to create a sorting algorithm which will first pick the Group with greater sum of meters and then sort the width in descending
I am clueless how to store this data ? should it be a dictionary or a 3d array ? or three lists ?
and with the right data structure how can i actually sort it. I am not asking for the full code even if you guide me towards the right path i will find my way .Thanks

答:
The sorting algorithm can be simply created with a divide et impera approach.

In fact sorting the groups and sorting the (width, meters) pairs are different problems that we can solve independently.

The choice of the data structure is up to you and depends on what you need; a group could be a list a namedtuple(width, meter) for example or if you need a bit more efficiency a 2d numpy array Nx2.

The container of the various groups could be a list (or a numpy array) if you don't need to name the groups, a list of (name, data) tuple or a dictionary name->data; there's no strict rule and there are advantages and disadvantages for every possibility (for example in a list of (name, data) could be difficult to find efficiently the data knowing the name, but it is very easy, 1 LOC, to sort. While a dictionary provide an excellent way to retrieve data but could be a little more messy to have it sorted).

Here an example of configuration where I use a dictionary name->data for storing the various groups (which won't be sorted!); a list which will contain only the name of the groups in a sorted way; lists of namedtuple for the data.

In this way I can retrieve data easily and if I want to look a the order I can access the list for names and then the dictionary for the data

from collections import namedtuple

GroupData = namedtuple("GroupData", ["Width", "Meters"])

# Container of groups:
groups = {"Group 1": [GroupData(144, 500), GroupData(142, 650)],
          "Group 2": [GroupData(140, 800), GroupData(156, 450)]}

# Sorted list of names of groups
sorted_groups = sorted([name for name in groups],
                        key=lambda name:sum(data.Meters for data in groups[name]),
                        reverse=True)

# Sort each group
for group_data in groups.values():
    group_data.sort(key=lambda data:data.Width, reverse=True)

print(groups)
print(sorted_groups)
```

Title: How to sort this 3D data in python?

Body:
I have the following data:

Groups

inside every group there are widths

and every width has a meter

for example:

 Group 1:
|Width|Meters|
--------------
|144  |500   |
--------------
|142  | 450  |

Group 2:
|Width|Meters|
--------------
|140  |500   |
--------------
|156  | 450  |

Now i need to create a sorting algorithm which will first pick the Group with greater sum of meters and then sort the width in descending
I am clueless how to store this data ? should it be a dictionary or a 3d array ? or three lists ?
and with the right data structure how can i actually sort it. I am not asking for the full code even if you guide me towards the right path i will find my way .Thanks


问:
Indexing a 3D array along 1 axis using a 2D array
Say that I have a numpy array a with the shape: [z, y, x], and another array b with the shape: [y, x].

Array b contains indices along z that I would like to extract from a for each y and x.

So far I have the following inelegant way of doing this:

```<code> from_a = np.full_like(b, np.nan)

 for i in range(y):
  for j in range(x):

   des_ind = b[i,j]

   from_a[i,j] = a[des_ind,i,j]

</code>```

Is there a nice neat pythonic way of doing this?

Body:
Say that I have a numpy array a with the shape: [z, y, x], and another array b with the shape: [y, x].

Array b contains indices along z that I would like to extract from a for each y and x.

So far I have the following inelegant way of doing this:

 from_a = np.full_like(b, np.nan)

 for i in range(y):
  for j in range(x):

   des_ind = b[i,j]

   from_a[i,j] = a[des_ind,i,j]

Is there a nice neat pythonic way of doing this?

Body:
You could use the array b directly as index for a:

import numpy as np
z, y, x = 3, 4, 5
a = np.random.randint(10, (z, y, x))
# array([[[2, 1, 8, 3, 0],  | [[9, 3, 6, 8, 7],  | [[6, 6, 2, 1, 4],
#         [4, 0, 1, 2, 9],  |  [5, 9, 0, 7, 1],  |  [3, 9, 4, 4, 8],
#         [0, 0, 7, 2, 6],  |  [7, 9, 8, 4, 9],  |  [9, 7, 0, 3, 0],
#         [3, 5, 2, 9, 3]], |  [6, 8, 9, 5, 9]], |  [4, 3, 0, 1, 1]]])

b = np.random.randint(z, size=(y, x))
# array([[1, 1, 1, 0, 2],
#        [1, 2, 1, 1, 2],
#        [2, 0, 0, 0, 2],
#        [0, 0, 1, 0, 0]])

from_a = a[b,
           np.arange(y)[:, np.newaxis],
           np.arange(x)[np.newaxis, :]]
# array([[9, 3, 6, 3, 4],
#        [5, 9, 0, 7, 8],
#        [9, 0, 7, 2, 0],
#        [3, 5, 9, 9, 3]])

See also advanced indexing  for numpy arrays.


问:
multicore nodejs game server
I'm developing a card game backend with nodejs, I'm using socket.io and Redis as an adaptor so different instances can access to all sockets.

I'm planning to save match states which might be between 5 to 10 KB in Redis and while players in a match might be connected to different instances when each one of them performs an action, their instance will update match state in Redis.

it seems to be ok but I feel it has some problems, for example, in case of any crash or restarts I need to fetch all matches and do some actions on them but how to make each instance handle a part of matches?
also, I will start a timer for the next player while it might be connected to a different instance so when they play their turn it will handle in another instance and can't stop the timer because the timer was started in another instance!

I think if I could have an instance in charge of a specific match it would solve most of my problems but I don't know how to achieve it.

any advice or suggestion would be appreciated.

答:
I am not sure to follow the exact problem here, but you should be able to create an highly available system, that will allow you to not restart from scratch.

Use an high available Redis instance, for example using Redis Sentinel, or Redis Cloud instances that provide HA

Using Node JS Socket.io you can also deploy it on many server (backed by Redis),take a look to https://socket.io/docs/using-multiple-nodes/#Using-Node-JS-Cluster

This should allow you to have an "alway-on" architecture that can scale.

Title: multicore nodejs game server


问:
Typescript treats boolean like true | false when strictNullCheck is off
I am having the following typescript code:

```<code>type PossiblePromise<T> = T extends Promise<infer U>
  ? T | U
  : T | Promise<T>;
type Z = PossiblePromise<boolean>;

const a = "a"
const f: () => Z = () => Promise.resolve(!!a);
</code>```

With strictNullChecks set to false.

The resulting type Z is boolean | Promise<false> | Promise<true>, but I would expect it to be boolean | Promise<boolean>. So last line produces an error:

```<code>Type 'Promise<boolean>' is not assignable to type 'boolean | Promise<false> | Promise<true>'.
  Type 'Promise<boolean>' is not assignable to type 'Promise<false>'.
    Type 'boolean' is not assignable to type 'false'.(2322)
input.ts(7, 10): The expected type comes from the return type of this signature.
</code>```

Any ideas why typescript behaves like this treating boolean as true | false which should not be the case with strictNullChecks off.

How is it possible to achieve PossiblePromise<T> type that works with boolean correctly?

https://www.typescriptlang.org/play/?strictNullChecks=false&ssl=6&ssc=1&pln=7&pc=47#code/C4TwDgpgBACg9gZwQSwEYBsIwE5wLbIIQA8AKgHxQC8UpUEAHsBAHYAmCsuBRxyLAMwjYoAVXIBYAFBQoAflpQAPmOmyAXIpU58hEhQDc00JCgAtarEQoMWbnuKo4cTAEMW5I1OkBjOCwRgKFdLACJXUN9-QKgBTQAKAEpqSgsaJJSuXSIAOmwIBBcANwh4gEIy10SDIA

答:
```<code>type Z = PossiblePromise<Boolean>;
</code>```

Body:
I am having the following typescript code:

type PossiblePromise<T> = T extends Promise<infer U>
  ? T | U
  : T | Promise<T>;
type Z = PossiblePromise<boolean>;

const a = "a"
const f: () => Z = () => Promise.resolve(!!a);

With strictNullChecks set to false.

The resulting type Z is boolean | Promise<false> | Promise<true>, but I would expect it to be boolean | Promise<boolean>. So last line produces an error:

Type 'Promise<boolean>' is not assignable to type 'boolean | Promise<false> | Promise<true>'.
  Type 'Promise<boolean>' is not assignable to type 'Promise<false>'.
    Type 'boolean' is not assignable to type 'false'.(2322)
input.ts(7, 10): The expected type comes from the return type of this signature.

Any ideas why typescript behaves like this treating boolean as true | false which should not be the case with strictNullChecks off.

How is it possible to achieve PossiblePromise<T> type that works with boolean correctly?

https://www.typescriptlang.org/play/?strictNullChecks=false&ssl=6&ssc=1&pln=7&pc=47#code/C4TwDgpgBACg9gZwQSwEYBsIwE5wLbIIQA8AKgHxQC8UpUEAHsBAHYAmCsuBRxyLAMwjYoAVXIBYAFBQoAflpQAPmOmyAXIpU58hEhQDc00JCgAtarEQoMWbnuKo4cTAEMW5I1OkBjOCwRgKFdLACJXUN9-QKgBTQAKAEpqSgsaJJSuXSIAOmwIBBcANwh4gEIy10SDIA

Body: type Z = PossiblePromise<Boolean>;


问:
How to force localized date picker in html5?
I have a website where users have to enter dates. I use the html form of type date.

Format is sometimes mm/dd/yyyy sometimes mm.dd.yyyy This is probably confusing for my local users. How is this chosen?
Is there a solution to show the entered dates in a forced local format? Or force it to be always  dd.mm.yyyy?

Edit: It's fairly standard code, not much to see here.

```<code><div class="form-group">
    <label for="edate">Entry date:</label>
    <input autocomplete="off" autofocus class="form-control" name="edate"
        id="edate" placeholder="2019-01-01" type="date" required>
</div>
</code>```

This is an image preview of the code in Firefox (FF and Windows Installations are in German, as well as keyboard layout, IP address and anything else I can think of):

答:
From what I understand, the date format on  is based on the user's own language settings.

If the user's browser language setting uses English (United Kingdom), for example, then the date picker for them will display as dd/mm/yyyy. You should be able to test this out for yourself with a quick language switch.

Edit: see the top answer here, which seems to confirm this, and explores 'presentation format': Is there any way to change input type="date" format?

Body:
I have a website where users have to enter dates. I use the html form of type date.

Format is sometimes mm/dd/yyyy sometimes mm.dd.yyyy This is probably confusing for my local users. How is this chosen?
Is there a solution to show the entered dates in a forced local format? Or force it to be always  dd.mm.yyyy?

Edit: It's fairly standard code, not much to see here.

    Entry date:
    <input autocomplete="off" autofocus class="form-control" name="edate"
        id="edate" placeholder="2019-01-01" type="date" required>

This is an image preview of the code in Firefox (FF and Windows Installations are in German, as well as keyboard layout, IP address and anything else I can think of):


问:
How to get second non null value per row in pandas
How to get second non null value per row in pandas. I know that using first_valid_index() we can get first non null value per row but how to get second non null value.
Any help?</p>

答:
You can use df.notna() with cumsum and idxmax

Also , for handling cases where there can be no NaN values for a column use series.where with the same solution but a condition which checks for the sum of null values

```<code>df.notna().cumsum().eq(2).idxmax().where(df.isna().sum().gt(1))
</code>```

Example:

```<code>data = {'id': [np.nan,1,1,np.nan,2,3],
    'value': ['a','a',np.nan,np.nan,'b','c'],
    'obj_id': [np.nan,2,3,3,3,np.nan],
    'test': [1,2,3,4,5,6]}
df = pd.DataFrame (data)
</code>```

```<code>    id value  obj_id  test
0  NaN     a     NaN     1
1  1.0     a     2.0     2
2  1.0   NaN     3.0     3
3  NaN   NaN     3.0     4
4  2.0     b     3.0     5
5  3.0     c     NaN     6
</code>```

For a column level check:

```<code>df.notna().cumsum().eq(2).idxmax().where(df.notna().sum().gt(1))

id        2
value     1
obj_id    2
test      1
dtype: float64
</code>```

For rowlevel , you can use same logic but with axis=1:

```<code>df.notna().cumsum(1).eq(2).idxmax(1).where(df.notna().sum(1).gt(1))
0      test
1     value
2    obj_id
3      test
4     value
5     value
dtype: object
</code>```

Body:
You can use df.notna() with cumsum and idxmax

Also , for handling cases where there can be no NaN values for a column use series.where with the same solution but a condition which checks for the sum of null values

df.notna().cumsum().eq(2).idxmax().where(df.isna().sum().gt(1))

Example:

data = {'id': [np.nan,1,1,np.nan,2,3],
    'value': ['a','a',np.nan,np.nan,'b','c'],
    'obj_id': [np.nan,2,3,3,3,np.nan],
    'test': [1,2,3,4,5,6]}
df = pd.DataFrame (data)

    id value  obj_id  test
0  NaN     a     NaN     1
1  1.0     a     2.0     2
2  1.0   NaN     3.0     3
3  NaN   NaN     3.0     4
4  2.0     b     3.0     5
5  3.0     c     NaN     6

For a column level check:

df.notna().cumsum().eq(2).idxmax().where(df.notna().sum().gt(1))

id        2
value     1
obj_id    2
test      1
dtype: float64

For rowlevel , you can use same logic but with axis=1:

df.notna().cumsum(1).eq(2).idxmax(1).where(df.notna().sum(1).gt(1))
0      test
1     value
2    obj_id
3      test
4     value
5     value
dtype: object


问:
Why does my cooldown not work in python/pygame?
I have this shooter cooldown, and it should go up to 10 and reset, but just continues forever. Anyone know why?

```<code>def update(self):
    keystate = pygame.key.get_pressed()

    print(self.cooldown)

    if self.cooldown > 0:
        self.cooldown += 1
    elif self.cooldown >= 10:
        self.cooldown = 0

    if keystate[pygame.K_SPACE] and self.cooldown == 0:
        self.shoot()
        self.cooldown = 1
</code>```

Thanks

答:
```<code> if self.cooldown > 0:
</code>```

is always satisfied, change it to

```<code> if self.cooldown > 0 and self.cooldown < 10:
</code>```

Body:
I have this shooter cooldown, and it should go up to 10 and reset, but just continues forever. Anyone know why?

def update(self):
    keystate = pygame.key.get_pressed()

    print(self.cooldown)

    if self.cooldown > 0:
        self.cooldown += 1
    elif self.cooldown >= 10:
        self.cooldown = 0

    if keystate[pygame.K_SPACE] and self.cooldown == 0:
        self.shoot()
        self.cooldown = 1

Thanks

Body:
 if self.cooldown > 0:

is always satisfied, change it to

 if self.cooldown > 0 and self.cooldown < 10:


问:
How add values in different objects in an array?
How can I access only the first @NOTIFICATION_OPENED key?

How can I sum both values of @NOTIFICATION_OPENED?

This is my AJAX request:

```<code>$.getJSON("myapiurl", function(notificationData) {
  $.each(notificationData.data, function(index, value) {
    if (value["@NOTIFICATION_OPENED"]) {
      var notificationOpened = value["@NOTIFICATION_OPENED"]
    } else
      notificationOpened = 0;

    var val = {
      "notificationOpened": notificationOpened
    }
    _data.push(val)
  });
}
</code>```

This is the data I retrieve from the API using the above request:

```<code>{
  "data": [{
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  }, {
    "date": 1577923200000,
    "@NOTIFICATION_OPENED": 734
  }]
</code>```

答:
How can I access only the first @NOTIFICATION_OPENED key?

Simply take the first element of data, and then take the value of @NOTIFICATION_OPENED. for example:

var notification = {
    "data": [{
        "date": 1577836800000,
        "@NOTIFICATION_SENT": 62629,
        "@NOTIFICATION_OPENED": 404
    }, {
        "date": 1577923200000,
        "@NOTIFICATION_OPENED": 734
    }]
}

var firstNotificationData = notification.data[0]
var firstNotificationOpenedData = firstNotificationData["@NOTIFICATION_OPENED"]
console.log(firstNotificationOpenedData)```
</div>
</div>
</p>

<blockquote>
  <p>How can I sum both values of @NOTIFICATION_OPENED?</p>
</blockquote>

<p>You can use <code>reduce</code> to summarize the total of notification opened. for example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var notification = {
    "data": [{
        "date": 1577836800000,
        "@NOTIFICATION_SENT": 62629,
        "@NOTIFICATION_OPENED": 404
    }, {
        "date": 1577923200000,
        "@NOTIFICATION_OPENED": 734
    }]
}

var totalNotificationOpened = notification.data.reduce(function (acc, d) {
    return acc + d["@NOTIFICATION_OPENED"]
}, 0)

console.log(totalNotificationOpened)</code>```

Body:
How can I access only the first @NOTIFICATION_OPENED key?

How can I sum both values of @NOTIFICATION_OPENED?

This is my AJAX request:

$.getJSON("myapiurl", function(notificationData) {
  $.each(notificationData.data, function(index, value) {
    if (value["@NOTIFICATION_OPENED"]) {
      var notificationOpened = value["@NOTIFICATION_OPENED"]
    } else
      notificationOpened = 0;

    var val = {
      "notificationOpened": notificationOpened
    }
    _data.push(val)
  });
}

This is the data I retrieve from the API using the above request:

{
  "data": [{
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  }, {
    "date": 1577923200000,
    "@NOTIFICATION_OPENED": 734
  }]

Body:
How can I access only the first @NOTIFICATION_OPENED key?

Simply take the first element of data, and then take the value of @NOTIFICATION_OPENED. for example:

var notification = {
    "data": [{
        "date": 1577836800000,
        "@NOTIFICATION_SENT": 62629,
        "@NOTIFICATION_OPENED": 404
    }, {
        "date": 1577923200000,
        "@NOTIFICATION_OPENED": 734
    }]
}

var firstNotificationData = notification.data[0]
var firstNotificationOpenedData = firstNotificationData["@NOTIFICATION_OPENED"]
console.log(firstNotificationOpenedData)

How can I sum both values of @NOTIFICATION_OPENED?

You can use reduce to summarize the total of notification opened. for example:

var notification = {
    "data": [{
        "date": 1577836800000,
        "@NOTIFICATION_SENT": 62629,
        "@NOTIFICATION_OPENED": 404
    }, {
        "date": 1577923200000,
        "@NOTIFICATION_OPENED": 734
    }]
}

var totalNotificationOpened = notification.data.reduce(function (acc, d) {
    return acc + d["@NOTIFICATION_OPENED"]
}, 0)

console.log(totalNotificationOpened)


问:
how to combine 3 conditions by "OR" in jquery?
Is there anyway to combine 3 conditions by "OR" in jquery? Eg, $(t_obj).keyup(function(e) || $('#sendResp').click(function(e) || $('.emo').click(function(e) {  ? I have tested to combine them but I get error. How to combine them?

答:
If you want them all to call the same function you can just do:</p>

```<code>function myEventHandler(e) {
    //do stuff
}

$(t_obj).keyup(myEventHandler);
$('#sendResp').click(myEventHandler);
$('.emo').click(myEventHandler);
</code>```

Body:
If you want them all to call the same function you can just do:

function myEventHandler(e) {
    //do stuff
}

$(t_obj).keyup(myEventHandler);
$('#sendResp').click(myEventHandler);
$('.emo').click(myEventHandler);


问:
Is it a good practice to use DTO in the service layer?
I have a controller that converts dto to an entity and passes it to the service level.

```<code>@PostMapping(value = "/new", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<UserDto> create(@RequestBody UserDto userDto){
        User newUser= userService.save(userMapper.userDtoToUser(userDto));
        return ResponseEntity......body(userMapper.userToUserDto(newUser));
    }
</code>```

Will the correct decision be to transfer to the service not an entity, but a dto?
For example:

```<code>    public interface UserService{
      UserDto save(UserDto userDto);
}
</code>```

And will the decision be correct to convert  the entity and dto at the controller level?

答:
This is a bad practice to put any conversion logic in the controller. All conversion/population logic should be put in helper classes e.g. converters and populators. Check here for an example.

Also, your service class should get an entity (and not DTO) for CRUD operations because the DTO may not have all the values required to complete the CRUD operation successfully. However, a better practice will be to put all the CRUD operations to a common service e.g. EntityService and to pass it the entities (e.g. User) on which CRUD operation has to be performed e.g. YourEntityService.save(user). Check here and here for an example.

Body:
I have a controller that converts dto to an entity and passes it to the service level.

@PostMapping(value = "/new", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<UserDto> create(@RequestBody UserDto userDto){
        User newUser= userService.save(userMapper.userDtoToUser(userDto));
        return ResponseEntity......body(userMapper.userToUserDto(newUser));
    }

Will the correct decision be to transfer to the service not an entity, but a dto?
For example:

    public interface UserService{
      UserDto save(UserDto userDto);
}

And will the decision be correct to convert  the entity and dto at the controller level?


问:
Problem with django installation [python]
Last summer I wanted to learn to do web dev, so I installed Django 1.8, an unstable release. I installed it without pip. I recently decided to try again, but wanted to do work with the stable release, 1.7.1, and wanted to install with pip for simplicity.

I read that in order to remove Django that was installed without pip, one must delete the entire .egg from /Library/Python/2.7/site-packages/, so I did this.

Since then, I've been getting funny errors. When I issue 'pip install django', I get

```<code>bash-3.2$ pip install django
Downloading/unpacking django
  Downloading Django-1.7.1-py2.py3-none-any.whl (7.4MB): 7.4MB downloaded
Installing collected packages: django
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/req.py", line 1435, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/req.py", line 671, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/req.py", line 901, in move_wheel_files
    pycompile=self.pycompile,
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/wheel.py", line 215, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/wheel.py", line 205, in clobber
    os.makedirs(destdir)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django'
</code>```

When I check the spurious directory, I find that /django doesn't exist.
Issuing sudo will silence the errors, but I find that I still can't start a django project.

Has anyone seen this before or have any idea how to fix this?

答:
Windows user:
start power shell as (Run as Administrator) or Start CMD as (Run as Administrator)
after run the following command

For latest version:

```<code>pip install Django
</code>```

Or for Previous release version e.g. 2.2

```<code>pip install Django==2.2
</code>```

Body:
Last summer I wanted to learn to do web dev, so I installed Django 1.8, an unstable release. I installed it without pip. I recently decided to try again, but wanted to do work with the stable release, 1.7.1, and wanted to install with pip for simplicity.

I read that in order to remove Django that was installed without pip, one must delete the entire .egg from /Library/Python/2.7/site-packages/, so I did this.

Since then, I've been getting funny errors. When I issue 'pip install django', I get

bash-3.2$ pip install django
Downloading/unpacking django
  Downloading Django-1.7.1-py2.py3-none-any.whl (7.4MB): 7.4MB downloaded
Installing collected packages: django
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/req.py", line 1435, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/req.py", line 671, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/req.py", line 901, in move_wheel_files
    pycompile=self.pycompile,
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/wheel.py", line 215, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg/pip/wheel.py", line 205, in clobber
    os.makedirs(destdir)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django'

When I check the spurious directory, I find that /django doesn't exist.
Issuing sudo will silence the errors, but I find that I still can't start a django project.

Has anyone seen this before or have any idea how to fix this?

Body:
Windows user:
start power shell as (Run as Administrator) or Start CMD as (Run as Administrator)
after run the following command

For latest version:

pip install Django

Or for Previous release version e.g. 2.2

pip install Django==2.2


问:
Chrome Dev Tools pausing on rejected promise even though I'm catching it
I have the following typescript code where I throw a synchronous error from a promise creation function:

function testExc(url: string): Promise<GLTF | undefined> {
    try {
        const promise: Promise<GLTF> = new Promise((resolve, reject) => {
            throw Error('hi')
        })
        promise.catch((err) => { console.log(`Caught ${err}`) })
        return promise
    } catch (e) {
        return Promise.resolve()
    }
}
```

<p>which to my surprise triggers a "Paused on promise rejection" in Chrome Dev Tools on the <code>throw</code> line. I have "Pause on Exceptions" turned on, and "Pause on caught exceptions" turned off because I want to know about uncaught exceptions.</p>

<p>Why is it pausing? I'm catching exceptions two ways: with the <code>.catch</code> and the <code>try/catch</code> around the whole thing. When I continue, the <code>.catch</code> stanza catches it as expected.</p>

<p>I'm using Chrome 80.0.3987.116 on Windows 10, with typescript 3.7.</p>

<p>The transpiled JS code looks like this, if it's helpful:</p>

<pre class="lang-js prettyprint-override"><code>function testExc(url) {
  try {
    const promise = new Promise((resolve, reject) => {
      throw Error('hi');
      resolve(undefined);
    });
    promise.catch(err => {console.log(`Caught ${err}`);});
    return promise;
  }
  catch (e) {
    return Promise.resolve(undefined);
  }
}
</code>```

答:
This issue was raised in 2015 as a bug report for chromium.  Here are some relevant statements I can see in the discussion:

The constructor callback is called synchronously before the ".catch()" code is executed, so at the time when the exception is thrown it is indeed uncaught. Later it becomes caught ... (aandrey@chromium.org)

Try-catch scope is static. At the time of throw, we know that it's going to be caught. (yangguo@chromium.org)

At the point the promise implementation checks and invokes the rejection handler can be a lot later. DevTools semantics require to break at the throw site though, to make any sense of "break on exception". (yangguo@chromium.org)

So I guess the scenario we are discussing is the case where the Promise is rejected in the constructor ... In this case, there is no chance to attach a reject handler yet. (yangguo@chromium.org)

Long story short, when you throw an error inside a promise constructor, it's hard for devtools to identify that it is later handled.

Instead, handle it inside your constructor:

```<code>function testExc(url) {
  return new Promise((resolve, reject) => {
    try {
      throw new Error('hi');
    }
    catch (e) {
      console.log(`Caught ${e}`);
      resolve();
    }
  })
}
</code>```

Body:
I have the following typescript code where I throw a synchronous error from a promise creation function:

function testExc(url: string): Promise<GLTF | undefined> {
    try {
        const promise: Promise<GLTF> = new Promise((resolve, reject) => {
            throw Error('hi')
        })
        promise.catch((err) => { console.log(`Caught ${err}`) })
        return promise
    } catch (e) {
        return Promise.resolve()
    }
}

which to my surprise triggers a "Paused on promise rejection" in Chrome Dev Tools on the throw line. I have "Pause on Exceptions" turned on, and "Pause on caught exceptions" turned off because I want to know about uncaught exceptions.

Why is it pausing? I'm catching exceptions two ways: with the .catch and the try/catch around the whole thing. When I continue, the .catch stanza catches it as expected.

I'm using Chrome 80.0.3987.116 on Windows 10, with typescript 3.7.

The transpiled JS code looks like this, if it's helpful:

function testExc(url) {
  try {
    const promise = new Promise((resolve, reject) => {
      throw Error('hi');
      resolve(undefined);
    });
    promise.catch(err => {console.log(`Caught ${err}`);});
    return promise;
  }
  catch (e) {
    return Promise.resolve(undefined);
  }
}

Body:
This issue was raised in 2015 as a bug report for chromium.  Here are some relevant statements I can see in the discussion:

The constructor callback is called synchronously before the ".catch()" code is executed, so at the time when the exception is thrown it is indeed uncaught. Later it becomes caught ... (aandrey@chromium.org)

Try-catch scope is static. At the time of throw, we know that it's going to be caught. (yangguo@chromium.org)

At the point the promise implementation checks and invokes the rejection handler can be a lot later. DevTools semantics require to break at the throw site though, to make any sense of "break on exception". (yangguo@chromium.org)

So I guess the scenario we are discussing is the case where the Promise is rejected in the constructor ... In this case, there is no chance to attach a reject handler yet. (yangguo@chromium.org)

Long story short, when you throw an error inside a promise constructor, it's hard for devtools to identify that it is later handled.

Instead, handle it inside your constructor:

function testExc(url) {
  return new Promise((resolve, reject) => {
    try {
      throw new Error('hi');
    }
    catch (e) {
      console.log(`Caught ${e}`);
      resolve();
    }
  })
}


问:
How to define a CoffeeScript method in Haml using the ":coffeescript" tag
I am working with Rails and CoffeeScript, and need to define and call a function in a Haml file under the :coffeescript tag.

I tried using this code but it generates an "undefined tabsOnLoadMethod" error:

```<code>:coffeescript
  $ ->
    tabsOnLoadMethod ->
      alert 'hello team'
</code>```

I called the method using tabsOnLoadMethod();.

error:

```<code>ReferenceError: tabsOnLoadMethod is not defined
</code>```

Where is this going wrong?

答:
```<code>tabsOnLoadMethod ->
  alert 'hello team'
</code>```

is compiled to

```<code>tabsOnLoadMethod(function() {
  return alert('hello team');
});
</code>```

I think you are trying to call a function, rather than passing it another function / callback

```<code>tabsOnLoadMethod = ->
  alert 'hello team'
</code>```

If you want to call this method via html (eg. onclick listener), then you will have to attach it to this (using @) or window

```<code>@tabsOnLoadMethod = ->
  alert 'hello team'
</code>```

or

```<code>window.tabsOnLoadMethod = ->
  alert 'hello team'
</code>```

Body:
I am working with Rails and CoffeeScript, and need to define and call a function in a Haml file under the :coffeescript tag.

I tried using this code but it generates an "undefined tabsOnLoadMethod" error:

:coffeescript
  $ ->
    tabsOnLoadMethod ->
      alert 'hello team'

I called the method using tabsOnLoadMethod();.

error:

ReferenceError: tabsOnLoadMethod is not defined

Where is this going wrong?

Body:
tabsOnLoadMethod ->
  alert 'hello team'

is compiled to

tabsOnLoadMethod(function() {
  return alert('hello team');
});

I think you are trying to call a function, rather than passing it another function / callback

tabsOnLoadMethod = ->
  alert 'hello team'

If you want to call this method via html (eg. onclick listener), then you will have to attach it to this (using @) or window

@tabsOnLoadMethod = ->
  alert 'hello team'

or

window.tabsOnLoadMethod = ->
  alert 'hello team'


问:
How Netty uses thread pools?
Can you please explain how Netty uses thread pools to work? Do I understand correctly, that there are two kinds of thread-pools: boss and worker. Boss ones are used to do I/O and worker are used to call user callbacks (messageReceived) to process data?</p>

答:
Description related to Netty Nio implementation (3.2.4.Final) NioServerSocketChannelFactory.

The worker thread pool has to be able to deliver at least Number of Workers threads (currently default 2*number of cores).

Why?

In case of this implementation each worker has his own selector loop, this means that each worker will "eat up" one thread to sleep on the selector. Also that worker (and associated thread) is responsible for doing all the actual writes and reads (including fireing events on the pipeline, that means handlers are executed in that workers thread).

In case of the boss thread pool, actually the thread pool is unneeded because current implementation acquires only a single thread from it. That thread sleeps on the selector for server socket most of the time, after accepting connection that connection is registered with a worker. From that moment on worker is responsible for serving that connection.

ContentLicense: CC BY-SA 2.5

Title: How Netty uses thread pools?


问:
How to get all of device tokens from Firebase?
How to get device tokens (FCM registration tokens) from Firebase?

I'm making mobile app using firebase and its server using node.js.

I want to send push notification message from server, but I don't know how to get devices token.

How to get device tokens from external server? I'm using Firebase admin SDK now.

Is the device token only generated when the app is connected fcm server?

Should I save token to another database when user first run the app and register FCM server?

答:
I suggest not storing the tokens at all. Storing the token seems like a good idea until you realize that your users have multiple devices (iOS device, android device, desktop etc.) Now you have to manage storing multiple device tokens per user and that can get messy fast.

Instead, ignore the tokens that are generated and simply subscribe each user to a topic such as when user logs in or creates account subscribe them to a topic made of their userid

```<code>NSString* useridchannel = [NSString stringWithFormat:@"user_%ld", (long)userid];
[[FIRMessaging messaging] subscribeToTopic:useridchannel completion:^(NSError * _Nullable error) {
       NSLog(@"Subscribed user to topic %@", useridchannel);
}];
</code>```

When user logs out make sure to unsubscribe them from that topic as they probably don't want to receive notifications if they are no longer logged into your app

```<code>NSString* useridchannel = [NSString stringWithFormat:@"user_%ld", (long)userid];
[[FIRMessaging messaging] unsubscribeFromTopic:useridchannel completion:^(NSError * _Nullable error) {
         NSLog(@"Unsubscribed user from %@", useridchanel);
}];
</code>```

I realize that Device Groups are supposed to be used for this purpose, but again I don't want to be bothered with storing and managing tokens and also Firebase Admin SDK for PHP does not support sending messages to Device Groups. By using topics there is no need to deal with device tokens and you can send messages to all the users devices from server, the app, or firebase console easily.

Body:
I suggest not storing the tokens at all. Storing the token seems like a good idea until you realize that your users have multiple devices (iOS device, android device, desktop etc.) Now you have to manage storing multiple device tokens per user and that can get messy fast.

Instead, ignore the tokens that are generated and simply subscribe each user to a topic such as when user logs in or creates account subscribe them to a topic made of their userid

NSString* useridchannel = [NSString stringWithFormat:@"user_%ld", (long)userid];
[[FIRMessaging messaging] subscribeToTopic:useridchannel completion:^(NSError * _Nullable error) {
       NSLog(@"Subscribed user to topic %@", useridchannel);
}];

When user logs out make sure to unsubscribe them from that topic as they probably don't want to receive notifications if they are no longer logged into your app

NSString* useridchannel = [NSString stringWithFormat:@"user_%ld", (long)userid];
[[FIRMessaging messaging] unsubscribeFromTopic:useridchannel completion:^(NSError * _Nullable error) {
         NSLog(@"Unsubscribed user from %@", useridchanel);
}];

I realize that Device Groups are supposed to be used for this purpose, but again I don't want to be bothered with storing and managing tokens and also Firebase Admin SDK for PHP does not support sending messages to Device Groups. By using topics there is no need to deal with device tokens and you can send messages to all the users devices from server, the app, or firebase console easily.


问:
amazon-s3 upload fails for upload files in loop
Trying to upload 40k files to s3 from nodejs and aws-sdk I do promisify every thing code works fine upto 5800 records but after that it fails rest of files are not uploaded can anyone help why this happen so or i have to use some another approch for this or do i need to updation in my code?

Here is my code

```<code>public static convertClobAndUploadToS3(allClobAttachments: Array<RfAttachment>):
  Promise<FileConvertS3UploadResponse> {
  return new Promise(async (resolve, reject) => {
  const fileConvertResp: FileConvertS3UploadResponse = { processed: [], unprocessed: [] };
  for (let i = 0; i < allClobAttachments.length; i++) {
    const rfAttachment = allClobAttachments[i];
    const mainFileBufferFormat: Buffer = Buffer.from(rfAttachment.CLOB);
    const path = CONST.S3.PATH.MAIN_FILE;
    const fileName = rfAttachment.RF_ID + CONST.S3.EXT.MAIN_FILE;
     // upload only single file to s3 at a time and returns url
    const url = await GFIUtils.uploadFileToS3(config, fileName, mainFileBufferFormat, path);
    url ? fileConvertResp.processed.push({ RFID: rfAttachment.RF_ID, url, rfAttachment })
    : fileConvertResp.unprocessed.push(rfAttachment.RF_ID);
    if (fileConvertResp.processed.length === allClobAttachments.length) {
      logger.info(`CLOB STAGE::: All clob successfully uploaded!!! TOTAL CLOB:::${allClobAttachments.length}`);
      return resolve(fileConvertResp);
    } else if (fileConvertResp.unprocessed.length + fileConvertResp.processed.length
       === allClobAttachments.length) {
      logger.info(`allClobAttachments::: ${allClobAttachments.length}`);
      logger.info(`processed::: ${fileConvertResp.processed.length}`);
      logger.info(`unprocessed::: ${fileConvertResp.unprocessed.length}`);
      return reject(fileConvertResp);
    } else { continue; }
  }
  });
 }
</code>```

答:
Instead of doing this take a more safer approach and open up a subprocess using aws cli.

Use aws s3 sync or copy command to do this.

It would be lot faster as well as more fail proof then a brute force approach like calls inside a for loop.

In case if all the files are not in a single or some limited number of directories. You should generate a list of paths of the file you want to upload. Write that text file to disk. Use aws cli to upload or download using the paths from the text file.

Body:
Trying to upload 40k files to s3 from nodejs and aws-sdk I do promisify every thing code works fine upto 5800 records but after that it fails rest of files are not uploaded can anyone help why this happen so or i have to use some another approch for this or do i need to updation in my code?

Here is my code

public static convertClobAndUploadToS3(allClobAttachments: Array<RfAttachment>):
  Promise<FileConvertS3UploadResponse> {
  return new Promise(async (resolve, reject) => {
  const fileConvertResp: FileConvertS3UploadResponse = { processed: [], unprocessed: [] };
  for (let i = 0; i < allClobAttachments.length; i++) {
    const rfAttachment = allClobAttachments[i];
    const mainFileBufferFormat: Buffer = Buffer.from(rfAttachment.CLOB);
    const path = CONST.S3.PATH.MAIN_FILE;
    const fileName = rfAttachment.RF_ID + CONST.S3.EXT.MAIN_FILE;
     // upload only single file to s3 at a time and returns url
    const url = await GFIUtils.uploadFileToS3(config, fileName, mainFileBufferFormat, path);
    url ? fileConvertResp.processed.push({ RFID: rfAttachment.RF_ID, url, rfAttachment })
    : fileConvertResp.unprocessed.push(rfAttachment.RF_ID);
    if (fileConvertResp.processed.length === allClobAttachments.length) {
      logger.info(`CLOB STAGE::: All clob successfully uploaded!!! TOTAL CLOB:::${allClobAttachments.length}`);
      return resolve(fileConvertResp);
    } else if (fileConvertResp.unprocessed.length + fileConvertResp.processed.length
       === allClobAttachments.length) {
      logger.info(`allClobAttachments::: ${allClobAttachments.length}`);
      logger.info(`processed::: ${fileConvertResp.processed.length}`);
      logger.info(`unprocessed::: ${fileConvertResp.unprocessed.length}`);
      return reject(fileConvertResp);
    } else { continue; }
  }
  });
 }


问:
Running Batch Stript in Windows 7 causes process to be launched under wrong cmd process
Whenever I run a batch file on my comuter (64 bit architecture running 64 bit windows 7), the console window that is opened is running in 32-bit mode, and checking the task manager confirms I am indeed running everything as a 32-bit process.  I want to run the batch file under a 64-bit process, not a 32-bit process.  I have changed the comspec environment variable to point to the proper variable, to no avail.  Does anyone know how to fix this so that when I click on the batch file, it everything is run in 64-bit mode.

I realize I could simply open the 64 bit command window and run my batch file.  However, this is a workaround and doesn't get at the root of the problem, and won't help when I give file to others.

Thanks,
MM

答:
Can you run the scripts with the full path name to the executable?
"C:\Windows\System32\cmd.exe" /c <batch_name> should run 64-bit
"C:\Windows\SysWOW64\cmd.exe" /c <batch_name> would run in 32-bit

Otherwise, you could change the associations to run the extension .cmd with 64-bit (ftype cmdfile=C:\Windows\System32\cmd.exe /c "%1" %*) and .bat with 32-bit (ftype cmdfile=C:\Windows\SysWOW64\cmd.exe /c "%1" %*).


答:
You can use the pattern attribute on your input of type date :

```<code><input type="date" pattern="[0-9]{2}.[0-9]{2}.[0-9]{4}">
</code>```

But I don't know how browser will place the dd or mm...

Title: How to force localized date picker in html5?

Body:
You can use the pattern attribute on your input of type date :

<input type="date" pattern="[0-9]{2}.[0-9]{2}.[0-9]{4}">

But I don't know how browser will place the dd or mm...


问:
Jinja and nested dict
I wish to print a table in an html with Flask(jinja) from a nested dict:

Python part:

@app.route("/")

def index():

#the nested dict exemple:
    dict_temp = {0: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total':
''}, 1: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total': ''}, 2: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total': ''}}

    parent_dict = dict_temp

    return render_template("test.html", parent_dict = parent_dict)
```
<p>Jinja template with the table:</p>
<pre class="lang-html prettyprint-override"><code> <table style="width:100%">

  <tr>
    <th>Symbol</th>
    <th>Name</th>
    <th>Shares</th>
    <th>Price</th>
    <th>Total</th>
  </tr>

    {% for dict_item in parent_dict %}
    <tr>
        {% for key, value in dict_item.items() %}
            <td>{{value}}</td>
        {% endfor %}
    </tr>
    {% endfor %}

</table>

</code>```

The code work with this python:

parent_dict = [{'A':'item1 A','B':'item1 B'},{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}]
```
<p>How could I loop with <code>jinja</code> and a nested <code>dict</code> of this type:</p>
```{1:{'A':'item1 A','B':'item1 B'}, 2:{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... }
```

Or maybe I have to build my input differently?

答:
There are ways to iterate through nested dict in python but I dont think this can be done in templates in flask.

As you've suggested you can make use of the list of dict method as you've shown above.

For example

{1:{'A':'item1 A','B':'item1 B'}, 2:{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... }

becomes

```<code>[{'A':'item1 A','B':'item1 B'}, {'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... ]
</code>```

Iterate through in the template:

```<code>    {% for dict_item in list %}
       {% for key, value in dict_item.items() %}
          <h1>Key: {{key}}</h1>
          <h2>Value: {{value}}</h2>
       {% endfor %}
    {% endfor %}
</code>```

You can do the following to convert dict of dict to list of dict

list_of_dics = [value for value in dic_of_dics.values()].

See here

Title: Jinja and nested dict

Body:
I wish to print a table in an html with Flask(jinja) from a nested dict:

Python part:

@app.route("/")

def index():

#the nested dict exemple:
    dict_temp = {0: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total':
''}, 1: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total': ''}, 2: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total': ''}}

    parent_dict = dict_temp

    return render_template("test.html", parent_dict = parent_dict)

Jinja template with the table:

    Symbol
    Name
    Shares
    Price
    Total

    {% for dict_item in parent_dict %}

        {% for key, value in dict_item.items() %}
            {{value}}
        {% endfor %}

    {% endfor %}

The code work with this python:

parent_dict = [{'A':'item1 A','B':'item1 B'},{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}]

How could I loop with jinja and a nested dict of this type:

{1:{'A':'item1 A','B':'item1 B'}, 2:{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... }

Or maybe I have to build my input differently?

Body:
There are ways to iterate through nested dict in python but I dont think this can be done in templates in flask.

As you've suggested you can make use of the list of dict method as you've shown above.

For example

{1:{'A':'item1 A','B':'item1 B'}, 2:{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... }

becomes

[{'A':'item1 A','B':'item1 B'}, {'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... ]

Iterate through in the template:

    {% for dict_item in list %}
       {% for key, value in dict_item.items() %}
          <h1>Key: {{key}}</h1>
          <h2>Value: {{value}}</h2>
       {% endfor %}
    {% endfor %}

You can do the following to convert dict of dict to list of dict

list_of_dics = [value for value in dic_of_dics.values()].

See here


问:
What is the best way to program C# on a free platform? (Compiler / IDE / Debugger / etc)
Preferably also on linux - if necessary I'll install a basic version of Windows XP</p>

答: Eclipse is a great IDE and apparently there's a C# plug in for it. I've not used it however (the plugin) so I can't comment on its quality. </p>

OwnerDisplayName: andy

OwnerDisplayName: jcollum


问:
Uploading images to S3
I'm working on a image hosting web site, and I'm in a bit of a pickle. I chose Amazon S3 beacuse it's fast, it scales and the pay-as-you-go model.

When I upload images from my web site, I need to process them on the server - creating 3 different sizes, inserting data into the DB, and then I'd be ready to upload to S3 (all 3 sizes of the image).

I'm currently using plupload for the uploading, and I set it all up now working with my DB as storage for the images - just for testing purposes. But I just realized - this uploading to my web server, processing and THEN uploading to S3 would mean double the upload time per image right?

Is there any smart way of handling this scenario?

答:
We are doing something similar with processing of files and storage in S3. The main difference is that our webservers and processing servers are on EC2, so they don't incur any transfer cost to go to/from S3, and they have very high bandwidth to S3. Is it possible to run your image resizing process on an EC2 instance? You can either:

Accept uploads directly to a server process on the EC2 instance, process them immediately, and then save the images to S3, or...

Upload images directly to S3, somehow signal your EC2 process of the images arrival (SQS queue perhaps), and then have your server process respond to the signal by grabbing the files from S3, processing the images, and saving the resized images back to S3.

Basically, I'm saying you should take advantage of this (from S3 description on AWS site):

There is no Data Transfer charge for
  data transferred between Amazon EC2
  and Amazon S3 within the same Region
  or for data transferred between the
  Amazon EC2 Northern Virginia Region
  and the Amazon S3 US Standard Region.

Title: Uploading images to S3


问:
Wordpress: On jQuery button click preselect option in Contact Form 7 menu
I have a Wordpress site, where is a page with many items. When user clicks on item he wants, page will open. In this page there is a button "Contact". The thing I want to achieve is that when user hits the contact button, opens next page with the form and the select menu is preselected depending on the email on this item page. Can someone please help me with this?

Here is some parts of single post page, where is the button for the click to go to the form page:

```<code><button class="btn">
 <span>Contact</span>
</button>
</code>```

This page has a lot of information where is also mentioned email address for this specific item of this page:

```<code><p class="email">Email: <a href="mailto:<?php the_field('contact_email'); ?>">
 <?php the_field('contact_email'); ?>
</a></p>
</code>```

Here is my Contact Form 7 code:

```<code><div class="contact-form">
<div class="form-group">
  [text* your-name class:form-control placeholder "Name"]
</div>
<div class="form-group">
  [text* your-name class:form-control placeholder "Company"]
</div>
<div class="form-group">
  [email* your-email class:form-control placeholder "Email"]
</div>
<div class="form-group">
  [select* menu-105 class:form-control "Office 1|email1@example.com" "Office 2|email2@example.com" "Office 3|email3@example.com" "Office 4|email4@example.com"]
</div>
<div class="form-group">
  [text your-subject class:form-control placeholder "Subject"]
</div>
<div class="form-group">
  [textarea your-message x3 class:form-control placeholder "Message"]
</div>
<div class="form-group form-check">
 [acceptance acceptance-955 optional] By ticking this box you agree to this information here in <a href="https://www.google.com" target="_blank">privacy policy</a>.[/acceptance]
</div>
<div class="btn-container-right">
<div class="btn-wrapper">
  [submit "Send" class:btn-sm]
</div>
</div>
</div>
</code>```

The thing I want to achieve is that when user hits the contact button, opens next page with the form and the select menu is preselected depending on the email on this item page. Can someone please help me with this?

答:
Ok... so first, you want to pass a URL parameter to the contact form from the button.

So your updated link is, (where you're urlecoding the space as %20)

yourdomain.com/contact-form/?email=office%201

Then add this script to your theme .js files or wherever you can.

```<code>jQuery(document).ready(function($){
    $.urlParam = function (name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                          .exec(window.location.search);

        return (results !== null) ? results[1] || 0 : false;
    }
    // Since above function returns false if blank, check if email $_GET param is entered
    if ( false !== $.urlParam('email')){
        $('select[name="your-email"]').val(decodeURIComponent($.urlParam('email')))
            .change(); // set select name to the name of your form field in CF7
    }
});
</code>```

the decodeURIComponent is only if you're using a URL Encoded parameter... This is because you have a space in your selections "Office 1", "Office 2"

set the [name=] to the name of your CF7 field.

Body:
I have a Wordpress site, where is a page with many items. When user clicks on item he wants, page will open. In this page there is a button "Contact". The thing I want to achieve is that when user hits the contact button, opens next page with the form and the select menu is preselected depending on the email on this item page. Can someone please help me with this?

Here is some parts of single post page, where is the button for the click to go to the form page:

<button class="btn">
 Contact
</button>

This page has a lot of information where is also mentioned email address for this specific item of this page:

Email: <a href="mailto:<?php the_field('contact_email'); ?>">
 <?php the_field('contact_email'); ?>

Here is my Contact Form 7 code:

  [text* your-name class:form-control placeholder "Name"]

  [text* your-name class:form-control placeholder "Company"]

  [email* your-email class:form-control placeholder "Email"]

  [select* menu-105 class:form-control "Office 1|email1@example.com" "Office 2|email2@example.com" "Office 3|email3@example.com" "Office 4|email4@example.com"]

  [text your-subject class:form-control placeholder "Subject"]

  [textarea your-message x3 class:form-control placeholder "Message"]

 [acceptance acceptance-955 optional] By ticking this box you agree to this information here in privacy policy.[/acceptance]

  [submit "Send" class:btn-sm]

The thing I want to achieve is that when user hits the contact button, opens next page with the form and the select menu is preselected depending on the email on this item page. Can someone please help me with this?

Body:
Ok... so first, you want to pass a URL parameter to the contact form from the button.

So your updated link is, (where you're urlecoding the space as %20)

yourdomain.com/contact-form/?email=office%201

Then add this script to your theme .js files or wherever you can.

jQuery(document).ready(function($){
    $.urlParam = function (name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                          .exec(window.location.search);

        return (results !== null) ? results[1] || 0 : false;
    }
    // Since above function returns false if blank, check if email $_GET param is entered
    if ( false !== $.urlParam('email')){
        $('select[name="your-email"]').val(decodeURIComponent($.urlParam('email')))
            .change(); // set select name to the name of your form field in CF7
    }
});

the decodeURIComponent is only if you're using a URL Encoded parameter... This is because you have a space in your selections "Office 1", "Office 2"

set the [name=] to the name of your CF7 field.


问:
Repeated variables in ggplot2
A minimum working example code:

```<code>df <- data.frame()
df[1:2,"year"] <- 2012L
df[3:7, "year"] <- 2013L
df[8:16, "year"] <- 2014L
df$team <- c("Team_A", "Team_B", "Team_A", "Team_B", "Team_C",
         "Team_D", "Team_E", "Team_A", "Team_B", "Team_C",
         "Team_D", "Team_E", "Team_F", "Team_G", "Team_H",
         "Team_I")
df$matches <- c(4, 2, 9, 7, 3, 4, 1, 16, 13, 10, 8, 9, 2,3,1, 3)
df
</code>```

The dataframe looks like this:

```<code>    year     team  matches
1   2012    Team_A  4
2   2012    Team_B  2
3   2013    Team_A  9
4   2013    Team_B  7
5   2013    Team_C  3
6   2013    Team_D  4
7   2013    Team_E  1
8   2014    Team_A  16
9   2014    Team_B  13
10  2014    Team_C  10
11  2014    Team_D  8
12  2014    Team_E  9
13  2014    Team_F  2
14  2014    Team_G  3
15  2014    Team_H  1
16  2014    Team_I  3
</code>```

The matches are plot yearwise:

```<code>match_plot_yearwise <- ggplot(df, aes(matches, team, color = year)) +
  geom_segment(aes(x = matches, y = team, xend = matches, yend = team),
                   color= "grey50") +
  geom_point() +
  theme_minimal() +
  theme(
    panel.grid = element_blank(),
  )
match_plot_yearwise
</code>```

This gives the following plot:

If a team plays more than one year then, how to repeat the team name on y-axis that many times, instead of stacking it's each year match one above the other?

答:
This solution pastes team and year together in a single variable, but labels the y-axis with the team name only. I could not tell what you wanted to do with the geom_segment() so I omitted it. (In your example plots it creates segments with length 0.) I had to sort df so that the labels would appear in the correct places.

data

```<code>df <- read.table(textConnection('    year     team  matches
1   2012    Team_A  4
2   2012    Team_B  2
3   2013    Team_A  9
4   2013    Team_B  7
5   2013    Team_C  3
6   2013    Team_D  4
7   2013    Team_E  1
8   2014    Team_A  16
9   2014    Team_B  13
10  2014    Team_C  10
11  2014    Team_D  8
12  2014    Team_E  9
13  2014    Team_F  2
14  2014    Team_G  3
15  2014    Team_H  1
16  2014    Team_I  3'))
</code>```

code

```<code>library(dplyr)
library(ggplot2)

df <- df %>%
  arrange(team, year)

ggplot(df, aes(x = matches, y = interaction(year, team), color = factor(year))) +

  geom_point() +
  scale_y_discrete(labels = df$team) +
  theme_minimal() +

  theme(
    panel.grid = element_blank(),
  )
</code>```

output

Title: Repeated variables in ggplot2

Body:
A minimum working example code:

df <- data.frame()
df[1:2,"year"] <- 2012L
df[3:7, "year"] <- 2013L
df[8:16, "year"] <- 2014L
df$team <- c("Team_A", "Team_B", "Team_A", "Team_B", "Team_C",
         "Team_D", "Team_E", "Team_A", "Team_B", "Team_C",
         "Team_D", "Team_E", "Team_F", "Team_G", "Team_H",
         "Team_I")
df$matches <- c(4, 2, 9, 7, 3, 4, 1, 16, 13, 10, 8, 9, 2,3,1, 3)
df

The dataframe looks like this:

    year     team  matches
1   2012    Team_A  4
2   2012    Team_B  2
3   2013    Team_A  9
4   2013    Team_B  7
5   2013    Team_C  3
6   2013    Team_D  4
7   2013    Team_E  1
8   2014    Team_A  16
9   2014    Team_B  13
10  2014    Team_C  10
11  2014    Team_D  8
12  2014    Team_E  9
13  2014    Team_F  2
14  2014    Team_G  3
15  2014    Team_H  1
16  2014    Team_I  3

The matches are plot yearwise:

match_plot_yearwise <- ggplot(df, aes(matches, team, color = year)) +
  geom_segment(aes(x = matches, y = team, xend = matches, yend = team),
                   color= "grey50") +
  geom_point() +
  theme_minimal() +
  theme(
    panel.grid = element_blank(),
  )
match_plot_yearwise

This gives the following plot:

If a team plays more than one year then, how to repeat the team name on y-axis that many times, instead of stacking it's each year match one above the other?

Body:
This solution pastes team and year together in a single variable, but labels the y-axis with the team name only. I could not tell what you wanted to do with the geom_segment() so I omitted it. (In your example plots it creates segments with length 0.) I had to sort df so that the labels would appear in the correct places.

data

df <- read.table(textConnection('    year     team  matches
1   2012    Team_A  4
2   2012    Team_B  2
3   2013    Team_A  9
4   2013    Team_B  7
5   2013    Team_C  3
6   2013    Team_D  4
7   2013    Team_E  1
8   2014    Team_A  16
9   2014    Team_B  13
10  2014    Team_C  10
11  2014    Team_D  8
12  2014    Team_E  9
13  2014    Team_F  2
14  2014    Team_G  3
15  2014    Team_H  1
16  2014    Team_I  3'))

code

library(dplyr)
library(ggplot2)

df <- df %>%
  arrange(team, year)

ggplot(df, aes(x = matches, y = interaction(year, team), color = factor(year))) +

  geom_point() +
  scale_y_discrete(labels = df$team) +
  theme_minimal() +

  theme(
    panel.grid = element_blank(),
  )

output


问:
Jekyll markdown processing does not create hyperlink
I am trying to create a simple website for documentation using github page using markdown documents.

The directory structure is:

```<code>root
 |-- index.md
 +-- _topic
       |-- doc1.md
       |-- doc2.md
       |-- ...
       +-- docn.md
</code>```

The index.md file content:

```<code>---
title: TOC
---

{% for topic in site.topics %}
* [{{topic.title}}]({{topic.url}}]
{% endfor %}
</code>```

I was expecting the produced html will contain a list of hyperlinks since markdown uses []() for hyperlinks. Instead I see the following in Jekyll generated index.html:

```<code><ul>
  <li>
    <p>[doc1_title](/topics/doc1.html]</p>
  </li>
  <li>
    <p>[doc2_title](/topics/doc2.html]</p>
  </li>
  ...
  <li>
    <p>[docn_title](/topics/docn.html]</p>
  </li>
</ul>
</code>```

Any ideas what am I doing wrong here?

答:
You could try

```<code> {{ topic.url | relative_url }}
</code>```

which should give you the relative url of your topic

Body:
I am trying to create a simple website for documentation using github page using markdown documents.

The directory structure is:

root
 |-- index.md
 +-- _topic
       |-- doc1.md
       |-- doc2.md
       |-- ...
       +-- docn.md

The index.md file content:

---
title: TOC
---

{% for topic in site.topics %}
* [{{topic.title}}]({{topic.url}}]
{% endfor %}

I was expecting the produced html will contain a list of hyperlinks since markdown uses []() for hyperlinks. Instead I see the following in Jekyll generated index.html:

[doc1_title](/topics/doc1.html]

[doc2_title](/topics/doc2.html]

  ...

[docn_title](/topics/docn.html]

Any ideas what am I doing wrong here?

Body:
You could try

 {{ topic.url | relative_url }}

which should give you the relative url of your topic


问:
how to Create and Use SnackBar for ReUse(Globally) in Flutter
i want create SnackBar for reusable(globally)

i already created but its only for 1 page , i don't know how to create reusable.

below code:

```<code>import 'package:flutter/material.dart';

class SnackBarMain extends StatefulWidget {
  @override
  _SnackBarMainState createState() => _SnackBarMainState();
}

class _SnackBarMainState extends State<SnackBarMain> {
  final globalKey = GlobalKey<ScaffoldState>();
  String title = 'SnackBar';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: globalKey,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text(title),
      ),
      body: Center(
        child: RaisedButton(
          shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(18.0),
              side: BorderSide(color: Colors.purple)),
          onPressed: () => snackBarMsg(context),
          color: Colors.purple,
          textColor: Colors.white,
          child: Text("SnackBar",
              style: TextStyle(fontSize: 18)),
        ),
      ),
    );
  }

snackBarMsg(BuildContext context) {
    final sb = SnackBar(
      elevation: 0.0,
      //behavior: SnackBarBehavior.floating,
      content: Text('SnackBar Bottom Message'),
      duration: new Duration(seconds: 5000000),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
      ),
      //backgroundColor: Colors.redAccent,
      action: SnackBarAction(
        textColor: Color(0xFFFAF2FB),
        label: 'OK',
        onPressed: () {},
      ),
    );
    globalKey.currentState.showSnackBar(sb);
  }
}
</code>```

so any one please give me example for this

答:
You can have a class that has a static method show() which receives the context and shows a snackbar.
Check te code below.

```<code>class GlobalSnackBar {
  final String message;

  const GlobalSnackBar({
    @required this.message,
  });

  static show(
    BuildContext context,
    String message,
  ) {
    Scaffold.of(context).showSnackBar(
      SnackBar(
        elevation: 0.0,
        //behavior: SnackBarBehavior.floating,
        content: Text(message),
        duration: new Duration(seconds: 5000000),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
        ),
        //backgroundColor: Colors.redAccent,
        action: SnackBarAction(
          textColor: Color(0xFFFAF2FB),
          label: 'OK',
          onPressed: () {},
        ),
      ),
    );
  }
}
</code>```

And you can call it from anywhere like this:

```<code>class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('SHOW Snackbar'),
      onPressed: () => GlobalSnackBar.show(context, 'Test'),
    );
  }
}
</code>```

Remember that the context you pass to show() method has to be a descendant from Scaffold in order to show the SnackBar

Body:
i want create SnackBar for reusable(globally)

i already created but its only for 1 page , i don't know how to create reusable.

below code:

import 'package:flutter/material.dart';

class SnackBarMain extends StatefulWidget {
  @override
  _SnackBarMainState createState() => _SnackBarMainState();
}

class _SnackBarMainState extends State<SnackBarMain> {
  final globalKey = GlobalKey<ScaffoldState>();
  String title = 'SnackBar';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: globalKey,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text(title),
      ),
      body: Center(
        child: RaisedButton(
          shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(18.0),
              side: BorderSide(color: Colors.purple)),
          onPressed: () => snackBarMsg(context),
          color: Colors.purple,
          textColor: Colors.white,
          child: Text("SnackBar",
              style: TextStyle(fontSize: 18)),
        ),
      ),
    );
  }

snackBarMsg(BuildContext context) {
    final sb = SnackBar(
      elevation: 0.0,
      //behavior: SnackBarBehavior.floating,
      content: Text('SnackBar Bottom Message'),
      duration: new Duration(seconds: 5000000),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
      ),
      //backgroundColor: Colors.redAccent,
      action: SnackBarAction(
        textColor: Color(0xFFFAF2FB),
        label: 'OK',
        onPressed: () {},
      ),
    );
    globalKey.currentState.showSnackBar(sb);
  }
}

so any one please give me example for this

Body:
You can have a class that has a static method show() which receives the context and shows a snackbar.
Check te code below.

class GlobalSnackBar {
  final String message;

  const GlobalSnackBar({
    @required this.message,
  });

  static show(
    BuildContext context,
    String message,
  ) {
    Scaffold.of(context).showSnackBar(
      SnackBar(
        elevation: 0.0,
        //behavior: SnackBarBehavior.floating,
        content: Text(message),
        duration: new Duration(seconds: 5000000),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
        ),
        //backgroundColor: Colors.redAccent,
        action: SnackBarAction(
          textColor: Color(0xFFFAF2FB),
          label: 'OK',
          onPressed: () {},
        ),
      ),
    );
  }
}

And you can call it from anywhere like this:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('SHOW Snackbar'),
      onPressed: () => GlobalSnackBar.show(context, 'Test'),
    );
  }
}

Remember that the context you pass to show() method has to be a descendant from Scaffold in order to show the SnackBar


Title: array_unique with SORT_NUMBERIC behaviour

Body:
I've stumbled upon something weird and I don't understand why it works that way.

I have an array of numbers, they are all unique:

$array = [
    98602142989816970,
    98602142989816971,
    98602142989816980,
    98602142989816981,
    98602142989816982,
    98602142989816983,
    98602142989820095,
    98602142989820096,
    98602142989822060,
    98602142989822061,
];
var_dump($array);

array(10) {
  [0]=>
  int(98602142989816970)
  [1]=>
  int(98602142989816971)
  [2]=>
  int(98602142989816980)
  [3]=>
  int(98602142989816981)
  [4]=>
  int(98602142989816982)
  [5]=>
  int(98602142989816983)
  [6]=>
  int(98602142989820095)
  [7]=>
  int(98602142989820096)
  [8]=>
  int(98602142989822060)
  [9]=>
  int(98602142989822061)
}

If I do print_r(array_unique($array)); everything is fine, I get:

Array
(
    [0] => 98602142989816970
    [1] => 98602142989816971
    [2] => 98602142989816980
    [3] => 98602142989816981
    [4] => 98602142989816982
    [5] => 98602142989816983
    [6] => 98602142989820095
    [7] => 98602142989820096
    [8] => 98602142989822060
    [9] => 98602142989822061
)

But If I add SORT_NUMERIC flag print_r(array_unique($array, SORT_NUMERIC)); I get:

Array
(
    [0] => 98602142989816970
    [6] => 98602142989820095
    [8] => 98602142989822060
)

Why only those 3 numbers are returned?

update: I'm on 64-bit system.

For sort functions I've manually shuffled some of the values because in original array they are already sorted.

If I do sort($array); then response is as expected:

Array
(
    [0] => 98602142989816970
    [1] => 98602142989816971
    [2] => 98602142989816980
    [3] => 98602142989816981
    [4] => 98602142989816982
    [5] => 98602142989816983
    [6] => 98602142989820095
    [7] => 98602142989820096
    [8] => 98602142989822060
    [9] => 98602142989822061
)

But with sort($array, SORT_NUMERIC);, they are sorted incorrectly:

Array
(
    [0] => 98602142989816970
    [1] => 98602142989816982
    [2] => 98602142989816983
    [3] => 98602142989816980
    [4] => 98602142989816981
    [5] => 98602142989816971
    [6] => 98602142989820095
    [7] => 98602142989820096
    [8] => 98602142989822060
    [9] => 98602142989822061
)

Body:
It makes a difference whether the code runs under a 32-bit PHP or a 64-bit version, because the integer there is also 32-bit or 64-bit long.

$array = [
    98602142989816970,
    98602142989816971,
    98602142989816980,
    98602142989816981,
    98602142989816982,
    98602142989816983,
    98602142989820095,
    98602142989820096,
    98602142989822060,
    98602142989822061,
];
echo '<pre>';
var_dump(PHP_INT_MAX,$array);

The result for a 32-Bit-System:

int(2147483647)
array(10) {
  [0]=>
  float(9.8602142989817E+16)
  [1]=>
  float(9.8602142989817E+16)
  [2]=>
  float(9.8602142989817E+16)
  [3]=>
  float(9.8602142989817E+16)
  [4]=>
  float(9.8602142989817E+16)
  [5]=>
  float(9.8602142989817E+16)
  [6]=>
  float(9.860214298982E+16)
  [7]=>
  float(9.860214298982E+16)
  [8]=>
  float(9.8602142989822E+16)
  [9]=>
  float(9.8602142989822E+16)
}

PHP converts the values to float right away because they are all greater than PHP_INT_MAX.

The result for a 64 Bit System:

int(9223372036854775807)
array(10) {
  [0]=>
  int(98602142989816970)
  [1]=>
  int(98602142989816971)
  [2]=>
  int(98602142989816980)
  [3]=>
  int(98602142989816981)
  [4]=>
  int(98602142989816982)
  [5]=>
  int(98602142989816983)
  [6]=>
  int(98602142989820095)
  [7]=>
  int(98602142989820096)
  [8]=>
  int(98602142989822060)
  [9]=>
  int(98602142989822061)
}

An array_unique among the 32-bit system reduces the array because some values also exceed the accuracy of float.

If the SORT_NUMERIC option is not used, array_unique() and sort() work properly for the 64-bit version.


问:
.net interfaces with generic methods, errors in implementation
Bear in mind, this code works in C#, but not in VC++.net (infuriating).  I'm wondering where my mistake is on here.

Given the code:

```<code>public interface class iTest
{
   public:
   generic <typename T>
   virtual void AddCriteriaList(List<T> ^CriterionList);
};

generic <typename Q>
public ref class IUseInterface : iTest
{
   public:
   generic <typename T>
   virtual void AddCriteriaList(List<T> ^CriterionList)
   {

   }
};
</code>```

I get the error error C3766: 'IUseInterface' must provide an implementation for the interface method 'void iTest::AddCriteriaList(System::Collections::Generic::List ^)'

The strange thing, is if I remove the generic constraint (Q) on IUseInterface, the error goes away.  I don't understand how making my class generic would have ANYTHING to do with a generic on a specific function.

Any ideas?  Thanks

答:
I don't have the answer for that, but this works, if it's good enough for you:</p>

```<code>generic <typename T>
public interface class iTest
{
   public:
   virtual void AddCriteriaList(List<T> ^CriterionList);
};

generic <typename Q, typename T>
public ref class IUseInterface : iTest<T>
{
public:
   virtual void AddCriteriaList(List<T> ^CriterionList)
   {
   }
};
</code>```

Body:
Bear in mind, this code works in C#, but not in VC++.net (infuriating).  I'm wondering where my mistake is on here.

Given the code:

public interface class iTest
{
   public:
   generic <typename T>
   virtual void AddCriteriaList(List<T> ^CriterionList);
};

generic <typename Q>
public ref class IUseInterface : iTest
{
   public:
   generic <typename T>
   virtual void AddCriteriaList(List<T> ^CriterionList)
   {

   }
};

I get the error error C3766: 'IUseInterface' must provide an implementation for the interface method 'void iTest::AddCriteriaList(System::Collections::Generic::List ^)'

The strange thing, is if I remove the generic constraint (Q) on IUseInterface, the error goes away.  I don't understand how making my class generic would have ANYTHING to do with a generic on a specific function.

Any ideas?  Thanks

Body:
I don't have the answer for that, but this works, if it's good enough for you:

generic <typename T>
public interface class iTest
{
   public:
   virtual void AddCriteriaList(List<T> ^CriterionList);
};

generic <typename Q, typename T>
public ref class IUseInterface : iTest<T>
{
public:
   virtual void AddCriteriaList(List<T> ^CriterionList)
   {
   }
};


问:
Correct way to toggle CSS classes upon element onfocus and onblur (pure JS)
I'm a server-side dev dabbling in a bit of JS  front-end. Recently I added a position:fixed menu bar in on of my web applications (meant for the mobile web).

It works fine. But there's a usability issue. When the virtual keyboard opens, the bottom menu naturally moves up with it. Sometimes, this covers up textareas or inputs the user was supposed to type into.

Now the web-app in question has a ton of user-generated content. Ergo there can be several textareas or input elements on a given page.

How do I use pure JS to set position:absolute on the given menu bar when any textarea or input is focused, and reset it to position:fixed when the said focus is lost (i.e. blurred)?

Here's how I've setup the menu bar:

.design{
    background:coral;
    height:40px;
    width:100%;
    text-align:center;
    color:white;
    z-index:89;
}
.fix-it{
    position: fixed;
    bottom:0;
}
.abs-it{
    position: absolute;
    bottom:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bottom_nav" class="fix-it design">
BOTTOM MENU
</div></code>```

My pure JS knowledge is a work-in-progress. I'm trying to achieve my requirement via the following pure JS (and failing):

```<code>// selecting all textareas or inputs for processing (e.g. making fixed bottom menu 'absolute')
var input_btns = document.getElementsByClassName('inp');

// ensuring relevant CSS classes applied onfocus and onblur
for (var i=0, len=input_btns.length; i < len; i++) {
    input_btns[i].onfocus = document.getElementById("bottom_nav").classList.remove('fix-it').add('abs-it');
    input_btns[i].onblur = document.getElementById("bottom_nav").classList.remove('abs-it').add('fix-it');
}
</code>```

Unfortunately, this doesn't work. Upon initialization, the menu bar renders devoid of any CSS class at all!?

I'm stumped. Can an expert help me fix my code? I prefer pure JS solutions over the need to use any library for such a rudimentary task.

答:
You should wrap document.getElementById("bottom_nav").classList.remove('fix-it').add('abs-it'); in a function, so it's only run when the event is triggered

like this:

```<code>    input_btns[i].onfocus = () => {
      document.getElementById("bottom_nav").classList.remove('fix-it');
      document.getElementById("bottom_nav").classList.add('abs-it');
    }
</code>```

When you do an assignation the code after the = is executed immediately; what you need is a function that executes the code only when that function is called.

Body:
I'm a server-side dev dabbling in a bit of JS  front-end. Recently I added a position:fixed menu bar in on of my web applications (meant for the mobile web).

It works fine. But there's a usability issue. When the virtual keyboard opens, the bottom menu naturally moves up with it. Sometimes, this covers up textareas or inputs the user was supposed to type into.

Now the web-app in question has a ton of user-generated content. Ergo there can be several textareas or input elements on a given page.

How do I use pure JS to set position:absolute on the given menu bar when any textarea or input is focused, and reset it to position:fixed when the said focus is lost (i.e. blurred)?

Here's how I've setup the menu bar:

.design{
    background:coral;
    height:40px;
    width:100%;
    text-align:center;
    color:white;
    z-index:89;
}
.fix-it{
    position: fixed;
    bottom:0;
}
.abs-it{
    position: absolute;
    bottom:0;
}

BOTTOM MENU

My pure JS knowledge is a work-in-progress. I'm trying to achieve my requirement via the following pure JS (and failing):

// selecting all textareas or inputs for processing (e.g. making fixed bottom menu 'absolute')
var input_btns = document.getElementsByClassName('inp');

// ensuring relevant CSS classes applied onfocus and onblur
for (var i=0, len=input_btns.length; i < len; i++) {
    input_btns[i].onfocus = document.getElementById("bottom_nav").classList.remove('fix-it').add('abs-it');
    input_btns[i].onblur = document.getElementById("bottom_nav").classList.remove('abs-it').add('fix-it');
}

Unfortunately, this doesn't work. Upon initialization, the menu bar renders devoid of any CSS class at all!?

I'm stumped. Can an expert help me fix my code? I prefer pure JS solutions over the need to use any library for such a rudimentary task.

Body:
You should wrap document.getElementById("bottom_nav").classList.remove('fix-it').add('abs-it'); in a function, so it's only run when the event is triggered

like this:

    input_btns[i].onfocus = () => {
      document.getElementById("bottom_nav").classList.remove('fix-it');
      document.getElementById("bottom_nav").classList.add('abs-it');
    }

When you do an assignation the code after the = is executed immediately; what you need is a function that executes the code only when that function is called.