问:
Join these 2 tables to get this specific output?
I am using SQL Server 2014. I am working on a query where I want to extract information from 2 specific tables to create my final output.

An extract of the 2 tables (Rebookings and ResaList) are given below.

Rebookings Table (each CancelledID has its corresponding RebookingID):

```<code>CancelledID            RebookingID
  102                     541
  250                     351
  129                     800
  ...
</code>```

ResaList Table:

```<code>ID      Property         ArrivalDate       RN
100       X              2020-05-22         9
102       X              2020-03-05         7
250       D              2020-04-12        10
129       E              2020-03-15         8
351       D              2020-09-23         5
541       X              2020-06-01         7
800       E              2020-07-11         8
...
</code>```

Here is my desired output:

```<code>ID       Property        ArrivalDate         RN    RebookingID        Rebooking_ArrivalDate    Rebooking_RN     Tag
102         X            2020-03-05           7       541              2020-06-01                   7           Cancelled
250         D            2020-04-12          10       351              2020-09-23                   5           Re-booked
129         E            2020-03-15           8       800              2020-07-11                   8           Re-booked
</code>```

This is what I have done so far:

```<code>USE [MyDatabase]

select
  a.[ID],
  a.[Property],
  a.[Arrival Date],
  a.[RN],
  b.[RebookingID],
  (CASE WHEN a.[ID] in (SELECT [CancelledID] FROM [Rebookings]) THEN 'Re-booked'
      ELSE 'Cancelled'
      END) as [Tag]
from [ResaList] a
LEFT JOIN [Rebookings] b on b.[CancelledID] = a.[ID]
where a.[ID] in (SELECT [CancelledID] FROM [Rebookings])
GROUP BY a.[ID], a.[Property], a.[ArrivalDate], b.[RebookingID]
</code>```

I am stuck at how to bring Rebooking_ArrivalDate and Rebooking_RN into the above output. Any help would be appreciated.

答:
You can select the same table twice by using aliases.  </p>

```<code>SELECT
    *
    ,(CASE WHEN b.[ID] IS NOT NULL THEN 'Re-booked'
      ELSE 'Cancelled'
      END) as [Tag]
FROM ResaList AS a
LEFT JOIN Rebookings ON a.ID = Rebookings.CancelledID
LEFT JOIN ResaList AS b ON b.ID = Rebookings.RebookingID
</code>```

Body:
I am using SQL Server 2014. I am working on a query where I want to extract information from 2 specific tables to create my final output.

An extract of the 2 tables (Rebookings and ResaList) are given below.

Rebookings Table (each CancelledID has its corresponding RebookingID):

CancelledID            RebookingID
  102                     541
  250                     351
  129                     800
  ...

ResaList Table:

ID      Property         ArrivalDate       RN
100       X              2020-05-22         9
102       X              2020-03-05         7
250       D              2020-04-12        10
129       E              2020-03-15         8
351       D              2020-09-23         5
541       X              2020-06-01         7
800       E              2020-07-11         8
...

Here is my desired output:

ID       Property        ArrivalDate         RN    RebookingID        Rebooking_ArrivalDate    Rebooking_RN     Tag
102         X            2020-03-05           7       541              2020-06-01                   7           Cancelled
250         D            2020-04-12          10       351              2020-09-23                   5           Re-booked
129         E            2020-03-15           8       800              2020-07-11                   8           Re-booked

This is what I have done so far:

USE [MyDatabase]

select
  a.[ID],
  a.[Property],
  a.[Arrival Date],
  a.[RN],
  b.[RebookingID],
  (CASE WHEN a.[ID] in (SELECT [CancelledID] FROM [Rebookings]) THEN 'Re-booked'
      ELSE 'Cancelled'
      END) as [Tag]
from [ResaList] a
LEFT JOIN [Rebookings] b on b.[CancelledID] = a.[ID]
where a.[ID] in (SELECT [CancelledID] FROM [Rebookings])
GROUP BY a.[ID], a.[Property], a.[ArrivalDate], b.[RebookingID]

I am stuck at how to bring Rebooking_ArrivalDate and Rebooking_RN into the above output. Any help would be appreciated.

Body:
You can select the same table twice by using aliases.

SELECT
    *
    ,(CASE WHEN b.[ID] IS NOT NULL THEN 'Re-booked'
      ELSE 'Cancelled'
      END) as [Tag]
FROM ResaList AS a
LEFT JOIN Rebookings ON a.ID = Rebookings.CancelledID
LEFT JOIN ResaList AS b ON b.ID = Rebookings.RebookingID


来源: stackexchange

问:
specify group by field in django 1.2
I want to use annotate to count the number of occurances in my model, however it is not using the right field in the group by statment.  instead of using the field i want (i.e. the one specified in the count function) it uses the primary key of the model. e.g.

```<code>ObjectHistory.objects.annotate(revisions=Count('resource'))
</code>```

produces sql

```<code>SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`history_id`
</code>```

where history_id is the primary key of ObjectHistory

what I want is:

```<code>SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`resource_id
</code>```

I found that by putting

```<code>ObjectHistory.objects.values.('resource').annotate(revisions=Count('resource'))
</code>```

it put the right group by field but then i didn't have access to the other fields in the model.

How do I specify to use resource_id in the group by field?

答:
use the raw method as documented here

e.g.

ObjectHistory.objects.raw("SELECT *,
  COUNT(resources_objecthistory.resource_id)
  AS revisions FROM
  resources_objecthistory GROUP BY
  resources_objecthistory.`resource_id")

ContentLicense: CC BY-SA 2.5

Title: specify group by field in django 1.2

Body:
I want to use annotate to count the number of occurances in my model, however it is not using the right field in the group by statment.  instead of using the field i want (i.e. the one specified in the count function) it uses the primary key of the model. e.g.

ObjectHistory.objects.annotate(revisions=Count('resource'))

produces sql

SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`history_id`

where history_id is the primary key of ObjectHistory

what I want is:

SELECT *, COUNT(`resources_objecthistory`.`resource_id`) AS `revisions` FROM `resources_objecthistory` GROUP BY `resources_objecthistory`.`resource_id

I found that by putting

ObjectHistory.objects.values.('resource').annotate(revisions=Count('resource'))

it put the right group by field but then i didn't have access to the other fields in the model.

How do I specify to use resource_id in the group by field?

ContentLicense: CC BY-SA 3.0


问:
NoSuchBeanException, even when Bean is defined
I have 2 classes.

Target.java: Class to be tested

Helper.java: Helper class

```<code>@Component
public class Helper {

  public void helperMethod() {
    // some code
  }
}

@Service
public class Target {
  private final Helper helper;

  public Target(Helper helper) {
    this.helper = helper;
  }

  public void someMethod() {
    helper.helperMethod();
  }
}
</code>```

I am testing someMethod() method of Target class. But when running the test case it gives following error:

Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.abc.def.Helper' available: expected at least 1 bean which qualifies as autowire candidate.

Other answers that I have seen for similar question were because of not writing @Component, but I have done that too.

答:
Not sure if I understood you correctly, but I also had similiar issue when writing tests for my application using JUnit. My workaround was to put in my TestClass configuration where I define beans which i need for testing. E.g.</p>

```<code>@RunWith(SpringRunner.class)
public class TestSomeService {

    @TestConfiguration
    static class TestSomeServiceConfiguration {

        @Bean
        public Helper helper() { return new Helper(); }

        @Bean
        public Target targer() {
            return new Target(
                helper()
            );
        }

    }

    @Autowired
    private Target targetUnderTest;

    @Test
    public void testTarget() {
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 2 classes.

Target.java: Class to be tested

Helper.java: Helper class

@Component
public class Helper {

  public void helperMethod() {
    // some code
  }
}

@Service
public class Target {
  private final Helper helper;

  public Target(Helper helper) {
    this.helper = helper;
  }

  public void someMethod() {
    helper.helperMethod();
  }
}

I am testing someMethod() method of Target class. But when running the test case it gives following error:

Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.abc.def.Helper' available: expected at least 1 bean which qualifies as autowire candidate.

Other answers that I have seen for similar question were because of not writing @Component, but I have done that too.

Body:
Not sure if I understood you correctly, but I also had similiar issue when writing tests for my application using JUnit. My workaround was to put in my TestClass configuration where I define beans which i need for testing. E.g.

@RunWith(SpringRunner.class)
public class TestSomeService {

    @TestConfiguration
    static class TestSomeServiceConfiguration {

        @Bean
        public Helper helper() { return new Helper(); }

        @Bean
        public Target targer() {
            return new Target(
                helper()
            );
        }

    }

    @Autowired
    private Target targetUnderTest;

    @Test
    public void testTarget() {
    }

}


问:
How to use artifact from google artifact registry
I have published my project .jar to artifact registry. I'm not sure how to refer to it, to use as a dependency in another project (with gradle). Thank you in advance.</p>

答: As described in this page, you have to register your project through this form and then to configurer your Gradle repositories as described</p>


问:
How to concatenate the id of the HTML element using Razor ASp.NET MVC
I have a grid column with checkboxes and I want to give them a different id. Id is based on the CustomerId in the Model. What syntax should I use to concatenate the chk_@item.CustomerId.

```<code>// using the telerik grid
id="chk_@item.OrderNumber"  // does not work
</code>```

// this will put the value of @item.Customernumber as the checkbox id

```<code>columns.Template(@<text><input type='checkbox' id="@item.Customernumber" name="@item.CustomerNumber" value="@item.OrderNumber" /></text>).Width(50)
</code>```

second option:

```<code>columns.Template(@<text><input type='checkbox' id="chk_@item.Customernumber" name="@item.CustomerNumber" value="@item.OrderNumber" /></text>).Width(50)
</code>```

the above will render as

```<code><input type="checkbox" id="chk_@item.Customernumber" value=... />
</code>```

答:
This does works now in latest MVC:

```<code>id="chk_@item.OrderNumber"
</code>```

Happy coding.

Body:
I have a grid column with checkboxes and I want to give them a different id. Id is based on the CustomerId in the Model. What syntax should I use to concatenate the chk_@item.CustomerId.

// using the telerik grid
id="chk_@item.OrderNumber"  // does not work

// this will put the value of @item.Customernumber as the checkbox id

columns.Template(@<text><input type='checkbox' id="@item.Customernumber" name="@item.CustomerNumber" value="@item.OrderNumber" /></text>).Width(50)

second option:

columns.Template(@<text><input type='checkbox' id="chk_@item.Customernumber" name="@item.CustomerNumber" value="@item.OrderNumber" /></text>).Width(50)

the above will render as

<input type="checkbox" id="chk_@item.Customernumber" value=... />

Body:
This does works now in latest MVC:

id="chk_@item.OrderNumber"

Happy coding.


问:
Set up tensorboard on Matterport - Mask RCNN
I am following this tutorial for image detection using Matterport repo.
I tried following this guide and edited the code to

How can I edit the following code to visualize the tensorboard ?

```<code>import tensorflow as tf
import datetime
%load_ext tensorboard

sess = tf.Session()

file_writer = tf.summary.FileWriter('/path/to/logs', sess.graph)
</code>```

And then in the model area

```<code># prepare config
config = KangarooConfig()
config.display()

# define the model
model = MaskRCNN(mode='training', model_dir='./', config=config)
model.keras_model.metrics_tensors = []

# Tensorflow board
logdir = os.path.join(
    "logs", datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)

# load weights (mscoco) and exclude the output layers
model.load_weights('mask_rcnn_coco.h5',
                   by_name=True,
                   exclude=[
                       "mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox",
                       "mrcnn_mask"
                   ])

# train weights (output layers or 'heads')
model.train(train_set,
            test_set,
            learning_rate=config.LEARNING_RATE,
            epochs=5,
            layers='heads')
</code>```

I am not sure where to  callbacks=[tensorboard_callback] ?

答:
You only have to open Anaconda Prompt and write tensorboard --logdir= yourlogdirectory, where yourlogdirectory is the directory containing the model checkpoint.

It should look something like this: logs\xxxxxx20200528T1755, where xxxx stands for the name you give to your configuration.

This command will generate a web address, copy it in our browser of preference.

Body:
I am following this tutorial for image detection using Matterport repo.
I tried following this guide and edited the code to

How can I edit the following code to visualize the tensorboard ?

import tensorflow as tf
import datetime
%load_ext tensorboard

sess = tf.Session()

file_writer = tf.summary.FileWriter('/path/to/logs', sess.graph)

And then in the model area

# prepare config
config = KangarooConfig()
config.display()

# define the model
model = MaskRCNN(mode='training', model_dir='./', config=config)
model.keras_model.metrics_tensors = []

# Tensorflow board
logdir = os.path.join(
    "logs", datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)

# load weights (mscoco) and exclude the output layers
model.load_weights('mask_rcnn_coco.h5',
                   by_name=True,
                   exclude=[
                       "mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox",
                       "mrcnn_mask"
                   ])

# train weights (output layers or 'heads')
model.train(train_set,
            test_set,
            learning_rate=config.LEARNING_RATE,
            epochs=5,
            layers='heads')

I am not sure where to  callbacks=[tensorboard_callback] ?


问:
HTML figure with both caption and notes
I would like to include a figure in a HTML document. This figure needs to have a title/caption (above) and some reading notes (below). This is the HTML equivalent of this example based on latex.

I know how to add a title to a Figure using figcaption:

Wikipedia logo

```

How can I add some reading notes below ?

答:
Just add a paragraph inside the figure.

Permitted content of a figure includes "flow content" which allows a p

A <figcaption> element, followed by flow content; or flow content followed by a
 element; or flow content.

MDN

img {
max-width:100%;
}

figure {
text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><figure>
  <figcaption>Wikipedia logo</figcaption>
  <img src="https://upload.wikimedia.org/wikipedia/commons/0/07/Wikipedia_logo_%28svg%29.svg">
  <p>Lorem ipsum dolor sit amet.</p>
</figure></code>```

Title: HTML figure with both caption and notes

Body:
I would like to include a figure in a HTML document. This figure needs to have a title/caption (above) and some reading notes (below). This is the HTML equivalent of this example based on latex.

I know how to add a title to a Figure using figcaption:

Wikipedia logo

How can I add some reading notes below ?

Body:
Just add a paragraph inside the figure.

Permitted content of a figure includes "flow content" which allows a p

A <figcaption> element, followed by flow content; or flow content followed by a <figcaption> element; or flow content.

MDN

img {
max-width:100%;
}

figure {
text-align:center;
}

<figure>
  <figcaption>Wikipedia logo</figcaption>
  <img src="https://upload.wikimedia.org/wikipedia/commons/0/07/Wikipedia_logo_%28svg%29.svg">
  <p>Lorem ipsum dolor sit amet.</p>
</figure>


问:
Memory assignment in C through pointers
I am learning how to use pointers, so i wrote the below program to assign integer values in the interval [1,100] to some random locations in the memory.

When i read those memory locations, printf displays all the values and then gives me a segmentation fault. This seems an odd behavior, because i was hoping to see either all the values OR a seg fault, but not both at the same time.

Can someone please explain why i got to see both?

Thanks. Here is the code

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    char first = 'f';
    char *ptr_first = &first;
    int i=1;
    for(i=1;i<101;i++)
        *(ptr_first+i) = i;
    for(i=1;i<101;i++)
        printf("%d\n", *(ptr_first+i));
    return EXIT_SUCCESS;
}
</code>```

答: since ptr_first pointer is pointing to a char variable first. Now when you are incrementing ptr_first, so incremented memory address location can be out of process memory address space, thats why kernel is sending segmentation fault to this process.</p>

Title: Memory assignment in C through pointers

Body:
I am learning how to use pointers, so i wrote the below program to assign integer values in the interval [1,100] to some random locations in the memory.

When i read those memory locations, printf displays all the values and then gives me a segmentation fault. This seems an odd behavior, because i was hoping to see either all the values OR a seg fault, but not both at the same time.

Can someone please explain why i got to see both?

Thanks. Here is the code

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char first = 'f';
    char *ptr_first = &first;
    int i=1;
    for(i=1;i<101;i++)
        *(ptr_first+i) = i;
    for(i=1;i<101;i++)
        printf("%d\n", *(ptr_first+i));
    return EXIT_SUCCESS;
}


问:
accept unevaluated logical expression as argument, defer execute
target code:

```<code>    test_box = TestBox(Checkers.begin_with("op") and Checkers.end_with("or"))
    test_box.run("operator")  # True
    test_box.run("option")  # False
</code>```

What I think(may be in the wrong way): TestBox may be a class or a method, and begin_with and end_with are classmethod of class Checkers, but how to make Checkers.begin_with("op") and Checkers.end_with("or") evaluated until test_box.run() was called?

答:
I have found a solution which use lambda, post here:</p>

```<code>class TestBox:
    def __init__(self, func):
        self._func = func

    def run(self, string):
        Checkers.string = string
        return self._func()

class Checkers:
    string = None

    @classmethod
    def begin_with(cls, val):
        return cls.string.startswith(val)

    @classmethod
    def end_with(cls, val):
        return cls.string.endswith(val)

if __name__ == '__main__':
    test_box = TestBox(lambda: Checkers.begin_with("op") or Checkers.end_with("or"))
    print(test_box.run("operator"))  # True
    print(test_box.run("xxtion"))  # False
    print(test_box.run("xxtionor"))  # True
</code>```

Body:
target code:

    test_box = TestBox(Checkers.begin_with("op") and Checkers.end_with("or"))
    test_box.run("operator")  # True
    test_box.run("option")  # False

What I think(may be in the wrong way): TestBox may be a class or a method, and begin_with and end_with are classmethod of class Checkers, but how to make Checkers.begin_with("op") and Checkers.end_with("or") evaluated until test_box.run() was called?

Body:
I have found a solution which use lambda, post here:

class TestBox:
    def __init__(self, func):
        self._func = func

    def run(self, string):
        Checkers.string = string
        return self._func()

class Checkers:
    string = None

    @classmethod
    def begin_with(cls, val):
        return cls.string.startswith(val)

    @classmethod
    def end_with(cls, val):
        return cls.string.endswith(val)

if __name__ == '__main__':
    test_box = TestBox(lambda: Checkers.begin_with("op") or Checkers.end_with("or"))
    print(test_box.run("operator"))  # True
    print(test_box.run("xxtion"))  # False
    print(test_box.run("xxtionor"))  # True


问:
Avoid empty spaces in vue-form-generator inputs
I'm using the schema-based form generator component for Vue.js (vue-form-generator)

Does anyone knows how to avoid dynamically empty spaces in the input field by using the trim() function?

Here is an example of the code.

答:
Override validator method by this:

```<code>validator: function(value, field, model) {
    if (value) {
        // if user input anything, then trim it and assign it to the model and validator value also.
        // this could be devastating as the user will fill difficulties in typing space
        // because as long as user type a space to write a separate word, the validator will remove this, test properly
        value = model.name = value.trim();
        return VueFormGenerator.validators.string(value, field, model)
    } else {
        return ["This field is required"];
    }
}

</code>```

Body:
Override validator method by this:

validator: function(value, field, model) {
    if (value) {
        // if user input anything, then trim it and assign it to the model and validator value also.
        // this could be devastating as the user will fill difficulties in typing space
        // because as long as user type a space to write a separate word, the validator will remove this, test properly
        value = model.name = value.trim();
        return VueFormGenerator.validators.string(value, field, model)
    } else {
        return ["This field is required"];
    }
}


问:
Are ARG values passed to scripts executed with RUN
If I have ARG values and then RUN a script in my Dockerfile, will that script be able to access those values while it runs during build time?</p>

答:
OK, I checked it and it seems to work in my limited example:

```<code>ARG foo=val1
ARG bar=val2
COPY foo.sh /foo.sh
RUN /foo.sh
</code>```

And foo.sh:

```<code>echo ============
echo hello, world
echo $foo
echo $bar
echo ============
</code>```

This prints:

```<code> ---> Running in c6c8d99ba28b
============
hello, world
val1
val2
============
Removing intermediate container c6c8d99ba28b
</code>```

Body:
OK, I checked it and it seems to work in my limited example:

ARG foo=val1
ARG bar=val2
COPY foo.sh /foo.sh
RUN /foo.sh

And foo.sh:

echo ============
echo hello, world
echo $foo
echo $bar
echo ============

This prints:

 ---> Running in c6c8d99ba28b
============
hello, world
val1
val2
============
Removing intermediate container c6c8d99ba28b


问:
CURRENT_DATE/CURDATE() not working as default DATE value
Pretty straight forward question here, I think this should work but it doesn't. Why doesn't it?</p>

```<code>CREATE TABLE INVOICE(
   INVOICEDATE DATE NOT NULL DEFAULT CURRENT_DATE
)
</code>```

答:
Currently from MySQL 8 you can set the following to a DATE column:

In MySQL Workbench, in the Default field next to the column, write: (curdate())

If you put just curdate() it will fail. You need the extra ( and ) at the beginning and end.

Body:
Pretty straight forward question here, I think this should work but it doesn't. Why doesn't it?

CREATE TABLE INVOICE(
   INVOICEDATE DATE NOT NULL DEFAULT CURRENT_DATE
)


问:
Understand Cassandra pooling options (setCoreConnectionsPerHost and setMaxConnectionsPerHost)?
I recently started working with Cassandra and I was reading more about connection pooling here. I was confuse about pool size and couldn't understand what does this mean here:

```<code>poolingOptions
    .setCoreConnectionsPerHost(HostDistance.LOCAL,  4)
    .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
    .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
    .setMaxConnectionsPerHost( HostDistance.REMOTE, 4)
    .setMaxRequestsPerConnection(2000);
</code>```

Below is what I want to understand in detail:

I would like to know what does setCoreConnectionsPerHost, setMaxConnectionsPerHost and setMaxRequestsPerConnection means?

What is LOCAL and REMOTE means here?

If someone can explain with an example then it will really help me understand better.

We have a 6 nodes cluster all in one dc with RF as 3 and we read/write as local quorum.

答:
Cassandra protocol allows to submit for execution multiple queries over the same network connection in parallel, without waiting for answer.  The setMaxRequestsPerConnection sets how many in-flight queries could be in one connection simultaneously - maximal limit depends on protocol, and since protocol v3, it's 32k, but in reality you need to keep it around 1000-2000 - if you have more, then it's a sign that server is not keeping with your queries.

Drivers are opening connections to every node in the cluster, and these connections are marked either as LOCAL - if they are to the nodes in the data center that is local to the application (either set explicitly in load balancing policy, or inferred from first contacted point), or as REMOTE if they are to the nodes that in the other data centers.

Also, driver can open several connections to nodes. And there are 2 values that control their number: core - the minimal number of connections, and max - what is the upper limit.  Driver will open new connections if you submit new requests that doesn't fit into the existing limit.

So in your example:

poolingOptions
    .setCoreConnectionsPerHost(HostDistance.LOCAL,  4)
    .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
    .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
    .setMaxConnectionsPerHost( HostDistance.REMOTE, 4)
    .setMaxRequestsPerConnection(2000);
```

for local data center, it will open 4 connections per node initially, and it may grow up to 10 connections

for other data centers it will open 2 connections, that could grow up to 4 connections

Body:
I recently started working with Cassandra and I was reading more about connection pooling here. I was confuse about pool size and couldn't understand what does this mean here:

poolingOptions
    .setCoreConnectionsPerHost(HostDistance.LOCAL,  4)
    .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
    .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
    .setMaxConnectionsPerHost( HostDistance.REMOTE, 4)
    .setMaxRequestsPerConnection(2000);

Below is what I want to understand in detail:

I would like to know what does setCoreConnectionsPerHost, setMaxConnectionsPerHost and setMaxRequestsPerConnection means?

What is LOCAL and REMOTE means here?

If someone can explain with an example then it will really help me understand better.

We have a 6 nodes cluster all in one dc with RF as 3 and we read/write as local quorum.

Body:
Cassandra protocol allows to submit for execution multiple queries over the same network connection in parallel, without waiting for answer.  The setMaxRequestsPerConnection sets how many in-flight queries could be in one connection simultaneously - maximal limit depends on protocol, and since protocol v3, it's 32k, but in reality you need to keep it around 1000-2000 - if you have more, then it's a sign that server is not keeping with your queries.

Drivers are opening connections to every node in the cluster, and these connections are marked either as LOCAL - if they are to the nodes in the data center that is local to the application (either set explicitly in load balancing policy, or inferred from first contacted point), or as REMOTE if they are to the nodes that in the other data centers.

Also, driver can open several connections to nodes. And there are 2 values that control their number: core - the minimal number of connections, and max - what is the upper limit.  Driver will open new connections if you submit new requests that doesn't fit into the existing limit.

So in your example:

poolingOptions
    .setCoreConnectionsPerHost(HostDistance.LOCAL,  4)
    .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
    .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
    .setMaxConnectionsPerHost( HostDistance.REMOTE, 4)
    .setMaxRequestsPerConnection(2000);

for local data center, it will open 4 connections per node initially, and it may grow up to 10 connections

for other data centers it will open 2 connections, that could grow up to 4 connections


问:
How to add a background color to a styled component based on condition using react and typescript?
how can i add background color to styled component based on the condition using react and typescript?

what i am trying to do?

I have a MainComponent which renders ListContent within DragAndDropComponent.

Now when user drags a file into DragAndDrop div i want its background color change to grey.

Below is my code,

```<code>function MainComponent () {
return (
    <Wrapper>
        <SomeOtheComponent/>
        <DragAndDrop>
            <ListContent> //this is the children for the DragAndDrop component and want this to
                //render within DragAndDrop component
                {condition_true && (
                    <FirstList/>
                )}
                {condition_true && (
                    <SecondList/>
                )}
            </ListContent>
        </Wrapper>
    );
}

const DragAndDrop: React.FC = ({ children }) => { //here i am passing children
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);

    React.useEffect(() => {
        // componentDidMount()
        setDragCounter(0);
    }, []);

    const handleDrag = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev + 1);
        if (e.dataTransfer.files) {
            setDragging(true);
        }
    };

    const handleDragOut = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev - 1);
        if (dragCounter === 0) {
            setDragging(false);
        }
    };

    const handleDrop = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragging(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            e.dataTransfer.clearData();
            setDragCounter(0);
        }
    };

    return (
        <DropZone //i want to change background color to this div if dragging true.
            ref={dropRef}
            onDragEnter={handleDragIn}
            onDragLeave={handleDragOut}
            onDragOver={handleDrag}
            onDrop={handleDrop}
        >
            {children}
        </DropZone>
    );
};

const DropZone = styled.div`
    height: 100%;
    //backgroun-color: how to change background color to grey if dragging state true.
`;
</code>```

Could someone help me with this. thanks.

答:
Try moving this statement up const [dragging, setDragging] = useState(false); to make it accessible outside

```<code>const DropZone = styled.div`
    height: 100%;
    background: ${ dragging ? "grey": ""}
`;
</code>```

Body:
how can i add background color to styled component based on the condition using react and typescript?

what i am trying to do?

I have a MainComponent which renders ListContent within DragAndDropComponent.

Now when user drags a file into DragAndDrop div i want its background color change to grey.

Below is my code,

function MainComponent () {
return (
    <Wrapper>
        <SomeOtheComponent/>
        <DragAndDrop>
            <ListContent> //this is the children for the DragAndDrop component and want this to
                //render within DragAndDrop component
                {condition_true && (
                    <FirstList/>
                )}
                {condition_true && (
                    <SecondList/>
                )}
            </ListContent>
        </Wrapper>
    );
}

const DragAndDrop: React.FC = ({ children }) => { //here i am passing children
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);

    React.useEffect(() => {
        // componentDidMount()
        setDragCounter(0);
    }, []);

    const handleDrag = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev + 1);
        if (e.dataTransfer.files) {
            setDragging(true);
        }
    };

    const handleDragOut = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev - 1);
        if (dragCounter === 0) {
            setDragging(false);
        }
    };

    const handleDrop = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragging(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            e.dataTransfer.clearData();
            setDragCounter(0);
        }
    };

    return (
        <DropZone //i want to change background color to this div if dragging true.
            ref={dropRef}
            onDragEnter={handleDragIn}
            onDragLeave={handleDragOut}
            onDragOver={handleDrag}
            onDrop={handleDrop}
        >
            {children}
        </DropZone>
    );
};

const DropZone = styled.div`
    height: 100%;
    //backgroun-color: how to change background color to grey if dragging state true.
`;

Could someone help me with this. thanks.

Body:
Try moving this statement up const [dragging, setDragging] = useState(false); to make it accessible outside

const DropZone = styled.div`
    height: 100%;
    background: ${ dragging ? "grey": ""}
`;


问:
How to install JLink in Docker's ubuntu?
I want to install JLink in my docker's ubuntu container. I downloaded JLink_Linux_V680_x86_64.deb and copied it from host OS to ubuntu container and tried to run

apt-get install ./JLink_Linux_V680_x86_64.deb

But couldn't install it.
How can I install JLink in the ubuntu container?

答:
You can try below command.

sudo docker cp JLink_Linux_x86_64.deb <container_id>:/home/JLink_Linux_x86_64.deb

ls /home/

dpkg -i /home/JLink_Linux_V647f_x86_64.deb

Check this for more details


问:
How to count rows which are divided into other variables as a whole?
This way i get one river and all provinces it flows through are counted:

```<code>SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER
</code>```

This way i get the same river multiple times and it counts for every country the provinces the river flows thorugh together:

```<code>SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER, Geo_River.COUNTRY
</code>```

I want to count the countries the river flows through but some country are divided into different provinces.
If so the country should be count as one and not by number of provinces.

```<code>CREATE TABLE Country
(Name VARCHAR(40) NOT NULL UNIQUE,
 Code VARCHAR(4) CONSTRAINT CountryKey PRIMARY KEY,
 Capital VARCHAR(40),
 Province VARCHAR(40),
 Area INTEGER CONSTRAINT CountryArea
   CHECK (Area >= 0),
 Population INTEGER CONSTRAINT CountryPop
   CHECK (Population >= 0));
</code>```

```<code>CREATE TABLE geo_River
(River VARCHAR(40) ,
 Country VARCHAR(4) ,
 Province VARCHAR(40) ,
 CONSTRAINT GRiverKey PRIMARY KEY (Province ,Country, River) );
</code>```

答:
Please provide example input and output as the question is not very clear.

This does not make sense:

```<code>SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER, Geo_River.COUNTRY
</code>```

Do you need to count the different countries the river is flowing through and you are not able to do that straight-forward as one country would have many provinces ?

Does something like this work,

```<code>SELECT Geo_River.RIVER, COUNT(distinct Geo_River.COUNTRY) as n_countries
FROM Geo_River
GROUP BY Geo_River.RIVER
</code>```

Assuming : SQL = MySQL.

Body:
This way i get one river and all provinces it flows through are counted:

SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER

This way i get the same river multiple times and it counts for every country the provinces the river flows thorugh together:

SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER, Geo_River.COUNTRY

I want to count the countries the river flows through but some country are divided into different provinces.
If so the country should be count as one and not by number of provinces.

CREATE TABLE Country
(Name VARCHAR(40) NOT NULL UNIQUE,
 Code VARCHAR(4) CONSTRAINT CountryKey PRIMARY KEY,
 Capital VARCHAR(40),
 Province VARCHAR(40),
 Area INTEGER CONSTRAINT CountryArea
   CHECK (Area >= 0),
 Population INTEGER CONSTRAINT CountryPop
   CHECK (Population >= 0));

CREATE TABLE geo_River
(River VARCHAR(40) ,
 Country VARCHAR(4) ,
 Province VARCHAR(40) ,
 CONSTRAINT GRiverKey PRIMARY KEY (Province ,Country, River) );

Body:
Please provide example input and output as the question is not very clear.

This does not make sense:

SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER, Geo_River.COUNTRY

Do you need to count the different countries the river is flowing through and you are not able to do that straight-forward as one country would have many provinces ?

Does something like this work,

SELECT Geo_River.RIVER, COUNT(distinct Geo_River.COUNTRY) as n_countries
FROM Geo_River
GROUP BY Geo_River.RIVER

Assuming : SQL = MySQL.


问:
Huge, inconsistent delay when accessing JSON data from a web address
I'm trying to get JSON data from websites (like themoviedb.org).  I can successfully retrieve the data, but sometimes when I do this there is a whopping delay that can last over a minute or I get a connection failed message (server timeout?).  When this happens the problem persists for the next few hours - but I can try later the same evening and the same code works almost instantly!

EDIT: I should also mention that when the first delay is finally over all other requests are then carried out instantly - it's just the first request that causes a big hold-up.  When I restart the app the delay happens all over again.

This doesn't appear to affect any other internet connection on my PC - and I can always manually copy and paste the same request into my browser for instant JSON results.  Something about my app or my Visual Studio 2015 setup is allowing this random delay to keep cropping up.

Here is the code for the app:

```<code>    public static HttpClient Client = new HttpClient();

    public MainWindow()
    {
        InitializeComponent();

        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        Mouse.OverrideCursor = Cursors.Wait;
        string url = "https://api.themoviedb.org/3/search/person?api_key=" + theMovieDbKey + "&query=%22Hanks%22";
        HttpResponseMessage response = await Client.GetAsync(url);
        string content = await response.Content.ReadAsStringAsync();
        Mouse.OverrideCursor = null;
        MessageBox.Show(content);
    }
</code>```

So far I've tried without success:

Switching from WebClient to HttpClient

Changing security protocols.

Disabling proxies.

Disabling diagnostic tools.

The second item on this Fiddler screen shows some info:

And here are the headers:

Any help would be greatly appreciated as I just don't know what is causing this.

EDIT: The headers from a successful browser request are:

答:
I figured it out with help from someone on another site.  It turns out that my server requests were all using IPv6 protocols which can lead to all sorts of random delays if your DNS setup isn't perfect.  Forcing my app to use IPv4 protocols fixed the issue immediately.

Note that requests to a HTTPS host require request headers to work correctly.

Here is the code that worked for me, I hope it helps someone else:

```<code>    public static HttpClient Client = new HttpClient();

    public MainWindow()
    {
        InitializeComponent();

        // Set required security protocols.
        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        // Set Host header required for HTTPS connections.
        Client.DefaultRequestHeaders.Add("Host", "api.themoviedb.org");
    }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        Mouse.OverrideCursor = Cursors.Wait;

        // Get DNS entries for the host.
        Uri uri = new Uri("https://api.themoviedb.org/3/search/person?api_key=" + theMovieDbKey + "&query=%22Hanks%22");
        var hostEntry = Dns.GetHostEntry(uri.Host);

        // Get IPv4 address
        var ip4 = hostEntry.AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork);

        // Build URI with numeric IPv4
        var uriBuilderIP4 = new UriBuilder(uri);
        uriBuilderIP4.Host = ip4.ToString();
        var uri4 = uriBuilderIP4.Uri;

        // Retrieve asynchronous string from specified URI.
        HttpResponseMessage response = await Client.GetAsync(uri4);
        string content = await response.Content.ReadAsStringAsync();
        Mouse.OverrideCursor = null;
        MessageBox.Show(content);
    }
</code>```

Body:
I'm trying to get JSON data from websites (like themoviedb.org).  I can successfully retrieve the data, but sometimes when I do this there is a whopping delay that can last over a minute or I get a connection failed message (server timeout?).  When this happens the problem persists for the next few hours - but I can try later the same evening and the same code works almost instantly!

EDIT: I should also mention that when the first delay is finally over all other requests are then carried out instantly - it's just the first request that causes a big hold-up.  When I restart the app the delay happens all over again.

This doesn't appear to affect any other internet connection on my PC - and I can always manually copy and paste the same request into my browser for instant JSON results.  Something about my app or my Visual Studio 2015 setup is allowing this random delay to keep cropping up.

Here is the code for the app:

    public static HttpClient Client = new HttpClient();

    public MainWindow()
    {
        InitializeComponent();

        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        Mouse.OverrideCursor = Cursors.Wait;
        string url = "https://api.themoviedb.org/3/search/person?api_key=" + theMovieDbKey + "&query=%22Hanks%22";
        HttpResponseMessage response = await Client.GetAsync(url);
        string content = await response.Content.ReadAsStringAsync();
        Mouse.OverrideCursor = null;
        MessageBox.Show(content);
    }

So far I've tried without success:

Switching from WebClient to HttpClient

Changing security protocols.

Disabling proxies.

Disabling diagnostic tools.

The second item on this Fiddler screen shows some info:

And here are the headers:

Any help would be greatly appreciated as I just don't know what is causing this.

EDIT: The headers from a successful browser request are:

Body:
I figured it out with help from someone on another site.  It turns out that my server requests were all using IPv6 protocols which can lead to all sorts of random delays if your DNS setup isn't perfect.  Forcing my app to use IPv4 protocols fixed the issue immediately.

Note that requests to a HTTPS host require request headers to work correctly.

Here is the code that worked for me, I hope it helps someone else:

    public static HttpClient Client = new HttpClient();

    public MainWindow()
    {
        InitializeComponent();

        // Set required security protocols.
        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        // Set Host header required for HTTPS connections.
        Client.DefaultRequestHeaders.Add("Host", "api.themoviedb.org");
    }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        Mouse.OverrideCursor = Cursors.Wait;

        // Get DNS entries for the host.
        Uri uri = new Uri("https://api.themoviedb.org/3/search/person?api_key=" + theMovieDbKey + "&query=%22Hanks%22");
        var hostEntry = Dns.GetHostEntry(uri.Host);

        // Get IPv4 address
        var ip4 = hostEntry.AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork);

        // Build URI with numeric IPv4
        var uriBuilderIP4 = new UriBuilder(uri);
        uriBuilderIP4.Host = ip4.ToString();
        var uri4 = uriBuilderIP4.Uri;

        // Retrieve asynchronous string from specified URI.
        HttpResponseMessage response = await Client.GetAsync(uri4);
        string content = await response.Content.ReadAsStringAsync();
        Mouse.OverrideCursor = null;
        MessageBox.Show(content);
    }


问:
value of a textarea element
I want to use value of a textarea element, but I am not able to get it

function postComment(element) {
  const content = element.previousSibling.value;
  console.log(content);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="" class="comment-editor">
  <div class="form-group">
    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>
  </div>
</form></code>```

It gives undefined as output

答:
Since you already have an ID for the <input> field, i would have used the following instead:

```<code>function postComment() {
  const content = document.getElementByID("someid").value;
  console.log(content);
}
</code>```

And no need for the parameter here:

```<code>onClick="postComment();"
</code>```

Title: value of a textarea element

Body:
I want to use value of a textarea element, but I am not able to get it

function postComment(element) {
  const content = element.previousSibling.value;
  console.log(content);
}

<form action="" class="comment-editor">

    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>

</form>

It gives undefined as output

Body:
Since you already have an ID for the <input> field, i would have used the following instead:

function postComment() {
  const content = document.getElementByID("someid").value;
  console.log(content);
}

And no need for the parameter here:

onClick="postComment();"


问:
Request external api when developing Outlook add-in
We are developing additional Outlook features.

I am getting an error when trying to post request to an external api.

I have registered the app domain in the manifest file, why can't I access the external api?

(I use angularjs and the backend uses asp.net core.)

Also, the part requested by the api cannot be confirmed on the network.

答:
Make sure CORS is supported on both sides. Or JSONP is used.

The same-origin policy enforced by the browser prevents a script loaded from one domain from getting or manipulating properties of a webpage from another domain. This means that, by default, the domain of a requested URL must be the same as the domain of the current webpage. For example, this policy will prevent a webpage in one domain from making XmlHttpRequest web-service calls to a domain other than the one where it is hosted.

Because Office Add-ins are hosted in a browser control, the same-origin policy applies to script running in their web pages as well.

The same-origin policy can be an unnecessary handicap in many situations, such as when a web application hosts content and APIs across multiple subdomains. There are a few common techniques for securely overcoming same-origin policy enforcement.

One way to overcome same-origin policy limitations is to use JSONP to provide a proxy for the web service. You do this by including a script tag with a src attribute that points to some script hosted on any domain. You can programmatically create the script tags, dynamically create the URL to point the src attribute to, and then pass parameters to the URL via URI query parameters. Web service providers create and host JavaScript code at specific URLs, and return different scripts depending on the URI query parameters. These scripts then execute where they are inserted and work as expected.

Another way to address same-origin policy limitations is to provide server-side code that uses OAuth 2.0 flows to enable one domain to get authorized access to resources hosted on another.

Use the cross-origin resource sharing feature of XmlHttpRequest2, see the "Cross Origin Resource Sharing (CORS)" section of New Tricks in XMLHttpRequest2.

Finally, I'd suggest using Fiddler to understand what is going on under the hood of HTTP (ajax) calls.


问:
jax-ws import and customizing package to namespace mapping
How do I customize the packages of the namespaces when using jax-ws to generate the java artifacts.

I'm running jax-ws iwsmport via maven.

I don't want to change the default package, I want to be able to map from more than one namespace to different packages.

答:
```<code><jaxb:bindings
            schemaLocation="../../wscontract/src/main/resources/wsdl/address.xsd"
    node="//xsd:schema[@targetNamespace='http://demo.iae.ws/address']">
    <jaxb:schemaBindings>
        <jaxb:package name="demo.ws.address" />
        <jaxb:nameXmlTransform>
            <jaxb:typeName prefix="Customer" />
        </jaxb:nameXmlTransform>
    </jaxb:schemaBindings>
</jaxb:bindings>
</code>```

Use JAXB bindings with the wsimport -b switch. You can find some sample files here.

Body:
<jaxb:bindings
            schemaLocation="../../wscontract/src/main/resources/wsdl/address.xsd"
    node="//xsd:schema[@targetNamespace='http://demo.iae.ws/address']">
    <jaxb:schemaBindings>
        <jaxb:package name="demo.ws.address" />
        <jaxb:nameXmlTransform>
            <jaxb:typeName prefix="Customer" />
        </jaxb:nameXmlTransform>
    </jaxb:schemaBindings>
</jaxb:bindings>

Use JAXB bindings with the wsimport -b switch. You can find some sample files here.


问:
Headless Umbraco CMS with ASP .NET Core
we have an ASP .NET Core website and would like to use Umbraco. It is my understanding there is no .Net Core version of Umbraco, therefore we would need to use a headless integration. To do this, I will need to create web api's in my project, however I am not able to use Umbraco.Web.WebApi, because there is no ASP .NET Core library, so I am assuming I need to custom create my own using the standard ASP .NET Web Api. If all these assumptions are correct, I have no idea how to begin. I was curious if there are any sample .NET Core projects that show how to create the Web Api? If these assumptions are not correct, could someone please help me better understand. Thanks!!</p>

答:
You are correct, Umbraco 8 requires 4.7 .net Framework rather than .net core.

If you want to self-host you can extend Umbraco 8 with either GraphQL or Head Rest Packages however these are not recently updated.

Alternatively, Umbraco offers Heart Core which is cloud only headless CMS which would work. This has a reset API and soon a Graph QL.

Title: Headless Umbraco CMS with ASP .NET Core


问:
Karma/Jasmine times out without running tests
I'm trying to run Karma/Jasmine from Grunt on a project generated with
http://newtriks.com/2013/12/31/automating-react-with-yeoman-and-grunt/

Karma launches PhantomJS (or Chrome) and, depending on singleRun, it either times out or just sits there and does nothing. I've tried changing captureTimeout and browserNoActivityTimeout based on reading solutions from people with similar problems, but it doesn't seem to work.

My relevant pacakge versions etc.:

NodeJS: 0.10.25

Karma: 0.12.16

Webpack: 1.1.11

webpack-dev-server: 1.4.1

karma-jasmine: 0.1.5

Linux: Ubuntu 14.04

I've found someone with the same problem on OS X:

I've tried updating all my dev dependencies to the latest versions but the problem still remains.

My console output is below. The webpack lines referring to bundle is now VALID/INVALID are worrying, but I can't find any info on what they mean. Here's my console output:

```<code>Running "karma:unit" (karma) task
DEBUG [config]: autoWatch set to false, because of singleRun
DEBUG [plugin]: Loading karma-* from /home/ed/workspace/wwb-app/node_modules
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-chrome-launcher.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-coffee-preprocessor.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-firefox-launcher.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-html2js-preprocessor.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-jasmine.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-phantomjs-launcher.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-requirejs.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-script-launcher.
DEBG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-webpack-plugin.
INFO [karma]: Karma v0.12.16 server started at  http://localhost:8080/
INFO [launcher]: Starting browser PhantomJS
DEBUG [temp-dir]: Creating temp dir at /tmp/karma-98204612
DEBUG [launcher]: /home/ed/workspace/wwb-app/node_modules/karma-phantomjs-launcher/node_modules/phantomjs/lib/phantom/bin/phantomjs /tmp/karma-98204612/capture.js
Hash: 89285186567c1bc5bb7f
Version: webpack 1.1.11
Time: 2ms
Asset  Size  Chunks       Chunk Names
webpack: bundle is now VALID.
webpack: bundle is now INVALID.
DEBUG [web-server]: serving: /home/ed/workspace/wwb-app/node_modules/karma/static/client.html
DEBUG [web-server]: serving: /home/ed/workspace/wwb-app/node_modules/karma/static/karma.js
DEBUG [web-server]: upgrade /socket.io/1/websocket/CjC8pnQq5It2z_kWYB98
DEBUG [karma]: A browser has connected on socket CjC8pnQq5It2z_kWYB98
INFO [PhantomJS 1.9.7 (Linux)]: Connected on socket CjC8pnQq5It2z_kWYB98 with id 98204612
DEBUG [launcher]: PhantomJS (id 98204612) captured in 1.704 secs
WARN [PhantomJS 1.9.7 (Linux)]: Disconnected (1 times), because no message in 30000 ms.

DEBUG [karma]: Run complete, exitting.
DEBUG [launcher]: Disconnecting all browsers
DEBUG [launcher]: Process PhantomJS exited with code 0
DEBUG [temp-dir]: Cleaning temp dir /tmp/karma-98204612
Warning: Task "karma:unit" failed. Use --force to continue.

Aborted due to warnings.
</code>```

Here's my karma.conf.js file:

```<code>'use strict';

module.exports = function (config) {
config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
        'test/helpers/**/*.js',
        'test/spec/components/**/*.js'
    ],
    preprocessors: {
        'test/spec/components/**/*.js': ['webpack']
    },
    webpack: {
        cache: true,
        module: {
            loaders: [{
                test: /\.css$/,
                loader: 'style!css'
            }, {
                test: /\.gif/,
                loader: 'url-loader?limit=10000&minetype=image/gif'
            }, {
                test: /\.jpg/,
                loader: 'url-loader?limit=10000&minetype=image/jpg'
            }, {
                test: /\.png/,
                loader: 'url-loader?limit=10000&minetype=image/png'
            }, {
                test: /\.js$/,
                loader: 'jsx-loader'
            }]
        }
    },
    webpackServer: {
        stats: {
            colors: true
        }
    },
    exclude: [],
    port: 8080,
    logLevel: config.LOG_DEBUG,
    colors: true,
    autoWatch: true,
    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],
    reporters: ['progress'],
    captureTimeout: 60000,
    browserNoActivityTimeout: 60000,
    singleRun: true
});
};
</code>```

答:
@Vijender's answer got me on the right track

It was as simple as replacing HttpClientModule in tests with HttpClientTestingModule.

```<code>  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ]
    }).compileComponents();
  }));
</code>```

Body:
I'm trying to run Karma/Jasmine from Grunt on a project generated with
http://newtriks.com/2013/12/31/automating-react-with-yeoman-and-grunt/

Karma launches PhantomJS (or Chrome) and, depending on singleRun, it either times out or just sits there and does nothing. I've tried changing captureTimeout and browserNoActivityTimeout based on reading solutions from people with similar problems, but it doesn't seem to work.

My relevant pacakge versions etc.:

NodeJS: 0.10.25

Karma: 0.12.16

Webpack: 1.1.11

webpack-dev-server: 1.4.1

karma-jasmine: 0.1.5

Linux: Ubuntu 14.04

I've found someone with the same problem on OS X:

I've tried updating all my dev dependencies to the latest versions but the problem still remains.

My console output is below. The webpack lines referring to bundle is now VALID/INVALID are worrying, but I can't find any info on what they mean. Here's my console output:

Running "karma:unit" (karma) task
DEBUG [config]: autoWatch set to false, because of singleRun
DEBUG [plugin]: Loading karma-* from /home/ed/workspace/wwb-app/node_modules
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-chrome-launcher.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-coffee-preprocessor.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-firefox-launcher.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-html2js-preprocessor.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-jasmine.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-phantomjs-launcher.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-requirejs.
DEBUG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-script-launcher.
DEBG [plugin]: Loading plugin /home/ed/workspace/wwb-app/node_modules/karma-webpack-plugin.
INFO [karma]: Karma v0.12.16 server started at  http://localhost:8080/
INFO [launcher]: Starting browser PhantomJS
DEBUG [temp-dir]: Creating temp dir at /tmp/karma-98204612
DEBUG [launcher]: /home/ed/workspace/wwb-app/node_modules/karma-phantomjs-launcher/node_modules/phantomjs/lib/phantom/bin/phantomjs /tmp/karma-98204612/capture.js
Hash: 89285186567c1bc5bb7f
Version: webpack 1.1.11
Time: 2ms
Asset  Size  Chunks       Chunk Names
webpack: bundle is now VALID.
webpack: bundle is now INVALID.
DEBUG [web-server]: serving: /home/ed/workspace/wwb-app/node_modules/karma/static/client.html
DEBUG [web-server]: serving: /home/ed/workspace/wwb-app/node_modules/karma/static/karma.js
DEBUG [web-server]: upgrade /socket.io/1/websocket/CjC8pnQq5It2z_kWYB98
DEBUG [karma]: A browser has connected on socket CjC8pnQq5It2z_kWYB98
INFO [PhantomJS 1.9.7 (Linux)]: Connected on socket CjC8pnQq5It2z_kWYB98 with id 98204612
DEBUG [launcher]: PhantomJS (id 98204612) captured in 1.704 secs
WARN [PhantomJS 1.9.7 (Linux)]: Disconnected (1 times), because no message in 30000 ms.

DEBUG [karma]: Run complete, exitting.
DEBUG [launcher]: Disconnecting all browsers
DEBUG [launcher]: Process PhantomJS exited with code 0
DEBUG [temp-dir]: Cleaning temp dir /tmp/karma-98204612
Warning: Task "karma:unit" failed. Use --force to continue.

Aborted due to warnings.

Here's my karma.conf.js file:

'use strict';

module.exports = function (config) {
config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
        'test/helpers/**/*.js',
        'test/spec/components/**/*.js'
    ],
    preprocessors: {
        'test/spec/components/**/*.js': ['webpack']
    },
    webpack: {
        cache: true,
        module: {
            loaders: [{
                test: /\.css$/,
                loader: 'style!css'
            }, {
                test: /\.gif/,
                loader: 'url-loader?limit=10000&minetype=image/gif'
            }, {
                test: /\.jpg/,
                loader: 'url-loader?limit=10000&minetype=image/jpg'
            }, {
                test: /\.png/,
                loader: 'url-loader?limit=10000&minetype=image/png'
            }, {
                test: /\.js$/,
                loader: 'jsx-loader'
            }]
        }
    },
    webpackServer: {
        stats: {
            colors: true
        }
    },
    exclude: [],
    port: 8080,
    logLevel: config.LOG_DEBUG,
    colors: true,
    autoWatch: true,
    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],
    reporters: ['progress'],
    captureTimeout: 60000,
    browserNoActivityTimeout: 60000,
    singleRun: true
});
};

Body:
@Vijender's answer got me on the right track

It was as simple as replacing HttpClientModule in tests with HttpClientTestingModule.

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ]
    }).compileComponents();
  }));


问:
How to view CommandLineParser parsing errors in Visual Studio 2015?
I'm trying to see the errors that occur when parsing command-line arguments using the CommandLineParser package and Visual Studio Professional 2015 (Update 3).  Here is the code I'm working with:

```<code>using System;
using System.IO;

namespace SampleParser
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set the CommandLineParser configuration options.
            var commandLineParser = new CommandLine.Parser(x =>
            {
                x.MutuallyExclusive = true;
                x.HelpWriter = Console.Error;
                x.IgnoreUnknownArguments = false;
            });

            // Parse the command-line arguments.
            var options = new CommandLineOptions();
            var optionsAreValid = commandLineParser.ParseArguments(args, options);

            if (!optionsAreValid)
            {
                return;
            }
        }
    }
}
</code>```

I was expecting to see some helpful info about the problems that cause optionsAreValid to be set to false appear in the Debug > Windows > Output window.  However, nothing's showing up... am I doing something wrong, am I looking in the wrong place, or are there other settings that need to be toggled before I'll see this info?

UPDATE #1

Here is the class that models the command line options after being (successfully) parsed:

```<code>namespace SampleParser
{
    class CommandLineOptions
    {
        [Option(HelpText = @"When set to ""true"", running the application will not make any changes.", Required = false)]
        public bool Preview { get; set; }

        [HelpOption]
        public string GetUsage()
        {
            return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
        }
    }
}
</code>```

答:
I know this is a very old question, but it is still ranked first result in google for my particular search. Since there is no satisfying solution given, I'm going to add one:

To just print the errors you can use the SentenceBuilder provided by the library itself:

using System;
using CommandLine;
using CommandLine.Text;

...

var result = Parser.Default.ParseArguments<Options>(args);
result
    .WithParsed(opt => ...)
    .WithNotParsed(errors => {
        var sentenceBuilder = SentenceBuilder.Create();
        foreach (var error in errors)
            Console.WriteLine(sentenceBuilder.FormatError(error));
    });
```
<p>To print the full help information including the errors encountered use the following:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using CommandLine;
using CommandLine.Text;

...

var result = Parser.Default.ParseArguments<Options>(args);
result
    .WithParsed(opt => ...)
    .WithNotParsed(errors => {
        var helpText = HelpText.AutoBuild(result,
                                          h => HelpText.DefaultParsingErrorsHandler(result, h),
                                          e => e);
        Console.WriteLine(helpText);
    });
</code>```

I hope this helps someone in the future!

Body:
I'm trying to see the errors that occur when parsing command-line arguments using the CommandLineParser package and Visual Studio Professional 2015 (Update 3).  Here is the code I'm working with:

using System;
using System.IO;

namespace SampleParser
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set the CommandLineParser configuration options.
            var commandLineParser = new CommandLine.Parser(x =>
            {
                x.MutuallyExclusive = true;
                x.HelpWriter = Console.Error;
                x.IgnoreUnknownArguments = false;
            });

            // Parse the command-line arguments.
            var options = new CommandLineOptions();
            var optionsAreValid = commandLineParser.ParseArguments(args, options);

            if (!optionsAreValid)
            {
                return;
            }
        }
    }
}

I was expecting to see some helpful info about the problems that cause optionsAreValid to be set to false appear in the Debug > Windows > Output window.  However, nothing's showing up... am I doing something wrong, am I looking in the wrong place, or are there other settings that need to be toggled before I'll see this info?

UPDATE #1

Here is the class that models the command line options after being (successfully) parsed:

namespace SampleParser
{
    class CommandLineOptions
    {
        [Option(HelpText = @"When set to ""true"", running the application will not make any changes.", Required = false)]
        public bool Preview { get; set; }

        [HelpOption]
        public string GetUsage()
        {
            return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
        }
    }
}

Body:
I know this is a very old question, but it is still ranked first result in google for my particular search. Since there is no satisfying solution given, I'm going to add one:

To just print the errors you can use the SentenceBuilder provided by the library itself:

using System;
using CommandLine;
using CommandLine.Text;

...

var result = Parser.Default.ParseArguments<Options>(args);
result
    .WithParsed(opt => ...)
    .WithNotParsed(errors => {
        var sentenceBuilder = SentenceBuilder.Create();
        foreach (var error in errors)
            Console.WriteLine(sentenceBuilder.FormatError(error));
    });

To print the full help information including the errors encountered use the following:

using System;
using CommandLine;
using CommandLine.Text;

...

var result = Parser.Default.ParseArguments<Options>(args);
result
    .WithParsed(opt => ...)
    .WithNotParsed(errors => {
        var helpText = HelpText.AutoBuild(result,
                                          h => HelpText.DefaultParsingErrorsHandler(result, h),
                                          e => e);
        Console.WriteLine(helpText);
    });

I hope this helps someone in the future!


问:
Best way to create a C++ Makefile that mkaes a prod build and creates debugging information?
I'm pretty confused about the idea of makefiles, can't really grasp how to execute stuff on it. I have a program which I would like to create a makefile

Would this be able to produce a build of my program and also output debug info? Honestly completely confused.

答:
There are two targets in the makefile.

The first target is named TMA1Question3.exe, depends on Loop.cpp and will call g++ -o Loop.exe Loop.cpp. It will build the artifact Loop.exe without debug info.

The second target is named debug, has no dependencies and will call g++ -g Loop.cpp. It will build the artifact a.out containing debug info.


问:
Supporting optional parameters in an Informatica Integration Assignment Step
My current implementation request body does not support optional attributes:

If say phoneHome is null, then the wanted behaviour is for the JSON to not include the attribute at all, e.g. what I want is :

```<code>{
    "phoneWork": "value here",
    "phoneMobile": "value here",
    "email": "value here"
}
</code>```

Not:

```<code>{
    "phoneHome": "",
    "phoneWork": "value here",
    "phoneMobile": "value here",
    "email": "value here"
}
</code>```

I have tried looping through all elements in the event and returning only the values that are not null, but I am not able to get it working.
Pseudocode:

```<code>for $i in
(
    $input.event_input[1]/xxx_Contact_Work_PHONE__c,
    $input.event_input[1]/xxx_Contact_Home_PHONE__c,
    $input.event_input[1]/xxx_Contact_Mobile_PHONE__c,
    $input.event_input[1]/xxx_Contact_Contact_EMAIL1__c
)
return if ($i = "null")
then do nothing
else add the attribute to a JSON
</code>```

Is there a way to do this?

答:
The following formula, when given an XML as input, will remove all elements with no data.

Example

With the following input

```<code><note>
  <to>Tove</to>
  <from></from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
  <element></element>
</note>
</code>```

it produces the following output

```<code><note>
  <to>Tove</to>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>
</code>```

This is the solution I found:

```<code><!--Initialize variable with the input XML-->
let $sources:=$input.XML_input
<!--Initialize variable with the distinct nodes using X-PATH-->
let $labels:=fn:distinct-values($sources/*/fn:node-name(.))
return
for $s in $sources
    return
    <source>
    {
    for $l in $labels
        <!--Return element if value exists, nothing if no value-->
        return
        if (fn:exists($s/*[fn:node-name()=$l]/text()))
        then ($s/*[fn:node-name()=$l])
        else ""
    }
    </source>
</code>```

Body:
My current implementation request body does not support optional attributes:

If say phoneHome is null, then the wanted behaviour is for the JSON to not include the attribute at all, e.g. what I want is :

{
    "phoneWork": "value here",
    "phoneMobile": "value here",
    "email": "value here"
}

Not:

{
    "phoneHome": "",
    "phoneWork": "value here",
    "phoneMobile": "value here",
    "email": "value here"
}

I have tried looping through all elements in the event and returning only the values that are not null, but I am not able to get it working.
Pseudocode:

for $i in
(
    $input.event_input[1]/xxx_Contact_Work_PHONE__c,
    $input.event_input[1]/xxx_Contact_Home_PHONE__c,
    $input.event_input[1]/xxx_Contact_Mobile_PHONE__c,
    $input.event_input[1]/xxx_Contact_Contact_EMAIL1__c
)
return if ($i = "null")
then do nothing
else add the attribute to a JSON

Is there a way to do this?

Body:
The following formula, when given an XML as input, will remove all elements with no data.

Example

With the following input

<note>
  <to>Tove</to>
  <from></from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
  <element></element>
</note>

it produces the following output

<note>
  <to>Tove</to>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

This is the solution I found:

<!--Initialize variable with the input XML-->
let $sources:=$input.XML_input
<!--Initialize variable with the distinct nodes using X-PATH-->
let $labels:=fn:distinct-values($sources/*/fn:node-name(.))
return
for $s in $sources
    return
    <source>
    {
    for $l in $labels
        <!--Return element if value exists, nothing if no value-->
        return
        if (fn:exists($s/*[fn:node-name()=$l]/text()))
        then ($s/*[fn:node-name()=$l])
        else ""
    }
    </source>


问:
string.split is not working for some reason
I am trying to print the last name of the person "Michael" by splitting the string into an array and calling out the next word available.

When I run this code, I get undefined. I tried using Pythontutor to see what am I doing wrong and it turns out that string.split() is not working.

Can you please take a look and help figure me out what am I doing wrong?

Here is my code:

function getMichaelLastName(inputText) {
  var names = inputText;
  var newN = [names.split(" ")];
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] == "Michael") {
      var Michael = newN[i++];
    }
    return Michael;
  }
}
console.log(
getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?")
)```

答:
function getMichaelLastName(inputText) {
    var Michaels = [];
    var names = inputText;
    var newN = names.split(' ');
    for (var i = 0; i < newN.length; i++) {
        const x = newN[i];
        if (x.includes( "Michael")) {
            if(newN[i+1].length>3)
                Michaels.push(newN[i + 1].replace('?',''));
        }

    }
    return Michaels;
}
console.log(
getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?")
)```


问:
Assert a URL redirection when second URL can not be resolved in TestCafe
I want to assert that the next URL gets resolved. It's a URL generated by SendGrid and changes one you search it in the browser. The problem is that to access the second you need access to our VPN. For security reasons I don't want to run the test behind our VPN but I would like to assert if the redirection from SendGrid is successful (I know exactly what the resolved URL going to look like).

```<code>http://link.novemberfirst.com/ls/click?upn=xv2uBCiA-2BCPo8h2-2F2dXgSrKknBTgupgeogOdcsRpYXuG4cjYbJP1rkCCJ1zjXTj38aokCt-2BgUcrLMVeDJ0JrFznoH-2B4JC2bxKIUkkwWGvQPWZcW89yPA45cRI4YcN4kxIWOMamgXF7h0x-2BEumL4yC4cDPD6ib2Q-2FupSBTSJJvOohq9d3QApg3ktPsAr3s71dx8_f_jH2AkQSF6IE8lczSdagr9wUDFh2rSjc-2FDARefysokTdqaEnXNbSWSyYzYz4pIdy3KyzKI2WI84SAhUWA6Ysrwbu-2FEyv-2FLVj28UDJ96u9m0SfvfLMgVTTOypSpnfzJhz8HBp-2BErWzxw-2BHQBTWKJQCCsahFPt7FAp2yflzLocMroRH-2Blyqk-2Be61Q84U19yBAQ11beRliiLdNHnzJwd88-2FGbgPTIQoQi0xlVBQxVt08NyA-3D
</code>```

The problems comes when using ClientFunction(() => document.location.href) you will get only a URL that have been resolved successfully, and since I am not connected to the VPN the last URL won't be displayed and cant be asserted.

Is there a way to create an assert after the redirection is done even if I can't resolve the second URL?

await t.navigateTo(URL);

const getLocation = ClientFunction(() => document.location.href);

await t.expect(getLocation()).contains('expected-url');
```

In this case the expected-url would be: https://app-uat.novemberfirst.cloud.ec/#/public/reset-password/208100002/61849181@abc.com/F1PMDcC05gYhlqh82UDnl183/dan

答:
Found the solution to this.

Basically when making a http request you have to disable any redirection to get the url.

```<code>private async resolveRedirectLink(url) {
    let redirectedURL;
    try{
        let response = await fetch(url, {redirect: 'manual'});
        let link = await response.text();
        let matches = link.match(/"(.*?)"/);
        redirectedURL = matches[1];
    }
    catch(error){
        redirectedURL = url;
        console.warn('Error redirecting URL: ' + error.message );
    }
    return redirectedURL;
}
</code>```

This is the snipped used in my code.

Body:
I want to assert that the next URL gets resolved. It's a URL generated by SendGrid and changes one you search it in the browser. The problem is that to access the second you need access to our VPN. For security reasons I don't want to run the test behind our VPN but I would like to assert if the redirection from SendGrid is successful (I know exactly what the resolved URL going to look like).

http://link.novemberfirst.com/ls/click?upn=xv2uBCiA-2BCPo8h2-2F2dXgSrKknBTgupgeogOdcsRpYXuG4cjYbJP1rkCCJ1zjXTj38aokCt-2BgUcrLMVeDJ0JrFznoH-2B4JC2bxKIUkkwWGvQPWZcW89yPA45cRI4YcN4kxIWOMamgXF7h0x-2BEumL4yC4cDPD6ib2Q-2FupSBTSJJvOohq9d3QApg3ktPsAr3s71dx8_f_jH2AkQSF6IE8lczSdagr9wUDFh2rSjc-2FDARefysokTdqaEnXNbSWSyYzYz4pIdy3KyzKI2WI84SAhUWA6Ysrwbu-2FEyv-2FLVj28UDJ96u9m0SfvfLMgVTTOypSpnfzJhz8HBp-2BErWzxw-2BHQBTWKJQCCsahFPt7FAp2yflzLocMroRH-2Blyqk-2Be61Q84U19yBAQ11beRliiLdNHnzJwd88-2FGbgPTIQoQi0xlVBQxVt08NyA-3D

The problems comes when using ClientFunction(() => document.location.href) you will get only a URL that have been resolved successfully, and since I am not connected to the VPN the last URL won't be displayed and cant be asserted.

Is there a way to create an assert after the redirection is done even if I can't resolve the second URL?

await t.navigateTo(URL);

const getLocation = ClientFunction(() => document.location.href);

await t.expect(getLocation()).contains('expected-url');

In this case the expected-url would be: https://app-uat.novemberfirst.cloud.ec/#/public/reset-password/208100002/61849181@abc.com/F1PMDcC05gYhlqh82UDnl183/dan

Body:
Found the solution to this.

Basically when making a http request you have to disable any redirection to get the url.

private async resolveRedirectLink(url) {
    let redirectedURL;
    try{
        let response = await fetch(url, {redirect: 'manual'});
        let link = await response.text();
        let matches = link.match(/"(.*?)"/);
        redirectedURL = matches[1];
    }
    catch(error){
        redirectedURL = url;
        console.warn('Error redirecting URL: ' + error.message );
    }
    return redirectedURL;
}

This is the snipped used in my code.


答:
Use a function that is passed the props object. Here I've destructured dragging and if truthy return the background: grey rule, otherwise it returns no rule.

passed props

```<code>const DropZone = styled.div`
  height: 100%;
  ${({ dragging }) => dragging && 'background-color:  grey;'}
`;
</code>```

EDIT: Add dragging prop type (<{ dragging?: boolean }>) for typescript

```<code>const DropZone = styled.div<{ dragging?: boolean }>`
  height: 100%;
  ${({ dragging }) => dragging && 'background-color:  grey;'}
`;
</code>```

Usage

```<code><DropZone
  ref={dropRef}
  dragging={dragging} // <-- pass dragging as prop here
  onDragEnter={handleDragIn}
  onDragLeave={handleDragOut}
  onDragOver={handleDrag}
  onDrop={handleDrop}
>
  {children}
</DropZone>
</code>```

Title: How to add a background color to a styled component based on condition using react and typescript?

Body:
how can i add background color to styled component based on the condition using react and typescript?

what i am trying to do?

I have a MainComponent which renders ListContent within DragAndDropComponent.

Now when user drags a file into DragAndDrop div i want its background color change to grey.

Below is my code,

function MainComponent () {
return (
    <Wrapper>
        <SomeOtheComponent/>
        <DragAndDrop>
            <ListContent> //this is the children for the DragAndDrop component and want this to
                //render within DragAndDrop component
                {condition_true && (
                    <FirstList/>
                )}
                {condition_true && (
                    <SecondList/>
                )}
            </ListContent>
        </Wrapper>
    );
}

const DragAndDrop: React.FC = ({ children }) => { //here i am passing children
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);

    React.useEffect(() => {
        // componentDidMount()
        setDragCounter(0);
    }, []);

    const handleDrag = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev + 1);
        if (e.dataTransfer.files) {
            setDragging(true);
        }
    };

    const handleDragOut = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev - 1);
        if (dragCounter === 0) {
            setDragging(false);
        }
    };

    const handleDrop = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragging(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            e.dataTransfer.clearData();
            setDragCounter(0);
        }
    };

    return (
        <DropZone //i want to change background color to this div if dragging true.
            ref={dropRef}
            onDragEnter={handleDragIn}
            onDragLeave={handleDragOut}
            onDragOver={handleDrag}
            onDrop={handleDrop}
        >
            {children}
        </DropZone>
    );
};

const DropZone = styled.div`
    height: 100%;
    //backgroun-color: how to change background color to grey if dragging state true.
`;

Could someone help me with this. thanks.

Body:
Use a function that is passed the props object. Here I've destructured dragging and if truthy return the background: grey rule, otherwise it returns no rule.

passed props

const DropZone = styled.div`
  height: 100%;
  ${({ dragging }) => dragging && 'background-color:  grey;'}
`;

EDIT: Add dragging prop type (<{ dragging?: boolean }>) for typescript

const DropZone = styled.div<{ dragging?: boolean }>`
  height: 100%;
  ${({ dragging }) => dragging && 'background-color:  grey;'}
`;

Usage

<DropZone
  ref={dropRef}
  dragging={dragging} // <-- pass dragging as prop here
  onDragEnter={handleDragIn}
  onDragLeave={handleDragOut}
  onDragOver={handleDrag}
  onDrop={handleDrop}
>
  {children}
</DropZone>


问:
How to validate start date and end date in angular formly
I have two simple fields (input) of the start date and end date I just want that end date should not be less than the start date

I am using angular 8
I am using ng module

so from myfile.json file I have created two text fields validated them with my date function (validation.ts) in HTML formly code is there

now I want to validate two dates I am new angular developer please help

```<code>json code
{
              "className": "col-md-6 col-xs-12",
              "key": "graduationstartdate",
              "type": "input",
              "templateOptions": {
                "label": "Course start Date",
                  "appearance": "outline"

              }
            },

            {
              "className": "col-md-6 col-xs-12",
              "key": "graduationenddate",
              "type": "input",
              "templateOptions": {
                "label": "Course End Date",
                "appearance": "outline"
              }
</code>```

```<code>validation.ts
it contains a function to validate the date
</code>```

```<code>form.html
contains formly code of form
</code>```

答:
Best way to achieve that is using reactive form. You can create a formGroup which will hold all the formcontrols and now create a custom validator and attach it to your form.
Please go through documentation about usage of custom validator: https://angular.io/guide/form-validation</p>

Body:
I have two simple fields (input) of the start date and end date I just want that end date should not be less than the start date

I am using angular 8
I am using ng module

so from myfile.json file I have created two text fields validated them with my date function (validation.ts) in HTML formly code is there

now I want to validate two dates I am new angular developer please help

json code
{
              "className": "col-md-6 col-xs-12",
              "key": "graduationstartdate",
              "type": "input",
              "templateOptions": {
                "label": "Course start Date",
                  "appearance": "outline"

              }
            },

            {
              "className": "col-md-6 col-xs-12",
              "key": "graduationenddate",
              "type": "input",
              "templateOptions": {
                "label": "Course End Date",
                "appearance": "outline"
              }

validation.ts
it contains a function to validate the date

form.html
contains formly code of form


问:
Space between Column's children in Flutter
I have a Column widget with two TextField widgets as children and I want to have some space between both of them.

I already tried mainAxisAlignment: MainAxisAlignment.spaceAround, but the result was not what I wanted.

答:
Columns Has no height by default,
You can Wrap your Column to the Container and add the specific height to your Container.
Then You can use something like below:</p>

```<code>Container(
   width: double.infinity,//Your desire Width
   height: height,//Your desire Height
   child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
         Text('One'),
         Text('Two')
      ],
   ),
),
</code>```

Body:
Columns Has no height by default,
You can Wrap your Column to the Container and add the specific height to your Container.
Then You can use something like below:

Container(
   width: double.infinity,//Your desire Width
   height: height,//Your desire Height
   child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
         Text('One'),
         Text('Two')
      ],
   ),
),


问:
How to add a marker from a different column to a seaborn pandas barplot
I have the following dataset, code and plot:

```<code>import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
data = [['tom', 10,15], ['matt', 13,10]]

df3 = pd.DataFrame(data, columns = ['Name', 'Attempts','L4AverageAttempts'])

f,ax = plt.subplots(nrows=1,figsize=(16,9))
sns.barplot(x='Attempts',y='Name',data=df3)
plt.show()
</code>```

How can get a marker of some description (dot, *, shape, etc) to show that tomhas averaged 15 (so is below his average) and  matt has averaged 10 so is above average. So a marker basxed off the L4AverageAttempts value for each person.

I have looked into axvline but that seems to be only a set number rather than a specific value for each y axis category. Any help would be much appreciated! thanks!

答:
You can simply plot a scatter plot on top of your bar plot using L4AverageAttempts as the x value:

You can use seaborn.scatterplot for this. Make sure to set the zorder parameter so that the markers appear on top of the bars.

```<code>import seaborn as sns
import pandas as pd
data = [['tom', 10,15], ['matt', 13,10]]

df3 = pd.DataFrame(data, columns = ['Name', 'Attempts','L4AverageAttempts'])

f,ax = plt.subplots(nrows=1,figsize=(16,9))
sns.barplot(x='Attempts',y='Name',data=df3)

sns.scatterplot(x='L4AverageAttempts', y="Name", data=df3, zorder=10, color='k', edgecolor='k')

plt.show()
</code>```

Body:
I have the following dataset, code and plot:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
data = [['tom', 10,15], ['matt', 13,10]]

df3 = pd.DataFrame(data, columns = ['Name', 'Attempts','L4AverageAttempts'])

f,ax = plt.subplots(nrows=1,figsize=(16,9))
sns.barplot(x='Attempts',y='Name',data=df3)
plt.show()

How can get a marker of some description (dot, *, shape, etc) to show that tomhas averaged 15 (so is below his average) and  matt has averaged 10 so is above average. So a marker basxed off the L4AverageAttempts value for each person.

I have looked into axvline but that seems to be only a set number rather than a specific value for each y axis category. Any help would be much appreciated! thanks!

Body:
You can simply plot a scatter plot on top of your bar plot using L4AverageAttempts as the x value:

You can use seaborn.scatterplot for this. Make sure to set the zorder parameter so that the markers appear on top of the bars.

import seaborn as sns
import pandas as pd
data = [['tom', 10,15], ['matt', 13,10]]

df3 = pd.DataFrame(data, columns = ['Name', 'Attempts','L4AverageAttempts'])

f,ax = plt.subplots(nrows=1,figsize=(16,9))
sns.barplot(x='Attempts',y='Name',data=df3)

sns.scatterplot(x='L4AverageAttempts', y="Name", data=df3, zorder=10, color='k', edgecolor='k')

plt.show()


答:
You can fetch value by this modification in your code</p>

```<code>const content = document.querySelector("#someid").value;
</code>```

Title: value of a textarea element

Body:
I want to use value of a textarea element, but I am not able to get it

function postComment(element) {
  const content = element.previousSibling.value;
  console.log(content);
}

<form action="" class="comment-editor">

    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>

</form>

It gives undefined as output

Body:
You can fetch value by this modification in your code

const content = document.querySelector("#someid").value;


问:
Drop and Recreate Index on MYSQL table, it will improve the performance?
I have Executed the query in the newly imported MySQL database but it takes 68sec to complete. Then I have dropped and recreated the same indexes on 2 main tables then it takes 24sec only.

Why it has occurred? Is it a good practice or not?

Thanks in Advance

答:
You are misinterpreting the results and the cause. Dropping and re-creating the indexes isn't what makes it go faster. There are two things that could be going on:

1) DB doesn't fit into RAM so when you recreated two indexes that made most of them stick in the buffer pool by the time you ran the query.

2) Table was fragmented or had very lightly filled blocks. Recreating indexes probably rebuilt the table and that may have improved page occupancy If your query requires a full table scan, this would have meant fewer GBs of table to scan and possibly less fragmented (can matter on spinning rust).

As a general rule you should never need to do that. If you disable the query cache (query_cache_type=0, query_cache_size=0 on MySQL < 8), and run the query twice, the second time is the speed you can expect with hit buffer pool.


问:
How to fill progressBar using separate thread?
I'm currently working on the following problem : How to use a thread in order to fill a progress bar (step by step) when the start button is clicked.
I encountered no problems building the thread or the progress bar.
However, when it came to filling the bar I proceeded as following :

```<code>public class event implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent ae) {
        Try t = new Try(250);
        Thread MyT = new Thread(t);

       MyT.start();

        try {
            MyT.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
        }

        pr.setValue(pr.getValue()+25);
        System.out.println("check");

        try {
            MyT.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
        }

        pr.setValue(pr.getValue()+25);
        System.out.println("check");

    }
}
</code>```

The problem here is that I expected the bar to be filled with 25 units after 500 ms, then again filled with other 25 units(step by step) after 5000ms. Instead my program won't fill the bar with 25 after 500 ms, but with 50 after 5000 ms. Why is that and how can I make the bar charge gradually, without modifying the thread class ?

答:
Yes, I know the question is old but maybe it helps someone.

I have implemented a progress bar class that provides a simple method, which fills the progress bar to a certain value in a specified amount of time.

Use like this:

   // create progress bar
   ProgressBar progressbar = new ProgressBar();

   // fill progress bar in steps each one second
   progressbar.fillInMills(1000, 25);
   progressbar.fillInMills(1000, 50);
   progressbar.fillInMills(1000, 75);
   progressbar.fillInMills(1000, 100);

   // resets to zero
   progressbar.reset();
```

<pre class="lang-java prettyprint-override"><code>
import javax.swing.JProgressBar;

public class ProgressBar extends JProgressBar {

        Thread thread;
        final int MAX = 100;
        final int MIN = 0;

        public ProgressBar() {
            super(HORIZONTAL);
            setMinimum(MIN);
            setMaximum(MAX);
        }

        /**
         * Fills the progress bar to the specified level in the specified time.
         *
         * @param millis the time in milliseconds
         * @param fillTo the level in percentage
         */
        public void fillInMills(final int millis, final int fillTo) {
            thread = new Thread(() -> {
                try {
                    final int startAt = getValue();
                    final int timeBetweenSteps = millis / Math.max(fillTo - startAt, 1);
                    for (int i = startAt; i <= fillTo; i++) {
                        setValue(i);
                        Thread.sleep(timeBetweenSteps);
                    }
                } catch (final InterruptedException ignored) {
                    // thread is cancelled
                }
            });

            thread.start();
        }

        /**
         * Resets the ProgressBars level to zero.
         */
        public void reset() {
            if (thread != null) {
                thread.interrupt();
            }
            this.setValue(0);
        }
    }

</code>```

If you need advanced features of the JProgressBar, see this Oracle Tutorial on Progress Bars for detailed info.

Body:
I'm currently working on the following problem : How to use a thread in order to fill a progress bar (step by step) when the start button is clicked.
I encountered no problems building the thread or the progress bar.
However, when it came to filling the bar I proceeded as following :

public class event implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent ae) {
        Try t = new Try(250);
        Thread MyT = new Thread(t);

       MyT.start();

        try {
            MyT.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
        }

        pr.setValue(pr.getValue()+25);
        System.out.println("check");

        try {
            MyT.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
        }

        pr.setValue(pr.getValue()+25);
        System.out.println("check");

    }
}

The problem here is that I expected the bar to be filled with 25 units after 500 ms, then again filled with other 25 units(step by step) after 5000ms. Instead my program won't fill the bar with 25 after 500 ms, but with 50 after 5000 ms. Why is that and how can I make the bar charge gradually, without modifying the thread class ?

Body:
Yes, I know the question is old but maybe it helps someone.

I have implemented a progress bar class that provides a simple method, which fills the progress bar to a certain value in a specified amount of time.

Use like this:

   // create progress bar
   ProgressBar progressbar = new ProgressBar();

   // fill progress bar in steps each one second
   progressbar.fillInMills(1000, 25);
   progressbar.fillInMills(1000, 50);
   progressbar.fillInMills(1000, 75);
   progressbar.fillInMills(1000, 100);

   // resets to zero
   progressbar.reset();

import javax.swing.JProgressBar;

public class ProgressBar extends JProgressBar {

        Thread thread;
        final int MAX = 100;
        final int MIN = 0;

        public ProgressBar() {
            super(HORIZONTAL);
            setMinimum(MIN);
            setMaximum(MAX);
        }

        /**
         * Fills the progress bar to the specified level in the specified time.
         *
         * @param millis the time in milliseconds
         * @param fillTo the level in percentage
         */
        public void fillInMills(final int millis, final int fillTo) {
            thread = new Thread(() -> {
                try {
                    final int startAt = getValue();
                    final int timeBetweenSteps = millis / Math.max(fillTo - startAt, 1);
                    for (int i = startAt; i <= fillTo; i++) {
                        setValue(i);
                        Thread.sleep(timeBetweenSteps);
                    }
                } catch (final InterruptedException ignored) {
                    // thread is cancelled
                }
            });

            thread.start();
        }

        /**
         * Resets the ProgressBars level to zero.
         */
        public void reset() {
            if (thread != null) {
                thread.interrupt();
            }
            this.setValue(0);
        }
    }

If you need advanced features of the JProgressBar, see this Oracle Tutorial on Progress Bars for detailed info.