问:
Kotlin: how to use reduce/fold with a data structure as the accumulative argument?
I want to use reduce/fold methods to create a new list from an existing List. This is the code I tried to write:

```<code>val list: List<Int> = listOf(1, 2, 3)
val newList = mutableListOf<Int>()
    val sum: List<Int> = list.fold(newList) { (acc: List<Int>, i: Int) -> {
        acc.add(i + 10)
        acc
    }}
</code>```

It doesn't compile.

I want that newList will be (11,12,13).
How can I do it in a functional manner?

In Javascript, for example, this code compiles:

```<code>list.reduce((acc, item) => {
   acc.push(item + 10)
   return acc;
}, [])
</code>```

答:
The most convenient and functional way to do what you want is using map function:

```<code>val list: List<Int> = listOf(1, 2, 3)
val newList: MutableList<Int> = list.map { it + 10 }.toMutableList()
</code>```

But if you really want to use fold for some (strange) reason, you can do it this way:

```<code>val newList: MutableList<Int> =
    list.fold(ArrayList()) { acc, x -> acc.apply { add(x + 10) } }
</code>```

Or this way:

```<code>val newList: MutableList<Int> =
    list.fold(ArrayList()) { acc, x ->
        acc += x + 10
        acc
    }
</code>```

Body:
I want to use reduce/fold methods to create a new list from an existing List. This is the code I tried to write:

val list: List<Int> = listOf(1, 2, 3)
val newList = mutableListOf<Int>()
    val sum: List<Int> = list.fold(newList) { (acc: List<Int>, i: Int) -> {
        acc.add(i + 10)
        acc
    }}

It doesn't compile.

I want that newList will be (11,12,13).
How can I do it in a functional manner?

In Javascript, for example, this code compiles:

list.reduce((acc, item) => {
   acc.push(item + 10)
   return acc;
}, [])

Body:
The most convenient and functional way to do what you want is using map function:

val list: List<Int> = listOf(1, 2, 3)
val newList: MutableList<Int> = list.map { it + 10 }.toMutableList()

But if you really want to use fold for some (strange) reason, you can do it this way:

val newList: MutableList<Int> =
    list.fold(ArrayList()) { acc, x -> acc.apply { add(x + 10) } }

Or this way:

val newList: MutableList<Int> =
    list.fold(ArrayList()) { acc, x ->
        acc += x + 10
        acc
    }


来源: stackexchange

问:
angular application not reachable by nginx on kubernetes
After creating my application, creating the image through the Dockerfile, I proceeded to configure it in a pod of kubernetes. However, I can't reach it via IP address. In fact, I noticed that there is no ip assigned.

```<code>NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes            ClusterIP   XX.XX.X.X       <none>        443/TCP   2d1h
app                   ClusterIP   XX.XX.XXX.XX   <none>        80/TCP    1h
</code>```

I have tried to edited the file yaml to set the selector run:ning, but I do not see the external ip.

This is the situation of the services:

```<code>NAMESPACE     NAME                                       TYPE
default       service/kubernetes                         ClusterIP
default       service/app                                ClusterIP
kube-system   service/kube-dns                           ClusterIP
kube-system   service/nginx-ingress-controller           LoadBalancer
kube-system   service/nginx-ingress-controller-metrics   ClusterIP
kube-system   service/nginx-ingress-default-backend      ClusterIP
</code>```

答:
To access your service from outside you have multiple options:

LoadBalancer service: You can create a Loadbalancer service
(supported on few environments).

NodePort service: Change the type of your service to NodePort
and you can access your service using any node's IP address.

Ingress: Create an ingress resource (as nginx is already running
in your cluster) and you can access your service via Ingress
controller (in your case nginx).

HostNetwork: You can run your pod on host network by adding the field
hostNetwork: true in your pod template. Using this you can directly
reach your pod without using service. This is not a recommended
approach though.

ContentLicense: CC BY-SA 4.0

Body:
After creating my application, creating the image through the Dockerfile, I proceeded to configure it in a pod of kubernetes. However, I can't reach it via IP address. In fact, I noticed that there is no ip assigned.

NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes            ClusterIP   XX.XX.X.X       <none>        443/TCP   2d1h
app                   ClusterIP   XX.XX.XXX.XX   <none>        80/TCP    1h

I have tried to edited the file yaml to set the selector run:ning, but I do not see the external ip.

This is the situation of the services:

NAMESPACE     NAME                                       TYPE
default       service/kubernetes                         ClusterIP
default       service/app                                ClusterIP
kube-system   service/kube-dns                           ClusterIP
kube-system   service/nginx-ingress-controller           LoadBalancer
kube-system   service/nginx-ingress-controller-metrics   ClusterIP
kube-system   service/nginx-ingress-default-backend      ClusterIP


问:
Count numbers that are lower by constant from current number
Imagine that I have a list of numbers (i.e. numbers column in data.table/data.frame).

```<code>1
5
5
10
11
12
</code>```

for each number in a list a want to count how many unique numbers are there which are lower than that particular number + 5.

The explanation for upper case, first number = 1, search range is 1+5 = 6, so three numbers are in range, less than or equal to: c(1,5,5), and then count unique is 2.
This is all by assuming we've got the additional condition, that the number must not only be lower than current_number + 5, but also its index in the list must be >= that of current_number.

The result in this case would be:

```<code>2
2
2
3
2
1
</code>```

Note: Is there a fast solution for huge dataset, in data.frame or data.table? My dataset is rather huge, 10+M rows.

答:
```<code>sapply(yourVector + 5, function(x, y) sum(x > y), y = unique(x))
</code>```

Body:
Imagine that I have a list of numbers (i.e. numbers column in data.table/data.frame).

1
5
5
10
11
12

for each number in a list a want to count how many unique numbers are there which are lower than that particular number + 5.

The explanation for upper case, first number = 1, search range is 1+5 = 6, so three numbers are in range, less than or equal to: c(1,5,5), and then count unique is 2.
This is all by assuming we've got the additional condition, that the number must not only be lower than current_number + 5, but also its index in the list must be >= that of current_number.

The result in this case would be:

2
2
2
3
2
1

Note: Is there a fast solution for huge dataset, in data.frame or data.table? My dataset is rather huge, 10+M rows.


问:
Virtualenv did not work on docker ubuntu18.04: Problem on Python2 -> Python3?
My environment on docker was built based on ubuntu 18.04.
The OS is in a transitional period shifting Python2 to Python3.

Where I need to use virtualenv command. However, below error occurred. How should I solve?

The command was called from a toolchain.

Therefore, I want to solve this problem with the exception of changing command.

$virtualenv --python=python3 venv
FileNotFoundError: [Errno 2] No such file or directory: '/home/user/hostcwd/venv/bin/python' -> '/home/user/hostcwd/venv/bin/python3'
```

<p><strong>Added @ 2/14 22:32</strong></p>

<p>in venv dir, directories bin, lib. a file pyvenv.cfg.</p>

```ls -la venv/bin/python
lrwxrwxrwx 1 user user 16 Feb 14 09:06 venv/bin/python -> /usr/bin/python3
```

答:
I'm not sure I understand your full problem. I just did the following:

```<code>$ docker pull ubuntu:bionic
$ docker run -it --rm ubuntu:bionic
</code>```

Now in the container

```<code>$ apt update
$ apt install python3-pip
$ pip install virtualenv
$ virtualenv -p python3 myenv
$ source myenv/bin/activate
(myenv) $ python

Python 3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code>```

So it setup the virutalenv for python properly. You can list those commands in a Dockerfile to replicate what I did pretty easily.

When I call ls -l $(which python3) before I source the environment I get

```<code>lrwxrwxrwx 1 root root 9 Oct 25  2018 /usr/bin/python3 -> python3.6
</code>```

So, perhaps, your virtualenv was installed with pip (for python2) and that is somehow causing an issue. I'd try purging virtualenv and installing it via python3. Containers are meant to be ephemeral and easily rebuilt. If there is any other configurations you're using to build your container that might help shed light on your situation please share.

Body:
My environment on docker was built based on ubuntu 18.04.
The OS is in a transitional period shifting Python2 to Python3.

Where I need to use virtualenv command. However, below error occurred. How should I solve?

The command was called from a toolchain.

Therefore, I want to solve this problem with the exception of changing command.

$virtualenv --python=python3 venv
FileNotFoundError: [Errno 2] No such file or directory: '/home/user/hostcwd/venv/bin/python' -> '/home/user/hostcwd/venv/bin/python3'

Added @ 2/14 22:32

in venv dir, directories bin, lib. a file pyvenv.cfg.

ls -la venv/bin/python
lrwxrwxrwx 1 user user 16 Feb 14 09:06 venv/bin/python -> /usr/bin/python3

Body:
I'm not sure I understand your full problem. I just did the following:

$ docker pull ubuntu:bionic
$ docker run -it --rm ubuntu:bionic

Now in the container

$ apt update
$ apt install python3-pip
$ pip install virtualenv
$ virtualenv -p python3 myenv
$ source myenv/bin/activate
(myenv) $ python

Python 3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

So it setup the virutalenv for python properly. You can list those commands in a Dockerfile to replicate what I did pretty easily.

When I call ls -l $(which python3) before I source the environment I get

lrwxrwxrwx 1 root root 9 Oct 25  2018 /usr/bin/python3 -> python3.6

So, perhaps, your virtualenv was installed with pip (for python2) and that is somehow causing an issue. I'd try purging virtualenv and installing it via python3. Containers are meant to be ephemeral and easily rebuilt. If there is any other configurations you're using to build your container that might help shed light on your situation please share.


问:
How to make a unique associative array?
I have an array which I populate like this:

```<code>array_push($comboUserPosts,
    array(
        'link'=> get_permalink(),
        'dates'=> $value,
        'title'=> get_the_title()
    )
);
</code>```

Then when I finish all my loop, I do:

```<code>array_unique($comboUserPosts);
</code>```

But it still gives me duplicates. If I do:

```<code>echo '```' . var_export($comboUserPosts, true) . '```';
</code>```

This is what I get:

```<code>array (
  0 =>
  array (
    'link' => 'https://example.com/test/test-values-users/',
    'dates' => '1920',
    'title' => 'test values users',
  ),
  1 =>
  array (
    'link' => 'https://example.com/test/test-values-users/',
    'dates' => ' 1954',
    'title' => 'test values users',
  ),
  2 =>
  array (
    'link' => 'https://example.com/test/provo-filter/',
    'dates' => '1600',
    'title' => 'provo filter',
  ),
  3 =>
  array (
    'link' => 'https://example.com/test/provo-filter/',
    'dates' => '1450',
    'title' => 'provo filter',
  ),
  4 =>
  array (
    'link' => 'https://example.com/test/provo-filter/',
    'dates' => '1330',
    'title' => 'provo filter',
  ),
)
</code>```

But by looking at that, I only have 2 unique links and title, I should only display those two links+title when I do:

```<code>foreach ($comboUserPosts as $value) { ?>
    <h2><a href="<?php echo $value['link']; ?>"><?php echo $value['title']; ?></a>
<?php }
</code>```

答:
you can use this method

```<code>array_unique($associativeArray,SORT_REGULAR);
</code>```

Define an associative array $associativeArray with name and age keys.

```<code>  $associativeArray[] = array("name" => "Yogesh Singh","no"=>4);
  $associativeArray[] = array("name" => "Sonarika Singh","no"=>4);
</code>```

Title: How to make a unique associative array?

Body:
I have an array which I populate like this:

array_push($comboUserPosts,
    array(
        'link'=> get_permalink(),
        'dates'=> $value,
        'title'=> get_the_title()
    )
);

Then when I finish all my loop, I do:

array_unique($comboUserPosts);

But it still gives me duplicates. If I do:

echo '
' . var_export($comboUserPosts, true) . '
';

This is what I get:

array (
  0 =>
  array (
    'link' => 'https://example.com/test/test-values-users/',
    'dates' => '1920',
    'title' => 'test values users',
  ),
  1 =>
  array (
    'link' => 'https://example.com/test/test-values-users/',
    'dates' => ' 1954',
    'title' => 'test values users',
  ),
  2 =>
  array (
    'link' => 'https://example.com/test/provo-filter/',
    'dates' => '1600',
    'title' => 'provo filter',
  ),
  3 =>
  array (
    'link' => 'https://example.com/test/provo-filter/',
    'dates' => '1450',
    'title' => 'provo filter',
  ),
  4 =>
  array (
    'link' => 'https://example.com/test/provo-filter/',
    'dates' => '1330',
    'title' => 'provo filter',
  ),
)

But by looking at that, I only have 2 unique links and title, I should only display those two links+title when I do:

foreach ($comboUserPosts as $value) { ?>

<a href="<?php echo $value['link']; ?>"><?php echo $value['title']; ?>
<?php }

Body:
you can use this method

array_unique($associativeArray,SORT_REGULAR);

Define an associative array $associativeArray with name and age keys.

  $associativeArray[] = array("name" => "Yogesh Singh","no"=>4);
  $associativeArray[] = array("name" => "Sonarika Singh","no"=>4);


问:
Unable to start HyperV VM with Minkube for Kubernetes Cluster for spark in windows 10
I am trying to create a Kubernetes cluster on Windows with the help of Minikube and Hyperv. I tried below things:

1) I have enabled HyperV after following this blog from Microsoft.I confirmed it using systeminfo command and it shows that hypervisor is detected.

2) I ran minikube start --vm-driver=hyperv in admin mode but facing below error:

```<code>* Suggestion: Start PowerShell as Administrator, and run: 'Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All'
* Documentation: https://minikube.sigs.k8s.io/docs/reference/drivers/hyperv/

X hyperv does not appear to be installed
</code>```

3) I also tried creating virtual switch for hyperv and using this command minikube start --vm-driver=hyperv --hyperv-virtual-switch="hypervswitch"but no luck. I also tried minikube start --alsologtostderr -v=7 and I can see from the below logs that hyperv is not installed.

```<code>status for hyperv: {Installed:false Healthy:false Error:C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online failed:
</code>```

Note: I am running each and every command in admin mode. I am not sure what is the problem.

I referred the official github issues blog for my issue but didn't help. Can anyone help me over here? I am stuck since days..

答:
I had the same problem, adding --force worked for me:

```<code>minikube start --vm-driver=hyperv --force
</code>```

Body:
I am trying to create a Kubernetes cluster on Windows with the help of Minikube and Hyperv. I tried below things:

1) I have enabled HyperV after following this blog from Microsoft.I confirmed it using systeminfo command and it shows that hypervisor is detected.

2) I ran minikube start --vm-driver=hyperv in admin mode but facing below error:

* Suggestion: Start PowerShell as Administrator, and run: 'Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All'
* Documentation: https://minikube.sigs.k8s.io/docs/reference/drivers/hyperv/

X hyperv does not appear to be installed

3) I also tried creating virtual switch for hyperv and using this command minikube start --vm-driver=hyperv --hyperv-virtual-switch="hypervswitch"but no luck. I also tried minikube start --alsologtostderr -v=7 and I can see from the below logs that hyperv is not installed.

status for hyperv: {Installed:false Healthy:false Error:C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online failed:

Note: I am running each and every command in admin mode. I am not sure what is the problem.

I referred the official github issues blog for my issue but didn't help. Can anyone help me over here? I am stuck since days..

Body:
I had the same problem, adding --force worked for me:

minikube start --vm-driver=hyperv --force


问:
how get key/value from nsuserdefaults .plist configuration file Xamarin forms
I am working as a Xamarin forms iOS enterprise app.
We pushed config.plist (Some key-value pair) file to a real device using Mobileiron/airwatch MDM/EMM(Services). Then we deploy the Apps on iPads using MobileIron. When the app starts, the app gets Url/ credentials from config.plist that pushed by MDM.

after googling I found config.plist stored in device which in NSUserDefaults

But I am don't know is the .plist stored in NSUserDefaults with apps bundle id or something else.

Please anybody has the same issue before writing to me how I have to implements or getting value from .plist

答:
I think you will find the details from your question on page 69-70 of Apple's MDM-Protocol-Reference. The MDM server deploys these settings using a dictionary that contains an array of bundle ids, with the settings for each app within their key. Because of how sandboxing works, your app just has to retrieve the com.apple.configuration.managed key to get its settings.

A great resource is https://www.appconfig.org/ios/


问:
reading JSON element using JS
I am receiving a JSON object from a PHP get request. It looks like this:

```<code>data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}
</code>```

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

```<code>eti=data["emp_type_id"];
var myVar = eti[0];
</code>```

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

答:
Neal's answer will help, but I think you have other problems.  Your json structure looks wrong

```<code>a) data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}
</code>```

should it be

```<code>b) data == {"user_id":"7","emp_type_id":["11","10"]}
</code>```

That is in english

a) emp_type_id an array of one object which has two fields 0 and 1?

b) emp_type_id an array of two items with values 11 and 10

If it should be b) then your json is wrong.

ContentLicense: CC BY-SA 3.0

Title: reading JSON element using JS

Body:
I am receiving a JSON object from a PHP get request. It looks like this:

data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

eti=data["emp_type_id"];
var myVar = eti[0];

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

Body:
Neal's answer will help, but I think you have other problems.  Your json structure looks wrong

a) data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}

should it be

b) data == {"user_id":"7","emp_type_id":["11","10"]}

That is in english

a) emp_type_id an array of one object which has two fields 0 and 1?

b) emp_type_id an array of two items with values 11 and 10

If it should be b) then your json is wrong.


问:
How do I send a message directly to a parking lot queue, prevent requeue and exit the program flow?
I currently have 4 queues:

test-queue

test-queue-short-term-dead-letter

test-queue-long-term-dead-letter

test-queue-parking-lot

When a message comes into test-queue, I do a check to see if the message is in the correct format. If it isn't I want to send the message directly to the parking lot queue.

I can't use AmqpRejectAndDontRequeue() because it will automatically send the message to the configured DLQ (test-queue-short-term-dead-letter).

Using RabbitTemplate.convertAndSend() with another exception such as BadRequestException doesn't work. The message goes to the parking lot queue as expected, however the same message will stay in the test-queue

Using RabbitTemplate.convertAndSend() on it's own won't work as the program continues execution.

All queues are bound to a single direct exchange, each with unique routing keys. The test-queue is configured with the following arguments:

x-dead-letter-exchange: ""

x-dead-letter-routing-key: <shortTermDeadLetterKey>

Receiver:

```<code>  @RabbitListener(queues = "test-queue")
  public void receiveMessage(byte[] person) {
    String personString = new String(person);

    if (!personString.matches(desiredRegex)) {
      rabbitTemplate.convertAndSend("test-exchange", "test-queue-parking-lot",
          "invalid person");
      log.info("Invalid person");
    }
    ...some other code which I dont want to run as the message has arrived in the incorrect format
}
</code>```

答:
The problem was solved by manually acknowledging the message and returning from the method.</p>

```<code>  @RabbitListener(queues = "test-queue")
  public void receiveMessage(byte[] person, Channel channel,
  @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception) {
    String personString = new String(person);

    if (!personString.matches(desiredRegex)) {
      rabbitTemplate.convertAndSend("test-exchange", "test-queue-parking-lot",
          "invalid person");
      log.info("Invalid person");
      channel.basicAck(tag, false);
      return;
    }
    ...some other code which I dont want to run as the message has arrived in the incorrect format
}
</code>```

Body:
I currently have 4 queues:

test-queue

test-queue-short-term-dead-letter

test-queue-long-term-dead-letter

test-queue-parking-lot

When a message comes into test-queue, I do a check to see if the message is in the correct format. If it isn't I want to send the message directly to the parking lot queue.

I can't use AmqpRejectAndDontRequeue() because it will automatically send the message to the configured DLQ (test-queue-short-term-dead-letter).

Using RabbitTemplate.convertAndSend() with another exception such as BadRequestException doesn't work. The message goes to the parking lot queue as expected, however the same message will stay in the test-queue

Using RabbitTemplate.convertAndSend() on it's own won't work as the program continues execution.

All queues are bound to a single direct exchange, each with unique routing keys. The test-queue is configured with the following arguments:

x-dead-letter-exchange: ""

x-dead-letter-routing-key: <shortTermDeadLetterKey>

Receiver:

  @RabbitListener(queues = "test-queue")
  public void receiveMessage(byte[] person) {
    String personString = new String(person);

    if (!personString.matches(desiredRegex)) {
      rabbitTemplate.convertAndSend("test-exchange", "test-queue-parking-lot",
          "invalid person");
      log.info("Invalid person");
    }
    ...some other code which I dont want to run as the message has arrived in the incorrect format
}

Body:
The problem was solved by manually acknowledging the message and returning from the method.

  @RabbitListener(queues = "test-queue")
  public void receiveMessage(byte[] person, Channel channel,
  @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception) {
    String personString = new String(person);

    if (!personString.matches(desiredRegex)) {
      rabbitTemplate.convertAndSend("test-exchange", "test-queue-parking-lot",
          "invalid person");
      log.info("Invalid person");
      channel.basicAck(tag, false);
      return;
    }
    ...some other code which I dont want to run as the message has arrived in the incorrect format
}


问:
How to change the color of all Labels in a UIView in Swift?
I found a similar question here. But the problem is it is in OBJ-C. I do not know the code and am working in SWIFT so please can anyone explain and translate this code in swift.
I am still new to swift so please help me.

Regards

答:
Create

```<code>var globalColor = UIColor.red

class CustomLbl:UILabel {
  override func awakeFromNib() {  // inside IB
    super.awakeFromNib()
    self.textColor = globalColor
  }
  override func draw(_ rect: CGRect) { // programmatically
     super.draw(rect)
     self.textColor = globalColor
  }
}
</code>```

And assign it in IB or code , for programmatically call

```<code>self.view.setNeedsDisplay()
</code>```

after you change global color

Body:
Create

var globalColor = UIColor.red

class CustomLbl:UILabel {
  override func awakeFromNib() {  // inside IB
    super.awakeFromNib()
    self.textColor = globalColor
  }
  override func draw(_ rect: CGRect) { // programmatically
     super.draw(rect)
     self.textColor = globalColor
  }
}

And assign it in IB or code , for programmatically call

self.view.setNeedsDisplay()

after you change global color


问:
spring-data-geode and spring-boot-starter-webflux application run failed
I have a webflux project and I am adding apache geode. In my build.gradle I have:

```<code>implementation 'org.springframework.data:spring-data-geode:2.2.4.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-webflux:2.2.4.RELEASE'
</code>```

Once adding the spring-data-geode implementation the application crashes with:

```<code>2020-01-28T16:29:51,965 INFO  [main] org.eclip.jetty.util.log.Log 169 initialized: Logging initialized @4337ms to org.eclipse.jetty.util.log.Slf4jLog
2020-01-28T16:29:52,050 WARN  [main] org.sprin.conte.suppo.AbstractApplicationContext 558 refresh: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start reactive web server; nested exception is java.lang.NoClassDefFoundError: org/eclipse/jetty/servlet/ServletHolder
2020-01-28T16:29:52,064 INFO  [main] org.sprin.boot.autoc.loggi.ConditionEvaluationReportLoggingListener 136 logMessage:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-01-28T16:29:52,072 ERROR [main] org.sprin.boot.SpringApplication 826 reportFailure: Application run failed
org.springframework.context.ApplicationContextException: Unable to start reactive web server; nested exception is java.lang.NoClassDefFoundError: org/eclipse/jetty/servlet/ServletHolder
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:81)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544)
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
</code>```

The trouble is, if I add

spring.main.web-application-type=none or spring.main.web-application-type=reactive to my application.properties then that interferes with the @ClientCacheApplication(name = "Web", locators = @Locator(host="1.2.3.4", port=10334), logLevel = "debug", subscriptionEnabled = true) annotation and the application does not connect to the geode locator, nor then run the @EnableClusterDefinedRegions which causes problems defining simple regions that I want to pick up from the server.

UPDATE To add spring-boot-starter-web to build.gradle and make the spring boot application type NONE as below appears to fix the instant problem, but...

```<code>SpringApplication app = new SpringApplication(Web.class);
app.setWebApplicationType(WebApplicationType.NONE);
SpringApplication.run(Web.class, args);
</code>```

... but then the webflux mapping cannot find the @Bean websocket handler:

```<code>2020-01-28T16:54:26,236 DEBUG [http-nio-8082-exec-2] org.sprin.web.servl.handl.AbstractHandlerMapping 412 getHandler: Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-01-28T16:54:26,246 DEBUG [http-nio-8082-exec-2] org.sprin.web.servl.resou.ResourceHttpRequestHandler 454 handleRequest: Resource not found
2020-01-28T16:54:26,246 DEBUG [http-nio-8082-exec-2] org.sprin.web.servl.FrameworkServlet 1131 logResult: Completed 404 NOT_FOUND
</code>```

and this causes the website to error:

The console log says

WebSocket connection to 'ws://localhost:8082/ws/data' failed: Error during WebSocket handshake: Unexpected response code: 404

答:
The problems with regions was because the classes using the regions defined by @EnableClusterDefinedRegions were (a) instantiated by new command rather than Spring @Autowired; and (b) in another package not seen by the Spring Boot @ComponentScan. Once these were fixed then the regions were auto-defined and handled using @Resource annotation.

@Resource(name = "Example") private Region<Object, Object> example

Also the main program was given

```<code>SpringApplication app = new SpringApplication(Web.class);
app.setWebApplicationType(WebApplicationType.REACTIVE);
SpringApplication.run(Web.class, args);
</code>```

The other problem was fixed by getting the correct dependencies in the build.gradle and then annotating endpoints for rSocket / webSocket with:

```<code>@MessageMapping(value = "helloWorld")
public Flux<String> getFluxSocket() {
    log.traceEntry();
    log.info("In hello world");

    return Flux.just("{\"Hello\":\"World\"}");
}
</code>```

or

```<code>@GetMapping(value = "/helloWorld", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> getRestSocket() {
    log.traceEntry();
    return Flux.just("Hello World");
}
</code>```

for HTTP endpoints.

Body:
I have a webflux project and I am adding apache geode. In my build.gradle I have:

implementation 'org.springframework.data:spring-data-geode:2.2.4.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-webflux:2.2.4.RELEASE'

Once adding the spring-data-geode implementation the application crashes with:

2020-01-28T16:29:51,965 INFO  [main] org.eclip.jetty.util.log.Log 169 initialized: Logging initialized @4337ms to org.eclipse.jetty.util.log.Slf4jLog
2020-01-28T16:29:52,050 WARN  [main] org.sprin.conte.suppo.AbstractApplicationContext 558 refresh: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start reactive web server; nested exception is java.lang.NoClassDefFoundError: org/eclipse/jetty/servlet/ServletHolder
2020-01-28T16:29:52,064 INFO  [main] org.sprin.boot.autoc.loggi.ConditionEvaluationReportLoggingListener 136 logMessage:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-01-28T16:29:52,072 ERROR [main] org.sprin.boot.SpringApplication 826 reportFailure: Application run failed
org.springframework.context.ApplicationContextException: Unable to start reactive web server; nested exception is java.lang.NoClassDefFoundError: org/eclipse/jetty/servlet/ServletHolder
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:81)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544)
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)

The trouble is, if I add

spring.main.web-application-type=none or spring.main.web-application-type=reactive to my application.properties then that interferes with the @ClientCacheApplication(name = "Web", locators = @Locator(host="1.2.3.4", port=10334), logLevel = "debug", subscriptionEnabled = true) annotation and the application does not connect to the geode locator, nor then run the @EnableClusterDefinedRegions which causes problems defining simple regions that I want to pick up from the server.

UPDATE To add spring-boot-starter-web to build.gradle and make the spring boot application type NONE as below appears to fix the instant problem, but...

SpringApplication app = new SpringApplication(Web.class);
app.setWebApplicationType(WebApplicationType.NONE);
SpringApplication.run(Web.class, args);

... but then the webflux mapping cannot find the @Bean websocket handler:

2020-01-28T16:54:26,236 DEBUG [http-nio-8082-exec-2] org.sprin.web.servl.handl.AbstractHandlerMapping 412 getHandler: Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-01-28T16:54:26,246 DEBUG [http-nio-8082-exec-2] org.sprin.web.servl.resou.ResourceHttpRequestHandler 454 handleRequest: Resource not found
2020-01-28T16:54:26,246 DEBUG [http-nio-8082-exec-2] org.sprin.web.servl.FrameworkServlet 1131 logResult: Completed 404 NOT_FOUND

and this causes the website to error:

The console log says

WebSocket connection to 'ws://localhost:8082/ws/data' failed: Error during WebSocket handshake: Unexpected response code: 404

Body:
The problems with regions was because the classes using the regions defined by @EnableClusterDefinedRegions were (a) instantiated by new command rather than Spring @Autowired; and (b) in another package not seen by the Spring Boot @ComponentScan. Once these were fixed then the regions were auto-defined and handled using @Resource annotation.

@Resource(name = "Example") private Region<Object, Object> example

Also the main program was given

SpringApplication app = new SpringApplication(Web.class);
app.setWebApplicationType(WebApplicationType.REACTIVE);
SpringApplication.run(Web.class, args);

The other problem was fixed by getting the correct dependencies in the build.gradle and then annotating endpoints for rSocket / webSocket with:

@MessageMapping(value = "helloWorld")
public Flux<String> getFluxSocket() {
    log.traceEntry();
    log.info("In hello world");

    return Flux.just("{\"Hello\":\"World\"}");
}

or

@GetMapping(value = "/helloWorld", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> getRestSocket() {
    log.traceEntry();
    return Flux.just("Hello World");
}

for HTTP endpoints.


问:
iOS 13.3.1 error "dyld: Library not loaded:...Reason: no suitable image found. Did find:..." application crash [swift][xcode]
After updating your phone to iOS 13.3.1 the application stopped running! Start and crash and error:

```<code>dyld: Library not loaded: @rpath/AppAuth.framework/AppAuth
  Referenced from: /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/AppName
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: code signature invalid for '/private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth'

    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: stat() failed with errno=25
    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: code signature invalid for '/private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth'

    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: stat() failed with errno=1
    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: code signature invalid for '/private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth'

    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: stat() failed with errno=1

</code>```

In a simulator (iOS 13.3) and on another phone with iOS 13.3, the application runs

Maybe someone who's faced a problem like this, please help.

答: Maybe it's something with a dynamic framework. If you are using CocoaPods, comment the use_frameworks! line in the Podfile, do a pod update, pod install, clean and run. </p>

Body:
After updating your phone to iOS 13.3.1 the application stopped running! Start and crash and error:

dyld: Library not loaded: @rpath/AppAuth.framework/AppAuth
  Referenced from: /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/AppName
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: code signature invalid for '/private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth'

    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: stat() failed with errno=25
    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: code signature invalid for '/private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth'

    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: stat() failed with errno=1
    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: code signature invalid for '/private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth'

    /private/var/containers/Bundle/Application/268CB30E-7E71-473D-BFC4-A548A20D6F00/AppName.app/Frameworks/AppAuth.framework/AppAuth: stat() failed with errno=1

In a simulator (iOS 13.3) and on another phone with iOS 13.3, the application runs

Maybe someone who's faced a problem like this, please help.


问:
Globalization difference in inline tags in ASP.NET
Is there any advantage/downfalls between using the inline write tag instead of the resource tag? Example:

```<code><%=Resources.Site.SampleString %>
</code>```

The resources tag (expression tag) as seen in any MSDN example:

```<code><asp:Literal id="Literal1" runat="server" text="<%$ Resources:Site, SampleString %>" />
</code>```

I find the first option far easier to use, and it has IntelliSense, but maybe it won't function the same?

答:
These methods will function exactly the same. The latter simply calls first one; there is a reason why strongly-typed resources access code is being generated in the background. Therefore you can use whatever method you please.

By the way, there is also another way - by using meta:resourcekey attribute. So you should be able to write:

```<code><asp:Literal id="Literal1" runat="server"
             meta:resourcekey="SampleString" text="Default one" />
</code>```

and it all should work exactly the same.

EDIT on implicit Localization.

What I forgot to mention, is that with meta:resourcekey certain conditions have to be met. The conditions are:

Values are taken from App_LocalResources, therefore related resource file need to exist

Related resource file name must be pagename.resx, for example: Default.aspx.resx, Default.aspx.es.resx

The resource file must contain keys in form of resourcekey.propertyname, for example SampleString.Text, SampleString.ID (although I wouldn't localize control ID's)

Because of how resources are generated, the key mentioned above must exist in invariant resource file (Default.aspx.resx), or it won't be localized.

Body:
Is there any advantage/downfalls between using the inline write tag instead of the resource tag? Example:

<%=Resources.Site.SampleString %>

The resources tag (expression tag) as seen in any MSDN example:

<asp:Literal id="Literal1" runat="server" text="<%$ Resources:Site, SampleString %>" />

I find the first option far easier to use, and it has IntelliSense, but maybe it won't function the same?

Body:
These methods will function exactly the same. The latter simply calls first one; there is a reason why strongly-typed resources access code is being generated in the background. Therefore you can use whatever method you please.

By the way, there is also another way - by using meta:resourcekey attribute. So you should be able to write:

<asp:Literal id="Literal1" runat="server"
             meta:resourcekey="SampleString" text="Default one" />

and it all should work exactly the same.

EDIT on implicit Localization.

What I forgot to mention, is that with meta:resourcekey certain conditions have to be met. The conditions are:

Values are taken from App_LocalResources, therefore related resource file need to exist

Related resource file name must be pagename.resx, for example: Default.aspx.resx, Default.aspx.es.resx

The resource file must contain keys in form of resourcekey.propertyname, for example SampleString.Text, SampleString.ID (although I wouldn't localize control ID's)

Because of how resources are generated, the key mentioned above must exist in invariant resource file (Default.aspx.resx), or it won't be localized.


问:
Iterate a SQL Query through multiple parameters one at a time and union the results
I have a query I have written for SQL Server 2012 to take a dynamic list of personnel and determine how long they spend each day in certain areas. When I run the query a person at a time, I get good results. However, if I pass all the parameters within an IN clause then I not only get less results, but some of the values are different and just plain wrong.

This will eventually be run within a report in SSRS, but even running the data straight in SSMS it is showing the same behavior.

The @People is a separate query that gathers a list of the people which were actually in the area that day. @Yesterday and @Today are just variables for dates.

```<code>SELECT *
FROM
    (SELECT
         AdmitType,
         Time,
         Person,
         Door,
         Direction,
         CASE
            WHEN Direction LIKE 'In' AND LEAD(Direction, 1) OVER(ORDER BY Time ASC) LIKE 'Out'
               THEN DATEDIFF (second, Time, LEAD(Time, 1) OVER(ORDER BY Time ASC))
               ELSE NULL
         END AS 'Duration'
     FROM
         ActivityLog
     WHERE
         Door IN ('Room1', 'Room2', 'Room3')
         AND Time BETWEEN @Yesterday AND @Today
         AND Person IN @People) s1
ORDER BY
    Person, Door, Time ASC
</code>```

If I run the above query and pass the @People parameter with a value of ('Tom', 'Dick', 'Harry') then I will get something like this back for Tom's entries (eliminating some columns and multiple people and doors for clarity):

```<code>Time    Direction    Duration
-----------------------------
7:12:04 IN           922
7:27:26 OUT          NULL
8:40:37 IN           NULL
9:07:04 OUT          NULL
</code>```

But If I run the query with just Tom listed in the IN clause, I get the following which is correct:

```<code>Time    Direction    Duration
-----------------------------
7:12:04 IN           922
7:27:26 OUT          NULL
8:40:37 IN           1587
9:07:04 OUT          NULL
</code>```

How can I either fix my query so that it returns the correct information with everyone selected (approximately 25 people usually) or take the parameter and run each person one at a time and union the results?

I have seen a query which passes a list one at a time and unions all the results, but I do not know how to write that in such a way as to accept the parameter input that would be passed from SSRS.

Additional Data Added from Alan Schofield suggestion:
When I added the PARTITION BY Clause I am now getting data for those previous NULLs, but it is not correct data.

```<code>SELECT *
FROM
    (SELECT
         AdmitType,
         Time,
         Person,
         Door,
         Direction,
         CASE
            WHEN Direction LIKE 'In' AND LEAD(Direction, 1) OVER(PARTITION BY Person, Door ORDER BY Time ASC) LIKE 'Out'
               THEN DATEDIFF (second, Time, LEAD(Time, 1) OVER(ORDER BY Time ASC))
               ELSE NULL
         END AS 'Duration'
     FROM
         ActivityLog
     WHERE
         Door IN ('Room1', 'Room2', 'Room3')
         AND Time BETWEEN @Yesterday AND @Today
         AND Person IN @People) s1
ORDER BY
    Person, Door, Time ASC
</code>```

HERE is a larger example data set with the new PARTITION BY clause results:

```<code>Time      Person     Door    Direction    Duration
18:07:22  John       Room1   IN           1308  (Correct)
18:29:10  John       Room1   Out          NULL
17:42:18  John       Room3   IN           1406  (Correct)
18:05:44  John       Room3   Out          NULL
7:12:04   Tom        Room1   IN           922   (Correct)
7:27:26   Tom        Room1   Out          NULL
8:40:37   Tom        Room1   IN           2    (Previously NULL, Now 2, should be 1587 and is when queried alone)
9:07:04   Tom        Room1   Out          NULL
9:09:07   Tom        Room1   IN           31   (Previously NULL, Now 31, should be 1256 and is when queried alone)
9:30:03   Tom        Room1   Out          NULL
9:38:48   Tom        Room1   IN           48   (Correct)
9:39:36   Tom        Room1   Out          NULL
9:39:45   Tom        Room1   Out          NULL
9:40:36   Tom        Room1   IN           90   (Correct)
9:42:06   Tom        Room1   Out          NULL
10:25:0   Tom        Room1   IN           47   (Previously 47, Now 47, Should be 8939 and is when queried alone)
12:54:08  Tom        Room1   Out          NULL
14:09:42  Tom        Room1   IN           39   (Correct)
14:10:21  Tom        Room1   Out          NULL
14:39:03  Tom        Room1   IN           1316 (Previously NULL, Now 1316, should be 4178 and is when queried alone)
15:48:41  Tom        Room1   Out          NULL
15:49:20  Tom        Room1   IN           52   (Previously NULL, Now 52, should be 1542 and is when queried alone)
16:15:02  Tom        Room1   Out          NULL
16:22:26  Tom        Room1   IN           292  (Previously 292, Now 292, should be 1504 and is when queried alone)
16:47:30  Tom        Room1   Out          NULL
</code>```

The data continues a lot more but hopefully this gives a better idea.

答:
Your WHERE clause is incorrect in the sense that it's not going to return the results you think.

If I run the above query and pass the @People parameter with a value
  of ('Tom', 'Dick', 'Harry')

This is incorrect. @People does not have a value of ('Tom', 'Dick', 'Harry'). It has a value of ('Tom, Dick, Harry').

```<code>WHERE
     Door IN ('Room1', 'Room2', 'Room3')
     AND Time BETWEEN @Yesterday AND @Today
     AND Person IN @People) s1
</code>```

Field Door's IN clause lists three distinct values, separated by T-SQL commas, and correctly filters the query.

You need to have a table-valued function to split the @People parameter into a table variable, and use that for the Person IN clause. Something like this:

```<code>CREATE function [dbo].[SplitListToTable]
(
    @List       AS NVARCHAR(MAX),
    @Delimiter  AS NVARCHAR(8) = ','
 )
RETURNS @SplitList TABLE (ListItem [nvarchar](4000))
BEGIN

DECLARE @NextString     AS NVARCHAR(4000)
DECLARE @Pos            AS INT
DECLARE @NextPos        AS INT
DECLARE @DelimiterCheck AS NVARCHAR(1)

--Initialize
SET @NextString = ''
SET @DelimiterCheck = RIGHT(@List, 1)

IF (@DelimiterCheck <> @Delimiter )
    SET @List = @List + @Delimiter

--Get position of first Comma
SET @Pos = CHARINDEX(@Delimiter, @List)
SET @NextPos = 1

--Loop while there is still a comma in the String of levels
WHILE (@pos <>  0)
    BEGIN
    SET @NextString = SUBSTRING(@List, 1, @Pos - 1)

    INSERT INTO @SplitList(ListItem) Values(@NextString)

    SET @List = SUBSTRING(@List, @Pos +1, LEN(@List))
    SET @NextPos = @Pos
    SET @Pos  = CHARINDEX(@Delimiter, @List)
    END

RETURN

END
GO
</code>```

Now, update your WHERE clause as such:

```<code>AND Person IN dbo.SplitListToTable(@People, ',')
</code>```

Body:
I have a query I have written for SQL Server 2012 to take a dynamic list of personnel and determine how long they spend each day in certain areas. When I run the query a person at a time, I get good results. However, if I pass all the parameters within an IN clause then I not only get less results, but some of the values are different and just plain wrong.

This will eventually be run within a report in SSRS, but even running the data straight in SSMS it is showing the same behavior.

The @People is a separate query that gathers a list of the people which were actually in the area that day. @Yesterday and @Today are just variables for dates.

SELECT *
FROM
    (SELECT
         AdmitType,
         Time,
         Person,
         Door,
         Direction,
         CASE
            WHEN Direction LIKE 'In' AND LEAD(Direction, 1) OVER(ORDER BY Time ASC) LIKE 'Out'
               THEN DATEDIFF (second, Time, LEAD(Time, 1) OVER(ORDER BY Time ASC))
               ELSE NULL
         END AS 'Duration'
     FROM
         ActivityLog
     WHERE
         Door IN ('Room1', 'Room2', 'Room3')
         AND Time BETWEEN @Yesterday AND @Today
         AND Person IN @People) s1
ORDER BY
    Person, Door, Time ASC

If I run the above query and pass the @People parameter with a value of ('Tom', 'Dick', 'Harry') then I will get something like this back for Tom's entries (eliminating some columns and multiple people and doors for clarity):

Time    Direction    Duration
-----------------------------
7:12:04 IN           922
7:27:26 OUT          NULL
8:40:37 IN           NULL
9:07:04 OUT          NULL

But If I run the query with just Tom listed in the IN clause, I get the following which is correct:

Time    Direction    Duration
-----------------------------
7:12:04 IN           922
7:27:26 OUT          NULL
8:40:37 IN           1587
9:07:04 OUT          NULL

How can I either fix my query so that it returns the correct information with everyone selected (approximately 25 people usually) or take the parameter and run each person one at a time and union the results?

I have seen a query which passes a list one at a time and unions all the results, but I do not know how to write that in such a way as to accept the parameter input that would be passed from SSRS.

Additional Data Added from Alan Schofield suggestion:
When I added the PARTITION BY Clause I am now getting data for those previous NULLs, but it is not correct data.

SELECT *
FROM
    (SELECT
         AdmitType,
         Time,
         Person,
         Door,
         Direction,
         CASE
            WHEN Direction LIKE 'In' AND LEAD(Direction, 1) OVER(PARTITION BY Person, Door ORDER BY Time ASC) LIKE 'Out'
               THEN DATEDIFF (second, Time, LEAD(Time, 1) OVER(ORDER BY Time ASC))
               ELSE NULL
         END AS 'Duration'
     FROM
         ActivityLog
     WHERE
         Door IN ('Room1', 'Room2', 'Room3')
         AND Time BETWEEN @Yesterday AND @Today
         AND Person IN @People) s1
ORDER BY
    Person, Door, Time ASC

HERE is a larger example data set with the new PARTITION BY clause results:

Time      Person     Door    Direction    Duration
18:07:22  John       Room1   IN           1308  (Correct)
18:29:10  John       Room1   Out          NULL
17:42:18  John       Room3   IN           1406  (Correct)
18:05:44  John       Room3   Out          NULL
7:12:04   Tom        Room1   IN           922   (Correct)
7:27:26   Tom        Room1   Out          NULL
8:40:37   Tom        Room1   IN           2    (Previously NULL, Now 2, should be 1587 and is when queried alone)
9:07:04   Tom        Room1   Out          NULL
9:09:07   Tom        Room1   IN           31   (Previously NULL, Now 31, should be 1256 and is when queried alone)
9:30:03   Tom        Room1   Out          NULL
9:38:48   Tom        Room1   IN           48   (Correct)
9:39:36   Tom        Room1   Out          NULL
9:39:45   Tom        Room1   Out          NULL
9:40:36   Tom        Room1   IN           90   (Correct)
9:42:06   Tom        Room1   Out          NULL
10:25:0   Tom        Room1   IN           47   (Previously 47, Now 47, Should be 8939 and is when queried alone)
12:54:08  Tom        Room1   Out          NULL
14:09:42  Tom        Room1   IN           39   (Correct)
14:10:21  Tom        Room1   Out          NULL
14:39:03  Tom        Room1   IN           1316 (Previously NULL, Now 1316, should be 4178 and is when queried alone)
15:48:41  Tom        Room1   Out          NULL
15:49:20  Tom        Room1   IN           52   (Previously NULL, Now 52, should be 1542 and is when queried alone)
16:15:02  Tom        Room1   Out          NULL
16:22:26  Tom        Room1   IN           292  (Previously 292, Now 292, should be 1504 and is when queried alone)
16:47:30  Tom        Room1   Out          NULL

The data continues a lot more but hopefully this gives a better idea.

Body:
Your WHERE clause is incorrect in the sense that it's not going to return the results you think.

If I run the above query and pass the @People parameter with a value
  of ('Tom', 'Dick', 'Harry')

This is incorrect. @People does not have a value of ('Tom', 'Dick', 'Harry'). It has a value of ('Tom, Dick, Harry').

WHERE
     Door IN ('Room1', 'Room2', 'Room3')
     AND Time BETWEEN @Yesterday AND @Today
     AND Person IN @People) s1

Field Door's IN clause lists three distinct values, separated by T-SQL commas, and correctly filters the query.

You need to have a table-valued function to split the @People parameter into a table variable, and use that for the Person IN clause. Something like this:

CREATE function [dbo].[SplitListToTable]
(
    @List       AS NVARCHAR(MAX),
    @Delimiter  AS NVARCHAR(8) = ','
 )
RETURNS @SplitList TABLE (ListItem [nvarchar](4000))
BEGIN

DECLARE @NextString     AS NVARCHAR(4000)
DECLARE @Pos            AS INT
DECLARE @NextPos        AS INT
DECLARE @DelimiterCheck AS NVARCHAR(1)

--Initialize
SET @NextString = ''
SET @DelimiterCheck = RIGHT(@List, 1)

IF (@DelimiterCheck <> @Delimiter )
    SET @List = @List + @Delimiter

--Get position of first Comma
SET @Pos = CHARINDEX(@Delimiter, @List)
SET @NextPos = 1

--Loop while there is still a comma in the String of levels
WHILE (@pos <>  0)
    BEGIN
    SET @NextString = SUBSTRING(@List, 1, @Pos - 1)

    INSERT INTO @SplitList(ListItem) Values(@NextString)

    SET @List = SUBSTRING(@List, @Pos +1, LEN(@List))
    SET @NextPos = @Pos
    SET @Pos  = CHARINDEX(@Delimiter, @List)
    END

RETURN

END
GO

Now, update your WHERE clause as such:

AND Person IN dbo.SplitListToTable(@People, ',')


问:
Is there a way to create a separate log file for each user ? (spring boot)
I am working on a spring boot application, i want to create a separate logging file for each user of the application, is this possible ?

For example: user1.log, user2.log, user3.log, ....

Thanks.

答:
It's possible but it will create as many log files as users. Imagine if your user base increases to 20K. Unless you have very strong need don't go for it.

Instead go for application level and user level loggings. To achieve this refer here - https://stackoverflow.com/a/9652239


问:
Java: How to print the String value of a Map element?
Could someone tell me how to get or print the String value of a map element?
The below code results in "The method values() is undefined for the type String."
I also tried .getValue() but the outcome is the same.

Thanks in advance!

```<code>Map<Integer, String> mapName = new HashMap<>();
mapName.put(0, "description_0");
mapName.put(1, "description_1");

for (Integer i : mapName.keySet()){
     System.out.println(mapName.get(i).values());
}

</code>```

答:
Answer provided by @Lino.</p>

```<code>for(String s : mapName.values()) System.out.println(s);
</code>```

Body:
Could someone tell me how to get or print the String value of a map element?
The below code results in "The method values() is undefined for the type String."
I also tried .getValue() but the outcome is the same.

Thanks in advance!

Map<Integer, String> mapName = new HashMap<>();
mapName.put(0, "description_0");
mapName.put(1, "description_1");

for (Integer i : mapName.keySet()){
     System.out.println(mapName.get(i).values());
}

Body:
Answer provided by @Lino.

for(String s : mapName.values()) System.out.println(s);


问:
How to disable auto scroll on dropdown of mat-select in angular material?
Scenario:
I type in letters in keyboard and the mat-select dropdown automatically scrolls(jumps) to the element in dropdown list.
For eg. if I type 'I' it is scrolling to Inventory while I want to search for the word 'Id'.
my list is not sorted..
so i want to avoid autoscroll to the word starting with letter
Can anyone help?</p>

答:
You can set typeaheadDebounceInterval on mat-select to e.g. 500 ms to delay the jump. Then you could have written 2 characters, e.g. i then d, so it will jump to the right word.

Disabling the jump is not possible. It is built-in in native html  elements


问:
getting dynamic substring xslt
I am pretty new to all of developing / using XSLT but for work we have to use this now.
I am busy mapping messages from application A to B and i run into something I cannot find the answer to.

as input field i have <sys_external_id>201000077_G001_S20_H10</sys_external_id>

now have i created below:

```<code><stopNumber>
    <xsl:value-of select="substring(sys_external_id, 16, 4)" />
</stopNumber>

<stopHandlingNumber>
    <xsl:value-of select="substring(sys_external_id, 20, 4)" />
</stopHandlingNumber>
</code>```

this gives me at the moment the correct answer ( S20 and H10 )
now is the "problem" that the value of S20 and H10 can differ.
for example the value can be S2100 or H110. also the G001 can also differ.

A substring-after does not work because i cannot determine where my end is ( as far as I know )

答:
In XSLT 2.0 you could do:

```<code><xsl:variable name="tokens" select="tokenize(sys_external_id, '_')" />

<stopNumber>
    <xsl:value-of select="$tokens[3]" />
</stopNumber>

<stopHandlingNumber>
    <xsl:value-of select="$tokens[4]" />
</stopHandlingNumber>
</code>```

If you're limited to XSLT 1.0, then it could be:

```<code><xsl:variable name="tail" select="substring-after(substring-after(sys_external_id, '_'), '_')" />

<stopNumber>
    <xsl:value-of select="substring-before($tail, '_')" />
</stopNumber>

<stopHandlingNumber>
    <xsl:value-of select="substring-after($tail, '_')" />
</stopHandlingNumber>
</code>```

This is assuming that the input string is simply a sequence of tokens delimited by an underscore.

Note also that some XSLT 1.0 processors support the EXSLT str:tokenize() extension function.

Title: getting dynamic substring xslt

Body:
I am pretty new to all of developing / using XSLT but for work we have to use this now.
I am busy mapping messages from application A to B and i run into something I cannot find the answer to.

as input field i have <sys_external_id>201000077_G001_S20_H10</sys_external_id>

now have i created below:

<stopNumber>
    <xsl:value-of select="substring(sys_external_id, 16, 4)" />
</stopNumber>

<stopHandlingNumber>
    <xsl:value-of select="substring(sys_external_id, 20, 4)" />
</stopHandlingNumber>

this gives me at the moment the correct answer ( S20 and H10 )
now is the "problem" that the value of S20 and H10 can differ.
for example the value can be S2100 or H110. also the G001 can also differ.

A substring-after does not work because i cannot determine where my end is ( as far as I know )

Body:
In XSLT 2.0 you could do:

<xsl:variable name="tokens" select="tokenize(sys_external_id, '_')" />

<stopNumber>
    <xsl:value-of select="$tokens[3]" />
</stopNumber>

<stopHandlingNumber>
    <xsl:value-of select="$tokens[4]" />
</stopHandlingNumber>

If you're limited to XSLT 1.0, then it could be:

<xsl:variable name="tail" select="substring-after(substring-after(sys_external_id, '_'), '_')" />

<stopNumber>
    <xsl:value-of select="substring-before($tail, '_')" />
</stopNumber>

<stopHandlingNumber>
    <xsl:value-of select="substring-after($tail, '_')" />
</stopHandlingNumber>

This is assuming that the input string is simply a sequence of tokens delimited by an underscore.

Note also that some XSLT 1.0 processors support the EXSLT str:tokenize() extension function.


问:
Deadlock in goroutine with GopherJS
Why is there a deadlock in the following code? I am trying to return something from the goroutine to outside

```<code>package main

import (
    "fmt"
    "syscall/js"
    "time"
)

func test(this js.Value, i []js.Value) interface{} {
    done := make(chan string, 1)

    go func() {
        doRequest := func(this js.Value, i []js.Value) interface{} {
            time.Sleep(time.Second)

            return 0
        }

        js.Global().Set("doRequest", js.FuncOf(doRequest))
        args := []js.Value{js.ValueOf("url")}
        var x js.Value
        doRequest(x, args)
        done <- "true"
    }()

    aa := <-done
    fmt.Println(aa)

    return 0
}

func main() {
    c := make(chan bool)
    js.Global().Set("test", js.FuncOf(test))
    <-c
}
</code>```

When I run this on a browser and call test(),  the following error will be shown

```<code>fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
.....
</code>```

答:
Pretty much what it says in the error message.  All goroutines are asleep.  main doesn't start anything and just does a channel receive, so it's blocked, and no other goroutines are running, so there's no possibility that main could ever wake up again, so the runtime panics.

If I recall correctly, unlike regular Go, GopherJS doesn't shut everything down and exit if main exits (in part because: what exactly would that even mean?  The closest analog to a Go program would be to close the webpage!  Which would kind of suck.  So GopherJS doesn't do that.).  So what you're doing to keep main alive is not necessary, strictly speaking, in GopherJS.

That said, if you say (for example) time.Sleep(time.Hour) at the end instead, then while all goroutines are still asleep (strictly speaking), main will eventually wake up, which the runtime knows, so it doesn't panic in that case.

As to your actual test function, once you do try it, you get a related error message: Uncaught Error: runtime error: cannot block in JavaScript callback, fix by wrapping code in goroutine.  test does a blocking call on a channel, and GopherJS won't allow that in a function called directly from Javascript, so it panics.  (When I run it in the playground, I also get Uncaught TypeError: r is not a function, but that's just fallout from the earlier error.)
 I think what you're trying to do is wait for doRequest to finish, print the value, and return, but that won't work.  You'll need to use a native Javascript promise, or some other asynchronous mechanism, for that.

Title: Deadlock in goroutine with GopherJS

Body:
Why is there a deadlock in the following code? I am trying to return something from the goroutine to outside

package main

import (
    "fmt"
    "syscall/js"
    "time"
)

func test(this js.Value, i []js.Value) interface{} {
    done := make(chan string, 1)

    go func() {
        doRequest := func(this js.Value, i []js.Value) interface{} {
            time.Sleep(time.Second)

            return 0
        }

        js.Global().Set("doRequest", js.FuncOf(doRequest))
        args := []js.Value{js.ValueOf("url")}
        var x js.Value
        doRequest(x, args)
        done <- "true"
    }()

    aa := <-done
    fmt.Println(aa)

    return 0
}

func main() {
    c := make(chan bool)
    js.Global().Set("test", js.FuncOf(test))
    <-c
}

When I run this on a browser and call test(),  the following error will be shown

fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
.....


问:
Qt4 Creator/QMAKE equivalent to "-mcmodel=medium" GCC compiler settings
I'm using Qt Creator to create a GUI for a fairly memory intensive C++ application on Linux. In order for the application to run properly, the -mcmodel=medium compiler flag must be set during compilation, otherwise the application will abruptly crash during execution (tried compiling in Qt without it, and it crashes as expected). How do I set the GCC flags in the .pro file  to deal with this directly or is there a Qt equivalent to this memory model flag setting?

Note: I've tried QMAKE_CXXFLAGS += -mcmodel=medium and it doesn't seem to work...

Correction: QMAKE_CXXFLAGS method appears to work. Error returned was actually a hardware memory bus error.

答:
```<code>QMAKE_CXXFLAGS += -mcmodel=medium
</code>```

Body: QMAKE_CXXFLAGS += -mcmodel=medium


问:
How to efficiently design components / configure store when using react-redux
If I have a component tree such that,

```<code>//App.js
const App = () => (
      <React.Fragment>
        <A />
        <B />
        <C />
      </React.Fragment>
    )

//A.js
const A = () => (
      <React.Fragment>
        <ChildA />
      </React.Fragment>
)
</code>```

Now, lets say all three components A, B, C are connected to store using connect().
The problem is if I update the store with data only relevant to component A, then B, C will also be re-rendered. One of the possible solution would be to configure the options parameter to avoid re-renders as mentioned in docs.

Does creating multiple reducer functions for each mutually exclusive components solve this problem ? If yes, how and if No, then what could be done to minimise unnecessary re-rendering.

UPDATE:
In addition to @tmdesigned's answer, if I create a child component of A, then some update in childA causes both A and childA to re-render, with childA re-rendering twice since both are connected to common reducer function.

See, @tmdesigned's sandbox link,

答:
In my opinion each component needs to have it own functionality, it's important this to prevent cases like you said. For example component A renders a list of persons it needs to have its own reducer and actions. For example:

persons state

```<code>persons: {
  data: [...]
  loading: false
  error: null
}
</code>```

persons actions
PERSONS_FETCH_INIT PERSONS_FETCH_SUCCESS PERSONS_FETCH_FAIL

Also you will need to use react memo, if the state that the component A is subscribed updates component A will trigger a re-render to the component App and then all the children components like B, C, etc will re-render.

Body:
If I have a component tree such that,

//App.js
const App = () => (
      <React.Fragment>

        <C />
      </React.Fragment>
    )

//A.js
const A = () => (
      <React.Fragment>
        <ChildA />
      </React.Fragment>
)

Now, lets say all three components A, B, C are connected to store using connect().
The problem is if I update the store with data only relevant to component A, then B, C will also be re-rendered. One of the possible solution would be to configure the options parameter to avoid re-renders as mentioned in docs.

Does creating multiple reducer functions for each mutually exclusive components solve this problem ? If yes, how and if No, then what could be done to minimise unnecessary re-rendering.

UPDATE:
In addition to @tmdesigned's answer, if I create a child component of A, then some update in childA causes both A and childA to re-render, with childA re-rendering twice since both are connected to common reducer function.

See, @tmdesigned's sandbox link,

Body:
In my opinion each component needs to have it own functionality, it's important this to prevent cases like you said. For example component A renders a list of persons it needs to have its own reducer and actions. For example:

persons state

persons: {
  data: [...]
  loading: false
  error: null
}

persons actions
PERSONS_FETCH_INIT PERSONS_FETCH_SUCCESS PERSONS_FETCH_FAIL

Also you will need to use react memo, if the state that the component A is subscribed updates component A will trigger a re-render to the component App and then all the children components like B, C, etc will re-render.


问:
Catching an exception in an overridden method in C#
Why does the following catch block does not catch any exception?
Does this have anything to do with the override->base.Method() relationship?

On the screenshot you can see that an SqlException with a number 2627 is thrown, but the catch block never catches it.

```<code>    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (SqlException ex) when (ex.Number == 2627)
        {
            Log.Error($"Duplicate key constraint violation occured while submitting changes, {ex.Message}");
            var (resource, duplicateKey) = ExtractDuplicateKeyViolationDetails(ex.Message);
            throw new DuplicateKeyException(resource, duplicateKey);
        }
        catch (SqlException ex) when (ex.Number == 547)
        {
            Log.Error($"Constraint violation occured while submitting changes, {ex.Message}");
            var (resource, property) = ExtractConstraintViolationDetails(ex.Message);
            throw new ConstraintViolationException(resource, property);
        }
    }
</code>```

答: You're running your code in debug mode. VS stops execution whenever an exception is thrown and that's what you're seeing. Hit F5 to continue execution and it'll enter the catch block.</p>

Body:
Why does the following catch block does not catch any exception?
Does this have anything to do with the override->base.Method() relationship?

On the screenshot you can see that an SqlException with a number 2627 is thrown, but the catch block never catches it.

    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (SqlException ex) when (ex.Number == 2627)
        {
            Log.Error($"Duplicate key constraint violation occured while submitting changes, {ex.Message}");
            var (resource, duplicateKey) = ExtractDuplicateKeyViolationDetails(ex.Message);
            throw new DuplicateKeyException(resource, duplicateKey);
        }
        catch (SqlException ex) when (ex.Number == 547)
        {
            Log.Error($"Constraint violation occured while submitting changes, {ex.Message}");
            var (resource, property) = ExtractConstraintViolationDetails(ex.Message);
            throw new ConstraintViolationException(resource, property);
        }
    }


问:
How to find and collect Objects to Map by its parameter?
Given enum:

```<code>enum Type {
  PRIMARY,
  SECONDARY
}
</code>```

and two different Sets of Objects with same parameter (type):

```<code>class OldObject {
  Long id;
  Type type;
}

class NewObject {
  Long id;
  String title;
  Type type;
}
</code>```

...which looks like:

```<code>Set<OldObject> ...
Set<NewObject> ...
</code>```

Beeing confused about Stream API with Collectors and Groupings I am not able to finish with a Map[OldObject, NewObject] with pairs grouped by Type. I am able to guarantee that both sets ale full and I am able to find pairs. I thought that I can start with stream of enum (but do not know if it is a good aproach):

```<code>Map<OldObject, NewObject> pairs = Optional.of(Schema.values())...
</code>```

答:
At the moment my code looks like:

        Map<OldObject, NewObject> compared = new HashMap<>();

        Arrays.stream(Type.values()).collect(Collectors.toSet()).forEach(s ->
                compared.put(
                        oldObjectsSet.stream()
                                .filter(o -> o.getType().equals(s))
                                .findFirst()
                                .orElseThrow(),
                        newObjectsSet.stream()
                                .filter(m -> m.getType().equals(s))
                                .findFirst()
                                .orElseThrow()
                ));
```

...which works but does not look great.

Body:
Given enum:

enum Type {
  PRIMARY,
  SECONDARY
}

and two different Sets of Objects with same parameter (type):

class OldObject {
  Long id;
  Type type;
}

class NewObject {
  Long id;
  String title;
  Type type;
}

...which looks like:

Set<OldObject> ...
Set<NewObject> ...

Beeing confused about Stream API with Collectors and Groupings I am not able to finish with a Map[OldObject, NewObject] with pairs grouped by Type. I am able to guarantee that both sets ale full and I am able to find pairs. I thought that I can start with stream of enum (but do not know if it is a good aproach):

Map<OldObject, NewObject> pairs = Optional.of(Schema.values())...

Body:
At the moment my code looks like:

        Map<OldObject, NewObject> compared = new HashMap<>();

        Arrays.stream(Type.values()).collect(Collectors.toSet()).forEach(s ->
                compared.put(
                        oldObjectsSet.stream()
                                .filter(o -> o.getType().equals(s))
                                .findFirst()
                                .orElseThrow(),
                        newObjectsSet.stream()
                                .filter(m -> m.getType().equals(s))
                                .findFirst()
                                .orElseThrow()
                ));

...which works but does not look great.


问:
Data structure keeping the order of ManyToMany items
For example,

There are two lines and a few stations.

```<code>Line X
Station A - Station B - Station C - Station D

Line Y
Station E - Station F - Station B - Station G
</code>```

Line X and Y are crossing at Station B

So my tables are like this below

Line Table

```<code>1 X  "LineX"
2 Y  "LineY"
</code>```

Station Table

```<code>1 A X
2 B X,Y
3 C X
4 D X
5 E Y
6 F Y
7 G Y
</code>```

Models are like this (This is django but using doctrine are almost same.)

```<code>class Line(models.Model):
    name = models.CharField(unique=True,max_length=255)
    def __str__(self):
        return self.name

class Station(models.Model):
    name = models.CharField(unique=True,max_length=255)
    lines = models.ManyToManyField(Line)
    def __str__(self):
        return self.name
</code>```

In this case, you can get the stations of LineX easily.

SELECT from station table where line (which include) Y

return A,B,C,D

However for LineY

it returns B,E,F,G

but B is not the top.

It's third station.

I think I should add some column to maintain the order of each lines.

What is the best practice for structure keeping the order of manytomany items?

I am familliar with Doctorine2 and django models.

I would appreciate any help of you.

答:
Warning: this answer considers the data structure in the DB only, and does not address django.

Perhaps you could implement a Line_Order table with foreign keys to the line, and the stations. I'd also have a direction tag (as I assume your lines are bi-directional and not circular)

E.g.

```<code>    Line_id    Station_id    Direction
1   1          1             Line X Eastbound
2   1          2             Line X Eastbound
...
5   1          4             Line X Westbound
...
10  2          5             Line Y Northbound
11  2          6             Line Y Northbound
12  2          2             Line Y Northbound
13  2          7             Line Y Northbound
...
</code>```

And then to be honest, I'd drop the Line column entirely from the stations table.

The above structure is brittle to changes. If your train lines are likely to be modified, then you may alternatively wish to consider a "Next station" table analogous to a linked list. Your table could list the line_id, the station_id, the next station_id and the previous station_id. The direction of travel may or may not be required depending on your implementation.

Body:
For example,

There are two lines and a few stations.

Line X
Station A - Station B - Station C - Station D

Line Y
Station E - Station F - Station B - Station G

Line X and Y are crossing at Station B

So my tables are like this below

Line Table

1 X  "LineX"
2 Y  "LineY"

Station Table

1 A X
2 B X,Y
3 C X
4 D X
5 E Y
6 F Y
7 G Y

Models are like this (This is django but using doctrine are almost same.)

class Line(models.Model):
    name = models.CharField(unique=True,max_length=255)
    def __str__(self):
        return self.name

class Station(models.Model):
    name = models.CharField(unique=True,max_length=255)
    lines = models.ManyToManyField(Line)
    def __str__(self):
        return self.name

In this case, you can get the stations of LineX easily.

SELECT from station table where line (which include) Y

return A,B,C,D

However for LineY

it returns B,E,F,G

but B is not the top.

It's third station.

I think I should add some column to maintain the order of each lines.

What is the best practice for structure keeping the order of manytomany items?

I am familliar with Doctorine2 and django models.

I would appreciate any help of you.

Body:
Warning: this answer considers the data structure in the DB only, and does not address django.

Perhaps you could implement a Line_Order table with foreign keys to the line, and the stations. I'd also have a direction tag (as I assume your lines are bi-directional and not circular)

E.g.

    Line_id    Station_id    Direction
1   1          1             Line X Eastbound
2   1          2             Line X Eastbound
...
5   1          4             Line X Westbound
...
10  2          5             Line Y Northbound
11  2          6             Line Y Northbound
12  2          2             Line Y Northbound
13  2          7             Line Y Northbound
...

And then to be honest, I'd drop the Line column entirely from the stations table.

The above structure is brittle to changes. If your train lines are likely to be modified, then you may alternatively wish to consider a "Next station" table analogous to a linked list. Your table could list the line_id, the station_id, the next station_id and the previous station_id. The direction of travel may or may not be required depending on your implementation.


问:
React navigation 5.0 header button
I trying to add right navigation header button directly on from Component, and implementation steps have been changed navigation 5.0 version, there is one method that provide add button with method

```<code>function HomeScreen({ navigation }) {
  const [count, setCount] = React.useState(0);

  navigation.setOptions({
    headerRight: () => (
      <Button onPress={() => setCount(c => c + 1)} title="Update count" />
    ),
  });

  return <Text>Count: {count}</Text>;
}
</code>```

but need to implement on it

```<code>export default class HomeScreen extends Component {

    constructor() {
        super()

    }
    render() {
        return ()
     }
}
</code>```

答:
Try this</p>

```<code> <Stack.Screen
    code..//
        options={{
        code...//
          headerRight: () => (
            <Button
              onPress={() => alert('This is a button!')}
              title="Info"
              color="#fff"
            />
          ),
        }}
      />
</code>```

Title: React navigation 5.0 header button

Body:
I trying to add right navigation header button directly on from Component, and implementation steps have been changed navigation 5.0 version, there is one method that provide add button with method

function HomeScreen({ navigation }) {
  const [count, setCount] = React.useState(0);

  navigation.setOptions({
    headerRight: () => (
      <Button onPress={() => setCount(c => c + 1)} title="Update count" />
    ),
  });

  return <Text>Count: {count}</Text>;
}

but need to implement on it

export default class HomeScreen extends Component {

    constructor() {
        super()

    }
    render() {
        return ()
     }
}

Body:
Try this

 <Stack.Screen
    code..//
        options={{
        code...//
          headerRight: () => (
            <Button
              onPress={() => alert('This is a button!')}
              title="Info"
              color="#fff"
            />
          ),
        }}
      />


问:
Vue / Router: How do I correctly fetch data before rendering page content?
I'm using Nuxt with Vue Router and Axios. I see Vue Router has this fantastic feature called Navigation Guards.

Unfortunately, in the example below, my beforeRouteEnter() function is called but seems to exit and switch pages before my manual next() method is called in fetchPageData(next).

What is the correct pattern here?

```<code>export default {
    beforeRouteEnter (to, from, next) {
        next(vm => {
            vm.fetchPageData(next);
        });
    },
    methods: {
        async fetchPageData(next) {
            const result = await this.$axios.$get('/api/v2/inventory/3906?apiKey=f54761e0-673e-4baf-86c1-0b85a6c8c118');
            this.$store.commit('property/setProperty', result[0]);
            next();
        }
    }
}
</code>```

I assume that my first call to next(vm => {}) is running asynchronously, allowing execution to continue, resulting in a page change before I (most likely incorrectly) try to callback next().

答:
What is happening there, is that you already calling next and that's
  why the route enters immediately.

Where you are calling next ?

```<code>beforeRouteEnter (to, from, next) {
    next(vm => {  // <= HERE you execute next
        vm.fetchPageData(next);
    });
},
</code>```

And the above code will execute vm.fetchPageData when the component is already rendered.

So even if you don't call next on the fetchPageData the route will enter.

By assuming that you want to enter the view after certain data is fetched by BE you can use beforeEnter on the router config:

```<code>const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        axios.get('api/...')
          .then(response => {
             store.commit('mutation', response)
             next()
          })
          .catch(e => {
            alert('Something went wrong')
            next(false)
          })
      }
    }
  ]
})
</code>```

Another solution would be to allow the route to enter but show a loader while data is being fetched: Checkout this answer

Body:
I'm using Nuxt with Vue Router and Axios. I see Vue Router has this fantastic feature called Navigation Guards.

Unfortunately, in the example below, my beforeRouteEnter() function is called but seems to exit and switch pages before my manual next() method is called in fetchPageData(next).

What is the correct pattern here?

export default {
    beforeRouteEnter (to, from, next) {
        next(vm => {
            vm.fetchPageData(next);
        });
    },
    methods: {
        async fetchPageData(next) {
            const result = await this.$axios.$get('/api/v2/inventory/3906?apiKey=f54761e0-673e-4baf-86c1-0b85a6c8c118');
            this.$store.commit('property/setProperty', result[0]);
            next();
        }
    }
}

I assume that my first call to next(vm => {}) is running asynchronously, allowing execution to continue, resulting in a page change before I (most likely incorrectly) try to callback next().

Body:
What is happening there, is that you already calling next and that's
  why the route enters immediately.

Where you are calling next ?

beforeRouteEnter (to, from, next) {
    next(vm => {  // <= HERE you execute next
        vm.fetchPageData(next);
    });
},

And the above code will execute vm.fetchPageData when the component is already rendered.

So even if you don't call next on the fetchPageData the route will enter.

By assuming that you want to enter the view after certain data is fetched by BE you can use beforeEnter on the router config:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        axios.get('api/...')
          .then(response => {
             store.commit('mutation', response)
             next()
          })
          .catch(e => {
            alert('Something went wrong')
            next(false)
          })
      }
    }
  ]
})

Another solution would be to allow the route to enter but show a loader while data is being fetched: Checkout this answer


问:
Confusing variable in auto generated Makefile by qmake
I recently started to take over a QT4.8 project for embedded Linux. After using qmake and .pro file to generate Makefiles in the project, it could not build properly.

The Makefile.Debug snippet causing problem is as following:

```<code>{..\GriduiWin}.cpp{debug\}.obj::
    $(CXX) -c $(CXXFLAGS) $(INCPATH) -Fodebug\ @<<
    $<
<<
</code>```

For << in the end, make is complaining for the missing tab at the beginning.

For @<< at the end of the second line, I couldn't figure out what is the issue here. The error message is << was unexpected at this time.

What does @<< mean in Makefile? Is this specific from qmake generated files? Or is this a reasonable syntax? How could I deal with this error? Thanks for help.

答: This generated Makefile turns out to be for nmake instead. Errors no longer shows when compiling with Microsoft Visual Studio command line tools. Thanks to MadScientist for the hint.

Body:
I recently started to take over a QT4.8 project for embedded Linux. After using qmake and .pro file to generate Makefiles in the project, it could not build properly.

The Makefile.Debug snippet causing problem is as following:

{..\GriduiWin}.cpp{debug\}.obj::
    $(CXX) -c $(CXXFLAGS) $(INCPATH) -Fodebug\ @<<
    $<
<<

For << in the end, make is complaining for the missing tab at the beginning.

For @<< at the end of the second line, I couldn't figure out what is the issue here. The error message is << was unexpected at this time.

What does @<< mean in Makefile? Is this specific from qmake generated files? Or is this a reasonable syntax? How could I deal with this error? Thanks for help.


问:
How to use sort V horizontally?
I have this table:

```<code>flame#43    king#402    Picnic#51   Sar#360     far#66
flame#61    king#63     Picknic#67  Sar#66      far#65
flame#63    king#60     Packnic#69  Sar#64      far#58
</code>```

My desired output is:

```<code>flame#43  Picnick#51 far#66     Sar#360  king#402

flame#61  king#63    far#65     Sar#66   Picknic#67

far#58    king#60    flame#63   Sar#64   Packnic#69
</code>```

Does anyone know how to sort horizontally based on value when we have a text also?

I tried to used sort -V in variable combinations \with combination with  sort kn  .Also I tried to modified this code

```<code>awk ' {split( $0, a, " " ); asort( a );
for( i = 1; i <= length(a); i++ ) printf( "%s ", a[i] );
printf( "\n" ); }'
</code>```

which sorts tables only when we have a numeric value table horizontally.

答:
I used asorti function to sort an array where indexes are the numbers extracted from the elements. I filled the elements with leading zeros, because asorti sorts lexically not numerically. After sorting, I just print elements.

```<code>awk '{
    split($0, a, " ");

    for (i in a) {
        # extract number
        v = a[i]
        gsub(/.*#/, "", v)
        # because asorti sorts alphabetically, I fill indexes with zeros
        b[sprintf("%020d", v)] = a[i]
    }

    # sort using indexes
    n = asorti(b, dest)

    # output
    for (i = 1; i <= n; i++) {
        printf "%s%s", b[dest[i]], i == n ? "\n" : " "
    }

    # if we dont delete b, it will only grow. So delete it.
    delete b
}' <<'EOF'
flame#43    king#402    Picnic#51   Sar#360     far#66
flame#61    king#63     Picknic#67  Sar#66      far#65
flame#63    king#60     Packnic#69  Sar#64      far#58
EOF
</code>```

outputs:

```<code>flame#43 Picnic#51 far#66 Sar#360 king#402
flame#61 king#63 far#65 Sar#66 Picknic#67
far#58 king#60 flame#63 Sar#64 Packnic#69
</code>```

I tested on tutorialspoint. You can pipe the output to column -t -s ' ' -o ' ' to have the columnized output or do it in awk like with printf "%-9s%s".

Title: How to use sort V horizontally?

Body:
I have this table:

flame#43    king#402    Picnic#51   Sar#360     far#66
flame#61    king#63     Picknic#67  Sar#66      far#65
flame#63    king#60     Packnic#69  Sar#64      far#58

My desired output is:

flame#43  Picnick#51 far#66     Sar#360  king#402

flame#61  king#63    far#65     Sar#66   Picknic#67

far#58    king#60    flame#63   Sar#64   Packnic#69

Does anyone know how to sort horizontally based on value when we have a text also?

I tried to used sort -V in variable combinations \with combination with  sort kn  .Also I tried to modified this code

awk ' {split( $0, a, " " ); asort( a );
for( i = 1; i <= length(a); i++ ) printf( "%s ", a[i] );
printf( "\n" ); }'

which sorts tables only when we have a numeric value table horizontally.

Body:
I used asorti function to sort an array where indexes are the numbers extracted from the elements. I filled the elements with leading zeros, because asorti sorts lexically not numerically. After sorting, I just print elements.

awk '{
    split($0, a, " ");

    for (i in a) {
        # extract number
        v = a[i]
        gsub(/.*#/, "", v)
        # because asorti sorts alphabetically, I fill indexes with zeros
        b[sprintf("%020d", v)] = a[i]
    }

    # sort using indexes
    n = asorti(b, dest)

    # output
    for (i = 1; i <= n; i++) {
        printf "%s%s", b[dest[i]], i == n ? "\n" : " "
    }

    # if we dont delete b, it will only grow. So delete it.
    delete b
}' <<'EOF'
flame#43    king#402    Picnic#51   Sar#360     far#66
flame#61    king#63     Picknic#67  Sar#66      far#65
flame#63    king#60     Packnic#69  Sar#64      far#58
EOF

outputs:

flame#43 Picnic#51 far#66 Sar#360 king#402
flame#61 king#63 far#65 Sar#66 Picknic#67
far#58 king#60 flame#63 Sar#64 Packnic#69

I tested on tutorialspoint. You can pipe the output to column -t -s ' ' -o ' ' to have the columnized output or do it in awk like with printf "%-9s%s".


问:
How to get a boolean variable DEBUG in a Freemarker?
How to find out if a project is in debug mode and get a variable of a logical type in the freemarker template.

Example:

```<code>    <#if (DEBUG)??>
        <script src="/static/jquery/jquery.js"></script>
    <#else>
        <script src="/static/jquery/jquery.min.js"></script>
    </#if>
</code>```

答:
I simplified the same using the equals operator:</p>

```<code><#if DEBUG == true>
    <script src="/static/jquery/jquery.js"></script>
<#else>
    <script src="/static/jquery/jquery.min.js"></script>
</#if>
</code>```

Body:
How to find out if a project is in debug mode and get a variable of a logical type in the freemarker template.

Example:

    <#if (DEBUG)??>

    <#else>

    </#if>

Body:
I simplified the same using the equals operator:

<#if DEBUG == true>
    <script src="/static/jquery/jquery.js"></script>
<#else>
    <script src="/static/jquery/jquery.min.js"></script>
</#if>


问:
Map an array in a functional component
```<code>function TypeArticleOne(props) {
let apiData = props.apiData;
const [ therapists, setTherapists ] = useState(apiData.topProfiles.therapists);
const [speciality, setSpeciality]= useState('ABA');
const [pageLoading, setPageLoading]= useState(true);

const topProfilesUrl = 'therapists/top/profiles'

useEffect(() => {
    console.log(speciality);
    getTopTherapists();
    window.scrollTo(0, 0);

}, []);

const getTopTherapists = () => {
    setPageLoading(true);
    loadTopTherapists();

};

const loadTopTherapists = () => {
    console.log("second");
    props.actions.reqGetTherapistsTopProfiles({
        body: {},
        headers: null,
        resource: `${topProfilesUrl}`
    })
};

useEffect(() => {

    if (apiData.topProfiles && apiData.topProfiles.success) {
        const therapistsLoad = apiData.topProfiles.therapists;
        setPageLoading(false);
        setTherapists([therapists].concat(therapistsLoad));
    }
    }, []);
</code>```

How to map an array in a functional component? I want to map the therapists array from the functional component above.
I call the therapists in an array from an database and I need to map them to render in a card, inside an functional component.

```<code>const renderTherapists = (props) => {
    const items = props.therapists.map( (t, idx) => (
        <TherapistCard therapist={t} key={idx} />
    ))

    return (
        <div ref={0} className="therapist-list">
            { items }
        </div>
    )
}
</code>```

答:
EDIT: You probably don't need the React Fragment as you already have a  as pointed out in the comments. Possibly the point on destructuring might still help.

ORIGINAL:

You might need to wrap the array in a React Fragment (<>{array}</>). This is required as you cannot directly return an array of components.

Also not sure what the structure of your therapist object is, but if you want to destructure it then it should be ({t, idx}) => instead of (t, idx) => (add the curly braces).

```<code>const renderTherapists = (props) => {
    const items = props.therapists.map( ({t, idx}) => (
        <TherapistCard therapist={t} key={idx} />
    ))

    return (
        <div ref={0} className="therapist-list">
            <>
               { items }
            </>
        </div>
    )
}
</code>```

This is for React 16.2.0 and later. See the blog post here: https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html

Title: Map an array in a functional component

Body:
function TypeArticleOne(props) {
let apiData = props.apiData;
const [ therapists, setTherapists ] = useState(apiData.topProfiles.therapists);
const [speciality, setSpeciality]= useState('ABA');
const [pageLoading, setPageLoading]= useState(true);

const topProfilesUrl = 'therapists/top/profiles'

useEffect(() => {
    console.log(speciality);
    getTopTherapists();
    window.scrollTo(0, 0);

}, []);

const getTopTherapists = () => {
    setPageLoading(true);
    loadTopTherapists();

};

const loadTopTherapists = () => {
    console.log("second");
    props.actions.reqGetTherapistsTopProfiles({
        body: {},
        headers: null,
        resource: `${topProfilesUrl}`
    })
};

useEffect(() => {

    if (apiData.topProfiles && apiData.topProfiles.success) {
        const therapistsLoad = apiData.topProfiles.therapists;
        setPageLoading(false);
        setTherapists([therapists].concat(therapistsLoad));
    }
    }, []);

How to map an array in a functional component? I want to map the therapists array from the functional component above.
I call the therapists in an array from an database and I need to map them to render in a card, inside an functional component.

const renderTherapists = (props) => {
    const items = props.therapists.map( (t, idx) => (
        <TherapistCard therapist={t} key={idx} />
    ))

    return (

            { items }

    )
}

Body:
EDIT: You probably don't need the React Fragment as you already have a  as pointed out in the comments. Possibly the point on destructuring might still help.

ORIGINAL:

You might need to wrap the array in a React Fragment (<>{array}</>). This is required as you cannot directly return an array of components.

Also not sure what the structure of your therapist object is, but if you want to destructure it then it should be ({t, idx}) => instead of (t, idx) => (add the curly braces).

const renderTherapists = (props) => {
    const items = props.therapists.map( ({t, idx}) => (
        <TherapistCard therapist={t} key={idx} />
    ))

    return (
        <div ref={0} className="therapist-list">
            <>
               { items }
            </>
        </div>
    )
}

This is for React 16.2.0 and later. See the blog post here: https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html


问:
StringWriter or StringBuilder
What is the difference between StringWriter and StringBuilder and when should I use one or the other?

答: A StringWriter is used to write text to a file memory and a StringBuilder is used to append strings together in a memory-efficient manner.

OwnerDisplayName: MAC

Title: StringWriter or StringBuilder

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Andrew Hare