问:
actionEventListener ("click") does not work after inserting another item
I'm trying to add dynamically div elements inside filtersSpace div element and at the same time add an eventListener for each button inside the div elements but when I insert the second element the first one to be added does not work.

Can anybody help me ?

```<code>case "status":
        filtersSpace.innerHTML +=
            `<div class="card border-dark mx-2 my-3" style="width: 23%;">
                <h5 class="card-header">Status</h5>
                <div class="card-body">
                    <tr>
                        <select class="custom-select mr-sm-2" id="${'statusInput' + statusFilterCounter.toString(10)}">
                            <option selected value="Solved">Solved</option>
                            <option value="Open">Open</option>
                            <option value="Pending">Pending</option>
                        </select>
                    </tr>
                    <tr>
                        <button type="button" class="btn btn-dark my-2" style="width: 100%;"
                        id="${'statusActionButton' + statusFilterCounter.toString(10)}">
                            Filter
                        </button>
                        <button type="button" class="btn btn-outline-dark my-2" style="width: 100%;"
                        id="${'statusCancelButton' + statusFilterCounter.toString(10)}">
                            Cancel
                        </button>
                    </tr>
                </div>
            </div>`;
        defineFilter(
            "status",
            document.getElementById("statusInput" + statusFilterCounter.toString(10)),
            document.getElementById("statusActionButton" + statusFilterCounter.toString(10)),
            document.getElementById("statusCancelButton" + statusFilterCounter.toString(10))
        );
        statusFilterCounter += 1;
        statusLink.disabled = true;
        break;
</code>```

...

```<code>function defineFilter(filterType, input, actionButton, cancelButton) {
actionButton.addEventListener("click",
    function () {
        filters.push({filterType : filterType, value : input.value});
        actionButton.disabled = true;
        print();
        getDataFromJSon();
    }
);
cancelButton.addEventListener("click",
    function () {
        var quantity = this.id.charAt(this.id.length - 1);
        var counter = 0;
        for (var i = 0; i < filters.length; i++){
            if(filters[i].filterType == filterType){
                console.log(">>>");
                if(counter == quantity){
                    filters.splice(i, 1);
                    print();
                    getDataFromJSon();
                    break;
                }
                counter += 1;
            }
        }
        actionButton.disabled = false;
    }
);}
</code>```

答: you have to register for the new element the event listener</p>

Body:
I'm trying to add dynamically div elements inside filtersSpace div element and at the same time add an eventListener for each button inside the div elements but when I insert the second element the first one to be added does not work.

Can anybody help me ?

case "status":
        filtersSpace.innerHTML +=
            `

Status

                        <select class="custom-select mr-sm-2" id="${'statusInput' + statusFilterCounter.toString(10)}">
                            <option selected value="Solved">Solved</option>
                            <option value="Open">Open</option>
                            <option value="Pending">Pending</option>
                        </select>

                        <button type="button" class="btn btn-dark my-2" style="width: 100%;"
                        id="${'statusActionButton' + statusFilterCounter.toString(10)}">
                            Filter
                        </button>
                        <button type="button" class="btn btn-outline-dark my-2" style="width: 100%;"
                        id="${'statusCancelButton' + statusFilterCounter.toString(10)}">
                            Cancel
                        </button>

`;
        defineFilter(
            "status",
            document.getElementById("statusInput" + statusFilterCounter.toString(10)),
            document.getElementById("statusActionButton" + statusFilterCounter.toString(10)),
            document.getElementById("statusCancelButton" + statusFilterCounter.toString(10))
        );
        statusFilterCounter += 1;
        statusLink.disabled = true;
        break;

...

function defineFilter(filterType, input, actionButton, cancelButton) {
actionButton.addEventListener("click",
    function () {
        filters.push({filterType : filterType, value : input.value});
        actionButton.disabled = true;
        print();
        getDataFromJSon();
    }
);
cancelButton.addEventListener("click",
    function () {
        var quantity = this.id.charAt(this.id.length - 1);
        var counter = 0;
        for (var i = 0; i < filters.length; i++){
            if(filters[i].filterType == filterType){
                console.log(">>>");
                if(counter == quantity){
                    filters.splice(i, 1);
                    print();
                    getDataFromJSon();
                    break;
                }
                counter += 1;
            }
        }
        actionButton.disabled = false;
    }
);}


来源: stackexchange

问:
Laravel pass subdomain as a value to another route
now I have this code

```<code>    Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
    Route::any('/', function($subdomain)
    {
        Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index');
    });
});
</code>```

I want to pass {subdomain} to  Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index'); for when call subdomain.localhost/identifier I call AController@index I should pass the value of subdomain to AController@index

答:
Please try this.</p>

```<code>Route::domain('{account}.myapp.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
now I have this code

    Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
    Route::any('/', function($subdomain)
    {
        Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index');
    });
});

I want to pass {subdomain} to  Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index'); for when call subdomain.localhost/identifier I call AController@index I should pass the value of subdomain to AController@index

Body:
Please try this.

Route::domain('{account}.myapp.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});


问:
Symfony3.4 Form errors rendered twice
I have a form with author and message fields and NotBlank() validation on both.

In twig, I do this:

```<code>{{ form_start(form) }}

    {{ form_errors(form.author) }}
    {{ form_label(form.author) }}
    {{ form_widget(form.author) }}

    {{ form_errors(form.message) }}
    {{ form_label(form.message) }}
    {{ form_widget(form.message) }}

{{ form_end(form) }}
</code>```

If I press Save button with empty fields I EXPECT to see this:

But I get this:

Somehow the bottom error message comes from the {{ form_label(...) }} I say this, because if I comment the labels out and use static HTML for labels, the output is like on first picture.

I would prefer not to use static HTML for labels, but I don't understand where the second error messages came from.

Below my code:

Form

```<code>class TestFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('author', TextType::class, ['required' => false, 'constraints' => [new NotBlank()]])
            ->add('message', TextType::class, ['required' => false, 'constraints' => [new NotBlank()]])
            ->add('save', SubmitType::class)
        ;
    }
}
</code>```

Controller

```<code>class TestController extends Controller
{
    /**
     * @Route("/testing", name="test")
     * @param Request $request
     * @return RedirectResponse|Response
     */
    public function index(Request $request)
    {
        $form = $this->createForm(TestFormType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid())
        {
            return $this->redirectToRoute('test');
        }

        return $this->render('test/index.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}
</code>```

Template
    {% extends 'base.html.twig' %}
    {% block title %}Hello TestController!{% endblock %}

```<code>{% block body %}

    <p>This is a test...</p>

    {{ form_start(form) }}

        {{ form_errors(form.author) }}
        {{ form_label(form.author) }}
        {{ form_widget(form.author) }}

        {{ form_errors(form.message) }}
        {{ form_label(form.message) }}
        {{ form_widget(form.message) }}

    {{ form_end(form) }}

{% endblock %}
</code>```

答:
For bootstrap theme error block is integrated in label.
So you need either to remove form_errors block in your template or to override form_label block.
You can use form_row (as @Adrien suggests in commentaries) as there is no form_errors call

Title: Symfony3.4 Form errors rendered twice

Body:
I have a form with author and message fields and NotBlank() validation on both.

In twig, I do this:

{{ form_start(form) }}

    {{ form_errors(form.author) }}
    {{ form_label(form.author) }}
    {{ form_widget(form.author) }}

    {{ form_errors(form.message) }}
    {{ form_label(form.message) }}
    {{ form_widget(form.message) }}

{{ form_end(form) }}

If I press Save button with empty fields I EXPECT to see this:

But I get this:

Somehow the bottom error message comes from the {{ form_label(...) }} I say this, because if I comment the labels out and use static HTML for labels, the output is like on first picture.

I would prefer not to use static HTML for labels, but I don't understand where the second error messages came from.

Below my code:

Form

class TestFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('author', TextType::class, ['required' => false, 'constraints' => [new NotBlank()]])
            ->add('message', TextType::class, ['required' => false, 'constraints' => [new NotBlank()]])
            ->add('save', SubmitType::class)
        ;
    }
}

Controller

class TestController extends Controller
{
    /**
     * @Route("/testing", name="test")
     * @param Request $request
     * @return RedirectResponse|Response
     */
    public function index(Request $request)
    {
        $form = $this->createForm(TestFormType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid())
        {
            return $this->redirectToRoute('test');
        }

        return $this->render('test/index.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}

Template
    {% extends 'base.html.twig' %}
    {% block title %}Hello TestController!{% endblock %}

{% block body %}

This is a test...

    {{ form_start(form) }}

        {{ form_errors(form.author) }}
        {{ form_label(form.author) }}
        {{ form_widget(form.author) }}

        {{ form_errors(form.message) }}
        {{ form_label(form.message) }}
        {{ form_widget(form.message) }}

    {{ form_end(form) }}

{% endblock %}


问:
Iphone dev : how can I get a result from google currency converter?
Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.

I have already tried something like that :

```<code>    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}
</code>```

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

答:
You better use an asynchronous request to avoid blocking your app. Easy using ASIHTTPRequest:</p>

```
<code>
- (IBAction)grabURLInBackground:(id)sender
{
   NSURL *url = [NSURL URLWithString:@"http://www.google.com/finance/converter?a=1&from=USD&to=GBP"];
   ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
   [request setDelegate:self];
   [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
   // Use when fetching text data
   NSString *responseString = [request responseString];

   [label setText: responseString];

}

- (void)requestFailed:(ASIHTTPRequest *)request
{
   NSError *error = [request error]; //you can log the error description

   [label setText:@"not working"];

}
</code>
```

ContentLicense: CC BY-SA 3.0

Body:
Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.

I have already tried something like that :

    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

Body:
You better use an asynchronous request to avoid blocking your app. Easy using ASIHTTPRequest:

- (IBAction)grabURLInBackground:(id)sender
{
   NSURL *url = [NSURL URLWithString:@"http://www.google.com/finance/converter?a=1&from=USD&to=GBP"];
   ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
   [request setDelegate:self];
   [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
   // Use when fetching text data
   NSString *responseString = [request responseString];

   [label setText: responseString];

}

- (void)requestFailed:(ASIHTTPRequest *)request
{
   NSError *error = [request error]; //you can log the error description

   [label setText:@"not working"];

}


问:
How can my site be able for mobile device
I wanna to make my logo(KP advisory) and text responsive when resize the browser in full width, but unfortunately just mi background image resize. Maybe it's not hard to do but i don't know where is the problem. Also need to be able for mobile devices. Please help.

HTML

```<code><div class="container">
        <div class="banner">
                <img src="logo1.png" class="logo" width="650px" height="215px">
                    <h4 class="heading mt-100">KP business & financial<br>advisory services d.o.o.
                Beograd<br><br>Resavska 23,<br>1100 Beograd, Srbija<br><br>
                <a href="mailto:office@kp-advisory.com " class="link">office@kp-advisory.com</a>
            </div>
    </div>
</code>```

CSS

```<code>.link {
    color:white;
}

html {
    background: fixed;
}

body {
    margin: 0;
    height: 100%;
    background: url('pozadina.png') no-repeat fixed;
    background-size: cover;
    align-content: center;
    width: 100%;
    /* overflow: hidden; */
}
.container {
    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center;
    height: 100vh;
}
.mt-100 {
    margin-top: 80p;
    font-size: 22px;
    align-content: center;
    font-family: 'Open Sans', sans-serif;
    font-weight: 100;
    height: 100%;

}
.banner {
    text-align: center;
    color: white;
    margin-top: -190px;
    overflow: hidden;
}

.logo {
  margin-top: 330px;
  background-size: cover;
    width: auto;
}
</code>```

答:
I'm not sure what you mean but here you have the basis to do a responsive website.

.link {
  color: white;
}

body {
  background: #4d4d4d;
  margin: 0;
  background-size: cover;
  align-content: center;
  width: 100%;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.mt-100 {
  font-size: 22px;
  align-content: center;
  font-family: 'Open Sans', sans-serif;
  font-weight: 100;
  transition: 0.24s;
}

.banner {
  text-align: center;
  color: white;
  overflow: hidden;
  width: 60%;
  transition: 0.24s;
}

.logo {
  background-size: cover;
  height: 200px;
  width: 200px;
  margin-top: 30px;
  transition: 0.24s;
}

@media screen and (max-width: 765px) {
  .banner {
    width: 100%;
  }

  .logo {
    height: 100px;
    width: 100px;
  }

  .mt-100 {
    font-size: 18px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
        <div class="banner">
                <img src="logo1.png" class="logo" width="650px" height="215px">
                    <h4 class="heading mt-100">KP business & financial<br>advisory services d.o.o.
                Beograd<br><br>Resavska 23,<br>1100 Beograd, Srbija<br><br>
                office@kp-advisory.com
            </div>
    </div></code>```

Body:
I wanna to make my logo(KP advisory) and text responsive when resize the browser in full width, but unfortunately just mi background image resize. Maybe it's not hard to do but i don't know where is the problem. Also need to be able for mobile devices. Please help.

HTML

KP business & financial
advisory services d.o.o.
                Beograd

Resavska 23,
1100 Beograd, Srbija

                office@kp-advisory.com

CSS

.link {
    color:white;
}

html {
    background: fixed;
}

body {
    margin: 0;
    height: 100%;
    background: url('pozadina.png') no-repeat fixed;
    background-size: cover;
    align-content: center;
    width: 100%;
    /* overflow: hidden; */
}
.container {
    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center;
    height: 100vh;
}
.mt-100 {
    margin-top: 80p;
    font-size: 22px;
    align-content: center;
    font-family: 'Open Sans', sans-serif;
    font-weight: 100;
    height: 100%;

}
.banner {
    text-align: center;
    color: white;
    margin-top: -190px;
    overflow: hidden;
}

.logo {
  margin-top: 330px;
  background-size: cover;
    width: auto;
}

Body:
I'm not sure what you mean but here you have the basis to do a responsive website.

.link {
  color: white;
}

body {
  background: #4d4d4d;
  margin: 0;
  background-size: cover;
  align-content: center;
  width: 100%;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.mt-100 {
  font-size: 22px;
  align-content: center;
  font-family: 'Open Sans', sans-serif;
  font-weight: 100;
  transition: 0.24s;
}

.banner {
  text-align: center;
  color: white;
  overflow: hidden;
  width: 60%;
  transition: 0.24s;
}

.logo {
  background-size: cover;
  height: 200px;
  width: 200px;
  margin-top: 30px;
  transition: 0.24s;
}

@media screen and (max-width: 765px) {
  .banner {
    width: 100%;
  }

  .logo {
    height: 100px;
    width: 100px;
  }

  .mt-100 {
    font-size: 18px;
  }
}

<div class="container">
        <div class="banner">
                <img src="logo1.png" class="logo" width="650px" height="215px">
                    <h4 class="heading mt-100">KP business & financial<br>advisory services d.o.o.
                Beograd<br><br>Resavska 23,<br>1100 Beograd, Srbija<br><br>
                <a href="mailto:office@kp-advisory.com " class="link">office@kp-advisory.com</a>
            </div>
    </div>


问:
flextable: How to merge rows with duplicate values for some columns
I'm making a table using flextable(). I would like to merge cells with duplicated srdr_id.

Given these data:

```<code>test <- structure(list(srdr_id = c("175124", "175124", "172545", "172545",
"172609", "172609", "172609"), full_name = c("TAU", "MI", "TAU",
"MI", "TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Assessed control", "Intervention", "Control", "Computer BI",
"Therapist BI"), arm_number = c(1L, 2L, 1L, 2L, 1L, 2L, 3L)), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))

  srdr_id full_name article_arm_name arm_number
  <chr>   <chr>     <chr>                 <int>
1 175124  TAU       Control                   1
2 175124  MI        WISEteens                 2
3 172545  TAU       Assessed control          1
4 172545  MI        Intervention              2
5 172609  TAU       Control                   1
6 172609  MI        Computer BI               2
7 172609  MI        Therapist BI              3
</code>```

I can do it with the following code - but would like to simplify the multiple merge_at() statements.

```<code>flextable(test) %>% theme_box() %>%
           merge_at(i = 1:2, j = 1) %>%
           merge_at(i = 3:4, j = 1) %>%
           merge_at(i = 5:7, j = 1)
</code>```

<img src="https://i.stack.imgur.com/EyUXu.png" alt="enter image description here">

Unfortunately, the simple solution, merge_v(j = ~srdr_id), no longer is sufficient when I add another column which is duplicated across common srdr_id's.

```<code>test_2 <- structure(list(srdr_id = c("175124", "175124", "172525", "172525",
"172545", "172545", "172609", "172609", "172609"), substances = c("alcohol",
"alcohol", "alcohol", "alcohol", "cannabis", "cannabis", "alcohol\n cannabis\n other drugs",
"alcohol\n cannabis\n other drugs", "alcohol\n cannabis\n other drugs"
), full_name = c("TAU", "MI", "TAU", "MI (parent)", "TAU", "MI",
"TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Treatment as usual", "Brief MI (b-MI)", "Assessed control",
"Intervention", "Control", "Computer BI", "Therapist BI")), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

# A tibble: 9 x 4
  srdr_id substances                         full_name   article_arm_name
  <chr>   <chr>                              <chr>       <chr>
1 175124  alcohol                            TAU         Control
2 175124  alcohol                            MI          WISEteens
3 172525  alcohol                            TAU         Treatment as usual
4 172525  alcohol                            MI (parent) Brief MI (b-MI)
5 172545  cannabis                           TAU         Assessed control
6 172545  cannabis                           MI          Intervention
7 172609  "alcohol\n cannabis\n other drugs" TAU         Control
8 172609  "alcohol\n cannabis\n other drugs" MI          Computer BI
9 172609  "alcohol\n cannabis\n other drugs" MI          Therapist BI
</code>```

答:
You can create a custom function for that as flextable does not have this option.

```<code>test_2 <- structure(list(srdr_id = c("175124", "175124", "172525", "172525",
"172545", "172545", "172609", "172609", "172609"), substances = c("alcohol",
"alcohol", "alcohol", "alcohol", "cannabis", "cannabis", "alcohol\n cannabis\n other drugs",
"alcohol\n cannabis\n other drugs", "alcohol\n cannabis\n other drugs"
), full_name = c("TAU", "MI", "TAU", "MI (parent)", "TAU", "MI",
"TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Treatment as usual", "Brief MI (b-MI)", "Assessed control",
"Intervention", "Control", "Computer BI", "Therapist BI")), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

merge_custom <- function(ft, x, columns){
  z <- rle(x)
  rows_at <- cumsum(z$lengths) - z$lengths + 1

  for(i in seq_along(rows_at)){
    for(j in columns)
      ft <- merge_at(x = ft, i = seq( rows_at[i], rows_at[i] + z$lengths[i] - 1), j = j)
  }

  ft
}

flextable(test_2) %>% merge_custom(x = test_2$srdr_id, columns=1:2) %>% theme_box()
</code>```

Body:
I'm making a table using flextable(). I would like to merge cells with duplicated srdr_id.

Given these data:

test <- structure(list(srdr_id = c("175124", "175124", "172545", "172545",
"172609", "172609", "172609"), full_name = c("TAU", "MI", "TAU",
"MI", "TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Assessed control", "Intervention", "Control", "Computer BI",
"Therapist BI"), arm_number = c(1L, 2L, 1L, 2L, 1L, 2L, 3L)), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))

  srdr_id full_name article_arm_name arm_number
  <chr>   <chr>     <chr>                 <int>
1 175124  TAU       Control                   1
2 175124  MI        WISEteens                 2
3 172545  TAU       Assessed control          1
4 172545  MI        Intervention              2
5 172609  TAU       Control                   1
6 172609  MI        Computer BI               2
7 172609  MI        Therapist BI              3

I can do it with the following code - but would like to simplify the multiple merge_at() statements.

flextable(test) %>% theme_box() %>%
           merge_at(i = 1:2, j = 1) %>%
           merge_at(i = 3:4, j = 1) %>%
           merge_at(i = 5:7, j = 1)

<img src="https://i.stack.imgur.com/EyUXu.png" alt="enter image description here">

Unfortunately, the simple solution, merge_v(j = ~srdr_id), no longer is sufficient when I add another column which is duplicated across common srdr_id's.

test_2 <- structure(list(srdr_id = c("175124", "175124", "172525", "172525",
"172545", "172545", "172609", "172609", "172609"), substances = c("alcohol",
"alcohol", "alcohol", "alcohol", "cannabis", "cannabis", "alcohol\n cannabis\n other drugs",
"alcohol\n cannabis\n other drugs", "alcohol\n cannabis\n other drugs"
), full_name = c("TAU", "MI", "TAU", "MI (parent)", "TAU", "MI",
"TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Treatment as usual", "Brief MI (b-MI)", "Assessed control",
"Intervention", "Control", "Computer BI", "Therapist BI")), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

# A tibble: 9 x 4
  srdr_id substances                         full_name   article_arm_name
  <chr>   <chr>                              <chr>       <chr>
1 175124  alcohol                            TAU         Control
2 175124  alcohol                            MI          WISEteens
3 172525  alcohol                            TAU         Treatment as usual
4 172525  alcohol                            MI (parent) Brief MI (b-MI)
5 172545  cannabis                           TAU         Assessed control
6 172545  cannabis                           MI          Intervention
7 172609  "alcohol\n cannabis\n other drugs" TAU         Control
8 172609  "alcohol\n cannabis\n other drugs" MI          Computer BI
9 172609  "alcohol\n cannabis\n other drugs" MI          Therapist BI

Body:
You can create a custom function for that as flextable does not have this option.

test_2 <- structure(list(srdr_id = c("175124", "175124", "172525", "172525",
"172545", "172545", "172609", "172609", "172609"), substances = c("alcohol",
"alcohol", "alcohol", "alcohol", "cannabis", "cannabis", "alcohol\n cannabis\n other drugs",
"alcohol\n cannabis\n other drugs", "alcohol\n cannabis\n other drugs"
), full_name = c("TAU", "MI", "TAU", "MI (parent)", "TAU", "MI",
"TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Treatment as usual", "Brief MI (b-MI)", "Assessed control",
"Intervention", "Control", "Computer BI", "Therapist BI")), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

merge_custom <- function(ft, x, columns){
  z <- rle(x)
  rows_at <- cumsum(z$lengths) - z$lengths + 1

  for(i in seq_along(rows_at)){
    for(j in columns)
      ft <- merge_at(x = ft, i = seq( rows_at[i], rows_at[i] + z$lengths[i] - 1), j = j)
  }

  ft
}

flextable(test_2) %>% merge_custom(x = test_2$srdr_id, columns=1:2) %>% theme_box()


问:
How to authenticate Freshdesk API in Zapier webhook?
I'm calling the Freshdesk API to update a ticket by adding tags. I'm having trouble authenticating the call. I have encoded username and password to base64(using an external tool).

I've tried the following:

Basic Auth: In Zapier's BasiAuth field, I tried username|password

In the header field, I added a key Authentication with value BasicUsername:password

In both cases I get the error You have to be logged in to perform this action.

答:
Zapier's basic auth field should work if everything is set up correctly (and there's no | in your password). In that field, you should be using your actual password, not the base64 encoded pair: david:mypass.

If you want to do it manually, that's fine too. the Authentication header should be something like Basic asdfasdf==. Note the space between the word "basic" and the "base64" encoded username:password.


问:
Integration of pubsubeat with elasticsearch
I am learning how to integrate pubsub with elasticsearch. There are various options like pubsubbeat, Google_pubsub input plugin, Google Cloud Pub/Sub Output Plugin.

I am currently trying to use pubsubbeat and stucked after running the command " ./pubsubbeat -c pubsubbeat.yml -e -d "*" " as suggested. Log of console is as follows

```<code>2019-05-23T14:42:19.949+0100    INFO    instance/beat.go:468    Home path: [/home/amishra/pubsubbeat-linux-amd64] Config path: [/home/amishra/pubsubbeat-linux-amd64] Data path: [/home/amishra/pubsubbeat-linux-amd64/data] Logs path: [/home/amishra/pubsubbeat-linux-amd64/logs]
2019-05-23T14:42:19.949+0100    DEBUG   [beat]  instance/beat.go:495    Beat metadata path: /home/amishra/pubsubbeat-linux-amd64/data/meta.json
2019-05-23T14:42:19.949+0100    INFO    instance/beat.go:475    Beat UUID: 4bd6119e-603a-426c-9d5b-6ac588bb000e
2019-05-23T14:42:19.949+0100    INFO    instance/beat.go:213    Setup Beat: pubsubbeat; Version: 6.2.2
2019-05-23T14:42:19.949+0100    DEBUG   [beat]  instance/beat.go:230    Initializing output plugins
2019-05-23T14:42:19.949+0100    DEBUG   [processors]    processors/processor.go:49  Processors:
2019-05-23T14:42:19.952+0100    INFO    pipeline/module.go:76   Beat name: allspark
2019-05-23T14:42:19.952+0100    INFO    [PubSub: dev/elk-logstash-poc/logstash-poc] beater/pubsubbeat.go:54 config retrieved: &{Project:dev Topic:elk-logstash-poc CredentialsFile:/home/amishra/key/key.json Subscription:{Name:logstash-poc RetainAckedMessages:false RetentionDuration:5h0m0s} Json:{Enabled:false AddErrorKey:false}}
</code>```

On second thought, I tried solution 2 but was getting below error and haven't able to resolve yet

```<code>io.grpc.internal.ManagedChannelImpl$NameResolverListenerImpl onError
WARNING: [io.grpc.internal.ManagedChannelImpl-1] Failed to resolve name. status=Status{code=UNAVAILABLE, description=Unable to resolve host pubsub.googleapis.com, cause=java.net.UnknownHostException: pubsub.googleapis.com
</code>```

Any lead on how to make thing working will be great help

答: The issue got resolved in unexpected way i.e. installing and deploying on fresh machine. Root cause is still unknown. </p>

Body:
I am learning how to integrate pubsub with elasticsearch. There are various options like pubsubbeat, Google_pubsub input plugin, Google Cloud Pub/Sub Output Plugin.

I am currently trying to use pubsubbeat and stucked after running the command " ./pubsubbeat -c pubsubbeat.yml -e -d "*" " as suggested. Log of console is as follows

2019-05-23T14:42:19.949+0100    INFO    instance/beat.go:468    Home path: [/home/amishra/pubsubbeat-linux-amd64] Config path: [/home/amishra/pubsubbeat-linux-amd64] Data path: [/home/amishra/pubsubbeat-linux-amd64/data] Logs path: [/home/amishra/pubsubbeat-linux-amd64/logs]
2019-05-23T14:42:19.949+0100    DEBUG   [beat]  instance/beat.go:495    Beat metadata path: /home/amishra/pubsubbeat-linux-amd64/data/meta.json
2019-05-23T14:42:19.949+0100    INFO    instance/beat.go:475    Beat UUID: 4bd6119e-603a-426c-9d5b-6ac588bb000e
2019-05-23T14:42:19.949+0100    INFO    instance/beat.go:213    Setup Beat: pubsubbeat; Version: 6.2.2
2019-05-23T14:42:19.949+0100    DEBUG   [beat]  instance/beat.go:230    Initializing output plugins
2019-05-23T14:42:19.949+0100    DEBUG   [processors]    processors/processor.go:49  Processors:
2019-05-23T14:42:19.952+0100    INFO    pipeline/module.go:76   Beat name: allspark
2019-05-23T14:42:19.952+0100    INFO    [PubSub: dev/elk-logstash-poc/logstash-poc] beater/pubsubbeat.go:54 config retrieved: &{Project:dev Topic:elk-logstash-poc CredentialsFile:/home/amishra/key/key.json Subscription:{Name:logstash-poc RetainAckedMessages:false RetentionDuration:5h0m0s} Json:{Enabled:false AddErrorKey:false}}

On second thought, I tried solution 2 but was getting below error and haven't able to resolve yet

io.grpc.internal.ManagedChannelImpl$NameResolverListenerImpl onError
WARNING: [io.grpc.internal.ManagedChannelImpl-1] Failed to resolve name. status=Status{code=UNAVAILABLE, description=Unable to resolve host pubsub.googleapis.com, cause=java.net.UnknownHostException: pubsub.googleapis.com

Any lead on how to make thing working will be great help


问:
Finding minimal jump zero crossings in numpy
For a data analysis task, I want to find zero crossings in a numpy array, coming from a convolution with first a sobel-like kernel, and then a mexican hat kernel. Zero crossings allow me to detect edges in the data.

Unfortunately, the data is somewhat noisy and I only want to find zero crossings with a minimal jump size, 20 in the follwing example:

```<code>import numpy as np
arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])
</code>```

Should result in

```<code>>>>array([1, 3, 7])
</code>```

or

```<code>>>>array([3, 7])
</code>```

Where 3 is the index of -1, just before the middle of the first jump and 7 is the index of -10

I have tried a modification of the following code (source: Efficiently detect sign-changes in python)

```<code>zero_crossings = np.where(np.diff(np.sign(np.trunc(arr/10))))[0]
</code>```

Which correctly ignores small jumps, but puts the zero-crossings at [1,5,7]

What would be an efficient way of doing this?

The definition of minimal jump is not strict, but results should be along the lines of my question.

Edit: For Clarification

```<code>arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])
arr_floored = np.trunc(arr/10)
>>>>np.array([10, 10, 0, 0, 0, 0, -10, -10, 10])
sgn = np.sign(arr_floored)
>>>>array([ 1,  1,  0,  0,  0,  0, -1, -1,  1])
dsgn = np.diff(sgn)
>>>>array([ 0, -1,  0,  0,  0, -1,  0,  2])
np.where(dsgn)
>>>>(array([1, 5, 7], dtype=int64),)
</code>```

Further edgecases:

```<code>arr = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
</code>```

Should result in

```<code>>>> np.array([10])
</code>```

Also just noticed: The problem might be ill-posed(in a mathematical sense). I will clarify it later today.

答:
Base case

I guess you want

```<code>import numpy as np
x = np.array([10, -50, -30, 50, 10, 3, -200, -12, 123])
indices = np.where(np.logical_and(np.abs(np.diff(x)) >= 20, np.diff(np.sign(x)) != 0))[0]
</code>```

read as: indices, where ((absolute differences of x) are larger or equal 20) and (the sign flips)

which returns

```<code>array([0, 2, 5, 7])
</code>```

Periodic signal

The usual numpy functions don't cover this case. I would suggest simply adding the first element in the end, via the pad function:

```<code>import numpy as np
x = np.array([10, 5, 0, -5, -10])
x = np.pad(x, (0, 1), 'wrap')
indices = np.where(np.logical_and(np.abs(np.diff(x)) >= 20, np.diff(np.sign(x)) != 0))[0]
</code>```

Body:
For a data analysis task, I want to find zero crossings in a numpy array, coming from a convolution with first a sobel-like kernel, and then a mexican hat kernel. Zero crossings allow me to detect edges in the data.

Unfortunately, the data is somewhat noisy and I only want to find zero crossings with a minimal jump size, 20 in the follwing example:

import numpy as np
arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])

Should result in

>>>array([1, 3, 7])

or

>>>array([3, 7])

Where 3 is the index of -1, just before the middle of the first jump and 7 is the index of -10

I have tried a modification of the following code (source: Efficiently detect sign-changes in python)

zero_crossings = np.where(np.diff(np.sign(np.trunc(arr/10))))[0]

Which correctly ignores small jumps, but puts the zero-crossings at [1,5,7]

What would be an efficient way of doing this?

The definition of minimal jump is not strict, but results should be along the lines of my question.

Edit: For Clarification

arr = np.array([12, 15, 9, 8, -1, 1, -12, -10, 10])
arr_floored = np.trunc(arr/10)
>>>>np.array([10, 10, 0, 0, 0, 0, -10, -10, 10])
sgn = np.sign(arr_floored)
>>>>array([ 1,  1,  0,  0,  0,  0, -1, -1,  1])
dsgn = np.diff(sgn)
>>>>array([ 0, -1,  0,  0,  0, -1,  0,  2])
np.where(dsgn)
>>>>(array([1, 5, 7], dtype=int64),)

Further edgecases:

arr = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]

Should result in

>>> np.array([10])

Also just noticed: The problem might be ill-posed(in a mathematical sense). I will clarify it later today.

Body:
Base case

I guess you want

import numpy as np
x = np.array([10, -50, -30, 50, 10, 3, -200, -12, 123])
indices = np.where(np.logical_and(np.abs(np.diff(x)) >= 20, np.diff(np.sign(x)) != 0))[0]

read as: indices, where ((absolute differences of x) are larger or equal 20) and (the sign flips)

which returns

array([0, 2, 5, 7])

Periodic signal

The usual numpy functions don't cover this case. I would suggest simply adding the first element in the end, via the pad function:

import numpy as np
x = np.array([10, 5, 0, -5, -10])
x = np.pad(x, (0, 1), 'wrap')
indices = np.where(np.logical_and(np.abs(np.diff(x)) >= 20, np.diff(np.sign(x)) != 0))[0]


问:
How to avoid \r while looping a multiline string
I want to loop through the output of an AWS CLI command which gives a multiline string.

I want to split the string into substring, but when I loop through it, \r is included in each of the substrings. Why does it happen?

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

physicalId=`aws ec2 describe-instances --filters "Name=tag:Name,Values=test-servers" --output text --query 'Reservations[*].Instances[*].InstanceId'`
echo physicalId="${physicalId}"

for i in $physicalId;
do
echo "$i";
aws ec2 describe-instances --instance-id $i --output text --query "Reservations[*].Instances[*].[ImageId]"

done
</code>```

echo physicalId="${physicalId}" gives this output:

```<code>echo 'physicalId=i-0a4a344429075
i-0a2a2aa22a2
i-a0aa212122a2a25'
</code>```

But on looping through the string, it gives i-0a4a344429075\r , i-0a2a2aa22a2\r, i-a0aa212122a2a25\r. Why does this happen? How to remove \r from the substring?

答:
try this</p>

```<code>echo "${physicalId//\\r/}"
</code>```

Body:
I want to loop through the output of an AWS CLI command which gives a multiline string.

I want to split the string into substring, but when I loop through it, \r is included in each of the substrings. Why does it happen?

#!/bin/bash -ex

physicalId=`aws ec2 describe-instances --filters "Name=tag:Name,Values=test-servers" --output text --query 'Reservations[*].Instances[*].InstanceId'`
echo physicalId="${physicalId}"

for i in $physicalId;
do
echo "$i";
aws ec2 describe-instances --instance-id $i --output text --query "Reservations[*].Instances[*].[ImageId]"

done

echo physicalId="${physicalId}" gives this output:

echo 'physicalId=i-0a4a344429075
i-0a2a2aa22a2
i-a0aa212122a2a25'

But on looping through the string, it gives i-0a4a344429075\r , i-0a2a2aa22a2\r, i-a0aa212122a2a25\r. Why does this happen? How to remove \r from the substring?

Body:
try this

echo "${physicalId//\\r/}"


问:
Problem with my quicksort, it doesn't sort correctly
OK I am trying to make Prima algorithm so i need my edges array sorted, I tried to use quicksort here but it didn't work as I planned.

```<code>#include <iostream>

using namespace std;

void Sort (int arr[100][4], int m, int l) {
     int i,j,x,v;

    i=m;
    j=l;
    x=(i+j)/2;
    do
    {
        while (((arr[i][3]<arr[x][3]))and(i<=l)) i++;
        while (((arr[j][3]>arr[x][3]))and(j>=m)) j--;
        if (i<=j)
        {
        v=arr[i][1];
        arr[i][1]=arr[j][1];
        arr[j][1]=v;
        v=arr[i][2];
        arr[i][2]=arr[j][2];
        arr[j][2]=v;
        v=arr[i][3];
        arr[i][3]=arr[j][3];
        arr[j][3]=v;
        i++;
        j--;
        }
    }
    while (i<=j);
    if (i<l) Sort(arr,i,l);
    if (m<j) Sort(arr,m,j);
}

int main () {
    int i,x,y,z,n,m;
    int a[100][4];
    fill(&a[0][0],&a[0][0]+400,0);
    cout<<"Enter number of nodes and edges\n";
    cin>>n>>m;
    cout<<"Enter edges and their weights\n";
    for (i=0;i<m;i++) {
        cin>>x>>y>>z;
        a[i][1]=min(x,y);
        a[i][2]=max(x,y);
        a[i][3]=z;
        }
    Sort (a,0,m-1);
    for (i=0;i<m;i++) {
        cout<<i+1<<") "<<a[i][1]<<' '<<a[i][2]<<' '<<a[i][3]<<endl;
    }
    return 0;
}

</code>```

what I put is

5 10

1 2 4

1 3 7

4 1 5

5 1 8

2 3 3

2 4 6

2 5 6

3 4 8

3 5 2

4 5 4

what I get is
1) 3 5 2

2) 2 3 3

3) 1 4 5

4) 1 2 4

5) 4 5 4

6) 2 5 6

7) 2 4 6

8) 1 3 7

9) 1 5 8

10) 3 4 8

I don't understand why 5 is going ahead of 4's. Hope you could help.

答:
Change the code to use the pivot value instead of the pivot index, and some fixes to make it more like conventional Hoare partition scheme:</p>

```<code>    i=m-1;
    j=l+1;
    x=arr[(i+j)/2][3];
    while(1)
    {
        while (arr[++i][3] < x);
        while (arr[--j][3] > x);
        if(i >= j)
            return j;
        // ...
</code>```

Body:
OK I am trying to make Prima algorithm so i need my edges array sorted, I tried to use quicksort here but it didn't work as I planned.

#include <iostream>

using namespace std;

void Sort (int arr[100][4], int m, int l) {
     int i,j,x,v;

    i=m;
    j=l;
    x=(i+j)/2;
    do
    {
        while (((arr[i][3]<arr[x][3]))and(i<=l)) i++;
        while (((arr[j][3]>arr[x][3]))and(j>=m)) j--;
        if (i<=j)
        {
        v=arr[i][1];
        arr[i][1]=arr[j][1];
        arr[j][1]=v;
        v=arr[i][2];
        arr[i][2]=arr[j][2];
        arr[j][2]=v;
        v=arr[i][3];
        arr[i][3]=arr[j][3];
        arr[j][3]=v;
        i++;
        j--;
        }
    }
    while (i<=j);
    if (i<l) Sort(arr,i,l);
    if (m<j) Sort(arr,m,j);
}

int main () {
    int i,x,y,z,n,m;
    int a[100][4];
    fill(&a[0][0],&a[0][0]+400,0);
    cout<<"Enter number of nodes and edges\n";
    cin>>n>>m;
    cout<<"Enter edges and their weights\n";
    for (i=0;i<m;i++) {
        cin>>x>>y>>z;
        a[i][1]=min(x,y);
        a[i][2]=max(x,y);
        a[i][3]=z;
        }
    Sort (a,0,m-1);
    for (i=0;i<m;i++) {
        cout<<i+1<<") "<<a[i][1]<<' '<<a[i][2]<<' '<<a[i][3]<<endl;
    }
    return 0;
}

what I put is

5 10

1 2 4

1 3 7

4 1 5

5 1 8

2 3 3

2 4 6

2 5 6

3 4 8

3 5 2

4 5 4

what I get is
1) 3 5 2

2) 2 3 3

3) 1 4 5

4) 1 2 4

5) 4 5 4

6) 2 5 6

7) 2 4 6

8) 1 3 7

9) 1 5 8

10) 3 4 8

I don't understand why 5 is going ahead of 4's. Hope you could help.

Body:
Change the code to use the pivot value instead of the pivot index, and some fixes to make it more like conventional Hoare partition scheme:

    i=m-1;
    j=l+1;
    x=arr[(i+j)/2][3];
    while(1)
    {
        while (arr[++i][3] < x);
        while (arr[--j][3] > x);
        if(i >= j)
            return j;
        // ...


问:
Multi-class multi-label confusion matrix with Sklearn
I am working with a multi-class multi-label output from my classifier. The total number of classes is 14 and instances can have multiple classes associated. For example:

```<code>y_true = np.array([[0,0,1], [1,1,0],[0,1,0])
y_pred = np.array([[0,0,1], [1,0,1],[1,0,0])
</code>```

The way I am making my confusion matrix right now:

```<code>matrix = confusion_matrix(y_true.argmax(axis=1), y_pred.argmax(axis=1))
print(matrix)
</code>```

Which gives an output like:

```<code>[[ 79   0   0   0  66   0   0 151   1   8   0   0   0   0]
 [  4   0   0   0  11   0   0  27   0   0   0   0   0   0]
 [ 14   0   0   0  21   0   0  47   0   1   0   0   0   0]
 [  1   0   0   0   4   0   0  25   0   0   0   0   0   0]
 [ 18   0   0   0  50   0   0  63   0   3   0   0   0   0]
 [  4   0   0   0   3   0   0  19   0   0   0   0   0   0]
 [  2   0   0   0   3   0   0  11   0   2   0   0   0   0]
 [ 22   0   0   0  20   0   0 138   1   5   0   0   0   0]
 [ 12   0   0   0   9   0   0  38   0   1   0   0   0   0]
 [ 10   0   0   0   3   0   0  40   0   4   0   0   0   0]
 [  3   0   0   0   3   0   0  14   0   3   0   0   0   0]
 [  0   0   0   0   2   0   0   3   0   0   0   0   0   0]
 [  2   0   0   0  11   0   0  32   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   3   0   0   0   0   0   7]]
</code>```

Now, I am not sure if the confusion matrix from sklearn is capable of handling multi-label multi-class data. Could someone help me with this?

答:
Now you can use (version 0.21) sklearn.metrics.multilabel_confusion_matrix

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.multilabel_confusion_matrix.html

We try to predict two labels for each example

```<code>import sklearn.metrics as skm
y_true = np.array([
                [0,0], [0,1], [1,1], [0,1], [0,1], [1,1]
              ])
 y_pred = np.array([
                [1,1], [0,1], [0,1], [1,0], [0,1], [1,1]
              ])

 cm = skm.multilabel_confusion_matrix(y_true, y_pred)
 print(cm)
 print( skm.classification_report(y_true,y_pred))
</code>```

Confusion matrix for labels:

```<code>[[[2 2]
  [1 1]]

 [[0 1]
  [1 4]]]
</code>```

Classification report:

```<code>              precision    recall  f1-score   support

         0       0.33      0.50      0.40         2
         1       0.80      0.80      0.80         5

micro avg        0.62      0.71      0.67         7
macro avg        0.57      0.65      0.60         7
weighted avg     0.67      0.71      0.69         7
samples avg      0.67      0.58      0.61         7
</code>```

Body:
I am working with a multi-class multi-label output from my classifier. The total number of classes is 14 and instances can have multiple classes associated. For example:

y_true = np.array([[0,0,1], [1,1,0],[0,1,0])
y_pred = np.array([[0,0,1], [1,0,1],[1,0,0])

The way I am making my confusion matrix right now:

matrix = confusion_matrix(y_true.argmax(axis=1), y_pred.argmax(axis=1))
print(matrix)

Which gives an output like:

[[ 79   0   0   0  66   0   0 151   1   8   0   0   0   0]
 [  4   0   0   0  11   0   0  27   0   0   0   0   0   0]
 [ 14   0   0   0  21   0   0  47   0   1   0   0   0   0]
 [  1   0   0   0   4   0   0  25   0   0   0   0   0   0]
 [ 18   0   0   0  50   0   0  63   0   3   0   0   0   0]
 [  4   0   0   0   3   0   0  19   0   0   0   0   0   0]
 [  2   0   0   0   3   0   0  11   0   2   0   0   0   0]
 [ 22   0   0   0  20   0   0 138   1   5   0   0   0   0]
 [ 12   0   0   0   9   0   0  38   0   1   0   0   0   0]
 [ 10   0   0   0   3   0   0  40   0   4   0   0   0   0]
 [  3   0   0   0   3   0   0  14   0   3   0   0   0   0]
 [  0   0   0   0   2   0   0   3   0   0   0   0   0   0]
 [  2   0   0   0  11   0   0  32   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   3   0   0   0   0   0   7]]

Now, I am not sure if the confusion matrix from sklearn is capable of handling multi-label multi-class data. Could someone help me with this?

Body:
Now you can use (version 0.21) sklearn.metrics.multilabel_confusion_matrix

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.multilabel_confusion_matrix.html

We try to predict two labels for each example

import sklearn.metrics as skm
y_true = np.array([
                [0,0], [0,1], [1,1], [0,1], [0,1], [1,1]
              ])
 y_pred = np.array([
                [1,1], [0,1], [0,1], [1,0], [0,1], [1,1]
              ])

 cm = skm.multilabel_confusion_matrix(y_true, y_pred)
 print(cm)
 print( skm.classification_report(y_true,y_pred))

Confusion matrix for labels:

[[[2 2]
  [1 1]]

 [[0 1]
  [1 4]]]

Classification report:

              precision    recall  f1-score   support

         0       0.33      0.50      0.40         2
         1       0.80      0.80      0.80         5

micro avg        0.62      0.71      0.67         7
macro avg        0.57      0.65      0.60         7
weighted avg     0.67      0.71      0.69         7
samples avg      0.67      0.58      0.61         7


问:
Node/Express Unhandled promise rejections are deprecated
I have been trying to resolve these unhandled Promise rejections that I continue to get in my code.

The current one I get is as follows:

[nodemon] starting mocha --recursive -R min   (node:35286)
  UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: The
  expression evaluated to a falsy value:

assert(count + 1 === newCount)

```<code>at Driver.count.then.newCount (/Users/danale/Projects/muber/test/controllers/drivers_controller.test.js:16:13)
at processTicksAndRejections (internal/process/next_tick.js:81:5) (node:35286) UnhandledPromiseRejectionWarning: Unhandled promise
</code>```

rejection. This error originated either by throwing inside of an async
  function without a catch block, or by rejecting a promise which was
  not handled with .catch(). (rejection id: 1) (node:35286) [DEP0018]
  DeprecationWarning: Unhandled promise rejections are deprecated. In
  the future, promise rejections that are not handled will terminate the
  Node.js process with a non-zero exit code.

The test that should be passing is this one:

```<code>const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("api/drivers")
        .send({ email: "test@test.com" })
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});
</code>```

To deal with the Promise rejections that I was getting earlier I did this:

```<code>const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

app.use(bodyParser.json());
routes(app);

module.exports = app;
</code>```

The controller I am trying to test is:

```<code>const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};
</code>```

I did try to add the catch() to the test like so:

```<code>describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count()
      .then(count => {
        request(app)
          .post("api/drivers")
          .send({ email: "test@test.com" })
          .end((err, res) => {
            Driver.count().then(newCount => {
              assert(count + 1 === newCount);
              done();
            });
          });
      })
      .catch(error => console.log(error));
  });
});
</code>```

but it did not resolve the error.

This is my route handler:

```<code>const DriversController = require("../controllers/drivers_controller");

module.exports = app => {
  // Watch for incoming requests of method GET to the route http://localhost:3050/api
  app.get("/api", DriversController.greeting);

  app.post("/api/drivers", DriversController.create);
};
</code>```

答:
To make it clear for future readers who may run into this problem, when there is an error/incorrect assertion in a Mocha test, an error is raised inside the promise:
For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves

After refactoring according to corschdi, I added the solution in link, this bypasses the error about the done() callback and takes you straight to the heart of the problem which is that the asynchronous test is indeed failing.

Body:
I have been trying to resolve these unhandled Promise rejections that I continue to get in my code.

The current one I get is as follows:

[nodemon] starting mocha --recursive -R min   (node:35286)
  UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: The
  expression evaluated to a falsy value:

assert(count + 1 === newCount)

at Driver.count.then.newCount (/Users/danale/Projects/muber/test/controllers/drivers_controller.test.js:16:13)
at processTicksAndRejections (internal/process/next_tick.js:81:5) (node:35286) UnhandledPromiseRejectionWarning: Unhandled promise

rejection. This error originated either by throwing inside of an async
  function without a catch block, or by rejecting a promise which was
  not handled with .catch(). (rejection id: 1) (node:35286) [DEP0018]
  DeprecationWarning: Unhandled promise rejections are deprecated. In
  the future, promise rejections that are not handled will terminate the
  Node.js process with a non-zero exit code.

The test that should be passing is this one:

const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("api/drivers")
        .send({ email: "test@test.com" })
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});

To deal with the Promise rejections that I was getting earlier I did this:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

app.use(bodyParser.json());
routes(app);

module.exports = app;

The controller I am trying to test is:

const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};

I did try to add the catch() to the test like so:

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count()
      .then(count => {
        request(app)
          .post("api/drivers")
          .send({ email: "test@test.com" })
          .end((err, res) => {
            Driver.count().then(newCount => {
              assert(count + 1 === newCount);
              done();
            });
          });
      })
      .catch(error => console.log(error));
  });
});

but it did not resolve the error.

This is my route handler:

const DriversController = require("../controllers/drivers_controller");

module.exports = app => {
  // Watch for incoming requests of method GET to the route http://localhost:3050/api
  app.get("/api", DriversController.greeting);

  app.post("/api/drivers", DriversController.create);
};


问:
TableView Image Load Problem.(Full Code fot the tableCell)

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

dictionary = [QuestionMutableArray objectAtIndex:0];

static NSString *CellIdentifier = @"BeginingCell";

BeginingCell *cell=(BeginingCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

```<code>NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:@"BeginingCell" owner:self options:nil ];

for(id CurrentObject in topLevelObjects)
{
    if ([CurrentObject isKindOfClass:[BeginingCell class]]) {

        cell=(BeginingCell *) CurrentObject;
        break;
    }
}
</code>```

}

// Configure the cell.

if(indexPath.row==0)
{

```<code>cell.SectionTitle.text=[dictionary objectForKey:@"question"];
cell.Option1.text=[dictionary objectForKey:@"option1"];
cell.Option2.text=[dictionary objectForKey:@"option2"];
cell.Option3.text=[dictionary objectForKey:@"option3"];
cell.Option4.text=[dictionary objectForKey:@"option4"];

UIImage *imgDef=[UIImage imageNamed:@"man_kirstie_alley.jpg"];
[cell.myImageView setImage:imgDef];

[MyTestArray release];

[cell.button1 setTitle:@"A." forState:UIControlStateNormal];
[cell.button2 setTitle:@"B." forState:UIControlStateNormal];
[cell.button3 setTitle:@"C." forState:UIControlStateNormal];
[cell.button4 setTitle:@"D." forState:UIControlStateNormal];
</code>```

}

return cell;

}

答:
I think you must create a cell first. You could use a default cell like this:</p>

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

//---try to get a reusable cell---

UITableViewCell *cell = [tableView
    dequeueReusableCellWithIdentifier:CellIdentifier];

//---create new cell if no reusable cell is available---
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
             reuseIdentifier:CellIdentifier] autorelease];
}

//---You would set the image here---
UIImage *imgDef=[UIImage imageNamed:@"man_kirstie_alley.jpg"];
cell.image = imgDef;

return cell;
</code>```

Body:
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

dictionary = [QuestionMutableArray objectAtIndex:0];

static NSString *CellIdentifier = @"BeginingCell";

BeginingCell *cell=(BeginingCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:@"BeginingCell" owner:self options:nil ];

for(id CurrentObject in topLevelObjects)
{
    if ([CurrentObject isKindOfClass:[BeginingCell class]]) {

        cell=(BeginingCell *) CurrentObject;
        break;
    }
}

}

// Configure the cell.

if(indexPath.row==0)
{

cell.SectionTitle.text=[dictionary objectForKey:@"question"];
cell.Option1.text=[dictionary objectForKey:@"option1"];
cell.Option2.text=[dictionary objectForKey:@"option2"];
cell.Option3.text=[dictionary objectForKey:@"option3"];
cell.Option4.text=[dictionary objectForKey:@"option4"];

UIImage *imgDef=[UIImage imageNamed:@"man_kirstie_alley.jpg"];
[cell.myImageView setImage:imgDef];

[MyTestArray release];

[cell.button1 setTitle:@"A." forState:UIControlStateNormal];
[cell.button2 setTitle:@"B." forState:UIControlStateNormal];
[cell.button3 setTitle:@"C." forState:UIControlStateNormal];
[cell.button4 setTitle:@"D." forState:UIControlStateNormal];

}

return cell;

}

Body:
I think you must create a cell first. You could use a default cell like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

//---try to get a reusable cell---

UITableViewCell *cell = [tableView
    dequeueReusableCellWithIdentifier:CellIdentifier];

//---create new cell if no reusable cell is available---
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
             reuseIdentifier:CellIdentifier] autorelease];
}

//---You would set the image here---
UIImage *imgDef=[UIImage imageNamed:@"man_kirstie_alley.jpg"];
cell.image = imgDef;

return cell;


问:
How do establish a connection to a channel in feathersjs?
I'm new to node and to feathersjs, and for my first app, I'm trying to have different parts of it communicate using channels.  I understand the operations and how they're used, but I don't understand how to establish a connection to a channel in the first place.

For example, here's some code from the official documentation:

```<code>app.on('login', (payload, { connection }) => {
  if(connection && connection.user.isAdmin) {
    // Join the admins channel
    app.channel('admins').join(connection);

    // Calling a second time will do nothing
    app.channel('admins').join(connection);
  }
});
</code>```

Where does "connection" come from?  There is no built-in function (unless I'm missing something obvious) in feathersjs to do this.

Thanks!

答:
Where does "connection" come from?

connection is a js object that represents the connection the user has established by logging in.

Try doing a console.log(connection) to see what it contains.

connection is in this case passed by the Feathers framework in the function call to the function that you have quoted.

Once you have obtained this connection object then you can use it for adding the user to a channel, and many other things.

Body:
I'm new to node and to feathersjs, and for my first app, I'm trying to have different parts of it communicate using channels.  I understand the operations and how they're used, but I don't understand how to establish a connection to a channel in the first place.

For example, here's some code from the official documentation:

app.on('login', (payload, { connection }) => {
  if(connection && connection.user.isAdmin) {
    // Join the admins channel
    app.channel('admins').join(connection);

    // Calling a second time will do nothing
    app.channel('admins').join(connection);
  }
});

Where does "connection" come from?  There is no built-in function (unless I'm missing something obvious) in feathersjs to do this.

Thanks!


问:
Company logo in PDF output only on the first page
I was wondering if there is a way to include the company logo to a PDF document created by R Markdown only on the first page of the document. I have searched for an answer and the closest I could find is this. There are multiple solutions presented in the answers, however, neither of them works for me because they either:

include the logo at every page of the document (not just first); or

include the chapter title in the header (and a horizontal line below it) along with the logo.

I am looking for a way to include just the plain logo, with no chapter titles only on the first page of a PDF R Markdown document and I've ran out of all the resources I could find online. Is there someone who could aid me?

Before anyone asks: yes, it strictly has to be a PDF document, not HTML.

答:
The \includegraphics code line is insert after the R SETUP chunk in markdown.
Here is an example of where I put the line \includegraphics :

```<code>---
geometry: "margin=1.5cm"
classoption: landscape
output:
  pdf_document: # Export to pdf
    number_sections: yes
includes:
          in_header: ltx.sty
---

```{r SETUP, include=FALSE, message=FALSE, warning=FALSE}

knitr::opts_chunk$set(echo = FALSE,
                  warning = FALSE,
                  message = FALSE,
                  results = "asis")

library(knitr)
library(kableExtra)
library(some_packages)

options(scipen = 999,
    digits = 2,
    width = 110)

```

\definecolor{astral}{RGB}{87,146,204}
\allsectionsfont{\color{astral}}
\setcounter{tocdepth}{5}

<!-- Title page -->
\includegraphics[width=7cm]{logo.jpg}

\begin{center}\begin{Large}
Project 1
\end{Large}\end{center}

\vfill

# Some R chunk
```{r results='asis'}
# Table, code, graphics.
```
</code>```

So the line is insert between the R SETUP chunk and the next R chunk.

Body:
The \includegraphics code line is insert after the R SETUP chunk in markdown.
Here is an example of where I put the line \includegraphics :

---
geometry: "margin=1.5cm"
classoption: landscape
output:
  pdf_document: # Export to pdf
    number_sections: yes
includes:
          in_header: ltx.sty
---

```{r SETUP, include=FALSE, message=FALSE, warning=FALSE}

knitr::opts_chunk$set(echo = FALSE,
                  warning = FALSE,
                  message = FALSE,
                  results = "asis")

library(knitr)
library(kableExtra)
library(some_packages)

options(scipen = 999,
    digits = 2,
    width = 110)

```

\definecolor{astral}{RGB}{87,146,204}
\allsectionsfont{\color{astral}}
\setcounter{tocdepth}{5}

<!-- Title page -->
\includegraphics[width=7cm]{logo.jpg}

\begin{center}\begin{Large}
Project 1
\end{Large}\end{center}

\vfill

# Some R chunk
```{r results='asis'}
# Table, code, graphics.
```

So the line is insert between the R SETUP chunk and the next R chunk.


问:
Any provision to push message between "Queues" by change the Queue name dynamically in stream @Input("suffix"+"QueueA")and@Input("suffix"+"QueueA")
Is there any provision to push message between two "Queues"  by change the Queue name dynamically in cloud.stream @Input("suffix"+"SampleQueueA") and @Input("suffix"+"SampleQueueB")

This use case with Sprig cloud stream using messaging server RabbitMQ.
I tried pushing messages into two different  Queues by dynamically changing the Queue name.

# Input bindings used for testing
spring:
rabbitmq:
host: 127.0.0.1
virtual-host: /defaultVH
username: guest
password: guest

cloud:
stream:
bindings:
ClientSampleQueueA:
binder: rabbit-A
contentType: application/x-java-object
group: groupA
destination: ClientSampleQueueA

VendorSampleQueueA:
binder: rabbit-A
contentType: application/x-java-object
group: groupA
destination: VendorSampleQueueA

# cloud.stream.bindings.input1.destination: customerId-1
# spring.cloud.stream.bindings.input2.destination: customerId-2

binders:
rabbit-A:
defaultCandidate: false
inheritEnvironment: false
type: rabbit
environment:
spring:
rabbitmq:
host: 127.0.0.1
virtualHost: /vhA
username: guest
password: guest
port: 5672
connection-timeout: 10000

```

```interface Sink {

String INPUT1 = "ClientSampleQueueA";
String INPUT2 = "VendorSampleQueueA";

@Input(INPUT1)
SubscribableChannel input1();

@Input(INPUT2)
SubscribableChannel input2();

}
```

```@Bean(name = "sourceChannel")
public MessageChannel localChannel() {
return new DirectChannel();
}

```

```
@Autowired
@Qualifier("sourceChannel")
private MessageChannel localChannel;
```

<p>Want to resolve the Queue dynamically by Object parameter.</p>

<pre class="lang-java prettyprint-override"><code>private void sendMessage(Object body, Object contentType) {
        localChannel.send(MessageBuilder.createMessage(body,
                new MessageHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, contentType))));
    }

</code>```

答:
But what is subscribed to localChannel.

As I said in my comment:

```<code>spring.cloud.stream.bindings.ClientSampleQueueA.destination=commonDest
spring.cloud.stream.bindings.ClientSampleQueueA.group=ClientSampleQueueA
spring.cloud.stream.rabbit.bindings.ClientSampleQueueA.bindingRoutingKey=ClientSampleQueueA
spring.cloud.stream.bindings.VendorSampleQueueA.destination=commonDest
spring.cloud.stream.rabbit.bindings.VendorSampleQueueA.bindingRoutingKey=VendorSampleQueueA
spring.cloud.stream.bindings.VendorSampleQueueA.group=ClientSampleQueueA
</code>```

and

```<code>spring.cloud.stream.bindings.sourceChannel.destination=commonDest
spring.cloud.stream.rabbit.bindings.sourceChannel.routingKeyExpression=headers.routeTo
</code>```

and then

```<code>private void sendMessage(Object body, Object contentType) {
    localChannel.send(MessageBuilder.withPayload(body)
          .setHeader(MessageHeaders.CONTENT_TYPE, contentType)
          .setHeader("routeTo", "VendorSampleQueueA")
          .build();
}
</code>```

Body:
Is there any provision to push message between two "Queues"  by change the Queue name dynamically in cloud.stream @Input("suffix"+"SampleQueueA") and @Input("suffix"+"SampleQueueB")

This use case with Sprig cloud stream using messaging server RabbitMQ.
I tried pushing messages into two different  Queues by dynamically changing the Queue name.

# Input bindings used for testing
spring:
rabbitmq:
host: 127.0.0.1
virtual-host: /defaultVH
username: guest
password: guest

cloud:
stream:
bindings:
ClientSampleQueueA:
binder: rabbit-A
contentType: application/x-java-object
group: groupA
destination: ClientSampleQueueA

VendorSampleQueueA:
binder: rabbit-A
contentType: application/x-java-object
group: groupA
destination: VendorSampleQueueA

# cloud.stream.bindings.input1.destination: customerId-1
# spring.cloud.stream.bindings.input2.destination: customerId-2

binders:
rabbit-A:
defaultCandidate: false
inheritEnvironment: false
type: rabbit
environment:
spring:
rabbitmq:
host: 127.0.0.1
virtualHost: /vhA
username: guest
password: guest
port: 5672
connection-timeout: 10000

interface Sink {

String INPUT1 = "ClientSampleQueueA";
String INPUT2 = "VendorSampleQueueA";

@Input(INPUT1)
SubscribableChannel input1();

@Input(INPUT2)
SubscribableChannel input2();

}

@Bean(name = "sourceChannel")
public MessageChannel localChannel() {
return new DirectChannel();
}

@Autowired
@Qualifier("sourceChannel")
private MessageChannel localChannel;

Want to resolve the Queue dynamically by Object parameter.

private void sendMessage(Object body, Object contentType) {
        localChannel.send(MessageBuilder.createMessage(body,
                new MessageHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, contentType))));
    }

Body:
But what is subscribed to localChannel.

As I said in my comment:

spring.cloud.stream.bindings.ClientSampleQueueA.destination=commonDest
spring.cloud.stream.bindings.ClientSampleQueueA.group=ClientSampleQueueA
spring.cloud.stream.rabbit.bindings.ClientSampleQueueA.bindingRoutingKey=ClientSampleQueueA
spring.cloud.stream.bindings.VendorSampleQueueA.destination=commonDest
spring.cloud.stream.rabbit.bindings.VendorSampleQueueA.bindingRoutingKey=VendorSampleQueueA
spring.cloud.stream.bindings.VendorSampleQueueA.group=ClientSampleQueueA

and

spring.cloud.stream.bindings.sourceChannel.destination=commonDest
spring.cloud.stream.rabbit.bindings.sourceChannel.routingKeyExpression=headers.routeTo

and then

private void sendMessage(Object body, Object contentType) {
    localChannel.send(MessageBuilder.withPayload(body)
          .setHeader(MessageHeaders.CONTENT_TYPE, contentType)
          .setHeader("routeTo", "VendorSampleQueueA")
          .build();
}


问:
how to create class that adds, deletes and find words in a dictionary?
This is what I have and I'm new to Java:</p>

```<code> import java.util.*;

 public class WordPairs
 {

     // ArrayList<String> names = new ArrayList<String>();
     // ArrayList<String> meanings = new ArrayList<String>();
     //names.add("empty");
     //meanings.add("empty");
     String searchName;
     String searchMeaning;
        String names[] = new String[25];
        String meanings[] = new String[25];
        int Q = 1;

  public void setWordAdd(String name,String meaning)
  {
   names[Q] = name;
     meanings[Q] = meaning;
     Q = Q++;
  }

  public void setWordDelete(String name)
  {
     for(int i=0;i<names.length;i++)
     {
        String check =  names[i];
        if(check == name)
        {

           String meanings = meanings.remove(i);
        }
     }
  }

  public void setWordSearch(String name)
  {
     int a = 1;

     for(i=0;i<names.size();i++)
     {
        string check = names.get(i);

        if(check == name)
        {
           searchName = names.get(i);
           searchMeaning = meanings.get(i);

           a = 0;
        }
     }

     if(a == 1)
     {
        searchName = "word can not be found";
        searchMeaning = "meaning can not be found";
     }
  }

  public String getSearchName()
  {
     return searchName;
  }

  public String getSearchMeaning()
  {
     return searchMeaning;

  }
}
</code>```

Body:
This is what I have and I'm new to Java:

 import java.util.*;

 public class WordPairs
 {

     // ArrayList<String> names = new ArrayList<String>();
     // ArrayList<String> meanings = new ArrayList<String>();
     //names.add("empty");
     //meanings.add("empty");
     String searchName;
     String searchMeaning;
        String names[] = new String[25];
        String meanings[] = new String[25];
        int Q = 1;

  public void setWordAdd(String name,String meaning)
  {
   names[Q] = name;
     meanings[Q] = meaning;
     Q = Q++;
  }

  public void setWordDelete(String name)
  {
     for(int i=0;i<names.length;i++)
     {
        String check =  names[i];
        if(check == name)
        {

           String meanings = meanings.remove(i);
        }
     }
  }

  public void setWordSearch(String name)
  {
     int a = 1;

     for(i=0;i<names.size();i++)
     {
        string check = names.get(i);

        if(check == name)
        {
           searchName = names.get(i);
           searchMeaning = meanings.get(i);

           a = 0;
        }
     }

     if(a == 1)
     {
        searchName = "word can not be found";
        searchMeaning = "meaning can not be found";
     }
  }

  public String getSearchName()
  {
     return searchName;
  }

  public String getSearchMeaning()
  {
     return searchMeaning;

  }
}


问:
How to add or remove an item from state array in react
I have state array and when user click on an item , item should be added to state array. I use type script, interface for data model.

This is the code I used

```<code>this.setState(prevState => ({
  this.state.activeItemList: [...prevState.activeItemList, newItem]
}))
</code>```

Interface

```<code>interface IState {     activeItemList?: IItem[] | null;  }
</code>```

Is this the correct way?

答:
First, you need to check if the array wasn't null or undefined then you can add a new element to exists array otherwise create an array with newItem.</p>

```<code> this.setState((prevState) => ({
        ...prevState,
        activeItemList: prevState.activeItemList ? [...prevState.activeItemList, newItem] : [newItem],
    }));
</code>```

Body:
I have state array and when user click on an item , item should be added to state array. I use type script, interface for data model.

This is the code I used

this.setState(prevState => ({
  this.state.activeItemList: [...prevState.activeItemList, newItem]
}))

Interface

interface IState {     activeItemList?: IItem[] | null;  }

Is this the correct way?

Body:
First, you need to check if the array wasn't null or undefined then you can add a new element to exists array otherwise create an array with newItem.

 this.setState((prevState) => ({
        ...prevState,
        activeItemList: prevState.activeItemList ? [...prevState.activeItemList, newItem] : [newItem],
    }));


问:
How to read the data type Dictionary to type [String]?
Here is my data structure:

The problem is I don't know how to snap back the Data which is also the Key properly. What I want is only the Key and the value "true" are only markers. And I don't even know what type of data I am currently stored and how to snap the key value back.

What I want this that:

```<code>["BAFS", "Econ", "Geog"]
</code>```

The following is how I write the data:

```<code>var subjectvalue: [String] = []
let structure = subjectvalue.reduce(into:[String:String](), { $0[$1] = "true"})
 let postRef = Database.database().reference().child("posts").child(id!).child("posts").setValue(structure)
</code>```

I had been stocked for few days. Anyone have idea to help? Thank you in advance.

答:
You can get the dictionary from the DataSnapshot. Then get .keys of the dictionary and remove all elements which are not "true"

```<code>let postRef = Database.database().reference().child("posts").child("id").child("posts")
postRef.observe(.value) { snapshot in
    if let dict = snapshot.value as? [String : String] {
        let result = Array(dict.keys).removeAll(where: { $0 != "true" })
        print(result)
    }
}
</code>```

Body:
Here is my data structure:

The problem is I don't know how to snap back the Data which is also the Key properly. What I want is only the Key and the value "true" are only markers. And I don't even know what type of data I am currently stored and how to snap the key value back.

What I want this that:

["BAFS", "Econ", "Geog"]

The following is how I write the data:

var subjectvalue: [String] = []
let structure = subjectvalue.reduce(into:[String:String](), { $0[$1] = "true"})
 let postRef = Database.database().reference().child("posts").child(id!).child("posts").setValue(structure)

I had been stocked for few days. Anyone have idea to help? Thank you in advance.

Body:
You can get the dictionary from the DataSnapshot. Then get .keys of the dictionary and remove all elements which are not "true"

let postRef = Database.database().reference().child("posts").child("id").child("posts")
postRef.observe(.value) { snapshot in
    if let dict = snapshot.value as? [String : String] {
        let result = Array(dict.keys).removeAll(where: { $0 != "true" })
        print(result)
    }
}


问:
Logical truthness in Clojure
What does the true? says actually?
(true? 0)=false. (if 0 "0 is true" "0 is false")=0 is true.
Why this happens?

答:
In addition to the given answer, some test code!</p>

```<code>; a simple way to define two functions that give the "truthy" or "falsey"
; value as an actual boolean (i.e. either the value 'true' or the value
; 'false' for an arbitrary Clojure 'thing'. These functions are _total_
; (i.e. defined for everything and never raise exceptions or return nil)

(defn truthy? [x] (if x true false))
(defn falsey? [x] (if x false true))

; Some test code
; https://clojure.github.io/clojure/clojure.test-api.html

(require '( clojure test ))

; clojure.test/is checks whether the value it is given is "truthy", not
; whether it is equal to the boolean 'true'!

(clojure.test/is true)  ; passes
(clojure.test/is 1)     ; passes
(clojure.test/is 0)     ; passes
(clojure.test/is ())    ; passes
(clojure.test/is nil)   ; ** fails **
(clojure.test/is false) ; ** fails **

; We will perform explicit comparison against the boolean values instead of
; testing for truthyness.

; WHAT'S FALSE?
; The function 'false?' gives 'true' only on 'false'
; Anything else is 'NOT false' (but not necessarily 'true')

(clojure.test/is (= false (false? '()     )))
(clojure.test/is (= false (false? []      )))
(clojure.test/is (= false (false? {}      )))
(clojure.test/is (= false (false? #{}     )))
(clojure.test/is (= false (false? nil     )))
(clojure.test/is (= true  (false? false   ))) ; only false is false
(clojure.test/is (= false (false? true    )))
(clojure.test/is (= false (false? 0       )))
(clojure.test/is (= false (false? 1       )))
(clojure.test/is (= false (false? "false" )))
(clojure.test/is (= false (false? "true"  )))
(clojure.test/is (= false (false? ""      )))
(clojure.test/is (= false (false? (fn []) ))) ; yeah that's far-fetched
(clojure.test/is (= false (false? (Boolean. false)))) ; an evil boxedJavaFalse is NOT false
(clojure.test/is (= false (false? (Boolean. true))))  ; an evil boxedJavaTrue  is NOT false

; WHAT'S TRUE?
; The function 'true?' gives 'true' only on 'true'
; Anything else is 'NOT true' (but not necessarily 'false')

(clojure.test/is (= false (true? '()     )))
(clojure.test/is (= false (true? []      )))
(clojure.test/is (= false (true? {}      )))
(clojure.test/is (= false (true? #{}     )))
(clojure.test/is (= false (true? nil     )))
(clojure.test/is (= false (true? false   )))
(clojure.test/is (= true  (true? true    ))) ; only true is true
(clojure.test/is (= false (true? 0       )))
(clojure.test/is (= false (true? 1       )))
(clojure.test/is (= false (true? "false" )))
(clojure.test/is (= false (true? "true"  )))
(clojure.test/is (= false (true? ""      )))
(clojure.test/is (= false (true? (fn []) ))) ; yeah that's far-fetched
(clojure.test/is (= false (true? (Boolean. false)))) ; an evil boxedJavaFalse is also NOT true
(clojure.test/is (= false (true? (Boolean. true))))  ; an evil boxedJavaTrue  is also NOT true

; What's TRUTHY?
; Every 'thing' is 'truthy' except 'nil' and 'false'

(clojure.test/is (= true  (truthy? '()     )))
(clojure.test/is (= true  (truthy? []      )))
(clojure.test/is (= true  (truthy? {}      )))
(clojure.test/is (= true  (truthy? #{}     )))
(clojure.test/is (= false (truthy? nil     ))) ; only nil and false are not truthy (i.e. falsey)
(clojure.test/is (= false (truthy? false   ))) ; only nil and false are not truthy (i.e. falsey)
(clojure.test/is (= true  (truthy? true    )))
(clojure.test/is (= true  (truthy? 0       )))
(clojure.test/is (= true  (truthy? 1       )))
(clojure.test/is (= true  (truthy? "false" )))
(clojure.test/is (= true  (truthy? "true"  )))
(clojure.test/is (= true  (truthy? ""      )))
(clojure.test/is (= true  (truthy? (fn []) ))) ; yeah that's far-fetched
(clojure.test/is (= true  (truthy? (Boolean. false)))) ; an evil boxedJavaFalse is also truthy
(clojure.test/is (= true  (truthy? (Boolean. true))))  ; an evil boxedJavaTrue  is also truthy

; What's FALSEY?
; By construction, no 'thing' is 'falsey' except 'nil' and 'false'

(map (fn [x]
         (clojure.test/is (= (falsey? x) (not (truthy? x))))
     )
     [ () [] {} #{} nil false true 0 1 "false" "true" "" (fn []) (Boolean. false) (Boolean. true) ]
)

; "not" of a 'thing' yields exactly "falsey?" of thing

(map (fn [x]
         (clojure.test/is (= (falsey? x) (not x)))
     )
     [ () [] {} #{} nil false true 0 1 "false" "true" "" (fn []) (Boolean. false) (Boolean. true) ]
)

; "not∘not" of a thing yields exactly "truthy?" of a thing
; this corresponds to JavaScript's "!!" -- "bang bang, you are a boolean!"
; which, given an object, yields that object's truthy boolean value.

(map (fn [x]
         (clojure.test/is (= (truthy? x) (not (not x))))
     )
     [ () [] {} #{} nil false true 0 1 "false" "true" "" (fn []) (Boolean. false) (Boolean. true) ]
)
</code>```

Title: Logical truthness in Clojure

Body:
In addition to the given answer, some test code!

; a simple way to define two functions that give the "truthy" or "falsey"
; value as an actual boolean (i.e. either the value 'true' or the value
; 'false' for an arbitrary Clojure 'thing'. These functions are _total_
; (i.e. defined for everything and never raise exceptions or return nil)

(defn truthy? [x] (if x true false))
(defn falsey? [x] (if x false true))

; Some test code
; https://clojure.github.io/clojure/clojure.test-api.html

(require '( clojure test ))

; clojure.test/is checks whether the value it is given is "truthy", not
; whether it is equal to the boolean 'true'!

(clojure.test/is true)  ; passes
(clojure.test/is 1)     ; passes
(clojure.test/is 0)     ; passes
(clojure.test/is ())    ; passes
(clojure.test/is nil)   ; ** fails **
(clojure.test/is false) ; ** fails **

; We will perform explicit comparison against the boolean values instead of
; testing for truthyness.

; WHAT'S FALSE?
; The function 'false?' gives 'true' only on 'false'
; Anything else is 'NOT false' (but not necessarily 'true')

(clojure.test/is (= false (false? '()     )))
(clojure.test/is (= false (false? []      )))
(clojure.test/is (= false (false? {}      )))
(clojure.test/is (= false (false? #{}     )))
(clojure.test/is (= false (false? nil     )))
(clojure.test/is (= true  (false? false   ))) ; only false is false
(clojure.test/is (= false (false? true    )))
(clojure.test/is (= false (false? 0       )))
(clojure.test/is (= false (false? 1       )))
(clojure.test/is (= false (false? "false" )))
(clojure.test/is (= false (false? "true"  )))
(clojure.test/is (= false (false? ""      )))
(clojure.test/is (= false (false? (fn []) ))) ; yeah that's far-fetched
(clojure.test/is (= false (false? (Boolean. false)))) ; an evil boxedJavaFalse is NOT false
(clojure.test/is (= false (false? (Boolean. true))))  ; an evil boxedJavaTrue  is NOT false

; WHAT'S TRUE?
; The function 'true?' gives 'true' only on 'true'
; Anything else is 'NOT true' (but not necessarily 'false')

(clojure.test/is (= false (true? '()     )))
(clojure.test/is (= false (true? []      )))
(clojure.test/is (= false (true? {}      )))
(clojure.test/is (= false (true? #{}     )))
(clojure.test/is (= false (true? nil     )))
(clojure.test/is (= false (true? false   )))
(clojure.test/is (= true  (true? true    ))) ; only true is true
(clojure.test/is (= false (true? 0       )))
(clojure.test/is (= false (true? 1       )))
(clojure.test/is (= false (true? "false" )))
(clojure.test/is (= false (true? "true"  )))
(clojure.test/is (= false (true? ""      )))
(clojure.test/is (= false (true? (fn []) ))) ; yeah that's far-fetched
(clojure.test/is (= false (true? (Boolean. false)))) ; an evil boxedJavaFalse is also NOT true
(clojure.test/is (= false (true? (Boolean. true))))  ; an evil boxedJavaTrue  is also NOT true

; What's TRUTHY?
; Every 'thing' is 'truthy' except 'nil' and 'false'

(clojure.test/is (= true  (truthy? '()     )))
(clojure.test/is (= true  (truthy? []      )))
(clojure.test/is (= true  (truthy? {}      )))
(clojure.test/is (= true  (truthy? #{}     )))
(clojure.test/is (= false (truthy? nil     ))) ; only nil and false are not truthy (i.e. falsey)
(clojure.test/is (= false (truthy? false   ))) ; only nil and false are not truthy (i.e. falsey)
(clojure.test/is (= true  (truthy? true    )))
(clojure.test/is (= true  (truthy? 0       )))
(clojure.test/is (= true  (truthy? 1       )))
(clojure.test/is (= true  (truthy? "false" )))
(clojure.test/is (= true  (truthy? "true"  )))
(clojure.test/is (= true  (truthy? ""      )))
(clojure.test/is (= true  (truthy? (fn []) ))) ; yeah that's far-fetched
(clojure.test/is (= true  (truthy? (Boolean. false)))) ; an evil boxedJavaFalse is also truthy
(clojure.test/is (= true  (truthy? (Boolean. true))))  ; an evil boxedJavaTrue  is also truthy

; What's FALSEY?
; By construction, no 'thing' is 'falsey' except 'nil' and 'false'

(map (fn [x]
         (clojure.test/is (= (falsey? x) (not (truthy? x))))
     )
     [ () [] {} #{} nil false true 0 1 "false" "true" "" (fn []) (Boolean. false) (Boolean. true) ]
)

; "not" of a 'thing' yields exactly "falsey?" of thing

(map (fn [x]
         (clojure.test/is (= (falsey? x) (not x)))
     )
     [ () [] {} #{} nil false true 0 1 "false" "true" "" (fn []) (Boolean. false) (Boolean. true) ]
)

; "not∘not" of a thing yields exactly "truthy?" of a thing
; this corresponds to JavaScript's "!!" -- "bang bang, you are a boolean!"
; which, given an object, yields that object's truthy boolean value.

(map (fn [x]
         (clojure.test/is (= (truthy? x) (not (not x))))
     )
     [ () [] {} #{} nil false true 0 1 "false" "true" "" (fn []) (Boolean. false) (Boolean. true) ]
)


问:
Invariant Violation: Query(...): Nothing was returned from render. This usually means a return statement is missing
I have a component name is Graph.js code given below:

```<code>import React, { Component } from "react";
import { View, Text } from "react-native";
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import Launches from "./Launches.js";
const client = new ApolloClient({
  uri: "http://127.0.0.1:4000/graphql"
});

export default class Graph extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <ApolloProvider client={client}>
        <View>
          <Text>Hello Apillo</Text>
        </View>
        <Launches />
      </ApolloProvider>
    );
  }
}
</code>```

And another file name is Launcher.js code given below:

```<code>import React, { Component } from "react";
import { View, Text } from "react-native";
import gql from "graphql-tag";
import { Query } from "react-apollo";

const LAUNCHES_QUERY = gql`
  query LaunchesQuery {
    launches {
      flight_number
      mission_name
    }
  }
`;
export default class Launches extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <View>
        <Query query={LAUNCHES_QUERY}>
          {({ loading, error, data }) => {
            if (loading) return <Text>Loading...</Text>;
            if (error) return console.log(error);
            let length = data.length;
            console.log(data);
            return <Text>Launches</Text>;
          }}
        </Query>
      </View>
    );
  }
}
</code>```

I setup graphql setup in my localhost and it worked well in http://localhost:4000/graphql.

When I call URI from react-native app its generated errors.

Error1: Network error: Network request failed

Error2: Invariant Violation: Query(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

I also tried to change URI http://localhost and given to http://127.0.0.1

Thanks in Advance

答:
The Query component must be outside of , it would be:</p>

```<code>...
  render() {
    return (
      <Query query={LAUNCHES_QUERY}>
        {({ loading, error, data }) => {
          if (loading) return <Text>Loading...</Text>;
          if (error) return console.log(error);
          let length = data.length;
          console.log(data);
          return <Text>Launches</Text>;
        }}
      </Query>
    );
  }
  ...
</code>```

Body:
I have a component name is Graph.js code given below:

import React, { Component } from "react";
import { View, Text } from "react-native";
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import Launches from "./Launches.js";
const client = new ApolloClient({
  uri: "http://127.0.0.1:4000/graphql"
});

export default class Graph extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <ApolloProvider client={client}>
        <View>
          <Text>Hello Apillo</Text>
        </View>
        <Launches />
      </ApolloProvider>
    );
  }
}

And another file name is Launcher.js code given below:

import React, { Component } from "react";
import { View, Text } from "react-native";
import gql from "graphql-tag";
import { Query } from "react-apollo";

const LAUNCHES_QUERY = gql`
  query LaunchesQuery {
    launches {
      flight_number
      mission_name
    }
  }
`;
export default class Launches extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <View>
        <Query query={LAUNCHES_QUERY}>
          {({ loading, error, data }) => {
            if (loading) return <Text>Loading...</Text>;
            if (error) return console.log(error);
            let length = data.length;
            console.log(data);
            return <Text>Launches</Text>;
          }}
        </Query>
      </View>
    );
  }
}

I setup graphql setup in my localhost and it worked well in http://localhost:4000/graphql.

When I call URI from react-native app its generated errors.

Error1: Network error: Network request failed

Error2: Invariant Violation: Query(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

I also tried to change URI http://localhost and given to http://127.0.0.1

Thanks in Advance

Body:
The Query component must be outside of , it would be:

...
  render() {
    return (
      <Query query={LAUNCHES_QUERY}>
        {({ loading, error, data }) => {
          if (loading) return <Text>Loading...</Text>;
          if (error) return console.log(error);
          let length = data.length;
          console.log(data);
          return <Text>Launches</Text>;
        }}
      </Query>
    );
  }
  ...


问:
How to stop asking for the credentials while deploying reports in ssrs 2008
While deploying reports I am getting login prompt asking for the User Name and password. I have tried providing all possible id and passwords but no use. I can access both the Report manager url and ReportServer url but if I start deploying reports through SQL Server Business Intelligence development studio I am getting the above mentioned prompt. Please let me know how to avoid this.</p>

答: I had the same problem, it was due to the wrong spelling of the TargetServerUrl in report project properties, make sure that it meet the same name in the Report Server Configuration Manager:


问:
How to paste special preserving the format in a new WorkBook in VBA
I would like copy and paste special (values & format) a range from workbook A to workbook B.
The problem is : the values are paste but not the format

I've tried all the PasteSpecial, but none of it worked...

```<code>Sub Macro_copy_paste_pivot()
    Dim date_report As String
    Dim appExcel As Excel.Application
    Dim XLBook As Workbook

    Set appExcel = CreateObject("Excel.Application")
    Set XLBook = appExcel.Workbooks.Add
    date_report = WorksheetFunction.WorkDay(Date, -1)
    date_report = Format(date_report, "yyyy-mm-dd")

    ' COPY and PASTE the pivot EXO
    Worksheets("Pivot EXO").Activate
    ActiveSheet.PivotTables("Pivot EXO").PivotFields( _
        "[Context].[AsOfDate].[AsOfDate]").VisibleItemsList = Array( _
        "[Context].[AsOfDate].&[" & date_report & "T00:00:00]")

    Range("P7:A24").Copy
    XLBook.Sheets.Add.Name = "EXO"
    XLBook.Worksheets("EXO").Range("P7:A24").PasteSpecial Paste:=xlPasteFormats

End Sub
</code>```

So, how can I paste format from a workbook A to workbook B?

答:
I solved my problem.

The problem was that I create a new Excel.Application.
With the code below, my paste special works fine.

But I don't understand why xlPasteFormats doesn't work when you paste in an other Excel.Application...

```<code>Sub Macro_copy_paste_pivot()
    Application.ScreenUpdating = False
    Dim date_report As String
    Dim XLBook As Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook

    Set XLBook = Workbooks.Add
    date_report = WorksheetFunction.WorkDay(Date, -1)
    date_report = Format(date_report, "yyyy-mm-dd")

    ' COPY and PASTE the pivot EXO
    wb.Worksheets("Pivot EXO").PivotTables("Pivot EXO").PivotFields( _
        "[Context].[AsOfDate].[AsOfDate]").VisibleItemsList = Array( _
        "[Context].[AsOfDate].&[" & date_report & "T00:00:00]")
    wb.Worksheets("Pivot EXO").Range(wb.Worksheets("Pivot EXO").Range("P7"), wb.Worksheets("Pivot EXO").Cells(Rows.count, 1).End(xlUp)).Copy
    XLBook.Sheets.Add.Name = "EXO"
    XLBook.Worksheets("EXO").Range("A1").PasteSpecial xlPasteValues
    XLBook.Worksheets("EXO").Range("A1").PasteSpecial xlPasteFormats

    ' Save and update the screen
    XLBook.SaveAs ("F:\path\Pivot_GOP_SCN_PAIR " & date_report & ".xlsx")
    XLBook.Close SaveChanges:=True
    Application.ScreenUpdating = True
End Sub
</code>```

Body:
I would like copy and paste special (values & format) a range from workbook A to workbook B.
The problem is : the values are paste but not the format

I've tried all the PasteSpecial, but none of it worked...

Sub Macro_copy_paste_pivot()
    Dim date_report As String
    Dim appExcel As Excel.Application
    Dim XLBook As Workbook

    Set appExcel = CreateObject("Excel.Application")
    Set XLBook = appExcel.Workbooks.Add
    date_report = WorksheetFunction.WorkDay(Date, -1)
    date_report = Format(date_report, "yyyy-mm-dd")

    ' COPY and PASTE the pivot EXO
    Worksheets("Pivot EXO").Activate
    ActiveSheet.PivotTables("Pivot EXO").PivotFields( _
        "[Context].[AsOfDate].[AsOfDate]").VisibleItemsList = Array( _
        "[Context].[AsOfDate].&[" & date_report & "T00:00:00]")

    Range("P7:A24").Copy
    XLBook.Sheets.Add.Name = "EXO"
    XLBook.Worksheets("EXO").Range("P7:A24").PasteSpecial Paste:=xlPasteFormats

End Sub

So, how can I paste format from a workbook A to workbook B?

Body:
I solved my problem.

The problem was that I create a new Excel.Application.
With the code below, my paste special works fine.

But I don't understand why xlPasteFormats doesn't work when you paste in an other Excel.Application...

Sub Macro_copy_paste_pivot()
    Application.ScreenUpdating = False
    Dim date_report As String
    Dim XLBook As Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook

    Set XLBook = Workbooks.Add
    date_report = WorksheetFunction.WorkDay(Date, -1)
    date_report = Format(date_report, "yyyy-mm-dd")

    ' COPY and PASTE the pivot EXO
    wb.Worksheets("Pivot EXO").PivotTables("Pivot EXO").PivotFields( _
        "[Context].[AsOfDate].[AsOfDate]").VisibleItemsList = Array( _
        "[Context].[AsOfDate].&[" & date_report & "T00:00:00]")
    wb.Worksheets("Pivot EXO").Range(wb.Worksheets("Pivot EXO").Range("P7"), wb.Worksheets("Pivot EXO").Cells(Rows.count, 1).End(xlUp)).Copy
    XLBook.Sheets.Add.Name = "EXO"
    XLBook.Worksheets("EXO").Range("A1").PasteSpecial xlPasteValues
    XLBook.Worksheets("EXO").Range("A1").PasteSpecial xlPasteFormats

    ' Save and update the screen
    XLBook.SaveAs ("F:\path\Pivot_GOP_SCN_PAIR " & date_report & ".xlsx")
    XLBook.Close SaveChanges:=True
    Application.ScreenUpdating = True
End Sub