问:
Ability to exclude one page from https redirection in nginx ingress controller
I have an app in Kubernetes which is served over https. So now I would like to exclude one URL from that rule and use HTTP to serve it for performance reasons. I am struggling with that the whole day and it seems impossible.

These are my ingress YAML:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["172.31.1.11"],"port":443,"protocol":"HTTPS","serviceName":"myservice:myservice","ingressName":"myservice:myservice","hostname":"app.server.test.mycompany.com","path":"/","allNodes":true}]'
    kubernetes.io/ingress.class: nginx
  creationTimestamp: "2020-02-17T13:14:19Z"
  generation: 1
  labels:
    app-kubernetes-io/instance: mycompany
    app-kubernetes-io/managed-by: Tiller
    app-kubernetes-io/name: mycompany
    helm.sh/chart: mycompany-1.0.0
    io.cattle.field/appId: mycompany
  name: mycompany
  namespace: mycompany
  resourceVersion: "565608"
  selfLink: /apis/extensions/v1beta1/namespaces/mycompany/ingresses/mycompany
  uid: c6b93108-a28f-4de6-a62b-487708b3f5d1
spec:
  rules:
  - host: app.server.test.mycompany.com
    http:
      paths:
      - backend:
          serviceName: mycompany
          servicePort: 80
        path: /
  tls:
  - hosts:
    - app.server.test.mycompany.com
    secretName: mycompany-tls-secret
status:
  loadBalancer:
    ingress:
    - ip: 172.31.1.11
</code>```

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["172.31.1.1"],"port":80,"protocol":"HTTP","serviceName":"mycompany:mycompany","ingressName":"mycompany:mycompany-particular-service","hostname":"app.server.test.mycompany.com","path":"/account_name/particular_service/","allNodes":true}]'
    nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
    nginx.ingress.kubernetes.io/use-regex: "true"
  creationTimestamp: "2020-02-17T13:14:19Z"
  generation: 1
  labels:
    app-kubernetes-io/instance: mycompany
    app-kubernetes-io/managed-by: Tiller
    app-kubernetes-io/name: mycompany
    helm.sh/chart: mycompany-1.0.0
    io.cattle.field/appId: mycompany
  name: mycompany-particular-service
  namespace: mycompany
  resourceVersion: "565609"
  selfLink: /apis/extensions/v1beta1/namespaces/mycompany/ingresses/mycompany-particular-service
  uid: 88127a02-e0d1-4b2f-b226-5e8d160c1654
spec:
  rules:
  - host: app.server.test.mycompany.com
    http:
      paths:
      - backend:
          serviceName: mycompany
          servicePort: 80
        path: /account_name/particular_service/
status:
  loadBalancer:
    ingress:
    - ip: 172.31.1.11
</code>```

So as you can see from above I would like to server /particular_service/ over HTTP. Ingress, however, redirects to HTTPS as TLS is enabled for that host in the first ingress.

Is there any way to disable TLS just for that one specific path when the same host is being used for configuration?

In short summary I would like to have:

```<code>https://app.server.test.mycompany.com
but
http://app.server.test.mycompany.com/account_name/particular_service/
</code>```

答:
I've tested with 2 ingress of the same domain, the first one with tls enabled and the second without tls and it worked.

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  name: echo-https
spec:
  tls:
  - hosts:
    - myapp.mydomain.com
    secretName: https-myapp.mydomain.com
  rules:
  - host: myapp.mydomain.com
    http:
      paths:
      - backend:
          serviceName: echo-svc
          servicePort: 80
        path: /
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
  name: echo-http
spec:
  rules:
  - host: myapp.mydomain.com
    http:
      paths:
      - backend:
          serviceName: echo-svc
          servicePort: 80
        path: /insecure
</code>```

By the Nginx docs:

By default the controller redirects HTTP clients to the HTTPS port 443 using a 308 Permanent Redirect response if TLS is enabled for that Ingress.

This can be disabled globally using ssl-redirect: "false" in the NGINX config map, or per-Ingress with the nginx.ingress.kubernetes.io/ssl-redirect: "false" annotation in the particular resource.

Please let me if that helps.

Body:
I have an app in Kubernetes which is served over https. So now I would like to exclude one URL from that rule and use HTTP to serve it for performance reasons. I am struggling with that the whole day and it seems impossible.

These are my ingress YAML:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["172.31.1.11"],"port":443,"protocol":"HTTPS","serviceName":"myservice:myservice","ingressName":"myservice:myservice","hostname":"app.server.test.mycompany.com","path":"/","allNodes":true}]'
    kubernetes.io/ingress.class: nginx
  creationTimestamp: "2020-02-17T13:14:19Z"
  generation: 1
  labels:
    app-kubernetes-io/instance: mycompany
    app-kubernetes-io/managed-by: Tiller
    app-kubernetes-io/name: mycompany
    helm.sh/chart: mycompany-1.0.0
    io.cattle.field/appId: mycompany
  name: mycompany
  namespace: mycompany
  resourceVersion: "565608"
  selfLink: /apis/extensions/v1beta1/namespaces/mycompany/ingresses/mycompany
  uid: c6b93108-a28f-4de6-a62b-487708b3f5d1
spec:
  rules:
  - host: app.server.test.mycompany.com
    http:
      paths:
      - backend:
          serviceName: mycompany
          servicePort: 80
        path: /
  tls:
  - hosts:
    - app.server.test.mycompany.com
    secretName: mycompany-tls-secret
status:
  loadBalancer:
    ingress:
    - ip: 172.31.1.11

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["172.31.1.1"],"port":80,"protocol":"HTTP","serviceName":"mycompany:mycompany","ingressName":"mycompany:mycompany-particular-service","hostname":"app.server.test.mycompany.com","path":"/account_name/particular_service/","allNodes":true}]'
    nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
    nginx.ingress.kubernetes.io/use-regex: "true"
  creationTimestamp: "2020-02-17T13:14:19Z"
  generation: 1
  labels:
    app-kubernetes-io/instance: mycompany
    app-kubernetes-io/managed-by: Tiller
    app-kubernetes-io/name: mycompany
    helm.sh/chart: mycompany-1.0.0
    io.cattle.field/appId: mycompany
  name: mycompany-particular-service
  namespace: mycompany
  resourceVersion: "565609"
  selfLink: /apis/extensions/v1beta1/namespaces/mycompany/ingresses/mycompany-particular-service
  uid: 88127a02-e0d1-4b2f-b226-5e8d160c1654
spec:
  rules:
  - host: app.server.test.mycompany.com
    http:
      paths:
      - backend:
          serviceName: mycompany
          servicePort: 80
        path: /account_name/particular_service/
status:
  loadBalancer:
    ingress:
    - ip: 172.31.1.11

So as you can see from above I would like to server /particular_service/ over HTTP. Ingress, however, redirects to HTTPS as TLS is enabled for that host in the first ingress.

Is there any way to disable TLS just for that one specific path when the same host is being used for configuration?

In short summary I would like to have:

https://app.server.test.mycompany.com
but
http://app.server.test.mycompany.com/account_name/particular_service/

Body:
I've tested with 2 ingress of the same domain, the first one with tls enabled and the second without tls and it worked.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  name: echo-https
spec:
  tls:
  - hosts:
    - myapp.mydomain.com
    secretName: https-myapp.mydomain.com
  rules:
  - host: myapp.mydomain.com
    http:
      paths:
      - backend:
          serviceName: echo-svc
          servicePort: 80
        path: /
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
  name: echo-http
spec:
  rules:
  - host: myapp.mydomain.com
    http:
      paths:
      - backend:
          serviceName: echo-svc
          servicePort: 80
        path: /insecure

By the Nginx docs:

By default the controller redirects HTTP clients to the HTTPS port 443 using a 308 Permanent Redirect response if TLS is enabled for that Ingress.

This can be disabled globally using ssl-redirect: "false" in the NGINX config map, or per-Ingress with the nginx.ingress.kubernetes.io/ssl-redirect: "false" annotation in the particular resource.

Please let me if that helps.


来源: stackexchange

问:
Open the most recent file in a shared folder
I would like to open the latest file in a shared folder.

I have a code to check the files in a folder of my laptop, like "Downloads" but I have to open a folder in a shared drive and then copy the info of this workbook and paste in another file.

```<code>'Force the explicit declaration of variables
Option Explicit

Sub OpenLatestFile()

    'Declare the variables
    Dim MyPath As String
    Dim MyFile As String
    Dim LatestFile As String
    Dim LatestDate As Date
    Dim LMD As Date

    'Specify the path to the folder
    MyPath = "P:\GTS\zdss\"

    'Make sure that the path ends in a backslash
    If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

    'Get the first Excel file from the folder
    MyFile = Dir(MyPath & "*.xls", vbNormal)

    'If no files were found, exit the sub
    If Len(MyFile) = 0 Then
        MsgBox "No files were found...", vbExclamation
        Exit Sub
    End If

    'Loop through each Excel file in the folder
    Do While Len(MyFile) > 0

        'Assign the date/time of the current file to a variable
        LMD = FileDateTime(MyPath & MyFile)

        'If the date/time of the current file is greater than the latest
        'recorded date, assign its filename and date/time to variables
        If LMD > LatestDate Then
            LatestFile = MyFile
            LatestDate = LMD
        End If

        'Get the next Excel file from the folder
        MyFile = Dir

    Loop

    'Open the latest file
    Workbooks.Open MyPath & LatestFile

End Sub
</code>```

答:
Here are 3 ideas. I am not sure whether one will solve your problem but maybe it could help you.

1) I have found this discussion on a forum (http://www.vbaexpress.com/forum/showthread.php?19669-Workbooks-Open-using-network-path). In my understanding, the problem seems close to your. Maybe try to use the few lines using to manage errors (begin by On Error Resume next).

2) I think you have already verified but the extension of the file is ".xls", not ".xlsx" ?

3) Doing operations on dates in VBA needs particular functions. Here, you are doing a comparison as if it is integers (LMD > LatestDate). Moreover, I am not sure that LatestDate will have a proper value, because you never define it in the beginning. I suggest to change the code in this way. First define LatestDate before the While statement with an arbitrary low value (so, you are sure that the variable has a value and the If LMD > LatestDate statement will work properly).

```<code>LatestDate = Format("01.01.1900", "dd.mm.yyyy")
</code>```

Second, change the If LMD > LatestDate statement :

```<code>If DateDiff("d",LatestDate,LMD) > 0 Then
</code>```

Of course, you need to change the parameter "d" (for day) in case you want a comparison in other unit.

Cheers.

ContentLicense: CC BY-SA 4.0

Body:
I would like to open the latest file in a shared folder.

I have a code to check the files in a folder of my laptop, like "Downloads" but I have to open a folder in a shared drive and then copy the info of this workbook and paste in another file.

'Force the explicit declaration of variables
Option Explicit

Sub OpenLatestFile()

    'Declare the variables
    Dim MyPath As String
    Dim MyFile As String
    Dim LatestFile As String
    Dim LatestDate As Date
    Dim LMD As Date

    'Specify the path to the folder
    MyPath = "P:\GTS\zdss\"

    'Make sure that the path ends in a backslash
    If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

    'Get the first Excel file from the folder
    MyFile = Dir(MyPath & "*.xls", vbNormal)

    'If no files were found, exit the sub
    If Len(MyFile) = 0 Then
        MsgBox "No files were found...", vbExclamation
        Exit Sub
    End If

    'Loop through each Excel file in the folder
    Do While Len(MyFile) > 0

        'Assign the date/time of the current file to a variable
        LMD = FileDateTime(MyPath & MyFile)

        'If the date/time of the current file is greater than the latest
        'recorded date, assign its filename and date/time to variables
        If LMD > LatestDate Then
            LatestFile = MyFile
            LatestDate = LMD
        End If

        'Get the next Excel file from the folder
        MyFile = Dir

    Loop

    'Open the latest file
    Workbooks.Open MyPath & LatestFile

End Sub

Body:
Here are 3 ideas. I am not sure whether one will solve your problem but maybe it could help you.

1) I have found this discussion on a forum (http://www.vbaexpress.com/forum/showthread.php?19669-Workbooks-Open-using-network-path). In my understanding, the problem seems close to your. Maybe try to use the few lines using to manage errors (begin by On Error Resume next).

2) I think you have already verified but the extension of the file is ".xls", not ".xlsx" ?

3) Doing operations on dates in VBA needs particular functions. Here, you are doing a comparison as if it is integers (LMD > LatestDate). Moreover, I am not sure that LatestDate will have a proper value, because you never define it in the beginning. I suggest to change the code in this way. First define LatestDate before the While statement with an arbitrary low value (so, you are sure that the variable has a value and the If LMD > LatestDate statement will work properly).

LatestDate = Format("01.01.1900", "dd.mm.yyyy")

Second, change the If LMD > LatestDate statement :

If DateDiff("d",LatestDate,LMD) > 0 Then

Of course, you need to change the parameter "d" (for day) in case you want a comparison in other unit.

Cheers.


问:
Add column names of a dataframe or from an R object to another dataframe
I'm currently working with a huge count matrix issued of single cell sequencing ...

So, in order to analyze them with R and my 8 Gb of RAM, I had to split it in several sub-matrices.

I simply used split in order to do that so I loose the heathers of the matrix.

So, I would like to add them back with R or find a better way to split them more efficiently.

My questions are:

1.  If a have an object called heathers with all the column names stocked inside, is there a way to efficiently add this object to a dataframe? I tried rbind but it doesn't really solve the problem.

2. Is there a better way to cut those huge count matrices into multiple parts? (I can't do it through R because I don't have enough RAM, R crashes if I try to import the whole matrix)

答:
You can access and mutate a data.frames column names with the names function:

```<code>df <- data.frame(foo = 1:5, bar = 6:10, opt = 11:15)

original_names <- names(df)

original_names
</code>```

Returns:

```<code>[1] "foo" "bar" "opt"
</code>```

And to assign new names:

```<code>names(df) <- c("new_col1", "new_col2", "new_col3")
</code>```

Now:

```<code>df
</code>```

Returns:

```<code>  new_col1 new_col2 new_col3
1        1        6       11
2        2        7       12
3        3        8       13
4        4        9       14
5        5       10       15
</code>```

And to 'undo' the renaming:

```<code>names(df) <- original_names
</code>```

And df has again its original names:

```<code>  foo bar opt
1   1   6  11
2   2   7  12
3   3   8  13
4   4   9  14
5   5  10  15
</code>```

Body:
You can access and mutate a data.frames column names with the names function:

df <- data.frame(foo = 1:5, bar = 6:10, opt = 11:15)

original_names <- names(df)

original_names

Returns:

[1] "foo" "bar" "opt"

And to assign new names:

names(df) <- c("new_col1", "new_col2", "new_col3")

Now:

df

Returns:

  new_col1 new_col2 new_col3
1        1        6       11
2        2        7       12
3        3        8       13
4        4        9       14
5        5       10       15

And to 'undo' the renaming:

names(df) <- original_names

And df has again its original names:

  foo bar opt
1   1   6  11
2   2   7  12
3   3   8  13
4   4   9  14
5   5  10  15


问:
Making transitionX animation with frame by frame animation cause lags
I have an ImageView. When user presses a button I want my view to set an image from R.drawable(every time image is different) and then do translationX animation with frame-by-frame animation. For this purpose, I use ObjectAnimtor.OfFloat(..."translationX"...) and in doOnStart I call AnimationDrawable.start() on my image( I set animation-list there). Actually, on doOnEnd I put in my View another image (animation-list) and start another animation. After that, I make my image invisible and return it to the start point using translationX. Testing it on real device and on emulator causes lags at the start of the animation and in the moment when I change image. I have no idea how to fix it.

```<code>view.setImageResource(
            this.resources.getIdentifier(
                "${spellCasted}_anim",
                "drawable", context!!.packageName
            )
        )
        val x1 = startXposition
        val x2 = firstXdestination
        val frameAnimation = view.drawable as AnimationDrawable
        ObjectAnimator.ofFloat(
                view,
                "translationX",
                x1.toFloat(),
                x2.toFloat()
            ).apply {
                duration = 900
                interpolator = LinearInterpolator()
                doOnStart {
                    view.visibility = View.VISIBLE
                    frameAnimation.start()
                }
                doOnEnd {
                    if (hasPost(splitSpell)) { //hasPost(..) check is there additional image to translate from x2 to x2 + 20
                        frameAnimation.stop()
                        view.setImageResource(
                            context!!.resources.getIdentifier(
                                "${spellCasted}stop_anim",
                                "drawable", context!!.packageName
                            )
                        )
                        ObjectAnimator.ofFloat(
                                view, "translationX",
                                x2.toFloat(),
                                x2.toFloat() +  20f
                            )
                                .apply {
                                    duration = 1200
                                    interpolator = LinearInterpolator()
                                    doOnStart {
                                        val frameAnimationStop =
                                            view.drawable as AnimationDrawable
                                        frameAnimationStop.start()
                                    }
                                    doOnEnd {
                                        setDefault(view, x1, isEnemy) //returns view to startPos
                                    }
                                    start()
                                }
                    } else {
                        setDefault(view, x1, isEnemy)//returns view to startPos
                    }
                }
                start()
            }
</code>```

答:
If you look at the javadoc for imageView.setImageResource, you'll see it says it will cause a latency hiccup because it loads the image on the UI thread.

I think you can fix this by pre-loading your next drawable in the background. I haven't tried this because I don't work with animation drawables, so sorry in advance if it doesn't cure the hiccups.

Coroutines will make this a lot easier to set up and keep orderly. You can start by creating a function that eliminates the need for nested Animator callbacks:

```<code>suspend fun Animator.runToCompletion(): Unit = suspendCoroutine { cont ->
    doOnEnd { cont.resume(Unit) }
    start()
}
</code>```

Then when you start the animation, you can start loading the next drawable in the background, and hopefully it will be ready by the time you need to show it:

```<code>val cxt = requireContext() // one source of failure if context is null

lifecycleScope.launch {

    // Start loading the second animation in a background thread
    val spellStopAnimationJob: Deferred<AnimationDrawable> = async(Dispatchers.Default) {
        cxt.getDrawable(ctx.resources.getIdentifier(
            "${spellCasted}stop_anim",
            "drawable", ctx.packageName
        ) as AnimationDrawable
    }

    view.setImageResource(
       resources.getIdentifier(
                "${spellCasted}_anim",
                "drawable", cxt.packageName
            )
    )
    val x1 = startXposition
    val x2 = firstXdestination
    val initialAnimation = view.drawable as AnimationDrawable
        .apply { start() }
    view.visibility = View.VISIBLE
    ObjectAnimator.ofFloat(
        view,
        "translationX",
        x1.toFloat(),
        x2.toFloat()
    ).apply {
        duration = 900L
        interpolator = LinearInterpolator()
    }.runToCompletion()

    if (hasPost(splitSpell)) { //hasPost(..) check is there additional image to translate from x2 to x2 + 20
        initialAnimation.stop()

        // Wait for the animation to be loaded (hopefully it's already done so no hiccup)
        val stopAnimation = spellStopAnimationJob.await()
            .apply { start() }
        view.setImageDrawable(stopAnimation)
        ObjectAnimator.ofFloat(
            view, "translationX",
            x2.toFloat(),
            x2.toFloat() + 20f
        ).apply {
            duration = 1200
            interpolator = LinearInterpolator()
        }.runToCompletion()
    }

    setDefault(view, x1, isEnemy)//returns view to startPos
}
</code>```

By the way that line x2.toFloat() + 20f is going to mess you up when you run this on different devices, since you're hard-coding an offset in pixels instead of DIP units. You should specify the number in DIP units and multiply by resources.displayMetrics.density to convert it to pixel units.

Body:
I have an ImageView. When user presses a button I want my view to set an image from R.drawable(every time image is different) and then do translationX animation with frame-by-frame animation. For this purpose, I use ObjectAnimtor.OfFloat(..."translationX"...) and in doOnStart I call AnimationDrawable.start() on my image( I set animation-list there). Actually, on doOnEnd I put in my View another image (animation-list) and start another animation. After that, I make my image invisible and return it to the start point using translationX. Testing it on real device and on emulator causes lags at the start of the animation and in the moment when I change image. I have no idea how to fix it.

view.setImageResource(
            this.resources.getIdentifier(
                "${spellCasted}_anim",
                "drawable", context!!.packageName
            )
        )
        val x1 = startXposition
        val x2 = firstXdestination
        val frameAnimation = view.drawable as AnimationDrawable
        ObjectAnimator.ofFloat(
                view,
                "translationX",
                x1.toFloat(),
                x2.toFloat()
            ).apply {
                duration = 900
                interpolator = LinearInterpolator()
                doOnStart {
                    view.visibility = View.VISIBLE
                    frameAnimation.start()
                }
                doOnEnd {
                    if (hasPost(splitSpell)) { //hasPost(..) check is there additional image to translate from x2 to x2 + 20
                        frameAnimation.stop()
                        view.setImageResource(
                            context!!.resources.getIdentifier(
                                "${spellCasted}stop_anim",
                                "drawable", context!!.packageName
                            )
                        )
                        ObjectAnimator.ofFloat(
                                view, "translationX",
                                x2.toFloat(),
                                x2.toFloat() +  20f
                            )
                                .apply {
                                    duration = 1200
                                    interpolator = LinearInterpolator()
                                    doOnStart {
                                        val frameAnimationStop =
                                            view.drawable as AnimationDrawable
                                        frameAnimationStop.start()
                                    }
                                    doOnEnd {
                                        setDefault(view, x1, isEnemy) //returns view to startPos
                                    }
                                    start()
                                }
                    } else {
                        setDefault(view, x1, isEnemy)//returns view to startPos
                    }
                }
                start()
            }

Body:
If you look at the javadoc for imageView.setImageResource, you'll see it says it will cause a latency hiccup because it loads the image on the UI thread.

I think you can fix this by pre-loading your next drawable in the background. I haven't tried this because I don't work with animation drawables, so sorry in advance if it doesn't cure the hiccups.

Coroutines will make this a lot easier to set up and keep orderly. You can start by creating a function that eliminates the need for nested Animator callbacks:

suspend fun Animator.runToCompletion(): Unit = suspendCoroutine { cont ->
    doOnEnd { cont.resume(Unit) }
    start()
}

Then when you start the animation, you can start loading the next drawable in the background, and hopefully it will be ready by the time you need to show it:

val cxt = requireContext() // one source of failure if context is null

lifecycleScope.launch {

    // Start loading the second animation in a background thread
    val spellStopAnimationJob: Deferred<AnimationDrawable> = async(Dispatchers.Default) {
        cxt.getDrawable(ctx.resources.getIdentifier(
            "${spellCasted}stop_anim",
            "drawable", ctx.packageName
        ) as AnimationDrawable
    }

    view.setImageResource(
       resources.getIdentifier(
                "${spellCasted}_anim",
                "drawable", cxt.packageName
            )
    )
    val x1 = startXposition
    val x2 = firstXdestination
    val initialAnimation = view.drawable as AnimationDrawable
        .apply { start() }
    view.visibility = View.VISIBLE
    ObjectAnimator.ofFloat(
        view,
        "translationX",
        x1.toFloat(),
        x2.toFloat()
    ).apply {
        duration = 900L
        interpolator = LinearInterpolator()
    }.runToCompletion()

    if (hasPost(splitSpell)) { //hasPost(..) check is there additional image to translate from x2 to x2 + 20
        initialAnimation.stop()

        // Wait for the animation to be loaded (hopefully it's already done so no hiccup)
        val stopAnimation = spellStopAnimationJob.await()
            .apply { start() }
        view.setImageDrawable(stopAnimation)
        ObjectAnimator.ofFloat(
            view, "translationX",
            x2.toFloat(),
            x2.toFloat() + 20f
        ).apply {
            duration = 1200
            interpolator = LinearInterpolator()
        }.runToCompletion()
    }

    setDefault(view, x1, isEnemy)//returns view to startPos
}

By the way that line x2.toFloat() + 20f is going to mess you up when you run this on different devices, since you're hard-coding an offset in pixels instead of DIP units. You should specify the number in DIP units and multiply by resources.displayMetrics.density to convert it to pixel units.


问:
Detecting length of overlap between two strings
```<code>int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}
</code>```

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

```<code>abcdefg
1234efg
</code>```

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?

答:
Assuming that you want an overlap at the same index in each string, as in your example:

```<code>int overlap(const char *s1, const char *s2){
    int length = 0;
    int i = 0;
    while (s1[i] && s2[i] && s1[i] != s2[i])
        i++;
    while (s1[i] && s2[i] && s1[i] == s2[i]) {
        i++;
        length++;
    }
    return length;
}
</code>```

will do the trick, although it's not very elegant.  It will find the length of the first overlap at the same offset.

So for abcdefgh90 and 1234efg890 it will return 3.

If you want the total number of matching characters then try:

```<code>int overlap(const char *s1, const char *s2){
    int length = 0;
    int i = 0;
    while (s1[i] && s2[i]) {
        if (s1[i] == s2[i]) {
            length++;
        }
        i++;
    }
    return length;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

abcdefg
1234efg

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?

Body:
Assuming that you want an overlap at the same index in each string, as in your example:

int overlap(const char *s1, const char *s2){
    int length = 0;
    int i = 0;
    while (s1[i] && s2[i] && s1[i] != s2[i])
        i++;
    while (s1[i] && s2[i] && s1[i] == s2[i]) {
        i++;
        length++;
    }
    return length;
}

will do the trick, although it's not very elegant.  It will find the length of the first overlap at the same offset.

So for abcdefgh90 and 1234efg890 it will return 3.

If you want the total number of matching characters then try:

int overlap(const char *s1, const char *s2){
    int length = 0;
    int i = 0;
    while (s1[i] && s2[i]) {
        if (s1[i] == s2[i]) {
            length++;
        }
        i++;
    }
    return length;
}


问:
Gensim Mallet: Output does not have terms for few topics
Below is the output that I get using Gensim Mallet wrapper. From this SO link I understood that LL/token means "model's log-liklihood divided by the total number of tokens". 1) However, for few topics like (1,8,11 etc.) I do not see any terms at all. 2) I tried to run the code for a range of topics from (10,20,2) (step of 2 starting from 10-20). But the output shows 17 as the last topic generated. I am missing something here..

```<code>0       2.77778 watch
1       2.77778
2       2.77778 receive tape hope purchase
3       2.77778 dvds wildlife pass yr interested
4       2.77778 dvd version walk bored
5       2.77778 volume courtyard trilogy
6       2.77778 crazy picture minute
7       2.77778 neighbor
8       2.77778
9       2.77778 buy mice trouble stay versus feeder
10      2.77778 inside stir tv mine life bird wonderful year fascinated
11      2.77778
12      2.77778
13      2.77778 recommend test real prefer greenery
14      2.77778 age
15      2.77778 funny triliogy play friend full minute
16      2.77778
17      2.77778 time tree

<950> LL/token: -22.17456
<960> LL/token: -22.22132
<970> LL/token: -22.24897
<980> LL/token: -22.11585
<990> LL/token: -22.38062
</code>```

答: This looks like the output you get when the input collection is much too small, or is divided into too few segments. "Documents" should be about 100-500 words, and there should be at least several hundred of them.</p>

Body:
Below is the output that I get using Gensim Mallet wrapper. From this SO link I understood that LL/token means "model's log-liklihood divided by the total number of tokens". 1) However, for few topics like (1,8,11 etc.) I do not see any terms at all. 2) I tried to run the code for a range of topics from (10,20,2) (step of 2 starting from 10-20). But the output shows 17 as the last topic generated. I am missing something here..

0       2.77778 watch
1       2.77778
2       2.77778 receive tape hope purchase
3       2.77778 dvds wildlife pass yr interested
4       2.77778 dvd version walk bored
5       2.77778 volume courtyard trilogy
6       2.77778 crazy picture minute
7       2.77778 neighbor
8       2.77778
9       2.77778 buy mice trouble stay versus feeder
10      2.77778 inside stir tv mine life bird wonderful year fascinated
11      2.77778
12      2.77778
13      2.77778 recommend test real prefer greenery
14      2.77778 age
15      2.77778 funny triliogy play friend full minute
16      2.77778
17      2.77778 time tree

<950> LL/token: -22.17456
<960> LL/token: -22.22132
<970> LL/token: -22.24897
<980> LL/token: -22.11585
<990> LL/token: -22.38062


问:
Undefined variable in view page laravel
Im getting error in laravel undefined variable all is good but won't know why its coming...
controller

view
 error

```<code>public function login(Request $req)
    {

        $user = users::where([

            ["email", "=", $req->email],
            ["password", "=", $req->password]

        ])->first();

        if (isset($user)) {

            $req->session()->put("log", $req->input());

            return redirect("/userlist");
        } else {
            $b="user not found";

            return view("login", compact("b"));
        }
</code>```

答:
You may fix it by defining $b variable inside your controller method

```<code>public function myLoginFunction() {
//...
$b = ...;
return view('viewName', ['b' => $b]);
}
</code>```

Edit

```<code>public function login(Request $req) {

    $user = users::where([

        ["email", "=", $req->email],
        ["password", "=", $req->password]

    ])->first();

    if (isset($user)) {

        $req->session()->put("log", $req->input());

        return redirect("/userlist");
    } else {

        return view("login");
    }
}
</code>```

App\Providers\AppServiceProvider

```<code>//...
public function boot()
{

    View::composer('login', function ($view) {
        $view->with('b', "user not found");
    });
}
</code>```

Title: Undefined variable in view page laravel

Body:
Im getting error in laravel undefined variable all is good but won't know why its coming...
controller

view
 error

public function login(Request $req)
    {

        $user = users::where([

            ["email", "=", $req->email],
            ["password", "=", $req->password]

        ])->first();

        if (isset($user)) {

            $req->session()->put("log", $req->input());

            return redirect("/userlist");
        } else {
            $b="user not found";

            return view("login", compact("b"));
        }

Body:
You may fix it by defining $b variable inside your controller method

public function myLoginFunction() {
//...
$b = ...;
return view('viewName', ['b' => $b]);
}

Edit

public function login(Request $req) {

    $user = users::where([

        ["email", "=", $req->email],
        ["password", "=", $req->password]

    ])->first();

    if (isset($user)) {

        $req->session()->put("log", $req->input());

        return redirect("/userlist");
    } else {

        return view("login");
    }
}

App\Providers\AppServiceProvider

//...
public function boot()
{

    View::composer('login', function ($view) {
        $view->with('b', "user not found");
    });
}


问:
cannot use import statement for scss files with typescript
I have added these declarations to an index.d.ts files:

```<code>declare module '*.module.scss' {
  const classes: { [key: string]: string };
  export default classes;
}
</code>```

But when I try and import a default import like this:

```<code>import styles from './Application.module.scss';
</code>```

I get this error:

Cannot find module './Application.module.scss'.ts

答:
In order to use SCSS modules in TypeScript, you will need style-loader, typings-for-css-modules-loader and sass-loader.

Use the following .scss rule in your webpack.config.js:

```<code>{
    test: /\.scss$/,
    include: [
        path.resolve(__dirname, "src/raw")
    ],
    use: [
        { loader: "style-loader" },
        {
            loader: "typings-for-css-modules-loader",
            options: {
                namedexport: true,
                camelcase: true,
                modules: true
            }
        },
        { loader: "sass-loader" }
    ]
}
</code>```

Body:
I have added these declarations to an index.d.ts files:

declare module '*.module.scss' {
  const classes: { [key: string]: string };
  export default classes;
}

But when I try and import a default import like this:

import styles from './Application.module.scss';

I get this error:

Cannot find module './Application.module.scss'.ts

Body:
In order to use SCSS modules in TypeScript, you will need style-loader, typings-for-css-modules-loader and sass-loader.

Use the following .scss rule in your webpack.config.js:

{
    test: /\.scss$/,
    include: [
        path.resolve(__dirname, "src/raw")
    ],
    use: [
        { loader: "style-loader" },
        {
            loader: "typings-for-css-modules-loader",
            options: {
                namedexport: true,
                camelcase: true,
                modules: true
            }
        },
        { loader: "sass-loader" }
    ]
}


答:
If a have an object called heathers with all the column names stocked inside, is there a way to efficiently add this object to a dataframe? I tried rbind but it doesn't really solve the problem.

You can add headers to a dataframe like this:

```<code>dataframe <- data.frame(c("a", "b","c"),
                        c("d", "e", "f"))

headers <- c("header_1" , "header_2")

names(dataframe) <- headers

dataframe

  header_1 header_2
1        a        d
2        b        e
3        c        f

</code>```

You could use bash for such tasks.

Title: Add column names of a dataframe or from an R object to another dataframe

Body:
I'm currently working with a huge count matrix issued of single cell sequencing ...

So, in order to analyze them with R and my 8 Gb of RAM, I had to split it in several sub-matrices.

I simply used split in order to do that so I loose the heathers of the matrix.

So, I would like to add them back with R or find a better way to split them more efficiently.

My questions are:

1.  If a have an object called heathers with all the column names stocked inside, is there a way to efficiently add this object to a dataframe? I tried rbind but it doesn't really solve the problem.

2. Is there a better way to cut those huge count matrices into multiple parts? (I can't do it through R because I don't have enough RAM, R crashes if I try to import the whole matrix)

Body:
If a have an object called heathers with all the column names stocked inside, is there a way to efficiently add this object to a dataframe? I tried rbind but it doesn't really solve the problem.

You can add headers to a dataframe like this:

dataframe <- data.frame(c("a", "b","c"),
                        c("d", "e", "f"))

headers <- c("header_1" , "header_2")

names(dataframe) <- headers

dataframe

  header_1 header_2
1        a        d
2        b        e
3        c        f

You could use bash for such tasks.


问:
How to rename files, removing all characters between certain values
I have a list of 15.000 documents where I need to remove a certain piece of text from the name.

The name structure is always: [xxx]_(xxx)_xxx.extension

I am trying to remove the (xxx)_ part of the filename. The length of xxx is variable.

I've only found ways to replace certain pieces of text or remove fixed pieces of text. Any help or guidelines are appreciated.

答:
If you want to trim multiple file names, you can try this using PowerShell.
1. Navigate to the directory where the files to rename are.
2. Excecute the following command.

```<code>dir | Rename-Item -NewName {$_.name.substring(0,$_.BaseName.length-N) + $_.Extension}
</code>```

where N in "length-N" is the number of characters you want to trim, from the last one, without counting the extension file.

Example:

I restored my files after a backup in Windows 10 and every document appeared with some extra characters, showing the day and time when I made the back up.

being FileName (2020_02_13 12_33_22 UTC).extension, I needed to trim everything between the parenthesis and take FileName.extension

So I have to trim 26 characters in every filename. Then N = 26

1) I open PowerShell and navigate to the folder where I will excecute the script.
2) I excecute the following script

```<code>dir | Rename-Item -NewName {$_.name.substring(0,$_.BaseName.length-26) + $_.Extension}
</code>```

Take care using this command, because it doesn't follow any parameters except to trim a given number of characters.

Body:
If you want to trim multiple file names, you can try this using PowerShell.
1. Navigate to the directory where the files to rename are.
2. Excecute the following command.

dir | Rename-Item -NewName {$_.name.substring(0,$_.BaseName.length-N) + $_.Extension}

where N in "length-N" is the number of characters you want to trim, from the last one, without counting the extension file.

Example:

I restored my files after a backup in Windows 10 and every document appeared with some extra characters, showing the day and time when I made the back up.

being FileName (2020_02_13 12_33_22 UTC).extension, I needed to trim everything between the parenthesis and take FileName.extension

So I have to trim 26 characters in every filename. Then N = 26

1) I open PowerShell and navigate to the folder where I will excecute the script.
2) I excecute the following script

dir | Rename-Item -NewName {$_.name.substring(0,$_.BaseName.length-26) + $_.Extension}

Take care using this command, because it doesn't follow any parameters except to trim a given number of characters.


问:
C++ invalid initialization of reference of type 'const std ::?
I'm trying to developp some c++ functions in order to reuse them within my R project.

```<code>#include <Rcpp.h>

using namespace Rcpp;

double scalar_product(std::vector<double> const& a, std::vector<double> const& b)
{
  if (a.size() != b.size()) { throw std::runtime_error("different sizes"); }

  return std::inner_product(a.begin(), a.end(), b.begin(), 0.0);
} // scalar_product

double hashC(double x, double y) {

double  ys = scalar_product(x , y);

    if (ys > 0) {
      return 1;
    } else if (ys == 0) {
      return 0;
    } else {
      return 0;
    }

}

/*** R
x=c(1,2,3,4)
  y=c(-1,-2,-3,-5)
  d=hashC(x,y)
  print("d")
  print(d)
  */
</code>```

I got an error : invalid initialization of reference of type 'const std :: ......

The error is shown within that line :

```<code> double  ys = scalar_product(x , y);
</code>```

Sorry but i'm not good at c++.

答: The arguments of scalar_product are both of type std::vector<double> const&, you are passing double type variables, the variables passed as argument must be of compatible type.

Body:
I'm trying to developp some c++ functions in order to reuse them within my R project.

#include <Rcpp.h>

using namespace Rcpp;

double scalar_product(std::vector<double> const& a, std::vector<double> const& b)
{
  if (a.size() != b.size()) { throw std::runtime_error("different sizes"); }

  return std::inner_product(a.begin(), a.end(), b.begin(), 0.0);
} // scalar_product

double hashC(double x, double y) {

double  ys = scalar_product(x , y);

    if (ys > 0) {
      return 1;
    } else if (ys == 0) {
      return 0;
    } else {
      return 0;
    }

}

/*** R
x=c(1,2,3,4)
  y=c(-1,-2,-3,-5)
  d=hashC(x,y)
  print("d")
  print(d)
  */

I got an error : invalid initialization of reference of type 'const std :: ......

The error is shown within that line :

 double  ys = scalar_product(x , y);

Sorry but i'm not good at c++.


问:
Best Logic to Print Prime Numbers with SQL query
What is the most efficient way to get prime numbers from 2 to 1000 via SQL in MongoDB/MySQL/CockroachDB?

My query in Oracle:

```<code>WITH NUM AS (
    SELECT LEVEL N
    FROM DUAL CONNECT BY LEVEL <= 1000
)
SELECT LISTAGG(B.N,'-') WITHIN GROUP(ORDER BY B.N) AS PRIMES
FROM (
    SELECT  N,
            CASE WHEN EXISTS (
                                SELECT NULL
                                FROM NUM N_INNER
                                WHERE N_INNER .N > 1
                                AND N_INNER.N < NUM.N
                                AND MOD(NUM.N, N_INNER.N)=0
                            ) THEN
                'NO PRIME'
            ELSE
                'PRIME'
            END IS_PRIME
        FROM NUM
    ) B
WHERE B.IS_PRIME='PRIME'
AND B.N!=1;
</code>```

答:
This worked in SQL Server. I reduce the order of nested loops.</p>
```<code>declare @var int
declare @i int
declare @result varchar (max)
set @var = 1
select @result = '2&3&5' --first few obvious prime numbers
while @var < 1000  --the first loop
begin
set @i = 3;
while @i <= @var/2  --the second loop which I attempted to reduce the order
begin
if @var%@i = 0
break;
if @i=@var/2
begin
set @result = @result + '&' + CAST(@var AS VARCHAR)
break;
end
else
set @i = @i + 1
end
set @var = @var + 1;
end
print @result
</code>```

Body:
What is the most efficient way to get prime numbers from 2 to 1000 via SQL in MongoDB/MySQL/CockroachDB?

My query in Oracle:

WITH NUM AS (
    SELECT LEVEL N
    FROM DUAL CONNECT BY LEVEL <= 1000
)
SELECT LISTAGG(B.N,'-') WITHIN GROUP(ORDER BY B.N) AS PRIMES
FROM (
    SELECT  N,
            CASE WHEN EXISTS (
                                SELECT NULL
                                FROM NUM N_INNER
                                WHERE N_INNER .N > 1
                                AND N_INNER.N < NUM.N
                                AND MOD(NUM.N, N_INNER.N)=0
                            ) THEN
                'NO PRIME'
            ELSE
                'PRIME'
            END IS_PRIME
        FROM NUM
    ) B
WHERE B.IS_PRIME='PRIME'
AND B.N!=1;

Body:
This worked in SQL Server. I reduce the order of nested loops.

declare @var int
declare @i int
declare @result varchar (max)
set @var = 1
select @result = '2&3&5' --first few obvious prime numbers
while @var < 1000  --the first loop
begin
set @i = 3;
while @i <= @var/2  --the second loop which I attempted to reduce the order
begin
if @var%@i = 0
break;
if @i=@var/2
begin
set @result = @result + '&' + CAST(@var AS VARCHAR)
break;
end
else
set @i = @i + 1
end
set @var = @var + 1;
end
print @result


问:
How can I disable shadowOffset scaling in KonvaJS?
I am using strokeScaleEnabled=false to disable stroke width scaling. However shadow offset is still scaling when I scale stage. I see no "shadowOffsetScaleEnabled" property to disable shadow offset scaling.

Is there any other API or I must re-calculate shadowOffset values based on stage scale?

答:
Currently with konva@4.1.5 there is no API for disabling shadow offset scaling.

So you have to reset it manually. With something like:

const OFFSET = 5;

shape.shadowOffsetX(OFFSET / stage.scaleX());
shape.shadowOffsetY(OFFSET / stage.scaleY());
```

Demo: https://jsbin.com/bikiwedero/1/edit?js,output

Body:
Currently with konva@4.1.5 there is no API for disabling shadow offset scaling.

So you have to reset it manually. With something like:

const OFFSET = 5;

shape.shadowOffsetX(OFFSET / stage.scaleX());
shape.shadowOffsetY(OFFSET / stage.scaleY());

Demo: https://jsbin.com/bikiwedero/1/edit?js,output


问:
which is a better approach for fibonacci series generation
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

```<code>#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}
</code>```

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

答:
Disadvantages I can immediately see:

By essentially making the state global, it's not thread-safe

You can only ever run through the sequence once, as there's no way to reset

I would favour an approach which keeps the state within an object which you can ask for the next value of - an iterator, basically. (I've never been certain how easily the Fibonacci sequence maps to C++ iterators; it works fine with C# and Java IEnumerable<T> and Iterable<T> though.)

Body:
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?


问:
Matching string from one file to another file and append the values
I have two text files with 350 m+ rows. Content of two text files are as follows:

```<code>file1:
>15_48499991_ENSG00000074803_C_G_G
CCAATCGCTTTCAAGTTAGTGTG
>15_48499991_ENSG00000074803_C_G_G
CAATCGCTTTCAAGTTAGTGTGA
>15_48499991_ENSG00000074803_C_G_G
AATCGCTTTCAAGTTAGTGTGAT

</code>```

```<code>file2:
CCAATCGCTTTCAAGTTAGTGTG -14.48
CAATCGCTTTCAAGTTAGTGTGA -29.94
AATCGCTTTCAAGTTAGTGTGAT -20.58

</code>```

I would like to match the value of column 1 of file 2 and the string in file1 and append the value after > of file1 with file2 whenever there is a match.

The desired output is:

```<code>15_48499991_ENSG00000074803_C_G_G    CCAATCGCTTTCAAGTTAGTGTG    -14.48
15_48499991_ENSG00000074803_C_G_G    CAATCGCTTTCAAGTTAGTGTGA    -29.94
15_48499991_ENSG00000074803_C_G_G    AATCGCTTTCAAGTTAGTGTGAT    -20.58
</code>```

Any suggestions would be helpful here.

Thanks

答:
using bash/ join, assuming the delimiter in file2 is a tab

```<code>join -t $'\t' -1 2 -2 1 \
          <(cat file1 | paste - - | sort -t $'\t' -k2,2) \
          <(sort -t $'\t' -k1,1 file2)
</code>```

Body:
I have two text files with 350 m+ rows. Content of two text files are as follows:

file1:
>15_48499991_ENSG00000074803_C_G_G
CCAATCGCTTTCAAGTTAGTGTG
>15_48499991_ENSG00000074803_C_G_G
CAATCGCTTTCAAGTTAGTGTGA
>15_48499991_ENSG00000074803_C_G_G
AATCGCTTTCAAGTTAGTGTGAT

file2:
CCAATCGCTTTCAAGTTAGTGTG -14.48
CAATCGCTTTCAAGTTAGTGTGA -29.94
AATCGCTTTCAAGTTAGTGTGAT -20.58

I would like to match the value of column 1 of file 2 and the string in file1 and append the value after > of file1 with file2 whenever there is a match.

The desired output is:

15_48499991_ENSG00000074803_C_G_G    CCAATCGCTTTCAAGTTAGTGTG    -14.48
15_48499991_ENSG00000074803_C_G_G    CAATCGCTTTCAAGTTAGTGTGA    -29.94
15_48499991_ENSG00000074803_C_G_G    AATCGCTTTCAAGTTAGTGTGAT    -20.58

Any suggestions would be helpful here.

Thanks

Body:
using bash/ join, assuming the delimiter in file2 is a tab

join -t $'\t' -1 2 -2 1 \
          <(cat file1 | paste - - | sort -t $'\t' -k2,2) \
          <(sort -t $'\t' -k1,1 file2)


问:
Converting text range to single integer
if I had a set of data containing the following:

```<code>0-3
0-3
0-3
2-6
2-6
2-6
2-6
2-6
1-3
</code>```

How would I covert this into a single number, say the upper value, or even better the average of the two numbers either side of the hyphen?

Any help would be much appreciated!

答:
Another base R solution

```<code>sapply(strsplit(dat,"-"),function(v) mean(as.numeric(v)))
</code>```

or

```<code>rowMeans(`class<-`(do.call(rbind,strsplit(dat,"-")),"numeric"))
</code>```

such that

```<code># [1] 1.5 4.0 2.0
</code>```

DATA

```<code>dat <- c("0-3", "2-6", "1-3")
</code>```

Title: Converting text range to single integer

Body:
if I had a set of data containing the following:

0-3
0-3
0-3
2-6
2-6
2-6
2-6
2-6
1-3

How would I covert this into a single number, say the upper value, or even better the average of the two numbers either side of the hyphen?

Any help would be much appreciated!

Body:
Another base R solution

sapply(strsplit(dat,"-"),function(v) mean(as.numeric(v)))

or

rowMeans(`class<-`(do.call(rbind,strsplit(dat,"-")),"numeric"))

such that

# [1] 1.5 4.0 2.0

DATA

dat <- c("0-3", "2-6", "1-3")


问:
How to add spaces between different tags
I have some code that looks like this

```<code><div class="topnav">
  <div>{{getGameView.Game.gameplayers[0].player.username}}</div>
  <p>VS</p>
  <div v-if="getGameView.Game.gameplayers.length > 1">
　  {{getGameView.Game.gameplayers[1].player.username}}
　</div>
  <div v-else>Waiting for opponent...</div>
</div>
</code>```

Which prints this: NameVSName
I am trying to make it so that between Name and VS there is some space but cannot figure out how to do it.

答:
You can insert a space in html with  .

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    nameA: "Job",
    nameB: "Bob"
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ nameA }} Vs {{ nameB }}
</div></code>```

How to insert spaces/tabs in text using HTML/CSS

Body:
I have some code that looks like this

{{getGameView.Game.gameplayers[0].player.username}}

VS

 1">
　  {{getGameView.Game.gameplayers[1].player.username}}

Waiting for opponent...

Which prints this: NameVSName
I am trying to make it so that between Name and VS there is some space but cannot figure out how to do it.

Body:
You can insert a space in html with &nbsp;.

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    nameA: "Job",
    nameB: "Bob"
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ nameA }}&nbsp;Vs&nbsp;{{ nameB }}
</div>

How to insert spaces/tabs in text using HTML/CSS


答:
A solution is to give to the VS element a class like .vs and add some padding to it:

p {
  margin: 0;
}

.topnav {
  display: flex;
}

.topnav .vs {
  padding-right: 10px;
  padding-left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="topnav">
  <div>Name</div>
  <p class="vs">VS</p>
  <div>Name</div>
</div></code>```

Title: How to add spaces between different tags

Body:
A solution is to give to the VS element a class like .vs and add some padding to it:

p {
  margin: 0;
}

.topnav {
  display: flex;
}

.topnav .vs {
  padding-right: 10px;
  padding-left: 10px;
}

<div class="topnav">
  <div>Name</div>
  <p class="vs">VS</p>
  <div>Name</div>
</div>


问:
TFS Client APIs for creating workitem templates?
Of course, it is pretty possible to create work items, get a list of work items etc in TFS.

In addition to this, we need to have the functionality of allowing our users to create their own work item templates, for various file types.

Whether the TFS Client APIs are capable of uploading work item templates to TFS server?

答:
There is a method to get the (XML) definition: Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemType.Export

And, Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemTypeCollection.Import which looks like you can upload XML to create a new work item type.

Suggestion, set up a VM with an instance of TFS Workgroup and perform lots of testing.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Richard


问:
how to handle accelerometer force close on android
I have a problem when the device orientation changed many times,
this the log :

```<code>05-17 11:28:53.121: ERROR/WindowManager(284): Activity com.korekapi.ipay.activity.Search has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43851260 that was originally added here
05-17 11:28:53.121: ERROR/WindowManager(284): android.view.WindowLeaked: Activity com.korekapi.ipay.activity.Search has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43851260 that was originally added here
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.view.ViewRoot.<init>(ViewRoot.java:214)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.view.Window$LocalWindowManager.addView(Window.java:409)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.Dialog.show(Dialog.java:238)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ProgressDialog.show(ProgressDialog.java:107)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ProgressDialog.show(ProgressDialog.java:90)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ProgressDialog.show(ProgressDialog.java:85)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.korekapi.ipay.activity.Search$SearchTask.onPreExecute(Search.java:124)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.os.AsyncTask.execute(AsyncTask.java:391)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.korekapi.ipay.activity.Search.doSearch(Search.java:101)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.korekapi.ipay.activity.Search.onCreate(Search.java:70)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3502)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.access$2200(ActivityThread.java:116)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1798)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.os.Looper.loop(Looper.java:123)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.main(ActivityThread.java:4203)
05-17 11:28:53.121: ERROR/WindowManager(284):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 11:28:53.121: ERROR/WindowManager(284):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
05-17 11:28:53.121: ERROR/WindowManager(284):     at dalvik.system.NativeStart.main(Native Method)
</code>```

so how to overcome the accelerometer in order not to reload / refresh during the orientation change

thanks for advance

答:
This is strictly speaking not an accelerometer problem. Your issue is that you are showing a ProgressDialog in your Search.java class (see 05-17 11:28:53.121: ERROR/WindowManager(284):     at com.korekapi.ipay.activity.Search$SearchTask.onPreExecute(Search.java:124)
) and not removing it when the orientation is changed and the Activity is destroyed by Android. The easiest solution is to prevent Android from destroying the Activity on orientation changes: see How to handle screen orientation change when progress dialog and background thread active? for more on this.

More complex is to clean up behind yourself and close all Dialogs: for this you will need to track any open dialogs and close them yourself.

Body:
I have a problem when the device orientation changed many times,
this the log :

05-17 11:28:53.121: ERROR/WindowManager(284): Activity com.korekapi.ipay.activity.Search has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43851260 that was originally added here
05-17 11:28:53.121: ERROR/WindowManager(284): android.view.WindowLeaked: Activity com.korekapi.ipay.activity.Search has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43851260 that was originally added here
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.view.ViewRoot.<init>(ViewRoot.java:214)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.view.Window$LocalWindowManager.addView(Window.java:409)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.Dialog.show(Dialog.java:238)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ProgressDialog.show(ProgressDialog.java:107)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ProgressDialog.show(ProgressDialog.java:90)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ProgressDialog.show(ProgressDialog.java:85)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.korekapi.ipay.activity.Search$SearchTask.onPreExecute(Search.java:124)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.os.AsyncTask.execute(AsyncTask.java:391)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.korekapi.ipay.activity.Search.doSearch(Search.java:101)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.korekapi.ipay.activity.Search.onCreate(Search.java:70)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3502)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.access$2200(ActivityThread.java:116)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1798)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.os.Looper.loop(Looper.java:123)
05-17 11:28:53.121: ERROR/WindowManager(284):     at android.app.ActivityThread.main(ActivityThread.java:4203)
05-17 11:28:53.121: ERROR/WindowManager(284):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 11:28:53.121: ERROR/WindowManager(284):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-17 11:28:53.121: ERROR/WindowManager(284):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
05-17 11:28:53.121: ERROR/WindowManager(284):     at dalvik.system.NativeStart.main(Native Method)

so how to overcome the accelerometer in order not to reload / refresh during the orientation change

thanks for advance


问:
OnChange for Storing Value of Selected Drop Down Option
I have a Material UI dropdown menu. I will make a search later on the basis of the selected option from the drop down menu. How exactly could I use onChange() to store the option selected?

For now, I am trying to print the stored value (criteria) using typography at the end but instead of showing the selected value, I get a black page.

```<code>export default class userSearchPage extends Component<{}, { searchItem: string, criteria: string }>{

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: '',
      criteria: '',
    };
    this.handleDropDownChange = this.handleDropDownChange.bind(this);
  }

  handleDropDownChange(selected: any) {
    this.setState({
        criteria: selected
    });
  }

  render() {
    return (
      <div>
        <PermanentDrawerLeft></PermanentDrawerLeft>
        <div className='main-content'>
          <MuiThemeProvider>
            <DropDownMenu onChange = {this.handleDropDownChange}>
              <MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
              <MenuItem value={1} style={{ fontSize: "20px" }} primaryText="First Name" />
              <MenuItem value={2} style={{ fontSize: "20px" }} primaryText="Last Name" />
              <MenuItem value={3} style={{ fontSize: "20px" }} primaryText="Phone Number" />
              <MenuItem value={4} style={{ fontSize: "20px" }} primaryText="Email" />
            </DropDownMenu>
          </MuiThemeProvider>
          <Typography>{this.state.criteria}</Typography>
          <br></br><br></br>
          <SearchBar
            onChange={e => this.setState({ searchItem: e })}
            value = {this.state.searchItem}
            onRequestSearch={() => console.log('onRequestSearch')}
            style={{
              margin: '0 auto',
              maxWidth: 800
            }}
          />
           <Typography>{this.state.criteria}</Typography>
        </div>
      </div>
    );
  }
}
</code>```

How could I fix this?

Note: This is typescript

Added

```<code>export default class userSearchPage extends Component<{}, { searchItem: string, criteria: any}>{

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: '',
      criteria: null,
    };
    this.handleDropDownChange = this.handleDropDownChange.bind(this);
  }

  handleDropDownChange(event: any) {
    console.log(event.target.value);
    this.setState({
      criteria: event.target.value
    });
  }

  render() {
    return (
      <div>
        <PermanentDrawerLeft></PermanentDrawerLeft>
        <div className='main-content'>
        <InputLabel id="demo-simple-select-label">Search By</InputLabel>
          <Select
            value={this.state.criteria}
            onChange={this.handleDropDownChange}
            displayEmpty
          >
            <MenuItem disabled value="  ">
              <em>Search By</em>
            </MenuItem>
            <MenuItem value={1}>First Name</MenuItem>
            <MenuItem value={2}>Last Name</MenuItem>
            <MenuItem value={3}>Phone Number</MenuItem>
            <MenuItem value={4}>Email</MenuItem>
          </Select>
        </div>
      </div>
    );
  }
}
</code>```

答: DropDownMenu menu should have the 'onChange' event that receives selected option as argument, which you can store in the components state</p>

Body:
I have a Material UI dropdown menu. I will make a search later on the basis of the selected option from the drop down menu. How exactly could I use onChange() to store the option selected?

For now, I am trying to print the stored value (criteria) using typography at the end but instead of showing the selected value, I get a black page.

export default class userSearchPage extends Component<{}, { searchItem: string, criteria: string }>{

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: '',
      criteria: '',
    };
    this.handleDropDownChange = this.handleDropDownChange.bind(this);
  }

  handleDropDownChange(selected: any) {
    this.setState({
        criteria: selected
    });
  }

  render() {
    return (

        <PermanentDrawerLeft></PermanentDrawerLeft>

          <MuiThemeProvider>
            <DropDownMenu onChange = {this.handleDropDownChange}>
              <MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
              <MenuItem value={1} style={{ fontSize: "20px" }} primaryText="First Name" />
              <MenuItem value={2} style={{ fontSize: "20px" }} primaryText="Last Name" />
              <MenuItem value={3} style={{ fontSize: "20px" }} primaryText="Phone Number" />
              <MenuItem value={4} style={{ fontSize: "20px" }} primaryText="Email" />
            </DropDownMenu>
          </MuiThemeProvider>
          <Typography>{this.state.criteria}</Typography>

          <SearchBar
            onChange={e => this.setState({ searchItem: e })}
            value = {this.state.searchItem}
            onRequestSearch={() => console.log('onRequestSearch')}
            style={{
              margin: '0 auto',
              maxWidth: 800
            }}
          />
           <Typography>{this.state.criteria}</Typography>

    );
  }
}

How could I fix this?

Note: This is typescript

Added

export default class userSearchPage extends Component<{}, { searchItem: string, criteria: any}>{

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: '',
      criteria: null,
    };
    this.handleDropDownChange = this.handleDropDownChange.bind(this);
  }

  handleDropDownChange(event: any) {
    console.log(event.target.value);
    this.setState({
      criteria: event.target.value
    });
  }

  render() {
    return (

        <PermanentDrawerLeft></PermanentDrawerLeft>

        <InputLabel id="demo-simple-select-label">Search By</InputLabel>
          <Select
            value={this.state.criteria}
            onChange={this.handleDropDownChange}
            displayEmpty
          >
            <MenuItem disabled value="  ">
              Search By
            </MenuItem>
            <MenuItem value={1}>First Name</MenuItem>
            <MenuItem value={2}>Last Name</MenuItem>
            <MenuItem value={3}>Phone Number</MenuItem>
            <MenuItem value={4}>Email</MenuItem>
          </Select>

    );
  }
}


问:
Numpy 1D arrays treated as column vectors when it comes to broadcasting
In the documentation on broadcasting rules, is is stated that two dimensions are compatible when either:

they are equal or

one of them is 1

This becomes clear with some of the examples that are shown, such as:

```<code>A      (4d array):  8 x 1 x 6 x 1
B      (3d array):      7 x 1 x 5
Result (4d array):  8 x 7 x 6 x 5
</code>```

This seems clear enough. However, I've been unable to find a specific example/explanation as to why 1D arrays are only broadcastable with 2d arrays, when the 1d array's shape is compatible with that of the second axis of the 2d array.
So for instance:

```<code>np.ones((2,3)) * np.arange(3)

array([[0., 1., 2.],
       [0., 1., 2.]])
</code>```

The 1d arange has been broadcast across the rows, as expected. However if we do:

```<code>np.ones((3, 2)) * np.arange(3)
</code>```

ValueError: operands could not be broadcast together with shapes (3,2) (3,)

We get an error for incompatible shapes. This might be quite simple, but I just want to know which is the correct interpretation. Is the reason behind this, that when it comes to broadcasting rules 1d arrays are treated as column vectors, and hence shape compatibility is checked along the second axis on the 2d array? And for larger arrays, is it always checked against the last axis on the larger ndarray?

答:
Is the reason behind this, that when it comes to broadcasting rules 1d arrays are treated as column vectors, and hence shape compatibility is checked along the second axis on the 2d array?

On the contrary, they are treated as row vectors and stacked vertically. You can see it in this figure from a related article.

You can do the same sketch in the case you presented:

```<code>A   3 x 2    # np.ones((3, 2))
B   2 x 3    # np.ones((2, 3))
C       3    # np.arange(3)
</code>```

Here A*C does not work, but B*C does. This is because C gets duplicated along the first dimension (i.e., rows). You can imagine missing dimensions as being "resized" by duplicating the dimensions coming after

Body:
In the documentation on broadcasting rules, is is stated that two dimensions are compatible when either:

they are equal or

one of them is 1

This becomes clear with some of the examples that are shown, such as:

A      (4d array):  8 x 1 x 6 x 1
B      (3d array):      7 x 1 x 5
Result (4d array):  8 x 7 x 6 x 5

This seems clear enough. However, I've been unable to find a specific example/explanation as to why 1D arrays are only broadcastable with 2d arrays, when the 1d array's shape is compatible with that of the second axis of the 2d array.
So for instance:

np.ones((2,3)) * np.arange(3)

array([[0., 1., 2.],
       [0., 1., 2.]])

The 1d arange has been broadcast across the rows, as expected. However if we do:

np.ones((3, 2)) * np.arange(3)

ValueError: operands could not be broadcast together with shapes (3,2) (3,)

We get an error for incompatible shapes. This might be quite simple, but I just want to know which is the correct interpretation. Is the reason behind this, that when it comes to broadcasting rules 1d arrays are treated as column vectors, and hence shape compatibility is checked along the second axis on the 2d array? And for larger arrays, is it always checked against the last axis on the larger ndarray?

Body:
Is the reason behind this, that when it comes to broadcasting rules 1d arrays are treated as column vectors, and hence shape compatibility is checked along the second axis on the 2d array?

On the contrary, they are treated as row vectors and stacked vertically. You can see it in this figure from a related article.

You can do the same sketch in the case you presented:

A   3 x 2    # np.ones((3, 2))
B   2 x 3    # np.ones((2, 3))
C       3    # np.arange(3)

Here A*C does not work, but B*C does. This is because C gets duplicated along the first dimension (i.e., rows). You can imagine missing dimensions as being "resized" by duplicating the dimensions coming after


问:
how to get result with group by and count of fileds in MySql
my table

```<code>CNT_ID  REGION   GRADE  MAX-CAPACITY  TOTAL-CAPACITY LASTDATE

1001    TN       FOOD   97             100            2020-02-17
1001    BG       BEV    76              90            2020-02-17
1001    KA       IND    88              90            2020-02-17
1001    BG       FOOD   91             100            2020-02-17
1001    ER       IND    90             100            2020-02-15
1001    TN       FOOD   78              80            2020-02-17
1001    TN       BEV    95             100            2020-02-17
1001    TN       FOOD   92             100            2020-02-16
</code>```

I want to get result based on... list by REGIONS -> AND COUNT OF MaxCapacity of(FOOD, BEV, IND) AND ORDERED BY LASTDATE desc

result expected:

```<code>REGION  FOODGRADE   BEVGRADE    INDGRADE    TOTALCAPACITY   LEFT    LASTDATE
TN      267             95          0       380             18      2020-02-17
BG      91              76          0       190             23      2020-02-17
KA      0               0           88      90              2       2020-02-17
ER      0               0           90      100             10      2020-02-17
</code>```

I TRIED THE FOLLOWING... but no luck:

```<code>SELECT COUNT(IF(GRADE='FOOD',1,NULL)) 'Food', COUNT(IF(GRADE='BEV',1,NULL)) 'Beve', *
FROM txn_viewinfo
WHERE LASTDATE = (SELECT MAX(LASTDATE)
                  FROM txn_viewinfo )
ORDER BY LASTDATE DESC;
</code>```

答:
As far as i can gather you are searching for

```<code>SELECT
  tv.`REGION`
  , SUM(IF(`GRADE` = 'FOOD', 1,0)) Food
  , SUM(IF(`GRADE` = 'BEV', 1,0)) bev
  , SUM(IF(`GRADE` = 'IND', 1,0)) ind
  , MAX(`MAX-CAPACITY`)
  , MAX(`TOTAL-CAPACITY`)
  ,LASTDATE
FROM txn_viewinfo tv INNER JOIN (SELECT `REGION`,MAX(LASTDATE) maxldate
                                 FROM txn_viewinfo
                                 GROUP BY `REGION`)  ld
                     ON tv.`LASTDATE` = ld.maxldate AND tv.`REGION` = ld.`REGION`
GROUP BY LASTDATE,`REGION`
ORDER BY LASTDATE DESC;
</code>```

This gives you a count of Grade  at the last day of entry

```<code>CREATE TABLE txn_viewinfo (
  `CNT_ID` INTEGER,
  `REGION` VARCHAR(2),
  `GRADE` VARCHAR(4),
  `MAX-CAPACITY` INTEGER,
  `TOTAL-CAPACITY` INTEGER,
  `LASTDATE` date
);

INSERT INTO txn_viewinfo
  (`CNT_ID`, `REGION`, `GRADE`, `MAX-CAPACITY`, `TOTAL-CAPACITY`, `LASTDATE`)
VALUES
  ('1001', 'TN', 'FOOD', '97', '100', '2020-02-17'),
  ('1001', 'BG', 'BEV', '76', '90', '2020-02-17'),
  ('1001', 'KA', 'IND', '88', '90', '2020-02-17'),
  ('1001', 'BG', 'FOOD', '91', '100', '2020-02-17'),
  ('1001', 'ER', 'IND', '90', '100', '2020-02-15'),
  ('1001', 'TN', 'FOOD', '78', '80', '2020-02-17'),
  ('1001', 'TN', 'BEV', '95', '100', '2020-02-17'),
  ('1001', 'TN', 'FOOD', '92', '100', '2020-02-16'),
  ('1001', 'TN', 'FOOD', '92', '100', '2020-02-16');
</code>```

```
✓

✓
```

```<code>SELECT
  tv.`REGION`
  , SUM(IF(`GRADE` = 'FOOD', 1,0)) Food
  , SUM(IF(`GRADE` = 'BEV', 1,0)) bev
  , SUM(IF(`GRADE` = 'IND', 1,0)) ind
  , MAX(`MAX-CAPACITY`)
  , MAX(`TOTAL-CAPACITY`)
  ,LASTDATE
FROM txn_viewinfo tv INNER JOIN (SELECT `REGION`,MAX(LASTDATE) maxldate
                                 FROM txn_viewinfo
                                 GROUP BY `REGION`)  ld
                     ON tv.`LASTDATE` = ld.maxldate AND tv.`REGION` = ld.`REGION`

GROUP BY LASTDATE,`REGION`
ORDER BY LASTDATE DESC;
</code>```

```
REGION | Food | bev | ind | MAX(`MAX-CAPACITY`) | MAX(`TOTAL-CAPACITY`) | LASTDATE
:----- | ---: | --: | --: | ------------------: | --------------------: | :---------
BG     |    1 |   1 |   0 |                  91 |                   100 | 2020-02-17
KA     |    0 |   0 |   1 |                  88 |                    90 | 2020-02-17
TN     |    2 |   1 |   0 |                  97 |                   100 | 2020-02-17
ER     |    0 |   0 |   1 |                  90 |                   100 | 2020-02-15
```

```<code>SELECt tv.*,ld.*
FROM txn_viewinfo tv INNER JOIN (SELECT `REGION`,MAX(LASTDATE) maxldate
                                 FROM txn_viewinfo
                                 GROUP BY `REGION`)  ld
                     ON tv.`LASTDATE` = ld.maxldate AND tv.`REGION` = ld.`REGION`
#WHERE tv.`LASTDATE` = ld.maxldate
</code>```

```
CNT_ID | REGION | GRADE | MAX-CAPACITY | TOTAL-CAPACITY | LASTDATE   | REGION | maxldate
-----: | :----- | :---- | -----------: | -------------: | :--------- | :----- | :---------
  1001 | TN     | FOOD  |           97 |            100 | 2020-02-17 | TN     | 2020-02-17
  1001 | BG     | BEV   |           76 |             90 | 2020-02-17 | BG     | 2020-02-17
  1001 | KA     | IND   |           88 |             90 | 2020-02-17 | KA     | 2020-02-17
  1001 | BG     | FOOD  |           91 |            100 | 2020-02-17 | BG     | 2020-02-17
  1001 | ER     | IND   |           90 |            100 | 2020-02-15 | ER     | 2020-02-15
  1001 | TN     | FOOD  |           78 |             80 | 2020-02-17 | TN     | 2020-02-17
  1001 | TN     | BEV   |           95 |            100 | 2020-02-17 | TN     | 2020-02-17
```

```<code>SELECT COUNT(IF(GRADE='FOOD',1,NULL)) 'Food'
, COUNT(IF(GRADE='BEV',1,NULL)) 'Beve'
, *
FROM txn_viewinfo
WHERE LASTDATE = (SELECT MAX(LASTDATE) FROM txn_viewinfo ) ORDER BY LATEST_READTIME DESC;
</code>```

```
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*
FROM txn_viewinfo
WHERE LASTDATE = (SELECT MAX(LASTDATE) FROM txn_viewinfo ' at line 3
```

db<>fiddle here

Body:
my table

CNT_ID  REGION   GRADE  MAX-CAPACITY  TOTAL-CAPACITY LASTDATE

1001    TN       FOOD   97             100            2020-02-17
1001    BG       BEV    76              90            2020-02-17
1001    KA       IND    88              90            2020-02-17
1001    BG       FOOD   91             100            2020-02-17
1001    ER       IND    90             100            2020-02-15
1001    TN       FOOD   78              80            2020-02-17
1001    TN       BEV    95             100            2020-02-17
1001    TN       FOOD   92             100            2020-02-16

I want to get result based on... list by REGIONS -> AND COUNT OF MaxCapacity of(FOOD, BEV, IND) AND ORDERED BY LASTDATE desc

result expected:

REGION  FOODGRADE   BEVGRADE    INDGRADE    TOTALCAPACITY   LEFT    LASTDATE
TN      267             95          0       380             18      2020-02-17
BG      91              76          0       190             23      2020-02-17
KA      0               0           88      90              2       2020-02-17
ER      0               0           90      100             10      2020-02-17

I TRIED THE FOLLOWING... but no luck:

SELECT COUNT(IF(GRADE='FOOD',1,NULL)) 'Food', COUNT(IF(GRADE='BEV',1,NULL)) 'Beve', *
FROM txn_viewinfo
WHERE LASTDATE = (SELECT MAX(LASTDATE)
                  FROM txn_viewinfo )
ORDER BY LASTDATE DESC;

Body:
As far as i can gather you are searching for

SELECT
  tv.`REGION`
  , SUM(IF(`GRADE` = 'FOOD', 1,0)) Food
  , SUM(IF(`GRADE` = 'BEV', 1,0)) bev
  , SUM(IF(`GRADE` = 'IND', 1,0)) ind
  , MAX(`MAX-CAPACITY`)
  , MAX(`TOTAL-CAPACITY`)
  ,LASTDATE
FROM txn_viewinfo tv INNER JOIN (SELECT `REGION`,MAX(LASTDATE) maxldate
                                 FROM txn_viewinfo
                                 GROUP BY `REGION`)  ld
                     ON tv.`LASTDATE` = ld.maxldate AND tv.`REGION` = ld.`REGION`
GROUP BY LASTDATE,`REGION`
ORDER BY LASTDATE DESC;

This gives you a count of Grade  at the last day of entry

CREATE TABLE txn_viewinfo (
  `CNT_ID` INTEGER,
  `REGION` VARCHAR(2),
  `GRADE` VARCHAR(4),
  `MAX-CAPACITY` INTEGER,
  `TOTAL-CAPACITY` INTEGER,
  `LASTDATE` date
);

INSERT INTO txn_viewinfo
  (`CNT_ID`, `REGION`, `GRADE`, `MAX-CAPACITY`, `TOTAL-CAPACITY`, `LASTDATE`)
VALUES
  ('1001', 'TN', 'FOOD', '97', '100', '2020-02-17'),
  ('1001', 'BG', 'BEV', '76', '90', '2020-02-17'),
  ('1001', 'KA', 'IND', '88', '90', '2020-02-17'),
  ('1001', 'BG', 'FOOD', '91', '100', '2020-02-17'),
  ('1001', 'ER', 'IND', '90', '100', '2020-02-15'),
  ('1001', 'TN', 'FOOD', '78', '80', '2020-02-17'),
  ('1001', 'TN', 'BEV', '95', '100', '2020-02-17'),
  ('1001', 'TN', 'FOOD', '92', '100', '2020-02-16'),
  ('1001', 'TN', 'FOOD', '92', '100', '2020-02-16');

✓

✓

SELECT
  tv.`REGION`
  , SUM(IF(`GRADE` = 'FOOD', 1,0)) Food
  , SUM(IF(`GRADE` = 'BEV', 1,0)) bev
  , SUM(IF(`GRADE` = 'IND', 1,0)) ind
  , MAX(`MAX-CAPACITY`)
  , MAX(`TOTAL-CAPACITY`)
  ,LASTDATE
FROM txn_viewinfo tv INNER JOIN (SELECT `REGION`,MAX(LASTDATE) maxldate
                                 FROM txn_viewinfo
                                 GROUP BY `REGION`)  ld
                     ON tv.`LASTDATE` = ld.maxldate AND tv.`REGION` = ld.`REGION`

GROUP BY LASTDATE,`REGION`
ORDER BY LASTDATE DESC;

REGION | Food | bev | ind | MAX(`MAX-CAPACITY`) | MAX(`TOTAL-CAPACITY`) | LASTDATE
:----- | ---: | --: | --: | ------------------: | --------------------: | :---------
BG     |    1 |   1 |   0 |                  91 |                   100 | 2020-02-17
KA     |    0 |   0 |   1 |                  88 |                    90 | 2020-02-17
TN     |    2 |   1 |   0 |                  97 |                   100 | 2020-02-17
ER     |    0 |   0 |   1 |                  90 |                   100 | 2020-02-15

SELECt tv.*,ld.*
FROM txn_viewinfo tv INNER JOIN (SELECT `REGION`,MAX(LASTDATE) maxldate
                                 FROM txn_viewinfo
                                 GROUP BY `REGION`)  ld
                     ON tv.`LASTDATE` = ld.maxldate AND tv.`REGION` = ld.`REGION`
#WHERE tv.`LASTDATE` = ld.maxldate

CNT_ID | REGION | GRADE | MAX-CAPACITY | TOTAL-CAPACITY | LASTDATE   | REGION | maxldate
-----: | :----- | :---- | -----------: | -------------: | :--------- | :----- | :---------
  1001 | TN     | FOOD  |           97 |            100 | 2020-02-17 | TN     | 2020-02-17
  1001 | BG     | BEV   |           76 |             90 | 2020-02-17 | BG     | 2020-02-17
  1001 | KA     | IND   |           88 |             90 | 2020-02-17 | KA     | 2020-02-17
  1001 | BG     | FOOD  |           91 |            100 | 2020-02-17 | BG     | 2020-02-17
  1001 | ER     | IND   |           90 |            100 | 2020-02-15 | ER     | 2020-02-15
  1001 | TN     | FOOD  |           78 |             80 | 2020-02-17 | TN     | 2020-02-17
  1001 | TN     | BEV   |           95 |            100 | 2020-02-17 | TN     | 2020-02-17

SELECT COUNT(IF(GRADE='FOOD',1,NULL)) 'Food'
, COUNT(IF(GRADE='BEV',1,NULL)) 'Beve'
, *
FROM txn_viewinfo
WHERE LASTDATE = (SELECT MAX(LASTDATE) FROM txn_viewinfo ) ORDER BY LATEST_READTIME DESC;

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*
FROM txn_viewinfo
WHERE LASTDATE = (SELECT MAX(LASTDATE) FROM txn_viewinfo ' at line 3

db<>fiddle here


问:
Angular 8: issue finding component nested through multiple ng-content
I am facing this issue when trying to find components nested within sub child components.

I have created an example of what I want to achieve:

import { Component, OnInit, ContentChildren, ElementRef, QueryList } from '@angular/core';

@Component({
  selector: 'app-grand-parent',
  template: '<ng-content></ng-content>',
})
export class GrandParentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'app-parent',
  template: '<ng-content></ng-content>',
})
export class ParentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'app-child',
  template: '<ng-content></ng-content>',
})
export class ChildComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'app-child-profile',
  template: '
Child Profile
',
})
export class ChildProfileComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'my-app',
  template: `

  <app-grand-parent>
    <app-parent>
      <app-child>
      <app-child-profile></app-child-profile>
      <app-child-profile></app-child-profile>
      <app-child-profile></app-child-profile>
      </app-child>
    </app-parent>
  </app-grand-parent>

`
})
export class AppComponent implements AfterContentInit  {
  @ContentChildren(ChildProfileComponent) profiles: QueryList<ChildProfileComponent>;

  ngAfterContentInit(): void {
    console.log(this.profiles);
  }
}
```

There is a full example in the following link:
https://stackblitz.com/edit/angular-rqh8gm

I don't want to use ngProjectAs as I want to dynamically query elements.

I could find the component through its parent component. Is there is a way to re-append it to grand parent component?

答:
For getting objects of profile component. You need to query it inside app-child component

1) You are finding it in Appcomponent but its not directly projected in it so you will not able to find it

2) You are projecting it inside app-child so this  will be available inside app-child

3) Example

In above case comp3 is projected inside comp2 not in comp1. Direct projection works here

Have a look

https://stackblitz.com/edit/angular-hwv8g7?embed=1&file=src/app/app.component.ts

Try this if you want access count in Appcomponent. For this you have to go through mulltiple loops

https://stackblitz.com/edit/angular-shh1up?embed=1&file=src/app/app.component.ts

This is my approach do let me know if you find some better way

Body:
I am facing this issue when trying to find components nested within sub child components.

I have created an example of what I want to achieve:

import { Component, OnInit, ContentChildren, ElementRef, QueryList } from '@angular/core';

@Component({
  selector: 'app-grand-parent',
  template: '<ng-content></ng-content>',
})
export class GrandParentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'app-parent',
  template: '<ng-content></ng-content>',
})
export class ParentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'app-child',
  template: '<ng-content></ng-content>',
})
export class ChildComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'app-child-profile',
  template: '
Child Profile
',
})
export class ChildProfileComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'my-app',
  template: `

  <app-grand-parent>
    <app-parent>
      <app-child>
      <app-child-profile></app-child-profile>
      <app-child-profile></app-child-profile>
      <app-child-profile></app-child-profile>
      </app-child>
    </app-parent>
  </app-grand-parent>

`
})
export class AppComponent implements AfterContentInit  {
  @ContentChildren(ChildProfileComponent) profiles: QueryList<ChildProfileComponent>;

  ngAfterContentInit(): void {
    console.log(this.profiles);
  }
}

There is a full example in the following link:
https://stackblitz.com/edit/angular-rqh8gm

I don't want to use ngProjectAs as I want to dynamically query elements.

I could find the component through its parent component. Is there is a way to re-append it to grand parent component?


问:
Handle MouseEvent.CLICK, MOUSE_DOWN in subclasses
I'm building a panel of buttons, that are enclosed in Canvas container. For this purpose I created a MyButton class, which is a subclass of UIComponent. MyButton class has 2 other subclasses: MyRadioButton and MyMenuButton, which have another behavior on MouseEvent.MOUSE_DOWN. MyMenuButtoncreates and shows a menu, that I build from XML and it builds ok.

I add listeners in the superclass like this:

```<code>this.addEventListener(MouseEvent.CLICK, handleClick);
this.addEventListener(MouseEvent.MOUSE_DOWN, handleMouse);
this.addEventListener(MouseEvent.MOUSE_UP, handleMouse);
</code>```

It's done at the creation stage.

In my subclasses I override handleMouse handler.

```<code>override protected handleMouse(event:MouseEvent) : void
{
  // subclass specific handling
}
</code>```

These button objects are added to canvas container as following:

in class MyButtonsContainer.as:

```<code>this.rowChildren.addChild(button);
</code>```

These buttons draw perfectly and in place. The problem is the behavior:
The event doesn't come to handleClick handler of superclass. And that's the question actually - why can it be?
Thanks in advance

EDIT: It appears that MOUSE_DOWN & MOUSE_UP interfere with CLICK event. When I remove listeners to them I get to click handler.How to cause them live together?

答:
I'm not 100% sure what you're asking, but I'd override click actions like this..

Base class:

```<code>public class MyButton extends UIComponent
{
    /**
     * Constructor
     */
    public function MyButton()
    {
        // listeners
        addEventListener(MouseEvent.CLICK, _click);
        // ...other listeners
    }

    /**
     * Called on dispatch of MouseEvent.CLICK
     */
    private function _click(e:MouseEvent):void
    {
        doClick();
    }

    /**
     * Override this method and fill with actions to
     * do when this is clicked
     */
    protected function doClick():void
    {
        trace("base class was clicked");
    }
}
</code>```

And the extending class:

```<code>public class MyOtherButton extends MyButton
{
    /**
     * Override doClick
     */
    override protected function doClick():void
    {
        super.doClick();
        trace("extending class was clicked");
    }
}
</code>```

After closely inspecting your code:

You've added two different listeners to one function for one, shouldn't these have seperate functions as they are called by contrasting events?

```<code>this.addEventListener(MouseEvent.MOUSE_DOWN, handleMouse);
this.addEventListener(MouseEvent.MOUSE_UP, handleMouse);
</code>```

Also, it seems like you're expecting handleMouse to be fired by a click event judging by the below code, which isn't the case.

```<code>override protected handleMouse(event:MouseEvent) : void
{
  // subclass specific handling
}
</code>```

Either that, or you're forgetting to override handleClick as well - which is the method that you're running on a click event. You possibly need to add this code:

```<code>override protected handleClick(event:MouseEvent) : void
{
  // subclass specific handling for a click
}
</code>```

Body:
I'm building a panel of buttons, that are enclosed in Canvas container. For this purpose I created a MyButton class, which is a subclass of UIComponent. MyButton class has 2 other subclasses: MyRadioButton and MyMenuButton, which have another behavior on MouseEvent.MOUSE_DOWN. MyMenuButtoncreates and shows a menu, that I build from XML and it builds ok.

I add listeners in the superclass like this:

this.addEventListener(MouseEvent.CLICK, handleClick);
this.addEventListener(MouseEvent.MOUSE_DOWN, handleMouse);
this.addEventListener(MouseEvent.MOUSE_UP, handleMouse);

It's done at the creation stage.

In my subclasses I override handleMouse handler.

override protected handleMouse(event:MouseEvent) : void
{
  // subclass specific handling
}

These button objects are added to canvas container as following:

in class MyButtonsContainer.as:

this.rowChildren.addChild(button);

These buttons draw perfectly and in place. The problem is the behavior:
The event doesn't come to handleClick handler of superclass. And that's the question actually - why can it be?
Thanks in advance

EDIT: It appears that MOUSE_DOWN & MOUSE_UP interfere with CLICK event. When I remove listeners to them I get to click handler.How to cause them live together?

Body:
I'm not 100% sure what you're asking, but I'd override click actions like this..

Base class:

public class MyButton extends UIComponent
{
    /**
     * Constructor
     */
    public function MyButton()
    {
        // listeners
        addEventListener(MouseEvent.CLICK, _click);
        // ...other listeners
    }

    /**
     * Called on dispatch of MouseEvent.CLICK
     */
    private function _click(e:MouseEvent):void
    {
        doClick();
    }

    /**
     * Override this method and fill with actions to
     * do when this is clicked
     */
    protected function doClick():void
    {
        trace("base class was clicked");
    }
}

And the extending class:

public class MyOtherButton extends MyButton
{
    /**
     * Override doClick
     */
    override protected function doClick():void
    {
        super.doClick();
        trace("extending class was clicked");
    }
}

After closely inspecting your code:

You've added two different listeners to one function for one, shouldn't these have seperate functions as they are called by contrasting events?

this.addEventListener(MouseEvent.MOUSE_DOWN, handleMouse);
this.addEventListener(MouseEvent.MOUSE_UP, handleMouse);

Also, it seems like you're expecting handleMouse to be fired by a click event judging by the below code, which isn't the case.

override protected handleMouse(event:MouseEvent) : void
{
  // subclass specific handling
}

Either that, or you're forgetting to override handleClick as well - which is the method that you're running on a click event. You possibly need to add this code:

override protected handleClick(event:MouseEvent) : void
{
  // subclass specific handling for a click
}


问:
Win10 Docker Installation of AzerothCore fails to build authserver and worldserver
Following the AzerothCore Docker guide on Windows 10 Pro N using Docker Desktop Version 2.2.0.3 (42716) and I am unable to build the authserver and worldserver binaries. docker-compose up will build the database without issue but cannot find the required files to build the binaries.

ERROR: for azerothcore-wotlk_ac-authserver_1 Cannot start service ac-authserver: OCI runtime create failed: container_linux.go:346: starting con
Creating azerothcore-wotlk_ac-worldserver_1 ... error

ERROR: for azerothcore-wotlk_ac-worldserver_1 Cannot start service ac-worldserver: OCI runtime create failed: container_linux.go:346: starting container process caused "exec \"/azeroth-server/bin/worldserver\": stat /azeroth-server/bin/worldserver: no such file or directory": unknown

I have system pruned and deleted source and started again. Seems this is destined to fail as it appears they aren't being compiled from the ./bin/acore-docker-build command - however no error pops up for this either.

答: I somehow got this working by shifting the azerothcore-wotlk folder from my C:/Users/USERNAME/ folder which is where it defaults to and placing it directly in to my C:/ - I also had to share my necessary drives with Docker in the Settings> Resources> File Sharing tab. I also ran git from the C:/ with administrator rights. I was able to successfully build using docker-compose up however my new issue is that commands written in to the git window while the server is built and active are ignored and do nothing. Ctrl+C does however forcibly shut it down.