问:
ggplot2 alternatives to fill in barplots, occurence of factor in multiple rows
I'm pretty new to R and I have a problem with plotting a barplot out of my data which looks like this:

```<code>condition answer
2    H
1    H
8    H
5    W
4    M
7    H
9    H
10   H
6    H
3    W
</code>```

The data consists of 100 rows with the conditions 1 to 10, each randomly generated 10 times (10 times condition 1, 10 times condition 8,...). Each of the conditions  also has a answer which could be H for Hit, M for Miss or W for wrong.

I want to plot the number of Hits for each condition in a barplot (for example 8 Hits out of 10 for condition 1,...) for that I tried to do the following in ggplot2

```<code>ggplot(data=test, aes(x=test$condition, fill=answer=="H"))+
  geom_bar()+labs(x="Conditions", y="Hitrate")+
  coord_cartesian(xlim = c(1:10), ylim = c(0:10))+
  scale_x_continuous(breaks=seq(1,10,1))
</code>```

And it looked like this:

This actually exactly what I need except for the red color which covers everything. You can see that conditions 3 to 5 have no blue bar, because there are no hits for these conditions.

Is there any way to get rid of this red color and to maybe count the amount of hits for the different conditions? -> I tried the count function of dplyr but it only showed me the amount of H when there where some for this particular condition. 3-5 where just "ignored" by count, there wasn't even a 0 in the output.-> but I'd still need those numbers for the plot

I'm sorry for this particular long post but I'm really at the end of knowledge considering this. I'd be open for suggestions or alternatives! Thanks in advance!

答:
One option is to just filter out anything but where answer == "H" from your dataset, and then plot.

An alternative is to use a grouped bar plot, made by setting position = "dodge":

```<code>test <- data.frame(condition = rep(1:10, each = 10),
                   answer = sample(c('H', 'M', 'W'), 100, replace = T))

ggplot(data=test) +
    geom_bar(aes(x = condition, fill = answer), position = "dodge") +
    labs(x="Conditions", y="Hitrate") +
    coord_cartesian(xlim = c(1:10), ylim = c(0:10)) +
    scale_x_continuous(breaks=seq(1,10,1))
</code>```

Also note that if the condition is actually a categorical variable, it may be better to make it a factor:

```<code>test$condition <- as.factor(test$condition)
</code>```

This means that you don't need the scale_x_continuous call, and that the grid lines will be cleaner.

Body:
I'm pretty new to R and I have a problem with plotting a barplot out of my data which looks like this:

condition answer
2    H
1    H
8    H
5    W
4    M
7    H
9    H
10   H
6    H
3    W

The data consists of 100 rows with the conditions 1 to 10, each randomly generated 10 times (10 times condition 1, 10 times condition 8,...). Each of the conditions  also has a answer which could be H for Hit, M for Miss or W for wrong.

I want to plot the number of Hits for each condition in a barplot (for example 8 Hits out of 10 for condition 1,...) for that I tried to do the following in ggplot2

ggplot(data=test, aes(x=test$condition, fill=answer=="H"))+
  geom_bar()+labs(x="Conditions", y="Hitrate")+
  coord_cartesian(xlim = c(1:10), ylim = c(0:10))+
  scale_x_continuous(breaks=seq(1,10,1))

And it looked like this:

This actually exactly what I need except for the red color which covers everything. You can see that conditions 3 to 5 have no blue bar, because there are no hits for these conditions.

Is there any way to get rid of this red color and to maybe count the amount of hits for the different conditions? -> I tried the count function of dplyr but it only showed me the amount of H when there where some for this particular condition. 3-5 where just "ignored" by count, there wasn't even a 0 in the output.-> but I'd still need those numbers for the plot

I'm sorry for this particular long post but I'm really at the end of knowledge considering this. I'd be open for suggestions or alternatives! Thanks in advance!

Body:
One option is to just filter out anything but where answer == "H" from your dataset, and then plot.

An alternative is to use a grouped bar plot, made by setting position = "dodge":

test <- data.frame(condition = rep(1:10, each = 10),
                   answer = sample(c('H', 'M', 'W'), 100, replace = T))

ggplot(data=test) +
    geom_bar(aes(x = condition, fill = answer), position = "dodge") +
    labs(x="Conditions", y="Hitrate") +
    coord_cartesian(xlim = c(1:10), ylim = c(0:10)) +
    scale_x_continuous(breaks=seq(1,10,1))

Also note that if the condition is actually a categorical variable, it may be better to make it a factor:

test$condition <- as.factor(test$condition)

This means that you don't need the scale_x_continuous call, and that the grid lines will be cleaner.


来源: stackexchange

问:
Method to download using generics asks for more context
I wrote a method using generics in order to make it reusable to any kind of download. It downloads json arrays and returns a generic object or an error.
This is my class to download json arrays from server:

```<code>import Foundation
enum Result<T> {
    case success(T)
    case failure(Error)
}
class LTLNetworkClient: NSObject {

    fileprivate var session : URLSession
    fileprivate var objectTask : URLSessionDataTask?

    override init() {
        let config = URLSessionConfiguration.ephemeral
        config.timeoutIntervalForResource = 5
        config.timeoutIntervalForRequest = 5
        self.session = URLSession.init(configuration: config)
    }

    /**
    Download asynchronously json object from Server and returns it into generic data models
    */
    func getData<K: Codable>(request: URLRequest, completion: @escaping (Result<[K]>) -> Void) {
        let sessionDataTask = URLSession.shared.dataTask(with: request) { (responseData, response, responseError) in
            if let jsonData = responseData {
                let decoder = JSONDecoder()
                do {
                    let response = try decoder.decode([K].self, from: jsonData)
                    let result: Result<[K]> = Result.success(response)
                    completion(result)
                } catch {
                    completion(.failure(error))
                }
            } else if let error = responseError {
                completion(.failure(error))
            } else {
                let error = NSError(domain: "Cannot form jsonData with Response Data", code: 501, userInfo: nil)
                completion(.failure(error))
            }
        }
        sessionDataTask.resume()
    }
}
</code>```

And this is how I call the method and the error I get:

Does anyone knows how to fix it and why this error appears?
Many thx in advance

答:
Here's your method declaration:

```<code>func getData<K: Codable>(request: URLRequest, completion: @escaping (Result<[K]>) -> Void)
</code>```

This method has a type parameter, K, which is only used in the type of the completion argument. When the compiler sees a call to getData, it has to deduce a concrete type for K based on the argument type of the closure you pass as completion.

And here's your call:

```<code>networkClient.getData(request: urlRequest) { (result) in
    // Do stuff
}
</code>```

In this call, the completion closure is { (result) in }. What is the type of result? There is no information given about it, so all the compiler knows is that result must be type Result<[K]> for some type K. It has no way to deduce a concrete type for K, so it emits an error.

You can make the type explicit like this:

```<code>networkClient.getData(request: urlRequest) { (_ result: Result<[SomeConcreteCodableType]>) -> Void in
    // Do stuff
}
</code>```

where SomeConcreteCodableType is some concrete type that conforms to Codable. The Codable conformance is required because of the constraint in getData's declaration.

A different solution is to change getData to take another argument that lets the caller specify K directly:

```<code>func getArray<K: Codable>(of: K.Type, for request: URLRequest,
    completion: @escaping (Result<[K]>) -> Void) {
    ...
}
</code>```

Then you call it like this:

```<code>networkClient.getArray(of: SomeConcreteCodableType.self, for: request) { result in
    // Do stuff
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote a method using generics in order to make it reusable to any kind of download. It downloads json arrays and returns a generic object or an error.
This is my class to download json arrays from server:

import Foundation
enum Result<T> {
    case success(T)
    case failure(Error)
}
class LTLNetworkClient: NSObject {

    fileprivate var session : URLSession
    fileprivate var objectTask : URLSessionDataTask?

    override init() {
        let config = URLSessionConfiguration.ephemeral
        config.timeoutIntervalForResource = 5
        config.timeoutIntervalForRequest = 5
        self.session = URLSession.init(configuration: config)
    }

    /**
    Download asynchronously json object from Server and returns it into generic data models
    */
    func getData<K: Codable>(request: URLRequest, completion: @escaping (Result<[K]>) -> Void) {
        let sessionDataTask = URLSession.shared.dataTask(with: request) { (responseData, response, responseError) in
            if let jsonData = responseData {
                let decoder = JSONDecoder()
                do {
                    let response = try decoder.decode([K].self, from: jsonData)
                    let result: Result<[K]> = Result.success(response)
                    completion(result)
                } catch {
                    completion(.failure(error))
                }
            } else if let error = responseError {
                completion(.failure(error))
            } else {
                let error = NSError(domain: "Cannot form jsonData with Response Data", code: 501, userInfo: nil)
                completion(.failure(error))
            }
        }
        sessionDataTask.resume()
    }
}

And this is how I call the method and the error I get:

Does anyone knows how to fix it and why this error appears?
Many thx in advance

Body:
Here's your method declaration:

func getData<K: Codable>(request: URLRequest, completion: @escaping (Result<[K]>) -> Void)

This method has a type parameter, K, which is only used in the type of the completion argument. When the compiler sees a call to getData, it has to deduce a concrete type for K based on the argument type of the closure you pass as completion.

And here's your call:

networkClient.getData(request: urlRequest) { (result) in
    // Do stuff
}

In this call, the completion closure is { (result) in }. What is the type of result? There is no information given about it, so all the compiler knows is that result must be type Result<[K]> for some type K. It has no way to deduce a concrete type for K, so it emits an error.

You can make the type explicit like this:

networkClient.getData(request: urlRequest) { (_ result: Result<[SomeConcreteCodableType]>) -> Void in
    // Do stuff
}

where SomeConcreteCodableType is some concrete type that conforms to Codable. The Codable conformance is required because of the constraint in getData's declaration.

A different solution is to change getData to take another argument that lets the caller specify K directly:

func getArray<K: Codable>(of: K.Type, for request: URLRequest,
    completion: @escaping (Result<[K]>) -> Void) {
    ...
}

Then you call it like this:

networkClient.getArray(of: SomeConcreteCodableType.self, for: request) { result in
    // Do stuff
}


问:
Is if statement in for loop faster than one by one if statements in Java?
I wonder that if I use a HashMap to collect the conditions and loop each one in one if statement can I reach higher performance rather than to write one by one if - else if statement?

In my opinion, one-by-one if-else, if statements may be faster because in for loop runs one more condition in each loop like, does the counter reach the target number? So actually each if statement, it runs 2 if statements. Of course inside of the statements different but if we talk about just statement performance, I think one-by-one type would be better?

Edit: this is just a sample code, my question is about the performance differences between the usage of these statements.

Map<String, Integer> words = new HashMap<String, Integer>
String letter ="d";
int n = 4;
words.put("a",1);
words.put("b",2);
words.put("c",3);
words.put("d",4);
words.put("e",5);

words.forEach((word,number)->{
if(letter.equals(word){
System.out.println(number*n);
});

```

<pre class="lang-java prettyprint-override"><code>String letter ="d";
int n = 4;
if(letter.equals("a"){
System.out.println(number*1);
}else if(letter.equals("b"){
System.out.println(number*2);
}else if(letter.equals("c"){
System.out.println(number*3);
}else if(letter.equals("d"){
System.out.println(number*4);
}else if(letter.equals("e"){
System.out.println(number*5);
}

</code>```

答:
If you have a Map and you want to retrieve one letter, I'm not sure why you would loop at all?

```<code>Map<String, Integer> words = new HashMap<String, Integer>
String letter ="d";
int n = 4;
words.put("a",1);
words.put("b",2);
words.put("c",3);
words.put("d",4);
words.put("e",5);

if (words.containsKey(letter) {
  System.out.println(words.get(letter)*n);
}
else
{
  System.out.println(letter + " doesn't exist in Map");
}
</code>```

If you aren't using the benefits of a Map, then why use a Map at all?

A forEach will actually touch every key in the list. The number of checks on your if/else is dependent on where it is in the list and how long the list of available letters is. If the letter you choose is the last one in the list then it would complete all checks before printing. If it is first then it will only do one which is much faster than having to check all.

It would be easy for you to write the two examples and run a timer to determine which is actually faster.
https://www.baeldung.com/java-measure-elapsed-time

There are a lot of wasted calculations if you have to run through 1 million if/else statements and only select one which could be anywhere in the list. This doesn't include typos and the horror of code maintenance. Using a Map with an index would be much quicker. If you are only talking about 100 if/else statements (still too many in my opinion) then you may be able to break even on speed.

Body:
I wonder that if I use a HashMap to collect the conditions and loop each one in one if statement can I reach higher performance rather than to write one by one if - else if statement?

In my opinion, one-by-one if-else, if statements may be faster because in for loop runs one more condition in each loop like, does the counter reach the target number? So actually each if statement, it runs 2 if statements. Of course inside of the statements different but if we talk about just statement performance, I think one-by-one type would be better?

Edit: this is just a sample code, my question is about the performance differences between the usage of these statements.

Map<String, Integer> words = new HashMap<String, Integer>
String letter ="d";
int n = 4;
words.put("a",1);
words.put("b",2);
words.put("c",3);
words.put("d",4);
words.put("e",5);

words.forEach((word,number)->{
if(letter.equals(word){
System.out.println(number*n);
});

String letter ="d";
int n = 4;
if(letter.equals("a"){
System.out.println(number*1);
}else if(letter.equals("b"){
System.out.println(number*2);
}else if(letter.equals("c"){
System.out.println(number*3);
}else if(letter.equals("d"){
System.out.println(number*4);
}else if(letter.equals("e"){
System.out.println(number*5);
}

Body:
If you have a Map and you want to retrieve one letter, I'm not sure why you would loop at all?

Map<String, Integer> words = new HashMap<String, Integer>
String letter ="d";
int n = 4;
words.put("a",1);
words.put("b",2);
words.put("c",3);
words.put("d",4);
words.put("e",5);

if (words.containsKey(letter) {
  System.out.println(words.get(letter)*n);
}
else
{
  System.out.println(letter + " doesn't exist in Map");
}

If you aren't using the benefits of a Map, then why use a Map at all?

A forEach will actually touch every key in the list. The number of checks on your if/else is dependent on where it is in the list and how long the list of available letters is. If the letter you choose is the last one in the list then it would complete all checks before printing. If it is first then it will only do one which is much faster than having to check all.

It would be easy for you to write the two examples and run a timer to determine which is actually faster.
https://www.baeldung.com/java-measure-elapsed-time

There are a lot of wasted calculations if you have to run through 1 million if/else statements and only select one which could be anywhere in the list. This doesn't include typos and the horror of code maintenance. Using a Map with an index would be much quicker. If you are only talking about 100 if/else statements (still too many in my opinion) then you may be able to break even on speed.


问:
Is there Dax code to take the difference between 2 rows from a summarized table
I need to be able to get the difference between 2 successive rows in a Summarized table, by rank, so that I can then get the average of the differences of each row. And I can't create a new table as I need this DAX query to be filterable

I've been able to get this far, but do not know how to add a difference column that will show the DSOValue difference between rows 1-2, 2-3, 3-4 ...

```<code>ADDCOLUMNS (
    SUMMARIZE (
        Table1,
        Table1[Date],
        "DSOValue", DIVIDE ( SUM ( 'Table1'[AR] ) * 91.5, SUM ( 'Table1'[Sales] ), 0 )
    ),
    "Rank", RANKX (
        Table1,
        CALCULATE (
            COUNTROWS ( Table1),
            FILTER ( Table1, Table1[Date] <= EARLIER ( Table1[Date] ) )
        ),,ASC,DENSE)
)
</code>```

I've tried embedding this code within another ADDCOLUMNS function, but it won't let me CALCULATE and FILTER on my created columns (DSOValue and RANK)

答:
you can use the following:

```<code>Diff = 'Table1'[ DSOValue ] - LOOKUPVALUE('Table1'[ DSOValue ]; 'Table1'[Date     ];CALCULATE( MAX('Table1'[Date     ]);FILTER('Table1';'Table1'[Date     ]<EARLIER('Table1'[Date     ]))))
</code>```

Note: You cannot use <= here, it will pick its own date and all will be null. It would also be easier to add an index column, when you have this you can use Lookupvalue with Index -1

Body:
I need to be able to get the difference between 2 successive rows in a Summarized table, by rank, so that I can then get the average of the differences of each row. And I can't create a new table as I need this DAX query to be filterable

I've been able to get this far, but do not know how to add a difference column that will show the DSOValue difference between rows 1-2, 2-3, 3-4 ...

ADDCOLUMNS (
    SUMMARIZE (
        Table1,
        Table1[Date],
        "DSOValue", DIVIDE ( SUM ( 'Table1'[AR] ) * 91.5, SUM ( 'Table1'[Sales] ), 0 )
    ),
    "Rank", RANKX (
        Table1,
        CALCULATE (
            COUNTROWS ( Table1),
            FILTER ( Table1, Table1[Date] <= EARLIER ( Table1[Date] ) )
        ),,ASC,DENSE)
)

I've tried embedding this code within another ADDCOLUMNS function, but it won't let me CALCULATE and FILTER on my created columns (DSOValue and RANK)

Body:
you can use the following:

Diff = 'Table1'[ DSOValue ] - LOOKUPVALUE('Table1'[ DSOValue ]; 'Table1'[Date     ];CALCULATE( MAX('Table1'[Date     ]);FILTER('Table1';'Table1'[Date     ]<EARLIER('Table1'[Date     ]))))

Note: You cannot use <= here, it will pick its own date and all will be null. It would also be easier to add an index column, when you have this you can use Lookupvalue with Index -1


问:
SyntaxError in Python robot controller code
I’m using approxeng.input.selectbinder for a robot controller and
def __init__(self, *requirements, print_events=False, **kwargs):
throws up a SyntaxError, specifically the print_events statement. I cannot understand why. This is the full code that gives the error:

```<code>from functools import reduce
from select import select
from threading import Thread

import approxeng.input.sys as sys
from approxeng.input.controllers import *

EV_KEY = 1
EV_REL = 2
EV_ABS = 3

class ControllerResource:
    """
    General resource which binds one or more controllers on entry and unbinds the event listening thread on exit.
    """

    def __init__(self, *requirements, print_events=True, **kwargs):
        """
        Create a new resource to bind and access one or more controllers. If no additional arguments are supplied this
        will find the first controller of any kind enabled by the library. Otherwise the requirements must be provided
        as a list of ControllerRequirement

        :param requirements:
            ControllerRequirement instances used, in order, to find and bind controllers. If empty this will
            be equivalent to supplying a single unfiltered requirement and will match the first specified controller.
        :param print_events:
            Defaults to False, if set to True then all events picked up by the binder will be printed to stdout. Use
            this when you're trying to figure out what events correspond to what axes and buttons!
        :param kwargs:
            Any addition keyword arguments are passed to the constructors for the controller classes. This is useful
            particularly to specify e.g. dead and hot zone ranges on discovery.
        :raises ControllerNotFoundError:
            If the requirement can't be satisfied, or no requirements are specified but there aren't any controllers.
        """

        self.discoveries = find_matching_controllers(*requirements, **kwargs)
        self.unbind = None
        self.print_events = print_events

    def __enter__(self):
        """
        Called on entering the resource block, returns the controller passed into the constructor.
        """
        self.unbind = bind_controllers(*self.discoveries, print_events=self.print_events)
        if len(self.discoveries) == 1:
            return self.discoveries[0].controller
        else:
            return tuple(discovery.controller for discovery in self.discoveries)

    def __exit__(self, exc_type, exc_value, traceback):
        """
        Called on resource exit, unbinds the controller, removing the listening thread.
        """
        self.unbind()

def bind_controllers(*discoveries, print_events=False):
    """
    Bind a controller or controllers to a set of evdev InputDevice instances, starting a thread to keep those
    controllers in sync with the state of the hardware.

    :param discoveries:
        ControllerDiscovery instances specifying the controllers and their associated input devices
    :param print_events:
        Defaults to False, if set to True then all events picked up by this binder will be printed to stdout
    :return:
        A function which can be used to stop the event reading thread and unbind from the device
    """

    discoveries = list(discoveries)

    class SelectThread(Thread):
        def __init__(self):
            Thread.__init__(self, name='evdev select thread')
            self.daemon = True
            self.running = True

            self.device_to_controller_discovery = {}
            for discovery in discoveries:
                for d in discovery.devices:
                    self.device_to_controller_discovery[d.fn] = discovery
            self.all_devices = reduce(lambda x, y: x + y, [discovery.devices for discovery in discoveries])

        def run(self):

            for discovery in discoveries:
                discovery.controller.device_unique_name = discovery.name

            while self.running:
                try:
                    r, w, x = select(self.all_devices, [], [], 0.5)
                    for fd in r:
                        active_device = fd
                        controller_discovery = self.device_to_controller_discovery[active_device.fn]
                        controller = controller_discovery.controller
                        controller_devices = controller_discovery.devices
                        prefix = None
                        if controller.node_mappings is not None and len(controller_devices) > 1:
                            try:
                                prefix = controller.node_mappings[active_device.name]
                            except KeyError:
                                pass
                        for event in active_device.read():
                            if print_events:
                                print(event)
                            if event.type == EV_ABS or event.type == EV_REL:
                                controller.axes.axis_updated(event, prefix=prefix)
                            elif event.type == EV_KEY:
                                # Button event
                                if event.value == 1:
                                    # Button down
                                    controller.buttons.button_pressed(event.code, prefix=prefix)
                                elif event.value == 0:
                                    # Button up
                                    controller.buttons.button_released(event.code, prefix=prefix)
                except Exception as e:
                    self.stop(e)

        def stop(self, exception=None):

            for discovery in discoveries:
                discovery.controller.device_unique_name = None
                discovery.controller.exception = exception

            self.running = False

    polling_thread = SelectThread()

    # Force an update of the LED and battery system cache
    sys.scan_cache(force_update=True)

    for device in polling_thread.all_devices:
        device.grab()

    def unbind():
        polling_thread.stop()
        for dev in polling_thread.all_devices:
            try:
                dev.ungrab()
            except IOError:
                pass

    polling_thread.start()

    return unbind
</code>```

答:
Minimal Reproducable Example

The following is a Minimal Reproducable Example of the issue in the question:

class ControllerResource:

    def __init__(self, *requirements, print_events=True, **kwargs):
        pass
```

<p>With Python 3.x this compiles just fine (i.e. you can import it without errors)., but with Python 2.x this raises a SyntaxError:</p>

<pre class="lang-none prettyprint-override"><code>  File "test.py", line 3
    def __init__(self, *requirements, print_events=True, **kwargs):
                                                 ^
SyntaxError: invalid syntax
</code>```

Explanation

The reason is that the argument list contains a regular (keyword) argument (i.e. print_events=True) after a varargs argument (i.e. *requirements).

In Python 3.x this is valid, and it would make the argument print_events a keyword-only argument (See PEP 3102 for more information and examples). Python 2.x does not support keyword-only arguments and thus the above code is not valid in Python 2.x.

Solution

First of all, I would highly recommend to use Python 3.x when possible, since Python 2.x is very old and it's not being maintained anymore after January 1, 2020.

However, if you really must use Python 2.x for whatever reasons, you could reorder the arguments for the __init__ method as follows:

class ControllerResource:

    def __init__(self, print_events=True, *requirements, **kwargs):
        pass
```

Body:
I’m using approxeng.input.selectbinder for a robot controller and
def __init__(self, *requirements, print_events=False, **kwargs):
throws up a SyntaxError, specifically the print_events statement. I cannot understand why. This is the full code that gives the error:

from functools import reduce
from select import select
from threading import Thread

import approxeng.input.sys as sys
from approxeng.input.controllers import *

EV_KEY = 1
EV_REL = 2
EV_ABS = 3

class ControllerResource:
    """
    General resource which binds one or more controllers on entry and unbinds the event listening thread on exit.
    """

    def __init__(self, *requirements, print_events=True, **kwargs):
        """
        Create a new resource to bind and access one or more controllers. If no additional arguments are supplied this
        will find the first controller of any kind enabled by the library. Otherwise the requirements must be provided
        as a list of ControllerRequirement

        :param requirements:
            ControllerRequirement instances used, in order, to find and bind controllers. If empty this will
            be equivalent to supplying a single unfiltered requirement and will match the first specified controller.
        :param print_events:
            Defaults to False, if set to True then all events picked up by the binder will be printed to stdout. Use
            this when you're trying to figure out what events correspond to what axes and buttons!
        :param kwargs:
            Any addition keyword arguments are passed to the constructors for the controller classes. This is useful
            particularly to specify e.g. dead and hot zone ranges on discovery.
        :raises ControllerNotFoundError:
            If the requirement can't be satisfied, or no requirements are specified but there aren't any controllers.
        """

        self.discoveries = find_matching_controllers(*requirements, **kwargs)
        self.unbind = None
        self.print_events = print_events

    def __enter__(self):
        """
        Called on entering the resource block, returns the controller passed into the constructor.
        """
        self.unbind = bind_controllers(*self.discoveries, print_events=self.print_events)
        if len(self.discoveries) == 1:
            return self.discoveries[0].controller
        else:
            return tuple(discovery.controller for discovery in self.discoveries)

    def __exit__(self, exc_type, exc_value, traceback):
        """
        Called on resource exit, unbinds the controller, removing the listening thread.
        """
        self.unbind()

def bind_controllers(*discoveries, print_events=False):
    """
    Bind a controller or controllers to a set of evdev InputDevice instances, starting a thread to keep those
    controllers in sync with the state of the hardware.

    :param discoveries:
        ControllerDiscovery instances specifying the controllers and their associated input devices
    :param print_events:
        Defaults to False, if set to True then all events picked up by this binder will be printed to stdout
    :return:
        A function which can be used to stop the event reading thread and unbind from the device
    """

    discoveries = list(discoveries)

    class SelectThread(Thread):
        def __init__(self):
            Thread.__init__(self, name='evdev select thread')
            self.daemon = True
            self.running = True

            self.device_to_controller_discovery = {}
            for discovery in discoveries:
                for d in discovery.devices:
                    self.device_to_controller_discovery[d.fn] = discovery
            self.all_devices = reduce(lambda x, y: x + y, [discovery.devices for discovery in discoveries])

        def run(self):

            for discovery in discoveries:
                discovery.controller.device_unique_name = discovery.name

            while self.running:
                try:
                    r, w, x = select(self.all_devices, [], [], 0.5)
                    for fd in r:
                        active_device = fd
                        controller_discovery = self.device_to_controller_discovery[active_device.fn]
                        controller = controller_discovery.controller
                        controller_devices = controller_discovery.devices
                        prefix = None
                        if controller.node_mappings is not None and len(controller_devices) > 1:
                            try:
                                prefix = controller.node_mappings[active_device.name]
                            except KeyError:
                                pass
                        for event in active_device.read():
                            if print_events:
                                print(event)
                            if event.type == EV_ABS or event.type == EV_REL:
                                controller.axes.axis_updated(event, prefix=prefix)
                            elif event.type == EV_KEY:
                                # Button event
                                if event.value == 1:
                                    # Button down
                                    controller.buttons.button_pressed(event.code, prefix=prefix)
                                elif event.value == 0:
                                    # Button up
                                    controller.buttons.button_released(event.code, prefix=prefix)
                except Exception as e:
                    self.stop(e)

        def stop(self, exception=None):

            for discovery in discoveries:
                discovery.controller.device_unique_name = None
                discovery.controller.exception = exception

            self.running = False

    polling_thread = SelectThread()

    # Force an update of the LED and battery system cache
    sys.scan_cache(force_update=True)

    for device in polling_thread.all_devices:
        device.grab()

    def unbind():
        polling_thread.stop()
        for dev in polling_thread.all_devices:
            try:
                dev.ungrab()
            except IOError:
                pass

    polling_thread.start()

    return unbind

Body:
Minimal Reproducable Example

The following is a Minimal Reproducable Example of the issue in the question:

class ControllerResource:

    def __init__(self, *requirements, print_events=True, **kwargs):
        pass

With Python 3.x this compiles just fine (i.e. you can import it without errors)., but with Python 2.x this raises a SyntaxError:

  File "test.py", line 3
    def __init__(self, *requirements, print_events=True, **kwargs):
                                                 ^
SyntaxError: invalid syntax

Explanation

The reason is that the argument list contains a regular (keyword) argument (i.e. print_events=True) after a varargs argument (i.e. *requirements).

In Python 3.x this is valid, and it would make the argument print_events a keyword-only argument (See PEP 3102 for more information and examples). Python 2.x does not support keyword-only arguments and thus the above code is not valid in Python 2.x.

Solution

First of all, I would highly recommend to use Python 3.x when possible, since Python 2.x is very old and it's not being maintained anymore after January 1, 2020.

However, if you really must use Python 2.x for whatever reasons, you could reorder the arguments for the __init__ method as follows:

class ControllerResource:

    def __init__(self, print_events=True, *requirements, **kwargs):
        pass


问:
SDK directory is not writable when building Android project on Ubuntu agent of Azure Pipelines
I'm configuring my build pipeline for an Android project. So far, all of my steps are working perfectly on Hosted VS2017 agent, including fetching the code, building with gradlew, publishing the artifact and deploying it to AppCenter.

However, on Hosted Ubuntu 1604, there are a few problems with gradlew step.

On VS2017 agent, this works with just: .\gradlew assembleDebug

On Ubuntu 1604, this is what I'm having right now:

```<code>chmod 775 gradlew
chmod 775 /usr/local/lib/android/sdk --> The fix I'm working on
./gradlew assembleDebug
</code>```

Running the build without the 2nd line, agent will throw this exception:

What went wrong: A problem occurred configuring project ':app'.

  Failed to install the following SDK components: build-tools;28.0.3 Android SDK Build-Tools 28.0.3

  The SDK directory is not writable (/usr/local/lib/android/sdk)

I'm a beginner with Ubuntu... why is it not writable? I tried to chmod but I got the exception while doing so: chmod: changing permissions of '/usr/local/lib/android/sdk': Operation not permitted.

Which direction should I look at to solve this problem now... ? Thank you all in advance!

答:
I had the same problem on a standard Ubuntu install.

The solution: install the Android SDK in your home directory.

The problem is, building a project with Gradle fails to work with a read-only SDK. Installing the Android SDK with apt leaves it read-only.

More precisely, everything in /usr/ is supposed to be read-only data, so it's owned by root with permissions set to 755. Your user doesn't have write access to it, only the owner does. Installing the SDK in your home directory (and making sure your user owns it) should solve the issue.

Installing the SDK

I haven't seen a good way to install just the SDK. There's another SO question addressing this; one of the ways listed there ought to work.
However, you may find it easier to just install Android Studio, and pick a custom location for the SDK.

Hope it helps!

Body:
I'm configuring my build pipeline for an Android project. So far, all of my steps are working perfectly on Hosted VS2017 agent, including fetching the code, building with gradlew, publishing the artifact and deploying it to AppCenter.

However, on Hosted Ubuntu 1604, there are a few problems with gradlew step.

On VS2017 agent, this works with just: .\gradlew assembleDebug

On Ubuntu 1604, this is what I'm having right now:

chmod 775 gradlew
chmod 775 /usr/local/lib/android/sdk --> The fix I'm working on
./gradlew assembleDebug

Running the build without the 2nd line, agent will throw this exception:

What went wrong: A problem occurred configuring project ':app'.

  Failed to install the following SDK components: build-tools;28.0.3 Android SDK Build-Tools 28.0.3

  The SDK directory is not writable (/usr/local/lib/android/sdk)

I'm a beginner with Ubuntu... why is it not writable? I tried to chmod but I got the exception while doing so: chmod: changing permissions of '/usr/local/lib/android/sdk': Operation not permitted.

Which direction should I look at to solve this problem now... ? Thank you all in advance!


问:
Parse page to get input and then submit post including this input value
I want to parse page where is form and this form includes token input
need to take this token value and send with my inputs

this is curl code what i was using before they added token input

$username = @$_POST['user'];
$password = @$_POST['password'];
$to = @$_POST['to'];
$text = @$_POST['text'];
$loginUrl = '';
$sendUrl = '';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$username&password=$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch)."/n";
}
//sending
curl_setopt($ch, CURLOPT_URL, $sendUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, "recipients=$to&message_body=$text");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name-send');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie-send.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch)."/n";
}
echo $answer;
```

<p>This is page what i want to parse</p>

<pre class="lang-html prettyprint-override"><code><form name="user_action" method="post" action="index.php?page=11&lang=ge">
<input type="hidden" name="csrf_token" value="7e71ea58eaaa55986b0fdc71b2d44c92">
<input type="text" id="user" name="user" class="round_border medium_box">
<input type="password" id="password" name="password" class="round_border medium_box">
<input type="submit" value="შესვლა" class="btn red_btn round_border medium">
</form>
</code>```

No i can't post without this token <input type="hidden" name="csrf_token" value="7e71ea58eaaa55986b0fdc71b2d44c92">

And all i need is to to parse this page first to get token and same time send post with this token

答:
Check out DOMDocument for parsing HTML. https://www.php.net/manual/en/class.domdocument.php

Here's what I'd try:

```<code><?php
$page = file_get_contents("https://wherever-the-form-is.com");
$dom = new DOMDocument();
$dom->loadHTML( $page );

// Get a list of all inputs
$inputs = $dom->getElementsByTagName( 'input' );
$total = $inputs->length;
$token = false;

// Loop through inputs looking for one with the right name
for( $i = 0; $i < $total; $i++ ) {
    if ( $inputs->item($i)->getAttribute('name') == 'csrf_token' ) {
        // When you find the right name, record the value and break out of the loop
        $token = $inputs->item($i)->getAttribute('value');
        break;
    }
}

if ( $token ) {
    // Your code here
}
</code>```

Body:
I want to parse page where is form and this form includes token input
need to take this token value and send with my inputs

this is curl code what i was using before they added token input

$username = @$_POST['user'];
$password = @$_POST['password'];
$to = @$_POST['to'];
$text = @$_POST['text'];
$loginUrl = '';
$sendUrl = '';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$username&password=$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch)."/n";
}
//sending
curl_setopt($ch, CURLOPT_URL, $sendUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, "recipients=$to&message_body=$text");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name-send');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie-send.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch)."/n";
}
echo $answer;

This is page what i want to parse

<form name="user_action" method="post" action="index.php?page=11&lang=ge">
<input type="hidden" name="csrf_token" value="7e71ea58eaaa55986b0fdc71b2d44c92">
<input type="text" id="user" name="user" class="round_border medium_box">
<input type="password" id="password" name="password" class="round_border medium_box">
<input type="submit" value="შესვლა" class="btn red_btn round_border medium">
</form>

No i can't post without this token <input type="hidden" name="csrf_token" value="7e71ea58eaaa55986b0fdc71b2d44c92">

And all i need is to to parse this page first to get token and same time send post with this token

Body:
Check out DOMDocument for parsing HTML. https://www.php.net/manual/en/class.domdocument.php

Here's what I'd try:

<?php
$page = file_get_contents("https://wherever-the-form-is.com");
$dom = new DOMDocument();
$dom->loadHTML( $page );

// Get a list of all inputs
$inputs = $dom->getElementsByTagName( 'input' );
$total = $inputs->length;
$token = false;

// Loop through inputs looking for one with the right name
for( $i = 0; $i < $total; $i++ ) {
    if ( $inputs->item($i)->getAttribute('name') == 'csrf_token' ) {
        // When you find the right name, record the value and break out of the loop
        $token = $inputs->item($i)->getAttribute('value');
        break;
    }
}

if ( $token ) {
    // Your code here
}


问:
Why do we use numpy.argmax() to return an index from a numpy array of predictions?
Let me preface this by saying, I am very new to neural networks, and this is my first time using numpy, tensorflow, or keras.

I wrote a neural network to recognize handwritten digits, using the MNIST data set. I followed this tutorial by Sentdex and noticed he was using print(np.argmax(predictions[0])) to print the first index from the numpy array of predictions.

I tried running the program with that line replaced by print(predictions[i]), (i was set to 0) but the output was not a number, it was:
[2.1975785e-08 1.8658861e-08 2.8842608e-06 5.7113186e-05 1.2067199e-10
 7.2511304e-09 1.6282028e-12 9.9993789e-01 1.3356166e-08 2.0409643e-06].

My code than I'm confused about is:

```<code>predictions = model.predict(x_test)
for i in range(10):
   plt.imshow(x_test[i])
   plt.show()
   print("PREDICTION: ", predictions[i])
</code>```

I read the numpy documentation for the argmax() function, and from what I understand, it takes in a x-dimensional array, converts it to a one-dimensional array, then returns the index of the largest value. The Keras documentation for model.predict() indicated that the function returns a numpy array of the networks predictions. So I don't understand why we have to use argmax() to properly print the prediction, because as I understand, it has a completely unrelated purpose.

Sorry for the bad code formatting, I couldn't figure out how to properly insert multi line chunks of code into my post

答: What any classification neural network outputs is a probability distribution over the class indices, meaning that the network assigns one probability to each class. The sum of these probabilities is 1.0. Then the network is trained to assign the highest probability to the correct class, so to recover the class index from the probabilities you have to take the location (index) that has the maximum probability. This is done with the argmax operation.

Body:
Let me preface this by saying, I am very new to neural networks, and this is my first time using numpy, tensorflow, or keras.

I wrote a neural network to recognize handwritten digits, using the MNIST data set. I followed this tutorial by Sentdex and noticed he was using print(np.argmax(predictions[0])) to print the first index from the numpy array of predictions.

I tried running the program with that line replaced by print(predictions[i]), (i was set to 0) but the output was not a number, it was:
[2.1975785e-08 1.8658861e-08 2.8842608e-06 5.7113186e-05 1.2067199e-10
 7.2511304e-09 1.6282028e-12 9.9993789e-01 1.3356166e-08 2.0409643e-06].

My code than I'm confused about is:

predictions = model.predict(x_test)
for i in range(10):
   plt.imshow(x_test[i])
   plt.show()
   print("PREDICTION: ", predictions[i])

I read the numpy documentation for the argmax() function, and from what I understand, it takes in a x-dimensional array, converts it to a one-dimensional array, then returns the index of the largest value. The Keras documentation for model.predict() indicated that the function returns a numpy array of the networks predictions. So I don't understand why we have to use argmax() to properly print the prediction, because as I understand, it has a completely unrelated purpose.

Sorry for the bad code formatting, I couldn't figure out how to properly insert multi line chunks of code into my post


问:
How do I check if a given user ID has authenticated my app?
I'm using the Facebook Graph API and want to check if a user has authenticated my Facebook app by user ID. How do I do this? </p>

答:
You use:

```<code>SELECT is_app_user FROM user WHERE uid=USER_ID
</code>```

This should return:

```<code>[
  {
    "is_app_user": true
  }
]
</code>```

If the user has logged in to your application.

ContentLicense: CC BY-SA 3.0

Body:
You use:

SELECT is_app_user FROM user WHERE uid=USER_ID

This should return:

[
  {
    "is_app_user": true
  }
]

If the user has logged in to your application.


问:
Default [PXDBInt] data field to Null value?
How can I have a numeric field allow and default to a Null / unspecified value?

When I add the control for this field to the screen it always defaults to "0" on new entities...

```<code>[PXDBInt]
[PXDefault(TypeCode.DBNull, "", PersistingCheck=PXPersistingCheck.Nothing)]
[PXUIField(DisplayName="Nullable Int")]
</code>```

答:
There is AllowNull attribute in px:PXNumberEdit control.
In this implementation you do not even need to add the PXDefault attribute to your field.

I added MinValue = 1, MaxValue = 999999 in c# code and DisplayFormat="n0" MaxLength="6" in .aspx  because of my task, it should work without this.

```<code>    <px:PXNumberEdit runat="server" ID="edUsrCapacity" DataField="UsrCapacity"
DisplayFormat="n0" MaxLength="6" AllowNull="True" />

    [PXDBInt(MinValue = 1, MaxValue = 999999)]
    [PXUIField(DisplayName = Messages.FsEquipment.Capacity)]
    public virtual int? UsrCapacity
    {
        get;
        set;
    }

    public abstract class usrCapacity : BqlInt.Field<usrCapacity>
    {
    }
</code>```

Body:
How can I have a numeric field allow and default to a Null / unspecified value?

When I add the control for this field to the screen it always defaults to "0" on new entities...

[PXDBInt]
[PXDefault(TypeCode.DBNull, "", PersistingCheck=PXPersistingCheck.Nothing)]
[PXUIField(DisplayName="Nullable Int")]

Body:
There is AllowNull attribute in px:PXNumberEdit control.
In this implementation you do not even need to add the PXDefault attribute to your field.

I added MinValue = 1, MaxValue = 999999 in c# code and DisplayFormat="n0" MaxLength="6" in .aspx  because of my task, it should work without this.

    <px:PXNumberEdit runat="server" ID="edUsrCapacity" DataField="UsrCapacity"
DisplayFormat="n0" MaxLength="6" AllowNull="True" />

    [PXDBInt(MinValue = 1, MaxValue = 999999)]
    [PXUIField(DisplayName = Messages.FsEquipment.Capacity)]
    public virtual int? UsrCapacity
    {
        get;
        set;
    }

    public abstract class usrCapacity : BqlInt.Field<usrCapacity>
    {
    }


问:
How to use debounceTime() and distinctUntilChanged() in async validator
I want to add debounceTime and distinctUntilChanged in my async validator.

mockAsyncValidator(): AsyncValidatorFn {
    return (control: FormControl): Observable<ValidationErrors | null> => {
      return control.valueChanges.pipe(
        debounceTime(500),
        distinctUntilChanged(),
        switchMap(value => {
          console.log(value);  // log works here
          return this.mockService.checkValue(value).pipe(response => {
            console.log(response);  // log did not work here
            if (response) {
              return { invalid: true };
            }
            return null;
          })
        })
      );
  }
```

<p>The code above did not work, the form status becomes <code>PENDING</code>.<br>
But when I use <code>timer</code> in this answer, the code works, but I can't use <code>distinctUntilChanged</code> then.</p>

<pre class="lang-js prettyprint-override"><code>return timer(500).pipe(
    switchMap(() => {
      return this.mockService.checkValue(control.value).pipe(response => {
        console.log(response);  // log works here
        if (response) {
          return { invalid: true };
        }
        return null;
      })
    })
  );
</code>```

I tried to use BehaviorSubject like

debouncedSubject = new BehaviorSubject<string>('');
```

<p>and use it in the <code>AsyncValidatorFn</code>, but still not work, like this:</p>

<pre class="lang-js prettyprint-override"><code>this.debouncedSubject.next(control.value);
return this.debouncedSubject.pipe(
  debounceTime(500),
  distinctUntilChanged(), // did not work
                          // I think maybe it's because of I next() the value
                          // immediately above
                          // but I don't know how to fix this
  take(1), // have to add this, otherwise, the form is PENDING forever
           // and this take(1) cannot add before debounceTime()
           // otherwise debounceTime() won't work
  switchMap(value => {
    console.log(value); // log works here
    return this.mockService.checkValue(control.value).pipe(response => {
        console.log(response);  // log works here
        if (response) {
          return { invalid: true };
        }
        return null;
      }
    );
  })
);
</code>```

答:
The problem is that a new pipe is being built every time the validatorFn executes as you are calling pipe() inside the validatorFn. The previous value isn't capture for discinct or debounce to work.  What you can do is setup two BehaviourSubjects externally, termDebouncer and validationEmitter in my case.

You can set up a factory method to create this validator and thereby re-use it. You could also extend AsyncValidator and create a class with DI setup. I'll show the factory method below.

```<code>export function AsyncValidatorFactory(mockService: MockService) {
  const termDebouncer = new BehaviorSubject('');
  const validationEmitter = new BehaviorSubject<T>(null);
  let prevTerm = '';
  let prevValidity = null;

  termDebouncer.pipe(
        map(val => (val + '').trim()),
        filter(val => val.length > 0),
        debounceTime(500),
        mergeMap(term => { const obs = term === prevTerm ? of(prevValidity) : mockService.checkValue(term);
          prevTerm = term;
          return obs; }),
        map(respose => { invalid: true } : null),
        tap(validity => prevValidity = validity)
    ).subscribe(validity => validationEmitter.next(validity))

  return (control: AbstractControl) => {
    termDebouncer.next(control.value)
    return validationEmitter.asObservable().pipe(take(2))
  }
}

</code>```

Edit: This code excerpt is from a use case other than Angular form validation, (React search widget to be precise.) the pipe operators might need changing to fit your use case.

Edit2: take(1) or first() to ensure that the observable completes after emitting the validation message. asObservable() will ensure that a new observable will be generated on the next call. You might also be able to skip asObservable() and just pipe() as the pipe operator branches the async pipeline and creates a new observable from there onwards. You might have to use take(2) to get past the fact that a behaviourSubject is stateful and holds a value.

Edit3: Use a merge map to deal with the fact distinctUntilChanged() will cause the observable to not emit and not complete.

Body:
I want to add debounceTime and distinctUntilChanged in my async validator.

mockAsyncValidator(): AsyncValidatorFn {
    return (control: FormControl): Observable<ValidationErrors | null> => {
      return control.valueChanges.pipe(
        debounceTime(500),
        distinctUntilChanged(),
        switchMap(value => {
          console.log(value);  // log works here
          return this.mockService.checkValue(value).pipe(response => {
            console.log(response);  // log did not work here
            if (response) {
              return { invalid: true };
            }
            return null;
          })
        })
      );
  }

The code above did not work, the form status becomes PENDING.

But when I use timer in this answer, the code works, but I can't use distinctUntilChanged then.

return timer(500).pipe(
    switchMap(() => {
      return this.mockService.checkValue(control.value).pipe(response => {
        console.log(response);  // log works here
        if (response) {
          return { invalid: true };
        }
        return null;
      })
    })
  );

I tried to use BehaviorSubject like

debouncedSubject = new BehaviorSubject<string>('');

and use it in the AsyncValidatorFn, but still not work, like this:

this.debouncedSubject.next(control.value);
return this.debouncedSubject.pipe(
  debounceTime(500),
  distinctUntilChanged(), // did not work
                          // I think maybe it's because of I next() the value
                          // immediately above
                          // but I don't know how to fix this
  take(1), // have to add this, otherwise, the form is PENDING forever
           // and this take(1) cannot add before debounceTime()
           // otherwise debounceTime() won't work
  switchMap(value => {
    console.log(value); // log works here
    return this.mockService.checkValue(control.value).pipe(response => {
        console.log(response);  // log works here
        if (response) {
          return { invalid: true };
        }
        return null;
      }
    );
  })
);

Body:
The problem is that a new pipe is being built every time the validatorFn executes as you are calling pipe() inside the validatorFn. The previous value isn't capture for discinct or debounce to work.  What you can do is setup two BehaviourSubjects externally, termDebouncer and validationEmitter in my case.

You can set up a factory method to create this validator and thereby re-use it. You could also extend AsyncValidator and create a class with DI setup. I'll show the factory method below.

export function AsyncValidatorFactory(mockService: MockService) {
  const termDebouncer = new BehaviorSubject('');
  const validationEmitter = new BehaviorSubject<T>(null);
  let prevTerm = '';
  let prevValidity = null;

  termDebouncer.pipe(
        map(val => (val + '').trim()),
        filter(val => val.length > 0),
        debounceTime(500),
        mergeMap(term => { const obs = term === prevTerm ? of(prevValidity) : mockService.checkValue(term);
          prevTerm = term;
          return obs; }),
        map(respose => { invalid: true } : null),
        tap(validity => prevValidity = validity)
    ).subscribe(validity => validationEmitter.next(validity))

  return (control: AbstractControl) => {
    termDebouncer.next(control.value)
    return validationEmitter.asObservable().pipe(take(2))
  }
}

Edit: This code excerpt is from a use case other than Angular form validation, (React search widget to be precise.) the pipe operators might need changing to fit your use case.

Edit2: take(1) or first() to ensure that the observable completes after emitting the validation message. asObservable() will ensure that a new observable will be generated on the next call. You might also be able to skip asObservable() and just pipe() as the pipe operator branches the async pipeline and creates a new observable from there onwards. You might have to use take(2) to get past the fact that a behaviourSubject is stateful and holds a value.

Edit3: Use a merge map to deal with the fact distinctUntilChanged() will cause the observable to not emit and not complete.


问:
how to pass pandas series element to another dataframe
I want to check if an error occurred.
I have this two dataframes, from excel files:

Log_frame is a dataframe of log files, reporting data recording and error:

```<code>               Time       Voltage[V]  Freq[Hz] Speed    Motor_Stt: ErrNo
           0  10:00          220         50     30           1      0
           1  10:10          220         50     30           1      0
           2  10:20          220         50      0           2      3601
           3  10:30          220         47      0           1      1500
           4  10:40          250         50      0           1      7707
           5  10:50          220         50      0           2      3601
           6  11:00          220         50      0           2      3601
           7  11:10          220         47      0           1      1500
           8  11:20          220         50     30           1      0
           9  11:30          220         50     30           1      0
</code>```

Dev_frame is the dataframe of error description:

```<code>    Fehler-Nr.         Descr                Cause

0   1500          Chk_Voltage      Voltage out of range
1   7707           Chk_Freq.       Freq. out of range
2   3601         Chk_Motor_Stt          Motor_defec
3   7704          switch_trip           chk_over_curr
</code>```

from Log_frame I can check if, which and how many errors occurred during a day by:

```<code>Err_log = Log_frame['ErrNo']
p = Err_log[Err_log != 0].drop_duplicates('first').reset_index(drop=True)
</code>```

and this result is a pandas series:

```<code><class 'pandas.core.series.Series'>
0    3601
1    1500
2    7707
</code>```

I can "pass" first error (or second and all the other) by this:

```<code>Dev_Err = Dev_frame['Fehler-Nr.']
n = Dev_Err[Dev_Err == p.iloc[0]] #or 1, 2 and so on
</code>```

I was wondering how to loop trough p.iloc[i].
Should I use a for loop or can be done by any pandas function

EDIT: e.g. if I put 1 in p.iloc[] I can get:

```<code>0   1500
</code>```

if 2:

```<code>1   7707
</code>```

答:
No need to create a loop to check each value, you can use isin method that pandas.DataFrame has as following:

```<code>n = dev_frame[dev_frame['Fehler-Nr.'].isin(p)]['Fehler-Nr.']
</code>```

which is going to return:

```<code>0    1500
1    7707
2    3601
Name: Fehler-Nr., dtype: int64
</code>```

Ref: pandas.DataFrame.isin

Body:
I want to check if an error occurred.
I have this two dataframes, from excel files:

Log_frame is a dataframe of log files, reporting data recording and error:

               Time       Voltage[V]  Freq[Hz] Speed    Motor_Stt: ErrNo
           0  10:00          220         50     30           1      0
           1  10:10          220         50     30           1      0
           2  10:20          220         50      0           2      3601
           3  10:30          220         47      0           1      1500
           4  10:40          250         50      0           1      7707
           5  10:50          220         50      0           2      3601
           6  11:00          220         50      0           2      3601
           7  11:10          220         47      0           1      1500
           8  11:20          220         50     30           1      0
           9  11:30          220         50     30           1      0

Dev_frame is the dataframe of error description:

    Fehler-Nr.         Descr                Cause

0   1500          Chk_Voltage      Voltage out of range
1   7707           Chk_Freq.       Freq. out of range
2   3601         Chk_Motor_Stt          Motor_defec
3   7704          switch_trip           chk_over_curr

from Log_frame I can check if, which and how many errors occurred during a day by:

Err_log = Log_frame['ErrNo']
p = Err_log[Err_log != 0].drop_duplicates('first').reset_index(drop=True)

and this result is a pandas series:

<class 'pandas.core.series.Series'>
0    3601
1    1500
2    7707

I can "pass" first error (or second and all the other) by this:

Dev_Err = Dev_frame['Fehler-Nr.']
n = Dev_Err[Dev_Err == p.iloc[0]] #or 1, 2 and so on

I was wondering how to loop trough p.iloc[i].
Should I use a for loop or can be done by any pandas function

EDIT: e.g. if I put 1 in p.iloc[] I can get:

0   1500

if 2:

1   7707

Body:
No need to create a loop to check each value, you can use isin method that pandas.DataFrame has as following:

n = dev_frame[dev_frame['Fehler-Nr.'].isin(p)]['Fehler-Nr.']

which is going to return:

0    1500
1    7707
2    3601
Name: Fehler-Nr., dtype: int64

Ref: pandas.DataFrame.isin


问:
How can I account for user time-zone while displaying timestamps from a mySQL database?
I have a chat program where when a user sends a chat, an automatic time-stamp is created in mySQL. When the chat log is displayed, I need to adjust all of the time-stamps based on the time zone each user is in...

ie.

Someone in California sees:

```<code>Bob: Hi (May 30 2019 10:00 AM)
Rob: Bye (May 30 2019 10:01 AM)
</code>```

Someone in Chicago sees:

```<code>Bob: Hi (May 30 2019 12:00 AM)
Rob: Bye (May 30 2019 12:01 AM)
</code>```

Meaning I can't store the timestamps in the database accounting for timezone, otherwise all users would see something like this:

(Assuming bob is in California and Rob is in Chicago, and the messages were sent 1 minutes apart)

```<code>Bob: Hi (May 30 2019 10:00 AM)
Rob: Bye (May 30 2019 12:01 AM)
</code>```

So when I pull out my date/times, here is the php code I use:

```<code>if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    echo "<label style = 'font-size:1.1vw';>".date('M j Y g:i A', strtotime($row['time']))."</label>"."<br>";
}

} else {

}
$conn->close();
</code>```

A PHP solution would be most ideal for me, but I am open to implementing javascript or jQuery solutions as well.

(P.S - I have no idea what time zone mySQL is storing, but it is not my current time zone... so a time-offset solution that goes off of my current time zone needs some kind of a workaround).

答:
Possible solution here

In JavaScript you would do something like this:

```<code>var dateToConvert = new Date(<?= json_encode($row['time']) ?>);
console.log('full date is ', dateToConvert.toLocaleString());
console.log('just the date is ', dateToConvert.toLocaleDateString());
console.log('just the time is ', dateToConvert.toLocaleTimeString());
</code>```

Body:
I have a chat program where when a user sends a chat, an automatic time-stamp is created in mySQL. When the chat log is displayed, I need to adjust all of the time-stamps based on the time zone each user is in...

ie.

Someone in California sees:

Bob: Hi (May 30 2019 10:00 AM)
Rob: Bye (May 30 2019 10:01 AM)

Someone in Chicago sees:

Bob: Hi (May 30 2019 12:00 AM)
Rob: Bye (May 30 2019 12:01 AM)

Meaning I can't store the timestamps in the database accounting for timezone, otherwise all users would see something like this:

(Assuming bob is in California and Rob is in Chicago, and the messages were sent 1 minutes apart)

Bob: Hi (May 30 2019 10:00 AM)
Rob: Bye (May 30 2019 12:01 AM)

So when I pull out my date/times, here is the php code I use:

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    echo "".date('M j Y g:i A', strtotime($row['time'])).""."
";
}

} else {

}
$conn->close();

A PHP solution would be most ideal for me, but I am open to implementing javascript or jQuery solutions as well.

(P.S - I have no idea what time zone mySQL is storing, but it is not my current time zone... so a time-offset solution that goes off of my current time zone needs some kind of a workaround).

Body:
Possible solution here

In JavaScript you would do something like this:

var dateToConvert = new Date(<?= json_encode($row['time']) ?>);
console.log('full date is ', dateToConvert.toLocaleString());
console.log('just the date is ', dateToConvert.toLocaleDateString());
console.log('just the time is ', dateToConvert.toLocaleTimeString());


问:
ORA-00439: feature not enabled: Basic Compression
I have a dump file which is exported from Oracle 11G enterprise edition (Server1). Now, i'm trying to import the same dump file into oracle 11G express edition (Server2).

I'm getting many errors and looks like the following error is a root error.

```<code>ORA-39083: Object type TABLE:"CCEFS"."CIP_USERS" failed to create with error:
ORA-00439: feature not enabled: Basic Compression Failing sql is:

 CREATE TABLE "CCEFS"."CIP_USERS" (
 "RECKEY" NUMBER(*,0) NOT NULL ENABLE,
 "USER_ID" VARCHAR2(50 BYTE),
 "NAME" VARCHAR2(50 BYTE),
 "ADMIN" VARCHAR2(1 BYTE),
 "DISABLE" VARCHAR2(1 BYTE) DEFAULT 'N',
 "CRE_DT" DATE DEFAULT sysdate,
 "CRE_USR" VARCHAR2 (50  BYTE),
 "UPD_DT" DATE,
 "UPD_USR" VARCHAR2(50 BYTE),
 "PASSWORD" VARCHAR2 (4000 BYTE),
 "GUEST_USR" VARCHAR2(1 BYTE) DEFAULT
</code>```

Could anyone help me on fixing the above issue? Also, please suggest the steps need to be followed while importing the dump file (exported from enterprise edition) into express edition.

答:
You can use the TRANSFORM parameter to turn off compression on the import. This worked while attempting to import onto the Oracle version running in Amazon RDS

https://docs.oracle.com/database/121/SUTIL/GUID-64FB67BD-EB67-4F50-A4D2-5D34518E6BDB.htm#SUTIL939

Body:
I have a dump file which is exported from Oracle 11G enterprise edition (Server1). Now, i'm trying to import the same dump file into oracle 11G express edition (Server2).

I'm getting many errors and looks like the following error is a root error.

ORA-39083: Object type TABLE:"CCEFS"."CIP_USERS" failed to create with error:
ORA-00439: feature not enabled: Basic Compression Failing sql is:

 CREATE TABLE "CCEFS"."CIP_USERS" (
 "RECKEY" NUMBER(*,0) NOT NULL ENABLE,
 "USER_ID" VARCHAR2(50 BYTE),
 "NAME" VARCHAR2(50 BYTE),
 "ADMIN" VARCHAR2(1 BYTE),
 "DISABLE" VARCHAR2(1 BYTE) DEFAULT 'N',
 "CRE_DT" DATE DEFAULT sysdate,
 "CRE_USR" VARCHAR2 (50  BYTE),
 "UPD_DT" DATE,
 "UPD_USR" VARCHAR2(50 BYTE),
 "PASSWORD" VARCHAR2 (4000 BYTE),
 "GUEST_USR" VARCHAR2(1 BYTE) DEFAULT

Could anyone help me on fixing the above issue? Also, please suggest the steps need to be followed while importing the dump file (exported from enterprise edition) into express edition.


问:
How can I bind a list to a parameter in a custom query in SQLAlchemy?
I am using this SQL for performance reasons:

```<code> sql_tmpl = """delete from Data where id_data in (:iddata) """
 params = {
                    'iddata':[1, 2,3 4],
                    }

 # 'session' is a session object from SQLAlchemy
 self.session.execute(text(sql_tmpl), params)
</code>```

However, I got an exception:

```<code>NotSupportedError: (NotSupportedError) ('Python type list not supported.  param=1', 'HY097')
</code>```

Is there a workaround that can allow me to bind a list to the parameter of the 'in' clause?

答:
A new approach to this problem that works for any database (not just relying on psycopg2's type adaptation) uses expanding bind parameters:

sql_tmpl = """delete from Data where id_data in :iddata"""
params = { 'iddata': [1, 2, 3, 4], }
# session is a session object from sqlalchemy
t = text(sql_tmpl)
t = t.bindparams(bindparam('iddata', expanding=True))
self.session.execute(t, params)
```

Body:
I am using this SQL for performance reasons:

 sql_tmpl = """delete from Data where id_data in (:iddata) """
 params = {
                    'iddata':[1, 2,3 4],
                    }

 # 'session' is a session object from SQLAlchemy
 self.session.execute(text(sql_tmpl), params)

However, I got an exception:

NotSupportedError: (NotSupportedError) ('Python type list not supported.  param=1', 'HY097')

Is there a workaround that can allow me to bind a list to the parameter of the 'in' clause?


答:
You can use apply :

```<code>select distinct t.id, t.START_DATE, t.END_DATE, coalesce(tt.feature, t.feature) as feature
from #test t outer apply
     ( select ' '+t1.feature
       from #test t1
       where t1.id = t.id and t1.end_date = t.end_date and t1.start_date <= t.start_date
       order by t1.start_date
       for xml path('')
     ) tt(feature)
order by t.id, t.START_DATE;
</code>```

Here is a db<>fiddle.

Title: Create new date ranges from overlapping date ranges and assign an ID

Body:
I have the following table

ID  | START_DATE | END_DATE   | FEATURE
---------------------------------------
001 | 1995-08-01 | 1997-12-31 | 1
001 | 1998-01-01 | 2017-03-31 | 4
001 | 2000-06-14 | 2017-03-31 | 5
001 | 2013-04-01 | 2017-03-31 | 8
002 | 1929-10-01 | 2006-05-25 | 1
002 | 2006-05-26 | 2016-11-10 | 4
002 | 2006-05-26 | 2016-11-10 | 7
002 | 2013-04-01 | 2016-11-10 | 8

I want to convert this table into a consolidated table which will look for overlapping date ranges and then combine these into new rows. Creating a non-overlapping set of date ranges.

The bit that I need the most help with is the consolidations of the 'feature' column which will concatenate each feature into the format below.

ID  | START_DATE | END_DATE   | FEATURE
---------------------------------------
001 | 1995-08-01 | 1997-12-31 | 1
001 | 1998-01-01 | 2000-06-13 | 4
001 | 2000-06-14 | 2013-03-31 | 45
001 | 2013-04-01 | 2017-03-31 | 458
002 | 1929-10-01 | 2006-05-25 | 1
002 | 2006-05-26 | 2013-03-31 | 47
002 | 2013-04-01 | 2016-11-10 | 478

I've used the following to create the test data.

CREATE TABLE #TEST (
    [ID] [varchar](10) NULL,
    [START_DATE] [date] NULL,
    [END_DATE] [date] NULL,
    [FEATURE] [int] NOT NULL
) ON [PRIMARY]
GO

INSERT INTO #TEST

VALUES

('001','1998-01-01','2017-03-31',4),
('001','2000-06-14','2017-03-31',5),
('001','2013-04-01','2017-03-31',8),
('001','1995-08-01','1997-12-31',1),
('002','2006-05-26','2016-11-10',4),
('002','2006-05-26','2016-11-10',7),
('002','2013-04-01','2016-11-10',8),
('002','1929-10-01','2006-05-25',1)

Body:
You can use apply :

select distinct t.id, t.START_DATE, t.END_DATE, coalesce(tt.feature, t.feature) as feature
from #test t outer apply
     ( select ' '+t1.feature
       from #test t1
       where t1.id = t.id and t1.end_date = t.end_date and t1.start_date <= t.start_date
       order by t1.start_date
       for xml path('')
     ) tt(feature)
order by t.id, t.START_DATE;

Here is a db<>fiddle.


问:
How to match a string between <>?
I tried \w+\:(\w+\-?\.?(\d+)?) but that is not correct

I have following text

<staticText:HelloWorld>_<xmlNode:Node.03>_<date:yyy-MM-dd>_<time:HH-mm-ss-fff>

The end result I want is something like the following

["staticText:HelloWorld", "xmlNode:Node.03","date:yyy-MM-dd","time:HH-mm-ss-fff"]
```

答:
You could use the following regex.

```<code><(.*?)>
</code>```

Then have a look at how groups work to retrieve the result.

```<code>Regex rx = new Regex("<(.*?)>");
string text = "<staticText:HelloWorld>_<xmlNode:Node.03>_<date:yyy-MM-dd>_<time:HH-mm-ss-fff>";

MatchCollection matches = rx.Matches(text);
Console.WriteLine(matches.Count);

foreach(Match match in matches){
    var groups = match.Groups;
    Console.WriteLine(groups[1]);
}
</code>```

Title: How to match a string between <>?

Body:
You could use the following regex.

<(.*?)>

Then have a look at how groups work to retrieve the result.

Regex rx = new Regex("<(.*?)>");
string text = "<staticText:HelloWorld>_<xmlNode:Node.03>_<date:yyy-MM-dd>_<time:HH-mm-ss-fff>";

MatchCollection matches = rx.Matches(text);
Console.WriteLine(matches.Count);

foreach(Match match in matches){
    var groups = match.Groups;
    Console.WriteLine(groups[1]);
}


问:
Parsing JSON effectively in Flutter/Dart
How to extract a pair of values out of a JSON using dart

This is the function I have so far:

This is the JSON:

```<code>{
    "displayNames": [
        "John Doe",
        "Chloé Kamgang",
        "Lady Testing of Tarth"
    ],
    "users": [
        {
            "uid": "1tcPRqNZ7wexX2DWa11V9Ay1zES2",
            "displayName": "John Doe"
        },
        {
            "uid": "aZg7Emp8H9W42irnM73NBdTe6YM2",
            "displayName": "Chloé Kamgang",
            "photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_1e189635-0bc0-4791-ba20-6aded7ad3e8f7210544.jpg621jpg?alt=media&token=f5cffac3-a20c-4a83-8241-4fab16a9bd66"
        },
        {
            "uid": "hXzyTuDE8eafnSxITmz7ZdMQDnw1",
            "displayName": "Lady Testing of Tarth",
            "photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_image_picker8162975920.jpg645jpg?alt=media&token=269007d1-09ee-4fe4-b7ad-72aa7cea756a"
        }
    ]
}

</code>```

And this is the function:

Future<List<Map<String, dynamic>>> getProfilesBySuggestion(
      String sSuggestion) async {
    try {
      List<Map<String, dynamic>> listToReturn = [];
      if (sSuggestion == null ||
          sSuggestion.isEmpty ||
          !sSuggestion.startsWith('@')) return listToReturn;

      //Getting all the names
      Map<String, dynamic> listUsers = await getAllUsers();
      if (listUsers == null) return listToReturn;

      //Returning only the names corresponding
      List<dynamic> listNames = listUsers['displayNames'];
      for (String name in listNames)
        if (name
            .toLowerCase()
            .startsWith(sSuggestion.substring(1).toLowerCase())) {
          List<Map<String, dynamic>> listOfusers = listUsers['users'] as List<Map<String, dynamic>>;
          Map<String, dynamic> rightOne = listOfusers.firstWhere((user) => user['displayName'] == name);
          String sPhotoURL = rightOne['photoURL'];
          print('** name = $name, photoURL = $sPhotoURL');
          listToReturn.add({'name': name, 'photoURL': sPhotoURL});
        }
      return listToReturn;
    } catch (error) {
      print('*** Error During getProfilesBySuggestion: ${error.toString()}');
      return [
        {'errorMessage': error.toString()}
      ];
    }
  }
```

What I want is a list of pair (name, photoURL). I am using the flutter_typeahead plugin, I want to display a list of names and their respective avatars. As you can see, I am using Firebase. Please let me know if there is a better option as well, as this will get pretty heavy with scale. Thank you!

答:
A good starting point when working with data that's not organised the way you want it, is to re-organize it. I'd merge the two lists adding the display name to each user. But, of course, you see immediately that that's not necessary as each user already contains their display name. (The displayNames branch of your json is unnecessary for your purposes.)

So, you can just work with the users branch. Note that what you are doing is extracting the members of the users list and subtly changing the tag name (from displayName to name - leaving photoURL the same). Is the tag name change necessary? If not you could basically achieve what you want with a single where.

That said, this should achieve what you want (including the tag name change):

```<code>Future<List<Map<String, dynamic>>> getProfilesBySuggestion(
    String sSuggestion) async {
  try {
    if (sSuggestion == null ||
        sSuggestion.isEmpty ||
        !sSuggestion.startsWith('@')) return [];

    //Getting all the names
    Map<String, dynamic> allUsers = await getAllUsers();
    if (allUsers == null) return [];

    //Returning only the names corresponding
    List<dynamic> users = allUsers['users'];

    var suffix = sSuggestion.substring(1).toLowerCase();

    return users
        .where((user) => user['displayName'].toLowerCase().startsWith(suffix))
        .map<Map<String, dynamic>>((user) => {
              'name': user['displayName'],
              'photoURL': user['photoURL'],
            })
        .toList();
  } catch (error) {
    print('*** Error During getProfilesBySuggestion: ${error.toString()}');
    return [
      {'errorMessage': error.toString()}
    ];
  }
}
</code>```

Body:
How to extract a pair of values out of a JSON using dart

This is the function I have so far:

This is the JSON:

{
    "displayNames": [
        "John Doe",
        "Chloé Kamgang",
        "Lady Testing of Tarth"
    ],
    "users": [
        {
            "uid": "1tcPRqNZ7wexX2DWa11V9Ay1zES2",
            "displayName": "John Doe"
        },
        {
            "uid": "aZg7Emp8H9W42irnM73NBdTe6YM2",
            "displayName": "Chloé Kamgang",
            "photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_1e189635-0bc0-4791-ba20-6aded7ad3e8f7210544.jpg621jpg?alt=media&token=f5cffac3-a20c-4a83-8241-4fab16a9bd66"
        },
        {
            "uid": "hXzyTuDE8eafnSxITmz7ZdMQDnw1",
            "displayName": "Lady Testing of Tarth",
            "photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_image_picker8162975920.jpg645jpg?alt=media&token=269007d1-09ee-4fe4-b7ad-72aa7cea756a"
        }
    ]
}

And this is the function:

Future<List<Map<String, dynamic>>> getProfilesBySuggestion(
      String sSuggestion) async {
    try {
      List<Map<String, dynamic>> listToReturn = [];
      if (sSuggestion == null ||
          sSuggestion.isEmpty ||
          !sSuggestion.startsWith('@')) return listToReturn;

      //Getting all the names
      Map<String, dynamic> listUsers = await getAllUsers();
      if (listUsers == null) return listToReturn;

      //Returning only the names corresponding
      List<dynamic> listNames = listUsers['displayNames'];
      for (String name in listNames)
        if (name
            .toLowerCase()
            .startsWith(sSuggestion.substring(1).toLowerCase())) {
          List<Map<String, dynamic>> listOfusers = listUsers['users'] as List<Map<String, dynamic>>;
          Map<String, dynamic> rightOne = listOfusers.firstWhere((user) => user['displayName'] == name);
          String sPhotoURL = rightOne['photoURL'];
          print('** name = $name, photoURL = $sPhotoURL');
          listToReturn.add({'name': name, 'photoURL': sPhotoURL});
        }
      return listToReturn;
    } catch (error) {
      print('*** Error During getProfilesBySuggestion: ${error.toString()}');
      return [
        {'errorMessage': error.toString()}
      ];
    }
  }

What I want is a list of pair (name, photoURL). I am using the flutter_typeahead plugin, I want to display a list of names and their respective avatars. As you can see, I am using Firebase. Please let me know if there is a better option as well, as this will get pretty heavy with scale. Thank you!

Body:
A good starting point when working with data that's not organised the way you want it, is to re-organize it. I'd merge the two lists adding the display name to each user. But, of course, you see immediately that that's not necessary as each user already contains their display name. (The displayNames branch of your json is unnecessary for your purposes.)

So, you can just work with the users branch. Note that what you are doing is extracting the members of the users list and subtly changing the tag name (from displayName to name - leaving photoURL the same). Is the tag name change necessary? If not you could basically achieve what you want with a single where.

That said, this should achieve what you want (including the tag name change):

Future<List<Map<String, dynamic>>> getProfilesBySuggestion(
    String sSuggestion) async {
  try {
    if (sSuggestion == null ||
        sSuggestion.isEmpty ||
        !sSuggestion.startsWith('@')) return [];

    //Getting all the names
    Map<String, dynamic> allUsers = await getAllUsers();
    if (allUsers == null) return [];

    //Returning only the names corresponding
    List<dynamic> users = allUsers['users'];

    var suffix = sSuggestion.substring(1).toLowerCase();

    return users
        .where((user) => user['displayName'].toLowerCase().startsWith(suffix))
        .map<Map<String, dynamic>>((user) => {
              'name': user['displayName'],
              'photoURL': user['photoURL'],
            })
        .toList();
  } catch (error) {
    print('*** Error During getProfilesBySuggestion: ${error.toString()}');
    return [
      {'errorMessage': error.toString()}
    ];
  }
}


问:
Changing a Parents Key with a subarray value 3 Dimensional Array
So the code below is mainly to generate the same Array I have, This array is generated via some other process that I do not have control over thus direct editing is not possible.

What I need to do is change the key that outputs on the second tier array
Array with the 'uid' on the 3rd array.  Below I have a visual of what it looks like now and what I need it to be.

```<code>```

(
    [0] => Array
        (
            [uid] => 155
            [amount] => 45
        )

    [1] => Array
        (
            [uid] => 156
            [amount] => 45
        )

    [2] => Array
        (
            [uid] => 157
            [amount] => 45
        )

    [3] => Array
        (
            [uid] => 158
            [amount] => 45
        )

    [4] => Array
        (
            [uid] => 159
            [amount] => 45
        )

    [5] => Array
        (
            [uid] => 160
            [amount] => 45
        )

)

Desired Output

Array
(
    [155] => Array
        (
            [uid] => 155
            [amount] => 45
        )

    [156] => Array
        (
            [uid] => 156
            [amount] => 45
        )

    [157] => Array
        (
            [uid] => 157
            [amount] => 45
        )

    [158] => Array
        (
            [uid] => 158
            [amount] => 45
        )

    [159] => Array
        (
            [uid] => 159
            [amount] => 45
        )

    [160] => Array
        (
            [uid] => 160
            [amount] => 45
        )

)
```
</code>```

I have tried some for each loops but they have generated some strange output and I have attempted to pass the value during the 2cnd tier array via array_push but only got errors.

```<code>$p_array = array(
$alpha = array('uid' => 155,'amount' => 45),
$alpha = array('uid' => 156,'amount' => 45),
$alpha = array('uid' => 157,'amount' => 45),
$alpha = array('uid' => 158,'amount' => 45),
$alpha = array('uid' => 159,'amount' => 45),
$alpha = array('uid' => 160,'amount' => 45)
);
print_r($p_array);
</code>```

答:
There's a function for that:

```<code>$result = array_column($array, null, 'uid');
</code>```

If you wanted to loop or if you have an old PHP version:

```<code>foreach($array as $v) {
    $result[$v['uid']] = $v;
}
</code>```

Body:
So the code below is mainly to generate the same Array I have, This array is generated via some other process that I do not have control over thus direct editing is not possible.

What I need to do is change the key that outputs on the second tier array
Array with the 'uid' on the 3rd array.  Below I have a visual of what it looks like now and what I need it to be.

(
    [0] => Array
        (
            [uid] => 155
            [amount] => 45
        )

    [1] => Array
        (
            [uid] => 156
            [amount] => 45
        )

    [2] => Array
        (
            [uid] => 157
            [amount] => 45
        )

    [3] => Array
        (
            [uid] => 158
            [amount] => 45
        )

    [4] => Array
        (
            [uid] => 159
            [amount] => 45
        )

    [5] => Array
        (
            [uid] => 160
            [amount] => 45
        )

)

Desired Output

Array
(
    [155] => Array
        (
            [uid] => 155
            [amount] => 45
        )

    [156] => Array
        (
            [uid] => 156
            [amount] => 45
        )

    [157] => Array
        (
            [uid] => 157
            [amount] => 45
        )

    [158] => Array
        (
            [uid] => 158
            [amount] => 45
        )

    [159] => Array
        (
            [uid] => 159
            [amount] => 45
        )

    [160] => Array
        (
            [uid] => 160
            [amount] => 45
        )

)

I have tried some for each loops but they have generated some strange output and I have attempted to pass the value during the 2cnd tier array via array_push but only got errors.

$p_array = array(
$alpha = array('uid' => 155,'amount' => 45),
$alpha = array('uid' => 156,'amount' => 45),
$alpha = array('uid' => 157,'amount' => 45),
$alpha = array('uid' => 158,'amount' => 45),
$alpha = array('uid' => 159,'amount' => 45),
$alpha = array('uid' => 160,'amount' => 45)
);
print_r($p_array);

Body:
There's a function for that:

$result = array_column($array, null, 'uid');

If you wanted to loop or if you have an old PHP version:

foreach($array as $v) {
    $result[$v['uid']] = $v;
}


答:
This line should be able to match the content:

```<code><(.*?)>
</code>```

It will catch the arrows at the end which you don't seem to want, but you could remove them after words without regex.

You should consider a website like https://regexr.com - it helps exponentially in writing regex by allowing you to paste your cases and see how it works with them.

Title: How to match a string between <>?

Body:
I tried \w+\:(\w+\-?\.?(\d+)?) but that is not correct

I have following text

<staticText:HelloWorld>_<xmlNode:Node.03>_<date:yyy-MM-dd>_<time:HH-mm-ss-fff>

The end result I want is something like the following

["staticText:HelloWorld", "xmlNode:Node.03","date:yyy-MM-dd","time:HH-mm-ss-fff"]

Body:
This line should be able to match the content:

<(.*?)>

It will catch the arrows at the end which you don't seem to want, but you could remove them after words without regex.

You should consider a website like https://regexr.com - it helps exponentially in writing regex by allowing you to paste your cases and see how it works with them.


问:
R: change file name in the for loop
This is a fake example:

```<code>i=1
for (i in 1:3){

m<- model()
result<- fit.model(data)

}
</code>```

Instead of overwrite the result every time, how do I change the name in the loop?

答:
assign the result to i and go to next loop. your results will be saved as result_1, result_2 depending on i</p>

```<code>assign(paste0("result_", i), result)
</code>```

Title: R: change file name in the for loop

Body:
This is a fake example:

i=1
for (i in 1:3){

m<- model()
result<- fit.model(data)

}

Instead of overwrite the result every time, how do I change the name in the loop?

Body:
assign the result to i and go to next loop. your results will be saved as result_1, result_2 depending on i

assign(paste0("result_", i), result)


问:
Am I able to serialize the Transaction Builder to send it to another party?
Is there anyway to serialize a transaction builder?

I’m trying to use the TwoPartyDealFlow to enable two parties to trade on-ledger tokens. I need to be able to add input states / outputs states / commands on both sides in order to use the .generateMove functionality from the token sdk.

Let me know if this is possible or if I should be using a different method.

答:
An alternative (and perhaps better) way would be to request the input/output states you require from counterparties and then add them to the TransactionBuilder.

You could do this from within a flow session using SendAndReceive.


问:
How to make a website secured using https
I am using amazon ec2 (apache2,ubuntu16.04) for my web application.I am trying to make my web app secure using ssl but i am unable to , steps i tried are -

step 1 : I have generated a key file and generated certificates

step 2 : Installed certificates in my server

step 3 : I have changed etc/apache2/sites-enabled/default.config  file to

```<code>    <virtualhost : 443>
   serveradmin      xxxxxxxxxxxxxxxx
   servername       xxxxxxxxxxxxxxxxx
   serveralias      xxxxxxxxxxxxxxxxx
  DocumentRoot      /var/www/html/xxxxx
  SSLEngine         on
  SSLCertificateFile     /path of cer/
  SSLCertificateKeyFile  /path of key/
  SSLCertificateChainFile  /path of cer/
</code>```

step4 : Restared apache and application.

```<code>Any help will be thankful.
</code>```

答:
That's a bad idea.

You should use aws certificate manager to generate your ssl cert.
But instead of downloading them, you attach them to a Application Load Balancer which should point to your machine.

To sum up, aws will handle ssl through load balancer and route the traffic to your instance using plain http.

And bonus: your application you have a valid ssl. The way you are doing things your site will end up looking like this:

Body:
I am using amazon ec2 (apache2,ubuntu16.04) for my web application.I am trying to make my web app secure using ssl but i am unable to , steps i tried are -

step 1 : I have generated a key file and generated certificates

step 2 : Installed certificates in my server

step 3 : I have changed etc/apache2/sites-enabled/default.config  file to

    <virtualhost : 443>
   serveradmin      xxxxxxxxxxxxxxxx
   servername       xxxxxxxxxxxxxxxxx
   serveralias      xxxxxxxxxxxxxxxxx
  DocumentRoot      /var/www/html/xxxxx
  SSLEngine         on
  SSLCertificateFile     /path of cer/
  SSLCertificateKeyFile  /path of key/
  SSLCertificateChainFile  /path of cer/

step4 : Restared apache and application.

Any help will be thankful.


问:
Define relation at model without migration which adds FK constraint?
When we define relationships between two tables at Rails, we usually do like

Run command for generate migration file like rails g migration AddUserToTask user:belongs_to

And add line at model to define type of relationships like has_many :users

Then, how about just do step2, which is just add line for define relationships at model?

Does it work?

If so, why we usually do step1?

=====

And, what happen in the case like below?

Just creating column which is necessary for association(like user_id). And this column doesn't have FK constraint at sql level.

And add line at model to define type of relationships like has_many :users with column name which is made at step 1

That means, there is the column needed for association, but it doesn't have FK constraint.

答:
Actually, you can set a relation just by creating the FK on the table (the migration), and manage all the query stuff by hand (set user_id, retrieve by user_id, etc.).

When, after run the migration, you set the association on the models you rely on Rails to do all that hard work.

So, you can live without the model association, but not without the table FK.


答:
Matches any string within the <>. Hope this helps.

<(.*?)>

Title: How to match a string between <>?


问:
SocketChannel: java.io.IOException: An existing connection was forcibly closed by the remote host
I'm using a SocketChannel with a network socket, and have to handle the expected exception of the other end of the socket closing the channel unexpectedly.

The problem is, I get this IOException:

```<code>java.io.IOException: An existing connection was forcibly closed by the remote host
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(Unknown Source)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    ...
</code>```

I need to distinguish between this exception, which is expected to happen, and unexpected exceptions, so that I can log/print the unexpected ones and handle this one. But it's just an ordinary IOException with a different text message, and although I always check SocketChannel.isOpen() and SocketChannel.isConnected(), they seem to return true in this case even though the other end of the socket has been closed.

What can/should I do?

答:
This could be a bit ugly... You could play catch with it. Double try the code, catching the first exception and determining the message. If it's what you expect, ignore it, or do what you were going to do before. If it's not what you expected, go ahead and throw it to the higher try.

Now that I think about it, you could do this in a single try if you wanted to, just by looking at the message.

That being said, I think you should re-evaluate the idea of relying on this exception for flow of control of your program. Are you sure you should have a design that says "I'm wanting for this exception to happen"?

```<code>try {
    try {
       // your code
    } catch(IOException innerIOE) {
        if(innerIOE.getMessage().begins("An existing connection was forcibly closed")) {
            log.info("Exception expected, yay.");
        }
        else {
            throw innerIOE;
        }
    } // end inner catch
} catch(IOException outerIOE) {
    // error handling code here, your "An existing connection was forcibly closed"
    // shouldn't make it out here
}
</code>```

Body:
I'm using a SocketChannel with a network socket, and have to handle the expected exception of the other end of the socket closing the channel unexpectedly.

The problem is, I get this IOException:

java.io.IOException: An existing connection was forcibly closed by the remote host
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(Unknown Source)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    ...

I need to distinguish between this exception, which is expected to happen, and unexpected exceptions, so that I can log/print the unexpected ones and handle this one. But it's just an ordinary IOException with a different text message, and although I always check SocketChannel.isOpen() and SocketChannel.isConnected(), they seem to return true in this case even though the other end of the socket has been closed.

What can/should I do?

Body:
This could be a bit ugly... You could play catch with it. Double try the code, catching the first exception and determining the message. If it's what you expect, ignore it, or do what you were going to do before. If it's not what you expected, go ahead and throw it to the higher try.

Now that I think about it, you could do this in a single try if you wanted to, just by looking at the message.

That being said, I think you should re-evaluate the idea of relying on this exception for flow of control of your program. Are you sure you should have a design that says "I'm wanting for this exception to happen"?

try {
    try {
       // your code
    } catch(IOException innerIOE) {
        if(innerIOE.getMessage().begins("An existing connection was forcibly closed")) {
            log.info("Exception expected, yay.");
        }
        else {
            throw innerIOE;
        }
    } // end inner catch
} catch(IOException outerIOE) {
    // error handling code here, your "An existing connection was forcibly closed"
    // shouldn't make it out here
}


问:
How use reduce() to concat an array and delete the items duplicated
I have a problem using the reduce function in JavaScript. My goal is to take an array of arrays and, using reduce, then concat all the values and delete the duplicates:

I have an array like this:
firstArray = [[1, 2],[2, 3, 4],[4, 5, 6]]

I need an array like this after apply reduce():
resultArray = [1, 2, 3, 4, 5, 6]

```<code>const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = arrayElements.reduce((total, value) => {
    return total.concat(value);
}, []);
</code>```

This is the fragment that I have, this only concat all the values, this is to say, [1, 2, 2, 3, 4, 5, 6]

答:
Here is the old fashioned ES5 way in case browser support is a concern.

var arrayElements = [[1,2],[2,3,4],[5,6]];
var newArray = arrayElements.reduce(function(total, value){
  return total.concat(value).filter(function (x, i, a) {
    return a.indexOf(x) == i;
  });
}, []);
console.log(newArray)```

Body:
I have a problem using the reduce function in JavaScript. My goal is to take an array of arrays and, using reduce, then concat all the values and delete the duplicates:

I have an array like this:
firstArray = [[1, 2],[2, 3, 4],[4, 5, 6]]

I need an array like this after apply reduce():
resultArray = [1, 2, 3, 4, 5, 6]

const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = arrayElements.reduce((total, value) => {
    return total.concat(value);
}, []);

This is the fragment that I have, this only concat all the values, this is to say, [1, 2, 2, 3, 4, 5, 6]