问:
SQL concat column with one to many relationship
I would like some help creating an SQL sub statement which would show a concatenated string value using Table2 shown below:

For brevity see the following example of what I am trying to achieve:

```<code>SELECT *, CONCAT(Table2.TypeCode) ConcatField FROM Table1
</code>```

Any help would be greatly appreciated, thank you.

答:
This may be good:</p>

```<code>WITH Concatetated AS (
    SELECT PrimaryId, '[' + STRING_AGG(TypeCode, '] [') + ']' AS "ConcatField"
    FROM Table2
    GROUP BY PrimaryId
)

SELECT t1."PrimaryId", t1."Name", c."ConcatField"
FROM Table1 t1
LEFT JOIN Concatetated c
  ON t1.PrimaryId = c.PrimaryId
</code>```

Body:
I would like some help creating an SQL sub statement which would show a concatenated string value using Table2 shown below:

For brevity see the following example of what I am trying to achieve:

SELECT *, CONCAT(Table2.TypeCode) ConcatField FROM Table1

Any help would be greatly appreciated, thank you.

Body:
This may be good:

WITH Concatetated AS (
    SELECT PrimaryId, '[' + STRING_AGG(TypeCode, '] [') + ']' AS "ConcatField"
    FROM Table2
    GROUP BY PrimaryId
)

SELECT t1."PrimaryId", t1."Name", c."ConcatField"
FROM Table1 t1
LEFT JOIN Concatetated c
  ON t1.PrimaryId = c.PrimaryId


来源: stackexchange

问:
SpringBoot 2.2.4 Actuator - path for custom management endpoints
After moving from spring-boot v1.3 to the newest spring-boot v2.2.4 we've lost the ability to have custom endpoints under management port.

Before we had our custom endpoints declared as:

```<code>@Component
public class CacheEndpoint implements MvcEndpoint {
 ...
   @Override
  public String getPath() {
    return "/v1/cache";
  }
  ...
  // mappings goes here
</code>```

Since MvcEndpoint has been removed from spring-boot actuator now we need to do next:

```<code>@Component
@RestControllerEndpoint(id = "cache")
public class CacheEndpoint {
    ...
    // mappings goes here
</code>```

Unfortunately, we've lost an option to have a custom root path for our custom management endpoints (before it was /v1/)

For back-compatibility, we still want to have default actuator endpoints such as health, metrics, env.. to be under / base path. e.g. host:<management_port>/health, but at the same time we still want to support our custom endpoints under /v1/ path, e.g. host:<management_port>/v1/cache

I tried a lot of things, googled even more, but no success yet.
Is there a way to achieve this?

答:
This is what I use for spring boot 2:

application.yml:

```<code>
management:
  endpoints:
    enabled-by-default: true
    web:
      exposure:
        include: "*"
      base-path: "/management" # <-- note, here is the context path
</code>```

All-in-all consider reading a migration guide for actuator from spring boot 1.x to 2.x

ContentLicense: CC BY-SA 4.0

Body:
After moving from spring-boot v1.3 to the newest spring-boot v2.2.4 we've lost the ability to have custom endpoints under management port.

Before we had our custom endpoints declared as:

@Component
public class CacheEndpoint implements MvcEndpoint {
 ...
   @Override
  public String getPath() {
    return "/v1/cache";
  }
  ...
  // mappings goes here

Since MvcEndpoint has been removed from spring-boot actuator now we need to do next:

@Component
@RestControllerEndpoint(id = "cache")
public class CacheEndpoint {
    ...
    // mappings goes here

Unfortunately, we've lost an option to have a custom root path for our custom management endpoints (before it was /v1/)

For back-compatibility, we still want to have default actuator endpoints such as health, metrics, env.. to be under / base path. e.g. host:<management_port>/health, but at the same time we still want to support our custom endpoints under /v1/ path, e.g. host:<management_port>/v1/cache

I tried a lot of things, googled even more, but no success yet.
Is there a way to achieve this?

Body:
This is what I use for spring boot 2:

application.yml:

management:
  endpoints:
    enabled-by-default: true
    web:
      exposure:
        include: "*"
      base-path: "/management" # <-- note, here is the context path

All-in-all consider reading a migration guide for actuator from spring boot 1.x to 2.x


问:
How to know the number of user that register every day POSTGRESQL
I would like to know how many users register every day.

But i don't have any idea how to make that.
You can find below the table.

答:
You use group by, assuming that "register" is defined by the created_at column:

```<code>select created_at::date, count(*) as num_created_users
from users
group by created_at::date;
</code>```

Body:
You use group by, assuming that "register" is defined by the created_at column:

select created_at::date, count(*) as num_created_users
from users
group by created_at::date;


问:
Can’t connect Project to Simulator
I have an issue that has been posted to this board on many occasions.  There seems to be several answers, but most of them are for older versions of XCode which are no longer applicable as folder location have changed etc.

XCode was working perfectly and then out of the blue, when I run the simulator I’m getting a dialog with the message:

Could not attach pid: “xxxx”

I’ve tried rebooting, clean build folder, deleting the app from the simulator, deleting derived data, etc.  Nothing seems to do the trick

The issue isn’t isn’t project specific as I create a new project and get the same error.  I’m on XCode 11.3.1

Thanks

答:
I saw the same while testing Xcode 11.3.1 on a slow machine running Mojave. Xcode is unable to attach to the ios Simulator process when started for debugging. </p>

<p>I don't know what caused it, but a workaround is to manually attach the debugger via the Xcode menu : "Debug" -> "Attach to Process" -> then select your process, probably already listed at the top unde "Likely Targets". </p>

Title: Can’t connect Project to Simulator

Body:
I saw the same while testing Xcode 11.3.1 on a slow machine running Mojave. Xcode is unable to attach to the ios Simulator process when started for debugging.

I don't know what caused it, but a workaround is to manually attach the debugger via the Xcode menu : "Debug" -> "Attach to Process" -> then select your process, probably already listed at the top unde "Likely Targets".


问:
How do I host WordPress classified website images on an external source?
I have a classified website pkwhistle.com that is leading multiple countries and has a huge collection of images media. Is there any way to store newly uploaded listing images automatically store outside WordPress and fetch back to my site. clasificadospr.com is the best example of my idea. Because this website is using service which I am actually asking about. It's using the "thumbor" service. Please help me in this matter so I can increase the speed of my website. More than 10thousand images on a website can kill speed.</p>

答:
Well, it's called hosting/loading your images from a CDN, and there are many providers that work nicely with Wordpress!

With 10.000 images you mostly end up with a premium solution such as WP offload Media from Deliciousbrains (highly recommended and I am not in any way affiliated to them, just love their products). They also have a free version.

You can hook it up with all the big assets storage providers (digitalOcean Spaces, Amazon's AWS)

And integration with WP is great, it syncs between the CDN and your Wordpress Library.

Alternatively, there are some free options, you can use photon from Wordpress, it does almost the same, but hosted on photon's servers. It comes with the Jetpack plugin.

Another free option is Cloudinary (they have a plugin as well). But it has a limited free plan.

Good luck!


Title: Merge Multi-Index Pandas Data Frames

Body:
I have three multi-index Pandas data frames -

df1 = {('parity', np.nan): {('20194', 1990): 0.3333333333333333,
                            ('22204', 1990): 0.0,
                            ('24060', 1990): 0.3333333333333333},
       ('parity', 0.0): {('20194', 1990): 0.0,
                         ('22204', 1990): 0.0,
                         ('24060', 1990): 0.3333333333333333},
       ('parity', 1.0): {('20194', 1990): 0.3333333333333333,
                         ('22204', 1990): 1.0,
                         ('24060', 1990): 0.0},
       ('parity', 2.0): {('20194', 1990): 0.3333333333333333,
                         ('22204', 1990): 0.0,
                         ('24060', 1990): 0.3333333333333333},
       ('education', 0.0): {('20194', 1990): 0.3333333333333333,
                            ('22204', 1990): 0.6666666666666666,
                            ('24060', 1990): 0.6666666666666666},
       ('education', 1.0): {('20194', 1990): 0.6666666666666666,
                            ('22204', 1990): 0.3333333333333333,
                            ('24060', 1990): 0.3333333333333333}}
df1 = pd.DataFrame(data = df1)

df2 = {('parity', 'zip'): {0: '20194', 1: '22204', 2: '24060'},
       ('parity', 'year'): {0: 1990, 1: 1990, 2: 1990},
       ('parity', 'parity'): {0: 1.5, 1: 1.0, 2: 1.0}}
df2 = pd.DataFrame(data = df2)

df3 = {'parity': {('20194', 1990): 1.5, ('22204', 1990): 1.0, ('24060', 1990): 1.0},
       'education': {('20194', 1990): 0.6666666666666666,
                     ('22204', 1990): 0.3333333333333333,
                     ('24060', 1990): 0.3333333333333333}}
df3 = pd.DataFrame(data = df3)

How do I merge all the data frames on the zip and year indexes and columns, such that they look like the image below?

Body:
Use concat with MultiIndex with levels zip and year in index and MultiIndex with 2 levels in columns:

#convert columns to MultiIndex in index
df2 = df2.set_index([('parity','zip'),('parity','year')])
#created new MultiIndex in columns
df3.columns = pd.MultiIndex.from_product([df3.columns, ['new']])
df = pd.concat([df1, df2, df3],axis=1).rename_axis(['zip','year'])
print (df)
              parity                               education           parity  \
                 NaN       0.0       1.0       2.0       0.0       1.0 parity
zip   year
20194 1990  0.333333  0.000000  0.333333  0.333333  0.333333  0.666667    1.5
22204 1990  0.000000  0.000000  1.000000  0.000000  0.666667  0.333333    1.0
24060 1990  0.333333  0.333333  0.000000  0.333333  0.666667  0.333333    1.0

                education
            new       new
zip   year
20194 1990  1.5  0.666667
22204 1990  1.0  0.333333
24060 1990  1.0  0.333333


问:
Scala SBT: standalone jar
The answer: Making stand-alone jar with Simple Build Tool seems like what I need, but it did not have enough information for me, so this is a followup.

(1) How do I adapt the answer to my need? I don't understand what would need to be changed.

(2) What command do I run to create the standalone jar?

(3) Where can I find the jar after it has been created?

What I've tried:

Pasting the code in the linked answer verbatim into my: project/build/dsg.scala file. The file now has a

class ForkRun(info: ProjectInfo) extends DefaultProject(info)

(from before, used for running projects in a separate VM from SBT) and the new:

trait AssemblyProject extends BasicScalaProject

from the linked answer.

I also tried pasting the body (all defs and the lazy val of the AssemblyProject into the body of ForkRun.

To create a jar I ran package at the SBT prompt and get:

```<code>[info] Packaging ./target/scala_2.8.1/dsg_2.8.1-1.0.jar ...
[info] Packaging complete.
</code>```

So I tried running the dsg_2.8.1-1.0.jar from the shell via:

```<code>java -jar dsg_2.8.1-1.0.jar
</code>```

But I get:

```<code>Failed to load Main-Class manifest attribute from
dsg_2.8.1-1.0.jar
</code>```

Could this be caused by having multiple entry points into my project? I select from a list when I execute run from the SBT prompt. Perhaps I need to specify the default when creating the package?

答:
Here's a writeup I did on one way to make an executable jar with SBT:

http://janxspirit.blogspot.com/2011/01/create-executable-scala-jar-with-sbt.html

ContentLicense: CC BY-SA 3.0

Title: Scala SBT: standalone jar

Body:
The answer: Making stand-alone jar with Simple Build Tool seems like what I need, but it did not have enough information for me, so this is a followup.

(1) How do I adapt the answer to my need? I don't understand what would need to be changed.

(2) What command do I run to create the standalone jar?

(3) Where can I find the jar after it has been created?

What I've tried:

Pasting the code in the linked answer verbatim into my: project/build/dsg.scala file. The file now has a

class ForkRun(info: ProjectInfo) extends DefaultProject(info)

(from before, used for running projects in a separate VM from SBT) and the new:

trait AssemblyProject extends BasicScalaProject

from the linked answer.

I also tried pasting the body (all defs and the lazy val of the AssemblyProject into the body of ForkRun.

To create a jar I ran package at the SBT prompt and get:

[info] Packaging ./target/scala_2.8.1/dsg_2.8.1-1.0.jar ...
[info] Packaging complete.

So I tried running the dsg_2.8.1-1.0.jar from the shell via:

java -jar dsg_2.8.1-1.0.jar

But I get:

Failed to load Main-Class manifest attribute from
dsg_2.8.1-1.0.jar

Could this be caused by having multiple entry points into my project? I select from a list when I execute run from the SBT prompt. Perhaps I need to specify the default when creating the package?


问:
How to remove a dynamic component on deletion in angular?
I am trying to create a mat-expansion panel and have mat-list inside it dynamiclly.
The code is as provided below:

```<code><mat-expansion-panel *ngFor="let bAttr of bAttrList" (opened)="openPanel(bAttr)">
            <mat-expansion-panel-header>
              <mat-panel-title>
                {{bAttr}}
              </mat-panel-title>
              <mat-panel-description>
                {{bAttr}}
              </mat-panel-description>
            </mat-expansion-panel-header>

            <mat-list *ngFor="let baValue of baValueList">
              <app-ba-update [baValue]="baValue" [bAttr]="bAttr" [lob]="lobSelected"></app-ba-update>

            </mat-list>

          </mat-expansion-panel>
</code>```

Here you can see, I am trying to call another child component for each bAttr element. Inside the child element , we have the option to edit and delete the baValue. Once I delete, I need to remove the element from the list / refresh the content of currently opened mat-expansion panel's mat-list.
When I expand the expansion panel, openPanel() method gets called and it sets the value of baValueList.
How do I let the parent element  know exactly which child element I need to remove, or tell the parent element to refresh the baValueList?

NOTE: There are multiple bAttr list and corresponding to them , there are multiple baValueList.

答:
You can update the variable on open and close of the panel and on the basis of that you need to add the condition on the selector as follow:

<mat-accordion>
  <mat-expansion-panel (opened)="panelOpenState = true" (closed)="panelOpenState = false">
    <mat-expansion-panel-header>
      <mat-panel-title>
        Self aware panel
      </mat-panel-title>
      <mat-panel-description>
        Currently I am {{panelOpenState ? 'open' : 'closed'}}
      </mat-panel-description>
    </mat-expansion-panel-header>
    <papp-ba-update *ngIf="panelOpenState">I'm visible because I am open</app-ba-update>
  </mat-expansion-panel>
</mat-accordion>

Body:
I am trying to create a mat-expansion panel and have mat-list inside it dynamiclly.
The code is as provided below:

<mat-expansion-panel *ngFor="let bAttr of bAttrList" (opened)="openPanel(bAttr)">
            <mat-expansion-panel-header>
              <mat-panel-title>
                {{bAttr}}
              </mat-panel-title>
              <mat-panel-description>
                {{bAttr}}
              </mat-panel-description>
            </mat-expansion-panel-header>

            <mat-list *ngFor="let baValue of baValueList">
              <app-ba-update [baValue]="baValue" [bAttr]="bAttr" [lob]="lobSelected"></app-ba-update>

            </mat-list>

          </mat-expansion-panel>

Here you can see, I am trying to call another child component for each bAttr element. Inside the child element , we have the option to edit and delete the baValue. Once I delete, I need to remove the element from the list / refresh the content of currently opened mat-expansion panel's mat-list.
When I expand the expansion panel, openPanel() method gets called and it sets the value of baValueList.
How do I let the parent element  know exactly which child element I need to remove, or tell the parent element to refresh the baValueList?

NOTE: There are multiple bAttr list and corresponding to them , there are multiple baValueList.


问:
Tensorflow Profile outputs 2 FLOPS for a Conv2D instead of 1
I was wondering if anybody has an idea why the number of FLOPs for a Conv2d operation is 2 instead of 1. In the example below, the input is a 1x1 image with 1 channel and the batch size is 1. The number of features in the convolution is also 1 with no bias. Ideally the number of multiplication should be 1. But the output of TF profiler says that the FLOPs is 2. Does the FLOPs include something other than the multiplication? Thanks.

Here is the example:

```<code>import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'  # assuming you have a gpu0
import tensorflow as tf
from keras import backend as K

def load_pb(pb):
    with tf.gfile.GFile(pb, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(graph_def, name='')
        return graph

def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
    from tensorflow.python.framework.graph_util import convert_variables_to_constants
    graph = session.graph
    with graph.as_default():
        freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
        output_names = output_names or []
        output_names += [v.op.name for v in tf.global_variables()]
        input_graph_def = graph.as_graph_def()
        if clear_devices:
            for node in input_graph_def.node:
                node.device = ""
        frozen_graph = convert_variables_to_constants(session, input_graph_def,output_names, freeze_var_names)
        return frozen_graph

# define the model
inp = tf.keras.layers.Input(batch_shape=(1, 1, 1, 1), name='input')
x = tf.keras.layers.Conv2D(1, kernel_size=(1, 1), strides=(1, 1), padding='same', name='conv', use_bias=False)(inp)
out = tf.keras.layers.Flatten(name='output')(x)
model = tf.keras.models.Model(inputs=inp, outputs=out)
model.summary()

# freeze the model
output_graph_def = freeze_session(K.get_session(), output_names=[out.op.name for out in model.outputs])
with tf.gfile.GFile('graph.pb', "wb") as f:
    f.write(output_graph_def.SerializeToString())

# load the protobuf and perform tf profiling
g2 = load_pb('./graph.pb')
with g2.as_default():
    opts = tf.profiler.ProfileOptionBuilder.float_operation()
    flops = tf.profiler.profile(g2, run_meta=tf.RunMetadata(), cmd='scope', options=opts)
    print('FLOP', flops.total_float_ops)
</code>```

The output is:

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           (1, 1, 1, 1)              0
_________________________________________________________________
conv (Conv2D)                (1, 1, 1, 1)              1
_________________________________________________________________
output (Flatten)             (1, 1)                    0
=================================================================
Total params: 1
Trainable params: 1
Non-trainable params: 0
_________________________________________________________________
Converted 1 variables to const ops.
Parsing Inputs...
=========================Options=============================
-max_depth                  10000
-min_bytes                  0
-min_peak_bytes             0
-min_residual_bytes         0
-min_output_bytes           0
-min_micros                 0
-min_accelerator_micros     0
-min_cpu_micros             0
-min_params                 0
-min_float_ops              1
-min_occurrence             0
-step                       -1
-order_by                   float_ops
-account_type_regexes       .*
-start_name_regexes         .*
-trim_name_regexes
-show_name_regexes          .*
-hide_name_regexes
-account_displayed_op_only  true
-select                     float_ops
-output                     stdout:
==================Model Analysis Report======================
Doc:
scope: The nodes in the model graph are organized by their names, which is hierarchical like filesystem.
flops: Number of float operations. Note: Please read the implementation for the math behind it.
Profile:
node name | # float_ops
_TFProfRoot (--/2 flops)
  conv/Conv2D (2/2 flops)
======================End of Report==========================
FLOP 2
</code>```

答:
Consider almost the same setup as you have, but instead there are n channels to the convolution.
Then you would have n multiplications, and then you would cumulatively sum the results of all multiplications.
Now one can say that you can initialize the sum by the result of the first multiplication, and then cumulatively sum the rest of then (n-1) multiplications.
But this would be a special treatment to the first multiplication, and instead it makes more sense to initialize the sum by 0, and then cumulatively sum it with all n multiplications.
In particular when n=1 you would have an absurd case where

```<code>sum = 0
mult = w1 * a1
sum = sum + mult
</code>```

which will result in 2 FLOPs, or 1 MAC which is (multiply-accumulate) operation.

Body:
I was wondering if anybody has an idea why the number of FLOPs for a Conv2d operation is 2 instead of 1. In the example below, the input is a 1x1 image with 1 channel and the batch size is 1. The number of features in the convolution is also 1 with no bias. Ideally the number of multiplication should be 1. But the output of TF profiler says that the FLOPs is 2. Does the FLOPs include something other than the multiplication? Thanks.

Here is the example:

import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'  # assuming you have a gpu0
import tensorflow as tf
from keras import backend as K

def load_pb(pb):
    with tf.gfile.GFile(pb, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(graph_def, name='')
        return graph

def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
    from tensorflow.python.framework.graph_util import convert_variables_to_constants
    graph = session.graph
    with graph.as_default():
        freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
        output_names = output_names or []
        output_names += [v.op.name for v in tf.global_variables()]
        input_graph_def = graph.as_graph_def()
        if clear_devices:
            for node in input_graph_def.node:
                node.device = ""
        frozen_graph = convert_variables_to_constants(session, input_graph_def,output_names, freeze_var_names)
        return frozen_graph

# define the model
inp = tf.keras.layers.Input(batch_shape=(1, 1, 1, 1), name='input')
x = tf.keras.layers.Conv2D(1, kernel_size=(1, 1), strides=(1, 1), padding='same', name='conv', use_bias=False)(inp)
out = tf.keras.layers.Flatten(name='output')(x)
model = tf.keras.models.Model(inputs=inp, outputs=out)
model.summary()

# freeze the model
output_graph_def = freeze_session(K.get_session(), output_names=[out.op.name for out in model.outputs])
with tf.gfile.GFile('graph.pb', "wb") as f:
    f.write(output_graph_def.SerializeToString())

# load the protobuf and perform tf profiling
g2 = load_pb('./graph.pb')
with g2.as_default():
    opts = tf.profiler.ProfileOptionBuilder.float_operation()
    flops = tf.profiler.profile(g2, run_meta=tf.RunMetadata(), cmd='scope', options=opts)
    print('FLOP', flops.total_float_ops)

The output is:

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           (1, 1, 1, 1)              0
_________________________________________________________________
conv (Conv2D)                (1, 1, 1, 1)              1
_________________________________________________________________
output (Flatten)             (1, 1)                    0
=================================================================
Total params: 1
Trainable params: 1
Non-trainable params: 0
_________________________________________________________________
Converted 1 variables to const ops.
Parsing Inputs...
=========================Options=============================
-max_depth                  10000
-min_bytes                  0
-min_peak_bytes             0
-min_residual_bytes         0
-min_output_bytes           0
-min_micros                 0
-min_accelerator_micros     0
-min_cpu_micros             0
-min_params                 0
-min_float_ops              1
-min_occurrence             0
-step                       -1
-order_by                   float_ops
-account_type_regexes       .*
-start_name_regexes         .*
-trim_name_regexes
-show_name_regexes          .*
-hide_name_regexes
-account_displayed_op_only  true
-select                     float_ops
-output                     stdout:
==================Model Analysis Report======================
Doc:
scope: The nodes in the model graph are organized by their names, which is hierarchical like filesystem.
flops: Number of float operations. Note: Please read the implementation for the math behind it.
Profile:
node name | # float_ops
_TFProfRoot (--/2 flops)
  conv/Conv2D (2/2 flops)
======================End of Report==========================
FLOP 2

Body:
Consider almost the same setup as you have, but instead there are n channels to the convolution.
Then you would have n multiplications, and then you would cumulatively sum the results of all multiplications.
Now one can say that you can initialize the sum by the result of the first multiplication, and then cumulatively sum the rest of then (n-1) multiplications.
But this would be a special treatment to the first multiplication, and instead it makes more sense to initialize the sum by 0, and then cumulatively sum it with all n multiplications.
In particular when n=1 you would have an absurd case where

sum = 0
mult = w1 * a1
sum = sum + mult

which will result in 2 FLOPs, or 1 MAC which is (multiply-accumulate) operation.


问:
jQuery (3.4.1 / 3.3.1) load.() don't work, found no solution so far
I'm messing with jQuery .load()

Here is my code sample:

```<code><html>
  <head>
    <meta charset="utf-8">
    <title>load demo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  </head>

  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("#div1").load('test.txt');
       });
     });
   </script>

   <body>
     <div id="div1">Old text</div>
     <button>Get new text</button>

  </body>
</html>
</code>```

It doesn't load neither on Safari (OSX) nor on Firefox (Rasperian). I knew this question was asked many times, but no answer did really helped.

答:
Your syntax is correct but maybe your file is not fetch from correct location

You should also handle error if any

also check this jquery-load-method

```<code> $(document).ready(function(){
  $("button").click(function(){
    $("#div1").load('/test.txt', function( response, status, xhr ) {
     if ( status == "error" ) {
        alert( "Sorry but there was an error: " + xhr.status + " " + xhr.statusText );
     }
    });
   });
 });
</code>```

Body:
I'm messing with jQuery .load()

Here is my code sample:

    <meta charset="utf-8">
    <title>load demo</title>

Old text

     <button>Get new text</button>

It doesn't load neither on Safari (OSX) nor on Firefox (Rasperian). I knew this question was asked many times, but no answer did really helped.

Body:
Your syntax is correct but maybe your file is not fetch from correct location

You should also handle error if any

also check this jquery-load-method

 $(document).ready(function(){
  $("button").click(function(){
    $("#div1").load('/test.txt', function( response, status, xhr ) {
     if ( status == "error" ) {
        alert( "Sorry but there was an error: " + xhr.status + " " + xhr.statusText );
     }
    });
   });
 });


问:
invoking a test method each time before other test methods
I have a test method as below that two other test methods are dependent to this method and this method should run before these two each time and not only once for both.

```<code> @Test(dataProvider = "requestParameterProvider", groups = "jsonRequest")
 public void saveNewActivity_correctValues(Service service,
 Map<String, Object> requestMap){}

 @Test(dependsOnMethods = "saveNewActivity_trackRequest_correctValues", dataProvider = "responseParameterProvider")
public void commitActivity_correctValues(Service service){}

@Test(dependsOnMethods = "saveNewActivity_trackRequest_correctValues", dataProvider = "exceptionParameterProvider")
public void failActivity_correctValues(Service service, FailureReason failureReason){}
</code>```

what happens at above case is saveNewActivity_correctValues method run once first and then two other method run after that. but i want first method to be invoked two times before each dependent method and once as separate test. i can't put first method as @BeforeMethod because it is already a test and have a provider of it's own.

答:
Use the @Before annotation on the method you want to run before all tests.

If you don't want it to run before all methods, but only some, either refactor your tests out into 2 classes and use @Before in one, and not in the other and move your methods appropriately.

The other option is to just call the method(s) from each test you want them to run before.

I'm assuming you are using JUnit - so see here:

http://junit.sourceforge.net/javadoc/org/junit/Before.html

If not, update your post with what you are using.

Body:
I have a test method as below that two other test methods are dependent to this method and this method should run before these two each time and not only once for both.

 @Test(dataProvider = "requestParameterProvider", groups = "jsonRequest")
 public void saveNewActivity_correctValues(Service service,
 Map<String, Object> requestMap){}

 @Test(dependsOnMethods = "saveNewActivity_trackRequest_correctValues", dataProvider = "responseParameterProvider")
public void commitActivity_correctValues(Service service){}

@Test(dependsOnMethods = "saveNewActivity_trackRequest_correctValues", dataProvider = "exceptionParameterProvider")
public void failActivity_correctValues(Service service, FailureReason failureReason){}

what happens at above case is saveNewActivity_correctValues method run once first and then two other method run after that. but i want first method to be invoked two times before each dependent method and once as separate test. i can't put first method as @BeforeMethod because it is already a test and have a provider of it's own.


问:
Can't count the occurences of the entity with a field of particular value inside a nested property using Spring Data ElasticSearch Repository
I have the Article entity and inside it there is a nested property, let's say Metadata.

I need to count all articles, which have a particular field inside this nested property, let's say indexed, assigned to e.g. 1.

Java Document Snippet:

```<code>@Document(indexName = "article", type = "article", useServerConfiguration = true, createIndex = false)
@Setting(settingPath = "/mappings/settings.json")
@Mapping(mappingPath = "/mappings/articles.json")
public class Article {

// getters and setters, empty constructor are omitted for brevity
    @Id
    private String id;

    private Metadata metadata;

// remainder of the body is omitted

}
</code>```

Metadata.class snippet

```<code>public class Metadata {

// getters and setters, empty constructor are omitted for brevity
    private Integer indexed;

// remainder of the body is omitted
}

</code>```

The query I use to retrieve articles, which satisfy the given criteria and which I put as a value of @org.springframework.data.elasticsearch.annotations.Query on top of the custom method:

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "metadata",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "metadata.indexed": 1
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}
</code>```

My custom Spring Data ElasticSearch repository snippet with a custom method:

```<code>public CustomSpringDataElasticsearchRepository extends ElasticsearchRepository<Article, String> {

    @Query("The query from above")
    Long countByMetadata_Indexed(int value);
}
</code>```

When I use the repository method shown above , I get java.lang.IllegalArgumentException: Expected 1 but found n results.

Custom Spring Data Elasticsearch Repository method(without @Query) returns 0(version without underscore returns 0 as well) though it should return everything correctly.

How do I get the correct results using Spring Data ElasticSearch Repository? Why does the custom method without @Query doesn't work as well?

UPD: The version of spring-data-elasticsearch used is 3.1.1.RELEASE.

答:
Repository query methods currently(3.2.4.RELEASE) don't support the count by the fields inside nested fields.

As was mentioned previously, @Query annotation doesn't support custom count queries as of the latest version(3.2.4.RELEASE).

In other words, currently, the only way to do this query through Spring Data ElasticSearch is to use ElasticsearchTemplate bean or ElasticsearchOperations bean.

Credit: P.J.Meisch

Body:
I have the Article entity and inside it there is a nested property, let's say Metadata.

I need to count all articles, which have a particular field inside this nested property, let's say indexed, assigned to e.g. 1.

Java Document Snippet:

@Document(indexName = "article", type = "article", useServerConfiguration = true, createIndex = false)
@Setting(settingPath = "/mappings/settings.json")
@Mapping(mappingPath = "/mappings/articles.json")
public class Article {

// getters and setters, empty constructor are omitted for brevity
    @Id
    private String id;

    private Metadata metadata;

// remainder of the body is omitted

}

Metadata.class snippet

public class Metadata {

// getters and setters, empty constructor are omitted for brevity
    private Integer indexed;

// remainder of the body is omitted
}

The query I use to retrieve articles, which satisfy the given criteria and which I put as a value of @org.springframework.data.elasticsearch.annotations.Query on top of the custom method:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "metadata",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "metadata.indexed": 1
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

My custom Spring Data ElasticSearch repository snippet with a custom method:

public CustomSpringDataElasticsearchRepository extends ElasticsearchRepository
 {

    @Query("The query from above")
    Long countByMetadata_Indexed(int value);
}

When I use the repository method shown above , I get java.lang.IllegalArgumentException: Expected 1 but found n results.

Custom Spring Data Elasticsearch Repository method(without @Query) returns 0(version without underscore returns 0 as well) though it should return everything correctly.

How do I get the correct results using Spring Data ElasticSearch Repository? Why does the custom method without @Query doesn't work as well?

UPD: The version of spring-data-elasticsearch used is 3.1.1.RELEASE.


问:
why I can receive the old app's push notification when the iphone app reinstall?
uninstall the app first, then reinstall, I can receive the push notification normally.
here is my analysis:
   client uninstalls app, but my provider server has the devicetoken. then reinstall,APNS delivers the same devicetoken to iphone,so when a new push item comes to APNS,it successly delivers the item to the client.
   my app has synchronized devicetoken records with the provider itself,but this problem comes when no launching after reinstall(if the user launch after reinstall,I can remove the register accounts under the devicetoken).how can i solve this problem?</p>

答:
It can not ever be delivered until you save the new device token from</p>

```<code>- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It can not ever be delivered until you save the new device token from

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken


答:
Query:

```<code>SELECT [Definition], isnull([1],0) AS Jan,
         isnull([2],0) AS Feb,
         isnull([3],0) AS Mar,
         isnull([4],0) AS Apr,
         isnull([5],0) AS May,
         isnull([6],0) AS Jun,
         isnull([7],0) AS Jul,
         isnull([8],0) AS Aug,
         isnull([9],0) AS Sep,
         isnull([10],0) AS Oct,
         isnull([11],0) AS Nov,
         isnull([12],0) AS [Dec]
        FROM
       (Select Id, MONTH(DateCrated) as TMonth,[Definition],Rating
          FROM GraphDetails
       WHERE YEAR(DateCrated) = 2020 AND GoalId = 1
        ) [source]
    PIVOT
    (
    sum(Rating)
        FOR TMonth
        IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
    ) AS pvtMonth
</code>```

Result :

Title: How can I get values of the Rating column together with their definition for every specific month by using Pivot with Month in MSSQL

Body:
Example :

Data:

GraphDetails
|----------------------------------------------------------|
| Id  GoalId  Definition                Rating  DateCrated |
| -------------------------------------------------------- |
| 1   2       Zero Infra Back Log       100     2020-02-05 |
| 2   2       Happy Customers           95      2020-02-05 |
| 3   2       Complete All Projects     100     2020-02-05 |
| 4   1       Zero Infra Back Log       100     2020-02-05 |
| 5   1       Happy Customers           98      2020-02-05 |
| 6   1       Complete All Projects     100     2020-02-05 |
|----------------------------------------------------------|

Query:

SELECT
 [1] AS Jan,
 [2] AS Feb,
 [3] AS Mar,
 [4] AS Apr,
 [5] AS May,
 [6] AS Jun,
 [7] AS Jul,
 [8] AS Aug,
 [9] AS Sep,
 [10] AS Oct,
 [11] AS Nov,
 [12] AS [Dec]
FROM
(Select Id, MONTH(DateRecorded) as TMonth
  FROM GraphDetails
    WHERE YEAR(DateRecorded) = 2020 AND GoalId = 1
    ) source
PIVOT
( Definition, Rating
    FOR TMonth
    IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth

I get this error:

Incorrect syntax near ','.

In line with " Definition, Rating "

Result should look like this:

|-------------------------------------------------------------------------------------------------|
| Definition              | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
|-------------------------------------------------------------------------------------------------|
| Zero Infra Back Log     | 0   | 100 | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   |
| Happy Customers         | 0   | 98  | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   |
| Complete All Projects   | 0   | 100 | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   | 0   |
|-------------------------------------------------------------------------------------------------|

Is this possible?
Any help, please!

Thank you!

*The code above was based on PIVOT with MONTH().

Body:
Query:

SELECT [Definition], isnull([1],0) AS Jan,
         isnull([2],0) AS Feb,
         isnull([3],0) AS Mar,
         isnull([4],0) AS Apr,
         isnull([5],0) AS May,
         isnull([6],0) AS Jun,
         isnull([7],0) AS Jul,
         isnull([8],0) AS Aug,
         isnull([9],0) AS Sep,
         isnull([10],0) AS Oct,
         isnull([11],0) AS Nov,
         isnull([12],0) AS [Dec]
        FROM
       (Select Id, MONTH(DateCrated) as TMonth,[Definition],Rating
          FROM GraphDetails
       WHERE YEAR(DateCrated) = 2020 AND GoalId = 1
        ) [source]
    PIVOT
    (
    sum(Rating)
        FOR TMonth
        IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
    ) AS pvtMonth

Result :


问:
Default Argument for Function Template not working
I have a function that prints out value_one if it is greater than or less value_two based on the comparison passed through.

```<code>template<typename T, typename cmp = less<T> >
void function(T value_one, T value_two, cmp) {
    cmp comparator;
    if (comparator(value_one, value_two)) {
        std::cout << value_one;
    }
}
</code>```

Now, this function defaults to using the less function object to decide to print value_one out or not, but can also use the more function object.

```<code>template<typename T>
class more {
public:
    bool operator()(const T& value_one, const T& value_two) {
        return value_one > value_two;
    }
};

template<typename T>
class less{
public:
    bool operator()(const T& value_one, const T& value_two) {
        return value_one < value_two;
    }
};
</code>```

when i call the following code in main

```<code>more<int> a;
function(7,5,a);
</code>```

7 is printed out as expected but the next code is deemed illegal, and VS tells me that no matching overloaded function can be found.

```<code>function(5,7);
</code>```

I thought that the cmp function object would default to less when not explicitly provided and thus would still be able to work. Why does this not work? Is there a way to make this code work without overloading it to just have two parameters?

答:
You have defaulted the type cmp, but not the argument of the function. In fact, you have not given it any name.

You also need to provide a default for the argument:

```<code>template<typename T, typename cmp = less<T> >
void function(T value_one, T value_two, cmp = {}) {
    // ...
}
</code>```

Body:
I have a function that prints out value_one if it is greater than or less value_two based on the comparison passed through.

template<typename T, typename cmp = less<T> >
void function(T value_one, T value_two, cmp) {
    cmp comparator;
    if (comparator(value_one, value_two)) {
        std::cout << value_one;
    }
}

Now, this function defaults to using the less function object to decide to print value_one out or not, but can also use the more function object.

template<typename T>
class more {
public:
    bool operator()(const T& value_one, const T& value_two) {
        return value_one > value_two;
    }
};

template<typename T>
class less{
public:
    bool operator()(const T& value_one, const T& value_two) {
        return value_one < value_two;
    }
};

when i call the following code in main

more<int> a;
function(7,5,a);

7 is printed out as expected but the next code is deemed illegal, and VS tells me that no matching overloaded function can be found.

function(5,7);

I thought that the cmp function object would default to less when not explicitly provided and thus would still be able to work. Why does this not work? Is there a way to make this code work without overloading it to just have two parameters?

Body:
You have defaulted the type cmp, but not the argument of the function. In fact, you have not given it any name.

You also need to provide a default for the argument:

template<typename T, typename cmp = less<T> >
void function(T value_one, T value_two, cmp = {}) {
    // ...
}


问:
permission denied error on tomcat docker image deployment to openshift container - /usr/local/tomcat/conf/web.xml (permission denied)
Here is my Dockerfile content. When I run this locally it works well but when I try to deploy it on the openshift container it throws permission denied error

```<code>    FROM tomcat:8.0.36-jre8
    CMD groupadd -r myuser -g 501
    CMD useradd -d /home/myuser -u 501 -m -s /bin/bash -g myuser myuser
    CMD chown -R myuser:myuser /usr/local/tomcat
    ADD target/ui-1.0.war /usr/local/tomcat/webapps/
    ADD docker-tomcat-conf/server.xml /usr/local/tomcat/conf/
    ADD docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF
    EXPOSE 8080
    CMD chmod +x /usr/local/tomcat/bin/catalina.sh
    ENTRYPOINT ["catalina.sh", "run"]
</code>```

and the error

```<code>    Parse error in application web.xml file at file:/usr/local/tomcat/conf/web.xml
java.io.FileNotFoundException: /usr/local/tomcat/conf/web.xml (Permission denied)
    at java.io.FileInputStream.open0(Native Method)
</code>```

答:
There are might be some policies on the openshift site which not allow you to run your container in priviledged mode (e.g. use root account to run processes)

You must to find out under which user tomcat is started (see openshift policies, ask your cluster administrator)  and align all neccessary file and folder permissions accordingly, using chown and/or chmod in Dockerfile.

Body:
Here is my Dockerfile content. When I run this locally it works well but when I try to deploy it on the openshift container it throws permission denied error

    FROM tomcat:8.0.36-jre8
    CMD groupadd -r myuser -g 501
    CMD useradd -d /home/myuser -u 501 -m -s /bin/bash -g myuser myuser
    CMD chown -R myuser:myuser /usr/local/tomcat
    ADD target/ui-1.0.war /usr/local/tomcat/webapps/
    ADD docker-tomcat-conf/server.xml /usr/local/tomcat/conf/
    ADD docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF
    EXPOSE 8080
    CMD chmod +x /usr/local/tomcat/bin/catalina.sh
    ENTRYPOINT ["catalina.sh", "run"]

and the error

    Parse error in application web.xml file at file:/usr/local/tomcat/conf/web.xml
java.io.FileNotFoundException: /usr/local/tomcat/conf/web.xml (Permission denied)
    at java.io.FileInputStream.open0(Native Method)


问:
D3 force simulation in Angular
I'm trying to have a d3 force simulation in Angular app. Basically what I have is run method that initialize and set simulation options and ticked method that updates simulation on each tick. I have a couple of problems related to this. (JavaScript version of the code works just fine)

My initial code is

```<code>private run() {
  this.simulation = d3.forceSimulation()
  //some code
  this.simulation.on('tick', this.ticked())
}

private ticked() {
  //code
}
</code>```

This does not work (simulation does not tick). But if I inline the ticked method like below, it works and simulation continues.

```<code>private run() {
  this.simulation = d3.forceSimulation()
  //some code
  this.simulation.on('tick', () => {
   //code
  })
}
</code>```

Is there a specific reason for this? I'm new to Angular and d3, it might be simple as how JavaScript behaves.

second question, previous code snippet (2nd one) works for few seconds and then simulation freeze. There are no error messages in the console. Can you guess why this is happening?
I hope this is detailed enough. I can add more details if needed.

答:
The first attempt you made you was passing the return value from your method 'ticked' to the event function.

The event 'on' receives two parameters, the first is the event you are binding to, in this case 'tick' and a callback function that executes when the event returns a value. You was passing as second argument a value, and not a callback function. So it was executing your function before the event was triggered.

You can use your function 'ticked' with the callback like this:

```<code>this.simulation.on('tick', () => this.ticked());
</code>```

Title: D3 force simulation in Angular

Body:
I'm trying to have a d3 force simulation in Angular app. Basically what I have is run method that initialize and set simulation options and ticked method that updates simulation on each tick. I have a couple of problems related to this. (JavaScript version of the code works just fine)

My initial code is

private run() {
  this.simulation = d3.forceSimulation()
  //some code
  this.simulation.on('tick', this.ticked())
}

private ticked() {
  //code
}

This does not work (simulation does not tick). But if I inline the ticked method like below, it works and simulation continues.

private run() {
  this.simulation = d3.forceSimulation()
  //some code
  this.simulation.on('tick', () => {
   //code
  })
}

Is there a specific reason for this? I'm new to Angular and d3, it might be simple as how JavaScript behaves.

second question, previous code snippet (2nd one) works for few seconds and then simulation freeze. There are no error messages in the console. Can you guess why this is happening?
I hope this is detailed enough. I can add more details if needed.

Body:
The first attempt you made you was passing the return value from your method 'ticked' to the event function.

The event 'on' receives two parameters, the first is the event you are binding to, in this case 'tick' and a callback function that executes when the event returns a value. You was passing as second argument a value, and not a callback function. So it was executing your function before the event was triggered.

You can use your function 'ticked' with the callback like this:

this.simulation.on('tick', () => this.ticked());


问:
Is "logout" useless on a REST API?
Considering that, by definition, a REST API is stateless: is the "logout" operation useless?

I mean, I'm creating a REST API using encrypted JWT. Each token has an expiration time of, let's say, 60 minutes. If I save on a database table the last tokens generated by the API, the "logout" would be done deleting them from the table of valid tokens. But, if I do that, I understand that the API will cease to be stateless, right?

So, I understand that I shouldn't do that. The only solution that I'm thinking is make the JWT expiration time shorter, to 5 minutes, don't implement a "logout" operation and just let the tokens expire.

Is this the correct approach?

答: With a short expiration time on the token I would think for most applications deleting the token from  the client on logout would be a good solution.  Anything more would rely on the server and no longer be stateless.</p>

Title: Is "logout" useless on a REST API?


问:
Saving multiple lists as a csv file in python
I am trying to read multiple xml files and extract the data from these files. I am trying to extract two sets of data and save them into two separate csv files.

From the extractData function, I get a list of data from a single file. In the createCSV function, I extract only the data which I require.

I want to save all the extracted data from all the files I read into one csv file. Currently, I am only able to save the last file.

```<code>import json
import os
import pandas as pd
import numpy as np
import bs4
import glob
import csv

def extractData(path):
    for filename in glob.glob(os.path.join(path, '*.xml')):
        genre = bs4.BeautifulSoup(open(filename, 'r', encoding="utf8"), features="lxml")
        #print(genre)
        if genre.find_all("name") == []:
            print('Not Available')
        else:
            tags = genre.find_all("name")
            genre_list = []
            for name in tags:
                genres = name.text.strip()
                genre_list.append(genres)
            #print(genre_list)
    return genre_list

def createCSV(list_genre):
    new_artist_list = []
    new_genre_list = []
    complete_list = pd.DataFrame(list_genre)
    new_col = len(complete_list)
    #print(complete_list)
    #print(new_col)
    if new_col == 2:
        #for complete_list in complete_lists:
        column_names_1 = ["Song", "Artist"]
        final_list_1 = complete_list.T
        final_list_1.columns = column_names_1
        #print(final_list_1)
        new_artist_list.append(final_list_1)
        #print(new_artist_list)
    elif new_col > 2:
        #for complete_list in complete_lists:
        column_names_2 = ["Song", "Artist", "Genre"]
        #print(complete_list)
        final_list_2 = complete_list.T
        final_list_3 = np.array(final_list_2)
        #print(final_list_3)
        song_list = final_list_3[:, 0]
        artist_list = final_list_3[:, 1]
        final_list_2['Genre'] = final_list_2[final_list_2.columns[2:]].apply(lambda x: ','.join(x.dropna().astype(str)), axis=1)
        #print(final_list_2['Genre'])
        combined = np.concatenate((song_list, artist_list))
        combined_list = np.concatenate((combined, final_list_2['Genre']))
        #print(combined_list)
        complete_list_final = pd.DataFrame(combined_list)
        #print(complete_list_final)
        complete_list_final_1 = complete_list_final.T
        complete_list_final_1.columns = column_names_2
        new_genre_list.append(complete_list_final_1)
        #print(new_genre_list)
    print(new_artist_list)
    print(new_genre_list)
    return new_artist_list, new_genre_list

def writeCSV(partial_list, complete_list):
    partial_lists = partial_list
    complete_lists = complete_list
    artist_init = []
    complete_init = []
    for i, j in zip(partial_lists, complete_lists):
        with open('data_only_artist_name.csv', 'w', encoding="utf8") as data_partial:
            artist_csv = csv.writer(data_partial)
            artist_csv.writerow(i)
            artist_init.append(artist_csv)

        with open('data_complete.csv', 'w', encoding="utf8") as data_complete:
            complete_csv = csv.writer(data_complete)
            complete_csv.writerow(j)
            complete_init.append(complete_csv)
            #print(new_genre_list)
    a = artist_init
    b = complete_init
    return a, b

path = 'XML Data'
data = extractData(path)
print(data)
partial, complete = createCSV(data)
list_partial, list_complete = writeCSV(partial, complete)
</code>```

答:
As mentioned by Serge, open your files in append mode to avoid overwriting them in the for loop:

```<code>def writeCSV(partial_list, complete_list):
    artist_init = []
    complete_init = []
    # Create empty files
    # Comment to keep previously written files
    open('data_only_artist_name.csv', 'w')
    open('data_complete.csv', 'w')
    for i, j in zip(partial_list, complete_list):
        with open('data_only_artist_name.csv', 'a', encoding="utf8") as data_partial:
            artist_csv = csv.writer(data_partial)
            artist_csv.writerow(i)
            artist_init.append(artist_csv)

        with open('data_complete.csv', 'a', encoding="utf8") as data_complete:
            complete_csv = csv.writer(data_complete)
            complete_csv.writerow(j)
            complete_init.append(complete_csv)
            #print(new_genre_list)
    return artist_init, complete_init
</code>```

Body:
I am trying to read multiple xml files and extract the data from these files. I am trying to extract two sets of data and save them into two separate csv files.

From the extractData function, I get a list of data from a single file. In the createCSV function, I extract only the data which I require.

I want to save all the extracted data from all the files I read into one csv file. Currently, I am only able to save the last file.

import json
import os
import pandas as pd
import numpy as np
import bs4
import glob
import csv

def extractData(path):
    for filename in glob.glob(os.path.join(path, '*.xml')):
        genre = bs4.BeautifulSoup(open(filename, 'r', encoding="utf8"), features="lxml")
        #print(genre)
        if genre.find_all("name") == []:
            print('Not Available')
        else:
            tags = genre.find_all("name")
            genre_list = []
            for name in tags:
                genres = name.text.strip()
                genre_list.append(genres)
            #print(genre_list)
    return genre_list

def createCSV(list_genre):
    new_artist_list = []
    new_genre_list = []
    complete_list = pd.DataFrame(list_genre)
    new_col = len(complete_list)
    #print(complete_list)
    #print(new_col)
    if new_col == 2:
        #for complete_list in complete_lists:
        column_names_1 = ["Song", "Artist"]
        final_list_1 = complete_list.T
        final_list_1.columns = column_names_1
        #print(final_list_1)
        new_artist_list.append(final_list_1)
        #print(new_artist_list)
    elif new_col > 2:
        #for complete_list in complete_lists:
        column_names_2 = ["Song", "Artist", "Genre"]
        #print(complete_list)
        final_list_2 = complete_list.T
        final_list_3 = np.array(final_list_2)
        #print(final_list_3)
        song_list = final_list_3[:, 0]
        artist_list = final_list_3[:, 1]
        final_list_2['Genre'] = final_list_2[final_list_2.columns[2:]].apply(lambda x: ','.join(x.dropna().astype(str)), axis=1)
        #print(final_list_2['Genre'])
        combined = np.concatenate((song_list, artist_list))
        combined_list = np.concatenate((combined, final_list_2['Genre']))
        #print(combined_list)
        complete_list_final = pd.DataFrame(combined_list)
        #print(complete_list_final)
        complete_list_final_1 = complete_list_final.T
        complete_list_final_1.columns = column_names_2
        new_genre_list.append(complete_list_final_1)
        #print(new_genre_list)
    print(new_artist_list)
    print(new_genre_list)
    return new_artist_list, new_genre_list

def writeCSV(partial_list, complete_list):
    partial_lists = partial_list
    complete_lists = complete_list
    artist_init = []
    complete_init = []
    for i, j in zip(partial_lists, complete_lists):
        with open('data_only_artist_name.csv', 'w', encoding="utf8") as data_partial:
            artist_csv = csv.writer(data_partial)
            artist_csv.writerow(i)
            artist_init.append(artist_csv)

        with open('data_complete.csv', 'w', encoding="utf8") as data_complete:
            complete_csv = csv.writer(data_complete)
            complete_csv.writerow(j)
            complete_init.append(complete_csv)
            #print(new_genre_list)
    a = artist_init
    b = complete_init
    return a, b

path = 'XML Data'
data = extractData(path)
print(data)
partial, complete = createCSV(data)
list_partial, list_complete = writeCSV(partial, complete)

Body:
As mentioned by Serge, open your files in append mode to avoid overwriting them in the for loop:

def writeCSV(partial_list, complete_list):
    artist_init = []
    complete_init = []
    # Create empty files
    # Comment to keep previously written files
    open('data_only_artist_name.csv', 'w')
    open('data_complete.csv', 'w')
    for i, j in zip(partial_list, complete_list):
        with open('data_only_artist_name.csv', 'a', encoding="utf8") as data_partial:
            artist_csv = csv.writer(data_partial)
            artist_csv.writerow(i)
            artist_init.append(artist_csv)

        with open('data_complete.csv', 'a', encoding="utf8") as data_complete:
            complete_csv = csv.writer(data_complete)
            complete_csv.writerow(j)
            complete_init.append(complete_csv)
            #print(new_genre_list)
    return artist_init, complete_init


问:
npm behind a proxy fails with status 403
I'm trying to run npm behind a proxy. I've tried both entering the proxy directly or through Authoxy:

```<code>npm config set proxy http://localhost:8999
npm config set https-proxy http://localhost:8999
</code>```

Regardless of which proxy I use, I always end up with the same error when running npm search:

```<code>npm info it worked if it ends with ok
npm verb cli [ 'node', '/usr/local/bin/npm', 'search' ]
npm info using npm@1.1.45
npm info using node@v0.8.4
npm verb config file /Users/xxx/.npmrc
npm verb config file /usr/local/etc/npmrc
npm verb config file /usr/local/lib/node_modules/npm/npmrc
npm WARN Building the local index for the first time, please be patient
npm verb url raw /-/all
npm verb url resolving [ 'https://registry.npmjs.org/', './-/all' ]
npm verb url resolved https://registry.npmjs.org/-/all
npm info retry registry request attempt 1 at 09:48:47
npm http GET https://registry.npmjs.org/-/all
npm info retry will retry, error on last attempt: Error: tunneling socket could not be established, sutatusCode=403
npm info retry registry request attempt 2 at 09:48:57
npm http GET https://registry.npmjs.org/-/all
npm info retry will retry, error on last attempt: Error: tunneling socket could not be established, sutatusCode=403
npm info retry registry request attempt 3 at 09:49:57
npm http GET https://registry.npmjs.org/-/all
npm ERR! Error: tunneling socket could not be established, sutatusCode=403
npm ERR!     at ClientRequest.onConnect (/usr/local/lib/node_modules/npm/node_modules/request/tunnel.js:148:19)
npm ERR!     at ClientRequest.g (events.js:185:14)
npm ERR!     at ClientRequest.EventEmitter.emit (events.js:115:20)
npm ERR!     at Socket.socketOnData (http.js:1383:11)
npm ERR!     at TCP.onread (net.js:410:27)
</code>```

The command always fails with sutatusCode [sic!] 403 - which means unauthorized. I have set up Authoxy to not require a username/password. The same error happens when I bypass Authoxy and provide the real proxy credentials for our NTLM proxy in the form of http:// user:pass@proxy:port.

How can I make this work through the proxy?

Update

I have created an issue on the NPM project to report this: https://github.com/isaacs/npm/issues/2866

答:
On windows 10, do

```<code>npm config edit
</code>```

This will open config file in a text editor. Delete all the set proxy variables by user and only let default values stay.

```<code>;;;;
; npm userconfig file
; this is a simple ini-formatted file
; lines that start with semi-colons are comments.
; read `npm help config` for help on the various options
;;;;

--->Delete everything proxy settings from here.

;;;;
; all options with default values
;;;;
</code>```

Close and save. Try again. That's what worked for me in my localhost.

Body:
I'm trying to run npm behind a proxy. I've tried both entering the proxy directly or through Authoxy:

npm config set proxy http://localhost:8999
npm config set https-proxy http://localhost:8999

Regardless of which proxy I use, I always end up with the same error when running npm search:

npm info it worked if it ends with ok
npm verb cli [ 'node', '/usr/local/bin/npm', 'search' ]
npm info using npm@1.1.45
npm info using node@v0.8.4
npm verb config file /Users/xxx/.npmrc
npm verb config file /usr/local/etc/npmrc
npm verb config file /usr/local/lib/node_modules/npm/npmrc
npm WARN Building the local index for the first time, please be patient
npm verb url raw /-/all
npm verb url resolving [ 'https://registry.npmjs.org/', './-/all' ]
npm verb url resolved https://registry.npmjs.org/-/all
npm info retry registry request attempt 1 at 09:48:47
npm http GET https://registry.npmjs.org/-/all
npm info retry will retry, error on last attempt: Error: tunneling socket could not be established, sutatusCode=403
npm info retry registry request attempt 2 at 09:48:57
npm http GET https://registry.npmjs.org/-/all
npm info retry will retry, error on last attempt: Error: tunneling socket could not be established, sutatusCode=403
npm info retry registry request attempt 3 at 09:49:57
npm http GET https://registry.npmjs.org/-/all
npm ERR! Error: tunneling socket could not be established, sutatusCode=403
npm ERR!     at ClientRequest.onConnect (/usr/local/lib/node_modules/npm/node_modules/request/tunnel.js:148:19)
npm ERR!     at ClientRequest.g (events.js:185:14)
npm ERR!     at ClientRequest.EventEmitter.emit (events.js:115:20)
npm ERR!     at Socket.socketOnData (http.js:1383:11)
npm ERR!     at TCP.onread (net.js:410:27)

The command always fails with sutatusCode [sic!] 403 - which means unauthorized. I have set up Authoxy to not require a username/password. The same error happens when I bypass Authoxy and provide the real proxy credentials for our NTLM proxy in the form of http:// user:pass@proxy:port.

How can I make this work through the proxy?

Update

I have created an issue on the NPM project to report this: https://github.com/isaacs/npm/issues/2866

Body:
On windows 10, do

npm config edit

This will open config file in a text editor. Delete all the set proxy variables by user and only let default values stay.

;;;;
; npm userconfig file
; this is a simple ini-formatted file
; lines that start with semi-colons are comments.
; read `npm help config` for help on the various options
;;;;

--->Delete everything proxy settings from here.

;;;;
; all options with default values
;;;;

Close and save. Try again. That's what worked for me in my localhost.


问:
Hide/remove/change color of a canvas circle When toched in Android
this is my first question here, so maybe I'll make some mistakes.

I want to create an Android app for touch test, and draw a cross on the screen, however I'm succeeded to draw cross, but now I want to implement test screen login.

What I want to do is that, When user clicks on any circle it should be removed/hidden or change color to transparent.

Any kind of help would be appreciated.

this is the link to my code.

https://github.com/akhlaqshah36/stackoverflow_questions/blob/master/drawCicles

and attached screenshot.

答:
I got the solution by using some formulas of distance and Using Pointer objects.

check the solution here if someone need it.

Solution Link drawing cross in canvas


问:
How to make timer task in informatica succeed after a duration
I'm curious as to how to make the status of the timer task changes to succeed? I have many sessions whereby some of them are connected in series and some are in parallel... After every session has run successfully, the status of the timer task is still showing running... How do I make it change to succeed as well...
The condition is if the workflow finishes below the allocated time of 20 minutes, the timer task has to change to succeed, but if it exceeds 20 minutes, then it should send an email to the assigned user and abort the workflow.....

Unix:

```<code> if[[ $Event_Exceed20min > 20 AND $EVent_Exceed20min.Status = Running ]]
    pmcmd stopworkflow -service informatica-integration-Service -d domain-name - u user-name -p password -f folder-name -w workflow-name
    $Event_Exceed20min.Status = SUCCEEDED
 fi
</code>```

答:
You can use UNIX script to do this. I dont see informatica alone can do this.

 You can create a script which will kick off the informatica using pmcmd,

 keep polling the status.

kick off the flow and start timer

start checking status

if timer goes >1200 seconds, abort and mail, else continue polling

Code sniped below...

```<code>#!/bin/bash

wf=$1
sess=$2
mailids="xyz@abc.com,abc@goog.com"
log="~/log/"$wf"log.txt"

echo "Start Workflow..."> $log
pmcmd  startworkflow -sv service -d domain -u username -p password  -f "FolderName" $wf

#Timer starts, works only in BASH
start=$SECONDS

while :
do
    #Check Timer, if >20min abort the flow.
    end=$SECONDS
    duration=$(( end - start ))
    if [ $duration -gt 1200 ]; then
    pmcmd stopworkflow -sv service -d domain -u username -p password -f prd_CLAIMS  -w  $wf
    STAT=$?
    #Error check if not aborted
    mailx -s "Workflow took >20min so aborted" $mailids
    fi

    pmcmd getsessionstatistics -sv service -d domain -u username -p password  -f prd_CLAIMS -w  $wf $sess > ~/log/tmp.txt
    STAT=$?
    if [ "$STAT" != 0 ]; then
    echo "Staus check failed" >> $log
    fi
    echo $(grep "[Succeeded] " ~/log/tmp.txt| wc -l) > ~/log/tmp2.txt
    STAT=$?
    if [ -s ~/log/tmp2.txt ]; then
    echo "Workflow Succeeded...">> $log
    exit
    fi
    sleep 30
done

echo "End Workflow...">> $log
</code>```

Body:
I'm curious as to how to make the status of the timer task changes to succeed? I have many sessions whereby some of them are connected in series and some are in parallel... After every session has run successfully, the status of the timer task is still showing running... How do I make it change to succeed as well...
The condition is if the workflow finishes below the allocated time of 20 minutes, the timer task has to change to succeed, but if it exceeds 20 minutes, then it should send an email to the assigned user and abort the workflow.....

Unix:

 if[[ $Event_Exceed20min > 20 AND $EVent_Exceed20min.Status = Running ]]
    pmcmd stopworkflow -service informatica-integration-Service -d domain-name - u user-name -p password -f folder-name -w workflow-name
    $Event_Exceed20min.Status = SUCCEEDED
 fi

Body:
You can use UNIX script to do this. I dont see informatica alone can do this.

 You can create a script which will kick off the informatica using pmcmd,

 keep polling the status.

kick off the flow and start timer

start checking status

if timer goes >1200 seconds, abort and mail, else continue polling

Code sniped below...

#!/bin/bash

wf=$1
sess=$2
mailids="xyz@abc.com,abc@goog.com"
log="~/log/"$wf"log.txt"

echo "Start Workflow..."> $log
pmcmd  startworkflow -sv service -d domain -u username -p password  -f "FolderName" $wf

#Timer starts, works only in BASH
start=$SECONDS

while :
do
    #Check Timer, if >20min abort the flow.
    end=$SECONDS
    duration=$(( end - start ))
    if [ $duration -gt 1200 ]; then
    pmcmd stopworkflow -sv service -d domain -u username -p password -f prd_CLAIMS  -w  $wf
    STAT=$?
    #Error check if not aborted
    mailx -s "Workflow took >20min so aborted" $mailids
    fi

    pmcmd getsessionstatistics -sv service -d domain -u username -p password  -f prd_CLAIMS -w  $wf $sess > ~/log/tmp.txt
    STAT=$?
    if [ "$STAT" != 0 ]; then
    echo "Staus check failed" >> $log
    fi
    echo $(grep "[Succeeded] " ~/log/tmp.txt| wc -l) > ~/log/tmp2.txt
    STAT=$?
    if [ -s ~/log/tmp2.txt ]; then
    echo "Workflow Succeeded...">> $log
    exit
    fi
    sleep 30
done

echo "End Workflow...">> $log


问:
Regular expression to discard "
I have the next regular expression: /i18n(-?).*="(.*)"/g for javascript.

I use https://www.regextester.com to check.

```<code><button i18n="@@user.button" data-test="download-confirmation_ok">
<a i18n-href="@@link.url" href="https://www.aaaa.es" target="_blank">
<div i18n="@@link.text">www.aaaa.es</div>
</code>```

I don't like data-test="download-confirmation_ok" and href="https://www.aaaa.es" target="_blank":
https://imgur.com/sQZQXzZ

I only want i18n or i18n-* text between "TEXT".

How can I discard rest of the tetx?

Thank.

答:
How about:

```<code>(?<=i18n[^=]*?=([\'\"])).*?(?=\1)
</code>```

As seen here

Explanation:

I'm using a positive lookbehind here, which you can learn more about here

Title: Regular expression to discard "

Body:
I have the next regular expression: /i18n(-?).*="(.*)"/g for javascript.

I use https://www.regextester.com to check.

<button i18n="@@user.button" data-test="download-confirmation_ok">

www.aaaa.es

I don't like data-test="download-confirmation_ok" and href="https://www.aaaa.es" target="_blank":
https://imgur.com/sQZQXzZ

I only want i18n or i18n-* text between "TEXT".

How can I discard rest of the tetx?

Thank.

Body:
How about:

(?<=i18n[^=]*?=([\'\"])).*?(?=\1)

As seen here

Explanation:

I'm using a positive lookbehind here, which you can learn more about here


问:
Help with this ragged array/substring program in C?
so, I have a ragged array (called names) of length 200. each pointer in the array points to a string that is no longer than 50 characters and has no white spaces. I also have a string given through user-input called inname, with length 50, inname will be one of the strings stored in names. I need to find a way to go through the strings in my ragged array and find the string with the largest substring overlap with inname, excluding inname itself as that will be in the file. If no string has an overlap then we print out "no recommendation".
I've been melting trying to puzzle this out for many hours now, helps? O:) SO basically, the program finds the name in the array with the largest substring overlap with inname.
will edit to provide additional info if you need it </p>

答:
This won't lead you to the most efficient way to find overlap (dynamic programming is one way--there are other crazy methods like suffix trees), but it should get you started:

First, think about how you would find the length of the overlap with the beginning of both strings aligned. For instance, find the longest overlap between these two:

```<code>programming
ungrammatical
</code>```

In this case, only a single m overlaps--a length of 1.

Then think about how you would "shift" the strings and look for the overlap when they are aligned differently. (Don't actually change the strings: just change how you loop through them to compare them.) What is the overlap between these two?

```<code>programming
 ungrammatical
</code>```

Think about how to look at all possible alignments. If you keep track of the longest one you find, you have the longest alignment between two particular strings.

After that, move on to checking all the different strings. Keep track of the one with the best match, and again, once you have looked at all of them, you have your answer.

Body:
This won't lead you to the most efficient way to find overlap (dynamic programming is one way--there are other crazy methods like suffix trees), but it should get you started:

First, think about how you would find the length of the overlap with the beginning of both strings aligned. For instance, find the longest overlap between these two:

programming
ungrammatical

In this case, only a single m overlaps--a length of 1.

Then think about how you would "shift" the strings and look for the overlap when they are aligned differently. (Don't actually change the strings: just change how you loop through them to compare them.) What is the overlap between these two?

programming
 ungrammatical

Think about how to look at all possible alignments. If you keep track of the longest one you find, you have the longest alignment between two particular strings.

After that, move on to checking all the different strings. Keep track of the one with the best match, and again, once you have looked at all of them, you have your answer.


问:
MySQL - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery
this is the code what im using

```<code>    $Last_Video         = $db->fetch_all('
    SELECT VID, thumb
    FROM video
    WHERE VID IN (
        SELECT VID
        FROM video
        WHERE title LIKE "%'.$Channel['name'].'%"
        ORDER BY viewtime DESC
        LIMIT 5)
    ORDER BY RAND()
    LIMIT 1
');
</code>```

This is the error what give me

```<code> Message:   Error during SQL execution: SELECT VID, thumb FROM video WHERE VID IN ( SELECT VID FROM video WHERE title LIKE "%funny%" ORDER BY viewtime DESC LIMIT 5) ORDER BY RAND() LIMIT 1<br />
 MySQL Error:   This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'<br />
MySQL Errno:    1235
</code>```

how i can fix this problem ? its other way to make it ... so i dont get the error ...

答:
add this is your in condition

(SELECT * FROM (
    SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC)
```

Body:
this is the code what im using

    $Last_Video         = $db->fetch_all('
    SELECT VID, thumb
    FROM video
    WHERE VID IN (
        SELECT VID
        FROM video
        WHERE title LIKE "%'.$Channel['name'].'%"
        ORDER BY viewtime DESC
        LIMIT 5)
    ORDER BY RAND()
    LIMIT 1
');

This is the error what give me

 Message:   Error during SQL execution: SELECT VID, thumb FROM video WHERE VID IN ( SELECT VID FROM video WHERE title LIKE "%funny%" ORDER BY viewtime DESC LIMIT 5) ORDER BY RAND() LIMIT 1

 MySQL Error:   This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

MySQL Errno:    1235

how i can fix this problem ? its other way to make it ... so i dont get the error ...


问:
Regex in sqlite
i have been thinking about this a lot.

So i wanna create a table which contains a password.
The password should at least be 6 chars long a contain minimum 2 numbers.

My version was:

```<code>create table User (
  passwort varchar(80) not null check (length(passwort) >= 6 and passwort like '%[0-9]%[0-9]%')
);
</code>```

The Problem with this approach is that the password has to contain [0-9] twice instead of the actual numbers. Does anyone know how to get rid of that problem ?

Thanks in advance.

答:
While I still recommend you split the work in 2 as per my comment, ie.

Check the length of the string.

Use the actual expression to check if the string contains 2 numbers.

You can use the following expression: ^(?=.{6,}).*?\d.*?\d.*?$. What is does is that it looks ahead for a minimum of 6 characters and then checks that the string is made up from 2 numbers, which can be separated by 0 or more characters.

An example of the expression is available here.

Title: Regex in sqlite

Body:
i have been thinking about this a lot.

So i wanna create a table which contains a password.
The password should at least be 6 chars long a contain minimum 2 numbers.

My version was:

create table User (
  passwort varchar(80) not null check (length(passwort) >= 6 and passwort like '%[0-9]%[0-9]%')
);

The Problem with this approach is that the password has to contain [0-9] twice instead of the actual numbers. Does anyone know how to get rid of that problem ?

Thanks in advance.


问:
How to create a request with indefinitely returns in Spring Boot
I have a web application with notifications for users (like facebook, twitter, instagram notifications). I need to return to my frontend notifications every time some term expires, so my backend has to check every time if there's any term about to expire or if it already expired. That's why I want to create a request that returns something each 5 minutes for example.

I've tried Spring @Schedule and WebSocket.

Using Schedule:

```<code>@Scheduled(fixedDelay = 1000)
    @GetMapping(value = "/notification/get", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<?> returnsNotification() throws InterruptedException {
        Thread.sleep(4000);
        List<Notification> notifications = seachNotifications();
        return new ResponseEntity<>(notifications, HttpStatus.OK);
    }
</code>```

My problem is that with this code my schedule don't work, so my frontend has to call the request everytime.

Using websocket I don't understand how to work with it yet.

答: Have you activated @Scheduled in your spring application with @EnableScheduling? </p>

Body:
I have a web application with notifications for users (like facebook, twitter, instagram notifications). I need to return to my frontend notifications every time some term expires, so my backend has to check every time if there's any term about to expire or if it already expired. That's why I want to create a request that returns something each 5 minutes for example.

I've tried Spring @Schedule and WebSocket.

Using Schedule:

@Scheduled(fixedDelay = 1000)
    @GetMapping(value = "/notification/get", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<?> returnsNotification() throws InterruptedException {
        Thread.sleep(4000);
        List<Notification> notifications = seachNotifications();
        return new ResponseEntity<>(notifications, HttpStatus.OK);
    }

My problem is that with this code my schedule don't work, so my frontend has to call the request everytime.

Using websocket I don't understand how to work with it yet.


问:
Unable to list AWS/EC2 ,AWS/S3, AWS/Glue namespace metric for cloudwatch exporter prometheus
I am currently using prom/cloudwatch-exporter:latest image for working with cloudwatch exporter for my prometheus server. i can able to list

```<code>'AWS/Lambda', 'AWS/ApplicationELB', 'AWS/Firehose', 'AWS/RDS', 'AWS/AutoScaling', 'AWS/ElasticBeanstalk'
</code>```

but when i try to add 'AWS/EC2' it does not display any other values in prometheus dropdown. it is also observed that it does not list values for AWS/S3,AWS/Glue

not sure is it supported or not. or i am missing something

答:
In my experience, this might happen if there are no metric data to show for the time period selected in Prometheus for those services. Try to expand your time range. </p>

<p>Also, if the exporter is causing problems you could consider using an IAM role-based data source in Prometheus.  </p>

Body:
I am currently using prom/cloudwatch-exporter:latest image for working with cloudwatch exporter for my prometheus server. i can able to list

'AWS/Lambda', 'AWS/ApplicationELB', 'AWS/Firehose', 'AWS/RDS', 'AWS/AutoScaling', 'AWS/ElasticBeanstalk'

but when i try to add 'AWS/EC2' it does not display any other values in prometheus dropdown. it is also observed that it does not list values for AWS/S3,AWS/Glue

not sure is it supported or not. or i am missing something

Body:
In my experience, this might happen if there are no metric data to show for the time period selected in Prometheus for those services. Try to expand your time range.

Also, if the exporter is causing problems you could consider using an IAM role-based data source in Prometheus.


问:
Horizontal scroll bar not appearing in TableLayoutPanel regardless of the size of the contents in the columns
I have a panel with AutoScroll = false and AutoSize = false which contains a TableLayoutPanel docked to it as Dock = DockStyle.Fill with the following property values:

```<code>ColumnCount = 2,
Dock = DockStyle.Fill,
CellBorderStyle = TableLayoutPanelCellBorderStyle.Single,
Visible = true,
AutoScroll = true,
AutoSize = false,
</code>```

Each column contains a panel with Dock = DockStyle.Fill, which contains a LinkLabel with the following property values:

```<code>AutoSize = true,
Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
UseCompatibleTextRendering = true,
Size = new Size(190, 19),
Font = new Font(this.Font.Name, 14.5f, FontStyle.Regular, GraphicsUnit.Pixel),
LinkBehavior = LinkBehavior.AlwaysUnderline,
Location = new Point(0, 0),
</code>```

The text of the LinkLabel, which is dynamically set programmatically, can contain pretty long links which require horizontal scrolling by the TableLayoutPanel. Vertical scrolling, when a lot of rows are present, appears as required. Horizontal scrolling (via horizontal scroll bars), on the other hand, does not seem to appear even when there are a lot of characters in the LinkLabel. I have tried fiddling around with the AutoSize property by setting them all to false for every Control as, from my past experience, these can cause scroll bars to not appear.

Thanks in advance.

答:
Using AutoSize = true for TableLayoutPanel is not a good idea as TableLayoutPanel scrolling is full of bugs. It is often necessary to put the TableLayoutPanel in a dedicated parent Panel, which will do the scrolling stuff.

The solution provided here may help you : TableLayoutPanel displays vertical scroll

Body:
I have a panel with AutoScroll = false and AutoSize = false which contains a TableLayoutPanel docked to it as Dock = DockStyle.Fill with the following property values:

ColumnCount = 2,
Dock = DockStyle.Fill,
CellBorderStyle = TableLayoutPanelCellBorderStyle.Single,
Visible = true,
AutoScroll = true,
AutoSize = false,

Each column contains a panel with Dock = DockStyle.Fill, which contains a LinkLabel with the following property values:

AutoSize = true,
Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
UseCompatibleTextRendering = true,
Size = new Size(190, 19),
Font = new Font(this.Font.Name, 14.5f, FontStyle.Regular, GraphicsUnit.Pixel),
LinkBehavior = LinkBehavior.AlwaysUnderline,
Location = new Point(0, 0),

The text of the LinkLabel, which is dynamically set programmatically, can contain pretty long links which require horizontal scrolling by the TableLayoutPanel. Vertical scrolling, when a lot of rows are present, appears as required. Horizontal scrolling (via horizontal scroll bars), on the other hand, does not seem to appear even when there are a lot of characters in the LinkLabel. I have tried fiddling around with the AutoSize property by setting them all to false for every Control as, from my past experience, these can cause scroll bars to not appear.

Thanks in advance.


问:
How do I create a text where it will show current date, but once date is selected it will show the selected date instead? Using SwiftUI. Thank you
I'm a new learner to programming and SwiftUI and I am trying to learn how create a personal diary app.

I want a text to show the current date on startup, but when you select a different date on the calendar, it'll show the selected date instead. I tried to use an if else condition but it doesn't work properly. I think it's because I used "if singleisPresented != false" so it only appears when I click the button. But what I should use instead? Many thanks guys.

I am using the RKCalendar (https://github.com/RaffiKian/RKCalendar) to help me with the calendar.

```<code>                Button(action: { self.singleIsPresented.toggle() }) {
                Image(systemName: "calendar")
                    .foregroundColor(.black)
                    .frame(width: 18, height: 25)
            }
            .sheet(isPresented: self.$singleIsPresented, content: {
                RKViewController(isPresented: self.$singleIsPresented, rkManager: self.rkManager)})
                .onAppear(perform: startUp)
                .navigationViewStyle(StackNavigationViewStyle())

                if singleIsPresented != false {
                Text(self.getTextFromDate(date: self.rkManager.selectedDate))
                    .font(.headline)
                    .fontWeight(.bold)

            } else {
                Text(currentDate(date: Date()))
                    .font(.headline)
                .fontWeight(.bold)

            }
</code>```

答:
You could try something like this:

```<code>Button(action: { self.singleIsPresented.toggle() }) {
                Text("Example 1 - Single Date Selection").foregroundColor(.blue)
            }
            .sheet(isPresented: self.$singleIsPresented, content: {
                RKViewController(isPresented: self.$singleIsPresented, rkManager: self.rkManager1)})

            if rkManager1.selectedDate != nil {
            Text(self.getTextFromDate(date: self.rkManager1.selectedDate))
            } else {
                Text("\(Date())")
            }
</code>```

This checks if the user selected a date and will show the current date until the user selects one. This way, even if they look at the calendar and don't select a date, it'll still show the current date.

Body:
I'm a new learner to programming and SwiftUI and I am trying to learn how create a personal diary app.

I want a text to show the current date on startup, but when you select a different date on the calendar, it'll show the selected date instead. I tried to use an if else condition but it doesn't work properly. I think it's because I used "if singleisPresented != false" so it only appears when I click the button. But what I should use instead? Many thanks guys.

I am using the RKCalendar (https://github.com/RaffiKian/RKCalendar) to help me with the calendar.

                Button(action: { self.singleIsPresented.toggle() }) {
                Image(systemName: "calendar")
                    .foregroundColor(.black)
                    .frame(width: 18, height: 25)
            }
            .sheet(isPresented: self.$singleIsPresented, content: {
                RKViewController(isPresented: self.$singleIsPresented, rkManager: self.rkManager)})
                .onAppear(perform: startUp)
                .navigationViewStyle(StackNavigationViewStyle())

                if singleIsPresented != false {
                Text(self.getTextFromDate(date: self.rkManager.selectedDate))
                    .font(.headline)
                    .fontWeight(.bold)

            } else {
                Text(currentDate(date: Date()))
                    .font(.headline)
                .fontWeight(.bold)

            }

Body:
You could try something like this:

Button(action: { self.singleIsPresented.toggle() }) {
                Text("Example 1 - Single Date Selection").foregroundColor(.blue)
            }
            .sheet(isPresented: self.$singleIsPresented, content: {
                RKViewController(isPresented: self.$singleIsPresented, rkManager: self.rkManager1)})

            if rkManager1.selectedDate != nil {
            Text(self.getTextFromDate(date: self.rkManager1.selectedDate))
            } else {
                Text("\(Date())")
            }

This checks if the user selected a date and will show the current date until the user selects one. This way, even if they look at the calendar and don't select a date, it'll still show the current date.


问:
How to give names to MobX flows
How do I give a name to my flows?
I currently see messages in the console (using dev tools) like:

```<code>action '<unnamed flow> - runid: 3 - init'
index.js:1 action '<unnamed flow> - runid: 3 - yield 0'
</code>```

My code (in typescript):

fetchMetricData = flow( function * (this: MetricDataStore) {
        const responseJson:IMetrics[] = yield Http.post("/metrics");
        this.metrics = responseJson;
});
```

答:
According to following text found in MobX Api Reference · MobX page:

Tip: it is recommended to give the generator function a name, this is the name that will show up in dev tools and such

Unfortunately, this is the only way to set the name (I use LiveScript and can't set names to function expressions while defining it).

In your case, you can turn your unnamed function expression into a named one. If you ever face another situation where you can't, you could also use Object.defineProperty(myFunction, 'name', {value: 'myExplicitName'}).

You can find the culprit in the code: mobx/flow.ts at master · mobxjs/mobx.

Title: How to give names to MobX flows

Body:
How do I give a name to my flows?
I currently see messages in the console (using dev tools) like:

action '<unnamed flow> - runid: 3 - init'
index.js:1 action '<unnamed flow> - runid: 3 - yield 0'

My code (in typescript):

fetchMetricData = flow( function * (this: MetricDataStore) {
        const responseJson:IMetrics[] = yield Http.post("/metrics");
        this.metrics = responseJson;
});


问:
How to update an array after splice in Svelte?
I'm learning Svelte, and read in the documentation that arrays need to be reassigned in order for a component or page to update it. For that they devised a more idiomatic solution. Instead of writing:

```<code>messages.push('hello');
messages = messages;
</code>```

you can write instead:

```<code>messages = [...messages, 'hello'];
</code>```

Alright, makes sense. But then the documentation says:

You can use similar patterns to replace pop, shift, unshift and splice.

But how? I cannot see how you can remove items from an array. More to the point, how could I write the following more idiomatically?

```<code>messages.splice(messages.indexOf('hello'), 1);
messages = messages;
</code>```

答:
You can perform the usual push and pop or `splice on your Array

But because Svelte's reactivity is triggered by assignments, using array methods like push and splice won't automatically cause updates.

According to All about Immutable Arrays and Objects in JavaScript you can do it this way...

```<code>let messages = ['something', 'another', 'hello', 'word', 'another', 'again'];

const indexOfHello = messages.indexOf('hello');

messages = [...messages.slice(0, indexOfHello), ...messages.slice(indexOfHello + 1)];
</code>```

Note the difference between splice and slice

The splice() method adds/removes items to/from an array, and returns
  the removed item(s).  Note: This method changes the original array.
  Syntax: array.splice(start, deleteCount, itemstoAdd, addThisToo);

But

The slice() method returns the selected elements in an array, as a new array object. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.
  Note: The original array will not be changed.

In order words

It return a shallow copy of a portion of an array into a new array
  object selected from begin to end (end not included). The original
  array will not be modified.
  Syntax: array.slice(start, end);

Body:
I'm learning Svelte, and read in the documentation that arrays need to be reassigned in order for a component or page to update it. For that they devised a more idiomatic solution. Instead of writing:

messages.push('hello');
messages = messages;

you can write instead:

messages = [...messages, 'hello'];

Alright, makes sense. But then the documentation says:

You can use similar patterns to replace pop, shift, unshift and splice.

But how? I cannot see how you can remove items from an array. More to the point, how could I write the following more idiomatically?

messages.splice(messages.indexOf('hello'), 1);
messages = messages;

Body:
You can perform the usual push and pop or `splice on your Array

But because Svelte's reactivity is triggered by assignments, using array methods like push and splice won't automatically cause updates.

According to All about Immutable Arrays and Objects in JavaScript you can do it this way...

let messages = ['something', 'another', 'hello', 'word', 'another', 'again'];

const indexOfHello = messages.indexOf('hello');

messages = [...messages.slice(0, indexOfHello), ...messages.slice(indexOfHello + 1)];

Note the difference between splice and slice

The splice() method adds/removes items to/from an array, and returns
  the removed item(s).  Note: This method changes the original array.
  Syntax: array.splice(start, deleteCount, itemstoAdd, addThisToo);

But

The slice() method returns the selected elements in an array, as a new array object. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.
  Note: The original array will not be changed.

In order words

It return a shallow copy of a portion of an array into a new array
  object selected from begin to end (end not included). The original
  array will not be modified.
  Syntax: array.slice(start, end);


问:
Check if at least two elements in an array are greater than zero - JavaScript/Typescript
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

```<code>const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false

</code>```

答:
Use filter() to remove values below zero and then check if the length of resulting array is greater than or equal to two

const twoGreaterThanZero = arr => arr.filter(x => x > 0).length >= 2;

console.log(twoGreaterThanZero([9, 1, 0])) //true
console.log(twoGreaterThanZero([0, 0, 0])) //false
console.log(twoGreaterThanZero([5, 0, 0])) //false```

Body:
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false