问:
Run a block of Script after every img element on page
I run a WordPress blog. I want that for every  tag on a single post page, I will have a script placed directly after it as though I was using the ::after in CSS.

I know for CSS I could do the below to display "read more" after all my  tags

img::before {
  content: "read more -";
}
```

But in my case "read more" is a script, an advertisement script specifically.

How do get my script code to display after all images on my webpages?

答:
If you wanted to execute code for each image, use a selector. Obviously, this can be narrowed down to what element you specifically want to target:

var imgs = Array.from(document.getElementsByTagName('img'))

imgs.forEach((img, i) => {
  // Code here
  img.insertAdjacentHTML('afterend', '
Test ' + i + '
')
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="" alt="img1" />
<img src="" alt="img2" />
<img src="" alt="img3" /></code>```

Body:
I run a WordPress blog. I want that for every  tag on a single post page, I will have a script placed directly after it as though I was using the ::after in CSS.

I know for CSS I could do the below to display "read more" after all my  tags

img::before {
  content: "read more -";
}

But in my case "read more" is a script, an advertisement script specifically.

How do get my script code to display after all images on my webpages?

Body:
If you wanted to execute code for each image, use a selector. Obviously, this can be narrowed down to what element you specifically want to target:

var imgs = Array.from(document.getElementsByTagName('img'))

imgs.forEach((img, i) => {
  // Code here
  img.insertAdjacentHTML('afterend', '<div>Test ' + i + '</div>')
})

<img src="" alt="img1" />
<img src="" alt="img2" />
<img src="" alt="img3" />


来源: stackexchange

问:
How to validate a string is JSON or not in Java?
I've already said, my question is different...question is already asked   here, but i want a predefined method in java which checksgiven string is json format or not.

if there is no predefined method then at least tell a code which checks JSON Format or not, without  using try catch block..

Thanks in advance...

答:
```<code>public boolean isValidJson(String jsonStr) {
    Object json = new JSONTokener(jsonStr)).nextValue();
    if (json instanceof JSONObject || json instanceof JSONArray) {
      return true;
    } else {
      return false;
    }
}
</code>```

Just pass any string in this function.

ContentLicense: CC BY-SA 3.0

Body:
public boolean isValidJson(String jsonStr) {
    Object json = new JSONTokener(jsonStr)).nextValue();
    if (json instanceof JSONObject || json instanceof JSONArray) {
      return true;
    } else {
      return false;
    }
}

Just pass any string in this function.

ContentLicense: CC BY-SA 4.0


问:
How to make the public 2D collection?
I want to create the public 2D collection, but don't know how.</p>

```<code>namespace AutoSqare
{
    class CarsInfo
    {
        public class Tech
        {
            public string Name { get; set; }
            public double KM { get; set; }
        }
        public var List<Tech> cars = new List<Tech>(); // error, of course
    }
}

</code>```

答:
You are getting an error because your are declaring your list of cars with var AND List

var is used as an implicit type and allow you to not specify the type of the variable. It will be strongly typed by the compilator.

Just declare your variable explicitely and you'll be ok ;)

```<code>public List<Tech> cars = new List<Tech>();
</code>```

Doc on var here

Title: How to make the public 2D collection?

Body:
I want to create the public 2D collection, but don't know how.

namespace AutoSqare
{
    class CarsInfo
    {
        public class Tech
        {
            public string Name { get; set; }
            public double KM { get; set; }
        }
        public var List<Tech> cars = new List<Tech>(); // error, of course
    }
}

Body:
You are getting an error because your are declaring your list of cars with var AND List

var is used as an implicit type and allow you to not specify the type of the variable. It will be strongly typed by the compilator.

Just declare your variable explicitely and you'll be ok ;)

public List<Tech> cars = new List<Tech>();

Doc on var here


问:
Ansible to get the netmask in CIDR
In order to get the value "24" corresponding to an IP address/networkmask, I have this working piece of code:

```<code>- set_fact:
    ip: "{{ ansible_default_ipv4.address }}/{{ansible_default_ipv4.netmask }}"

- set_fact:
    mask_cidr: "{{ ip | ipaddr('prefix') }}"
</code>```

Where ansible_default_ipv4.address = 172.16.1.67 and ansible_default_ipv4.netmask is 255.255.255.0 as per gather_facts or setup module.

I've tried different things to make this code "smarter" so I only need to set 1 fact instead of 2, but my filtering abilities are not strong.

Any ideas in how to convert these two facts in a smarter fact that do both things?

答:
I'm using this:</p>

```<code>mynetwork = {{ (ansible_default_ipv4.network + '/' + ansible_default_ipv4.netmask) | ipaddr('network/prefix') }}
</code>```

Title: Ansible to get the netmask in CIDR

Body:
In order to get the value "24" corresponding to an IP address/networkmask, I have this working piece of code:

- set_fact:
    ip: "{{ ansible_default_ipv4.address }}/{{ansible_default_ipv4.netmask }}"

- set_fact:
    mask_cidr: "{{ ip | ipaddr('prefix') }}"

Where ansible_default_ipv4.address = 172.16.1.67 and ansible_default_ipv4.netmask is 255.255.255.0 as per gather_facts or setup module.

I've tried different things to make this code "smarter" so I only need to set 1 fact instead of 2, but my filtering abilities are not strong.

Any ideas in how to convert these two facts in a smarter fact that do both things?

Body:
I'm using this:

mynetwork = {{ (ansible_default_ipv4.network + '/' + ansible_default_ipv4.netmask) | ipaddr('network/prefix') }}


问:
Retrieve Images from Firebase Storage Using Angular 7
I can not display the images stored in my firebase storage in my angular 7 app. How do I do this without using a service and a simple retrieval of the images from the root of the storage in component then loop in html.

I've already tried different methods to get the download URL but they aren't working. The other methods require using a service which I would not like to do in this case.

Component

```<code>import { Component, OnInit } from '@angular/core';
import { AngularFireStorage, AngularFireStorageReference } from '@angular/fire/storage';
import { Observable } from 'rxjs'

@Component({
  selector: 'app-imageviewer',
  templateUrl: './imageviewer.component.html',
  styleUrls: ['./imageviewer.component.css']
})

export class ImageviewerComponent implements OnInit {
  images: Observable<any[]>;

  constructor(private storage: AngularFireStorage) {
    storage.ref("/").getDownloadURL().subscribe(downloadURL => {
      this.images = downloadURL;

    });
   }
}
</code>```

HTML

```<code>        <div class="gal-list-view">
          <div style="margin: 20px">
              <div class="responsive" style="margin: 20px">
                  <div class="gallery" *ngFor="let image of images | async">
                    <a target="_blank">
                      <img src="{{image.url}}" alt="" width="600" height="400">
                    </a>
                    <div class="desc">Img Title</div>
                  </div>
              </div>
          </div>
        </div>
</code>```

I would like to just see the images display but it isn't showing anything on the page. If I am on Page 1 and click a link to go to the page showing the image gallery, it only shows an empty page and the link is still Page 1. But when I take out 'storage.ref("/").getDownloadURL().subscribe(downloadURL => {
      this.images = downloadURL;` Page 1 goes to Image-gallery.

答:
Using a service is recommended to implement any complex logic. It makes an angular app more modular and it also provides reusable methods.

You can use the following code to upload images to Firebase Storage and get the downloadUrl of each upload at the same time.

```<code>export class UploadService {
  private basePath = '/images';
  file: File;
  url = '';

  constructor(private afStorage: AngularFireStorage) { }

  handleFiles(event) {
    this.file = event.target.files[0];
  }

  //method to upload file at firebase storage
  async uploadFile() {
    if (this.file) {
      const filePath = `${this.basePath}/${this.file.name}`;    //path at which image will be stored in the firebase storage
      const snap = await this.afStorage.upload(filePath, this.file);    //upload task
      this.getUrl(snap);
    } else {alert('Please select an image'); }
  }

  //method to retrieve download url
  private async getUrl(snap: firebase.storage.UploadTaskSnapshot) {
    const url = await snap.ref.getDownloadURL();
    this.url = url;  //store the URL
    console.log(this.url);
  }
}
</code>```

Now, this url reference can be used anywhere to display the image.

I would recommend using a service to implement this for the reasons stated above.
Feel free to comment if anything is not clear.

Body:
I can not display the images stored in my firebase storage in my angular 7 app. How do I do this without using a service and a simple retrieval of the images from the root of the storage in component then loop in html.

I've already tried different methods to get the download URL but they aren't working. The other methods require using a service which I would not like to do in this case.

Component

import { Component, OnInit } from '@angular/core';
import { AngularFireStorage, AngularFireStorageReference } from '@angular/fire/storage';
import { Observable } from 'rxjs'

@Component({
  selector: 'app-imageviewer',
  templateUrl: './imageviewer.component.html',
  styleUrls: ['./imageviewer.component.css']
})

export class ImageviewerComponent implements OnInit {
  images: Observable<any[]>;

  constructor(private storage: AngularFireStorage) {
    storage.ref("/").getDownloadURL().subscribe(downloadURL => {
      this.images = downloadURL;

    });
   }
}

HTML

Img Title

I would like to just see the images display but it isn't showing anything on the page. If I am on Page 1 and click a link to go to the page showing the image gallery, it only shows an empty page and the link is still Page 1. But when I take out 'storage.ref("/").getDownloadURL().subscribe(downloadURL => {
      this.images = downloadURL;` Page 1 goes to Image-gallery.

Body:
Using a service is recommended to implement any complex logic. It makes an angular app more modular and it also provides reusable methods.

You can use the following code to upload images to Firebase Storage and get the downloadUrl of each upload at the same time.

export class UploadService {
  private basePath = '/images';
  file: File;
  url = '';

  constructor(private afStorage: AngularFireStorage) { }

  handleFiles(event) {
    this.file = event.target.files[0];
  }

  //method to upload file at firebase storage
  async uploadFile() {
    if (this.file) {
      const filePath = `${this.basePath}/${this.file.name}`;    //path at which image will be stored in the firebase storage
      const snap = await this.afStorage.upload(filePath, this.file);    //upload task
      this.getUrl(snap);
    } else {alert('Please select an image'); }
  }

  //method to retrieve download url
  private async getUrl(snap: firebase.storage.UploadTaskSnapshot) {
    const url = await snap.ref.getDownloadURL();
    this.url = url;  //store the URL
    console.log(this.url);
  }
}

Now, this url reference can be used anywhere to display the image.

I would recommend using a service to implement this for the reasons stated above.
Feel free to comment if anything is not clear.


问:
Show three dots when TextView is too long
One would think that showing three dots in 2019 at the end of string will be easy, but the opposite seems to be true. I have tried:

```<code>maxLines="1"
drawablePadding="10dp"
ellipsize="end"
ellipsize="marquee"
singleLine="true"
layout_width="match_parent"
layout_width="wrap_content"
</code>```

I went through dozens of questions here at stackoverflow, but it just doesn't work.

My layout file is quite simple:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_nearest_charger"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="40dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="55dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/colorCoarseDistance"
            android:textStyle="bold"
            android:textSize="20sp"
            android:text="1.2" />

        <TextView
            android:id="@+id/itemChargerUnits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="12sp"
            android:text="miles" />

    </LinearLayout>

    <ImageView
        android:id="@+id/itemChargerOperator"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="40dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/dot_cpo_cps_copy_5" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="7dp"
        android:layout_weight="2"
        android:drawablePadding="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="10dp"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="Kinross Park and Ride"
            android:textSize="18sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/itemChargerAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginStart="5dp"
                android:textSize="14sp"
                android:text="Junction Road" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
</code>```

All I need is to show three dots when TextView itemChargerTitle overflows. So far none of the solutions I found worked even in Android Studio preview.

答:
Try this

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_nearest_charger"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="40dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="55dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/colorPrimary"
            android:textStyle="bold"
            android:textSize="20sp"
            android:text="1.2" />

        <TextView
            android:id="@+id/itemChargerUnits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="12sp"
            android:text="miles" />

    </LinearLayout>

    <ImageView
        android:id="@+id/itemChargerOperator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="40dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/ic_launcher_background" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="7dp"
        android:layout_weight="8"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:maxLines="1"
            android:text="Kinross Parkcvcxvxcgjghjhjhjvxcvcvcvcvcv and Ride"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/itemChargerAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:textSize="14sp"
            android:text="Junction Road" />

    </LinearLayout>

</LinearLayout>
</code>```

OUTPUT

Body:
One would think that showing three dots in 2019 at the end of string will be easy, but the opposite seems to be true. I have tried:

maxLines="1"
drawablePadding="10dp"
ellipsize="end"
ellipsize="marquee"
singleLine="true"
layout_width="match_parent"
layout_width="wrap_content"

I went through dozens of questions here at stackoverflow, but it just doesn't work.

My layout file is quite simple:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_nearest_charger"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="40dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="55dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/colorCoarseDistance"
            android:textStyle="bold"
            android:textSize="20sp"
            android:text="1.2" />

        <TextView
            android:id="@+id/itemChargerUnits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="12sp"
            android:text="miles" />

    </LinearLayout>

    <ImageView
        android:id="@+id/itemChargerOperator"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="40dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/dot_cpo_cps_copy_5" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="7dp"
        android:layout_weight="2"
        android:drawablePadding="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="10dp"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="Kinross Park and Ride"
            android:textSize="18sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/itemChargerAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginStart="5dp"
                android:textSize="14sp"
                android:text="Junction Road" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

All I need is to show three dots when TextView itemChargerTitle overflows. So far none of the solutions I found worked even in Android Studio preview.

Body:
Try this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_nearest_charger"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="40dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="55dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/colorPrimary"
            android:textStyle="bold"
            android:textSize="20sp"
            android:text="1.2" />

        <TextView
            android:id="@+id/itemChargerUnits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="12sp"
            android:text="miles" />

    </LinearLayout>

    <ImageView
        android:id="@+id/itemChargerOperator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="40dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/ic_launcher_background" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="7dp"
        android:layout_weight="8"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:maxLines="1"
            android:text="Kinross Parkcvcxvxcgjghjhjhjvxcvcvcvcvcv and Ride"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/itemChargerAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:textSize="14sp"
            android:text="Junction Road" />

    </LinearLayout>

</LinearLayout>

OUTPUT


问:
I need code to run a SQL Server query which is stored in my local drive via VBA and get data into an Excel sheet
I have multiple SQL queries saved on my local drive, and each time I have to run SQL and copy data from SQL Server to Excel.</p>

答: You can retrieve SQL data from within Excel using default Excel functionality Eg Data/get data from SQL database, you can store the connection and queries it doesn't really require VBA</p>


问:
Create new variable with other variables on base of another variable
I have 4 date variables and 1 grouping variable. Based on the value in the grouping variable a date needs to be taken into a new variable.
My data looks like this: (https://www.dropbox.com/s/wlfv89qc1jzwfgk/vb.JPG)

I want to make a new variable based on the value of group. When group is A I need date1, when group is B I need date2, etc.

This is the code I've used:

```<code>if (tabel$group == A) {
  newvar <- tabel$date1
} else if (tabel$group == B) {
  newvar <- tabel$date2
} else if (tabel$group == C) {
  newvar <- tabel$date3
} else if (tabel$group == D) {
  newvar <- tabel$date4
}
</code>```

This code give me a warning message:

 (In if (tabel$group == 1) { :
  the condition has length > 1 and only the first element will be used

答:
I am sure this has been asked and answered several times before but I haven't found a good duplicate.

Nested ifelse() aren't always the best solution. It is cumbersome to code, read and maintain with lots of parentheses. Furthermore, ifelse() may change the type of the result unexpectedly, e.g., class Date.

So, I want to post some alternatives

Subsetting using match()

This one uses the specific fact that the first letter "A" corresponds to the first date column date1, etc. So, it may not be applicable in general:

```<code>indices <- matrix(c(seq.int(nrow(tabel)), match(tabel$group, LETTERS[1:4])), ncol = 2)
newvar <- tabel[, -1][indices]
newvar
</code>```

```<code> [1] "2011-01-01" "2011-01-02" "2011-01-03" "2012-02-04" "2012-02-05" "2012-02-06" "2013-03-07" "2013-03-08" "2013-03-09"
[10] "2014-04-10" "2014-04-11" "2014-04-12"
</code>```

The indices (row number, column number) which are used for subsetting are:

```<code>      [,1] [,2]
 [1,]    1    1
 [2,]    2    1
 [3,]    3    1
 [4,]    4    2
 [5,]    5    2
 [6,]    6    2
 [7,]    7    3
 [8,]    8    3
 [9,]    9    3
[10,]   10    4
[11,]   11    4
[12,]   12    4
</code>```

tabel[, -1] omits the first column (group).

case_when()

This is avectorised version of multiple if_else() statements from the dplyr package.

```<code>newvar <- dplyr::case_when(
  tabel$group == "A" ~ tabel$date1,
  tabel$group == "B" ~ tabel$date2,
  tabel$group == "C" ~ tabel$date3,
  tabel$group == "D" ~ tabel$date4)
</code>```

or

```<code>library(dplyr)
newvar <- tabel %>%
  transmute(value = case_when(group == "A" ~ date1,
                              group == "B" ~ date2,
                              group == "C" ~ date3,
                              group == "D" ~ date4)) %>%
  pull(value)
</code>```

Joining with a look-up table using data.table

Look-up tables treat the relation between group and column name as data and thus are easy to create and maintain. On the other hand, tabel has to be reshaped from wide to long format before it can be joined with lookup:

```<code>library(data.table)
lookup <- data.table(group = LETTERS[1:4], variable = paste0("date", 1:4))
newvar <- melt(setDT(tabel), id.vars = "group")[lookup, on = .(group, variable)]$value

lookup
</code>```

```<code>   group variable
1:     A    date1
2:     B    date2
3:     C    date3
4:     D    date4
</code>```

The reshaped long format is

```<code>melt(setDT(tabel), id.vars = "group")
</code>```

```<code>    group variable      value
 1:     A    date1 2011-01-01
 2:     A    date1 2011-01-02
 3:     A    date1 2011-01-03
 4:     B    date1 2011-01-04
 5:     B    date1 2011-01-05
 6:     B    date1 2011-01-06
 7:     C    date1 2011-01-07
 8:     C    date1 2011-01-08
 9:     C    date1 2011-01-09
10:     D    date1 2011-01-10
11:     D    date1 2011-01-11
12:     D    date1 2011-01-12
13:     A    date2 2012-02-01
14:     A    date2 2012-02-02
15:     A    date2 2012-02-03
16:     B    date2 2012-02-04
17:     B    date2 2012-02-05
18:     B    date2 2012-02-06
19:     C    date2 2012-02-07
20:     C    date2 2012-02-08
21:     C    date2 2012-02-09
22:     D    date2 2012-02-10
23:     D    date2 2012-02-11
24:     D    date2 2012-02-12
25:     A    date3 2013-03-01
26:     A    date3 2013-03-02
27:     A    date3 2013-03-03
28:     B    date3 2013-03-04
29:     B    date3 2013-03-05
30:     B    date3 2013-03-06
31:     C    date3 2013-03-07
32:     C    date3 2013-03-08
33:     C    date3 2013-03-09
34:     D    date3 2013-03-10
35:     D    date3 2013-03-11
36:     D    date3 2013-03-12
37:     A    date4 2014-04-01
38:     A    date4 2014-04-02
39:     A    date4 2014-04-03
40:     B    date4 2014-04-04
41:     B    date4 2014-04-05
42:     B    date4 2014-04-06
43:     C    date4 2014-04-07
44:     C    date4 2014-04-08
45:     C    date4 2014-04-09
46:     D    date4 2014-04-10
47:     D    date4 2014-04-11
48:     D    date4 2014-04-12
    group variable      value
</code>```

Joining with a look-up table using dplyr and tidyr

```<code>library(dplyr)
library(tidyr)
lookup <- tibble(group = LETTERS[1:4], key = paste0("date", 1:4))
newvar <- tabel %>%
  gather(key, value, -group) %>%
  inner_join(lookup) %>%
  pull(value)
</code>```

This works as above: create look-up table, reshape from wide to long format and join. pull() returns a simple result vector.

Reproducible data

```<code>tabel <- data.frame(group = rep(LETTERS[1:4], each = 3L),
                    date1 = as.Date("2011-01-01") + 0:11,
                    date2 = as.Date("2012-02-01") + 0:11,
                    date3 = as.Date("2013-03-01") + 0:11,
                    date4 = as.Date("2014-04-01") + 0:11)
tabel
</code>```

```<code>    group      date1      date2      date3      date4
 1:     A 2011-01-01 2012-02-01 2013-03-01 2014-04-01
 2:     A 2011-01-02 2012-02-02 2013-03-02 2014-04-02
 3:     A 2011-01-03 2012-02-03 2013-03-03 2014-04-03
 4:     B 2011-01-04 2012-02-04 2013-03-04 2014-04-04
 5:     B 2011-01-05 2012-02-05 2013-03-05 2014-04-05
 6:     B 2011-01-06 2012-02-06 2013-03-06 2014-04-06
 7:     C 2011-01-07 2012-02-07 2013-03-07 2014-04-07
 8:     C 2011-01-08 2012-02-08 2013-03-08 2014-04-08
 9:     C 2011-01-09 2012-02-09 2013-03-09 2014-04-09
10:     D 2011-01-10 2012-02-10 2013-03-10 2014-04-10
11:     D 2011-01-11 2012-02-11 2013-03-11 2014-04-11
12:     D 2011-01-12 2012-02-12 2013-03-12 2014-04-12
</code>```

Body:
I have 4 date variables and 1 grouping variable. Based on the value in the grouping variable a date needs to be taken into a new variable.
My data looks like this: (https://www.dropbox.com/s/wlfv89qc1jzwfgk/vb.JPG)

I want to make a new variable based on the value of group. When group is A I need date1, when group is B I need date2, etc.

This is the code I've used:

if (tabel$group == A) {
  newvar <- tabel$date1
} else if (tabel$group == B) {
  newvar <- tabel$date2
} else if (tabel$group == C) {
  newvar <- tabel$date3
} else if (tabel$group == D) {
  newvar <- tabel$date4
}

This code give me a warning message:

 (In if (tabel$group == 1) { :
  the condition has length > 1 and only the first element will be used

Body:
I am sure this has been asked and answered several times before but I haven't found a good duplicate.

Nested ifelse() aren't always the best solution. It is cumbersome to code, read and maintain with lots of parentheses. Furthermore, ifelse() may change the type of the result unexpectedly, e.g., class Date.

So, I want to post some alternatives

Subsetting using match()

This one uses the specific fact that the first letter "A" corresponds to the first date column date1, etc. So, it may not be applicable in general:

indices <- matrix(c(seq.int(nrow(tabel)), match(tabel$group, LETTERS[1:4])), ncol = 2)
newvar <- tabel[, -1][indices]
newvar

 [1] "2011-01-01" "2011-01-02" "2011-01-03" "2012-02-04" "2012-02-05" "2012-02-06" "2013-03-07" "2013-03-08" "2013-03-09"
[10] "2014-04-10" "2014-04-11" "2014-04-12"

The indices (row number, column number) which are used for subsetting are:

      [,1] [,2]
 [1,]    1    1
 [2,]    2    1
 [3,]    3    1
 [4,]    4    2
 [5,]    5    2
 [6,]    6    2
 [7,]    7    3
 [8,]    8    3
 [9,]    9    3
[10,]   10    4
[11,]   11    4
[12,]   12    4

tabel[, -1] omits the first column (group).

case_when()

This is avectorised version of multiple if_else() statements from the dplyr package.

newvar <- dplyr::case_when(
  tabel$group == "A" ~ tabel$date1,
  tabel$group == "B" ~ tabel$date2,
  tabel$group == "C" ~ tabel$date3,
  tabel$group == "D" ~ tabel$date4)

or

library(dplyr)
newvar <- tabel %>%
  transmute(value = case_when(group == "A" ~ date1,
                              group == "B" ~ date2,
                              group == "C" ~ date3,
                              group == "D" ~ date4)) %>%
  pull(value)

Joining with a look-up table using data.table

Look-up tables treat the relation between group and column name as data and thus are easy to create and maintain. On the other hand, tabel has to be reshaped from wide to long format before it can be joined with lookup:

library(data.table)
lookup <- data.table(group = LETTERS[1:4], variable = paste0("date", 1:4))
newvar <- melt(setDT(tabel), id.vars = "group")[lookup, on = .(group, variable)]$value

lookup

   group variable
1:     A    date1
2:     B    date2
3:     C    date3
4:     D    date4

The reshaped long format is

melt(setDT(tabel), id.vars = "group")

    group variable      value
 1:     A    date1 2011-01-01
 2:     A    date1 2011-01-02
 3:     A    date1 2011-01-03
 4:     B    date1 2011-01-04
 5:     B    date1 2011-01-05
 6:     B    date1 2011-01-06
 7:     C    date1 2011-01-07
 8:     C    date1 2011-01-08
 9:     C    date1 2011-01-09
10:     D    date1 2011-01-10
11:     D    date1 2011-01-11
12:     D    date1 2011-01-12
13:     A    date2 2012-02-01
14:     A    date2 2012-02-02
15:     A    date2 2012-02-03
16:     B    date2 2012-02-04
17:     B    date2 2012-02-05
18:     B    date2 2012-02-06
19:     C    date2 2012-02-07
20:     C    date2 2012-02-08
21:     C    date2 2012-02-09
22:     D    date2 2012-02-10
23:     D    date2 2012-02-11
24:     D    date2 2012-02-12
25:     A    date3 2013-03-01
26:     A    date3 2013-03-02
27:     A    date3 2013-03-03
28:     B    date3 2013-03-04
29:     B    date3 2013-03-05
30:     B    date3 2013-03-06
31:     C    date3 2013-03-07
32:     C    date3 2013-03-08
33:     C    date3 2013-03-09
34:     D    date3 2013-03-10
35:     D    date3 2013-03-11
36:     D    date3 2013-03-12
37:     A    date4 2014-04-01
38:     A    date4 2014-04-02
39:     A    date4 2014-04-03
40:     B    date4 2014-04-04
41:     B    date4 2014-04-05
42:     B    date4 2014-04-06
43:     C    date4 2014-04-07
44:     C    date4 2014-04-08
45:     C    date4 2014-04-09
46:     D    date4 2014-04-10
47:     D    date4 2014-04-11
48:     D    date4 2014-04-12
    group variable      value

Joining with a look-up table using dplyr and tidyr

library(dplyr)
library(tidyr)
lookup <- tibble(group = LETTERS[1:4], key = paste0("date", 1:4))
newvar <- tabel %>%
  gather(key, value, -group) %>%
  inner_join(lookup) %>%
  pull(value)

This works as above: create look-up table, reshape from wide to long format and join. pull() returns a simple result vector.

Reproducible data

tabel <- data.frame(group = rep(LETTERS[1:4], each = 3L),
                    date1 = as.Date("2011-01-01") + 0:11,
                    date2 = as.Date("2012-02-01") + 0:11,
                    date3 = as.Date("2013-03-01") + 0:11,
                    date4 = as.Date("2014-04-01") + 0:11)
tabel

    group      date1      date2      date3      date4
 1:     A 2011-01-01 2012-02-01 2013-03-01 2014-04-01
 2:     A 2011-01-02 2012-02-02 2013-03-02 2014-04-02
 3:     A 2011-01-03 2012-02-03 2013-03-03 2014-04-03
 4:     B 2011-01-04 2012-02-04 2013-03-04 2014-04-04
 5:     B 2011-01-05 2012-02-05 2013-03-05 2014-04-05
 6:     B 2011-01-06 2012-02-06 2013-03-06 2014-04-06
 7:     C 2011-01-07 2012-02-07 2013-03-07 2014-04-07
 8:     C 2011-01-08 2012-02-08 2013-03-08 2014-04-08
 9:     C 2011-01-09 2012-02-09 2013-03-09 2014-04-09
10:     D 2011-01-10 2012-02-10 2013-03-10 2014-04-10
11:     D 2011-01-11 2012-02-11 2013-03-11 2014-04-11
12:     D 2011-01-12 2012-02-12 2013-03-12 2014-04-12


问:
followupEvent not matching any intent
I'm using dialogflow-fulfillment to implement the backend of my service based on dialogflow. There's a point where I use the method agent.setFollowupEvent(targetIntent), the targetIntent requires a context to be matchable, let's call it targetContext.

I can't tell exactly when it stopped working (a week? month maybe?), but it worked and right now it's not working (and I don't think I've changed anything that could explain it). The targetIntent fulfillment never get called and I can see in the dialogflow console that it's because the request triggered by setFollowupEvent doesn't match any intent.

If I remove the requirement of the targetContext from the targetIntent, it works.

I think I'm setting the context correctly:

```<code>agent.context.set(targetContext, null, null);
agent.setFollowupEvent(targetIntent);
</code>```

Inspecting the body of the response that dialogflow-fulfillment is sending to dialogflow I see:

```<code>{
    "outputContexts": [{ "name": "projects/<myprojectid>/agent/sessions/<mysessionid>/contexts/<targetContext>" }],
    "followupEventInput": { "name": "<targetIntent>", "languageCode": "it" }
}
</code>```

The context is there, and I think is correct.
Any clues? The only thing I can think of is that we changed the agent type from free to enterprise.

答:
Obviously, I've found the solution just after asking the question...

The problem was the lifespan of the context, I did not set it, now it works with:

```<code>                                 |
                                 V
agent.context.set(targetContext, 1, null);
agent.setFollowupEvent(targetIntent);
</code>```

So the output become:

```<code>{
    "outputContexts": [{ "name": "projects/<myprojectid>/agent/sessions/<mysessionid>/contexts/<targetContext>", "lifespanCount": 1 }],
    "followupEventInput": { "name": "<targetIntent>", "languageCode": "it" }
}
</code>```

Still I'm quite sure it worked before, maybe not setting the lifespan used to default to 1?

Title: followupEvent not matching any intent

Body:
I'm using dialogflow-fulfillment to implement the backend of my service based on dialogflow. There's a point where I use the method agent.setFollowupEvent(targetIntent), the targetIntent requires a context to be matchable, let's call it targetContext.

I can't tell exactly when it stopped working (a week? month maybe?), but it worked and right now it's not working (and I don't think I've changed anything that could explain it). The targetIntent fulfillment never get called and I can see in the dialogflow console that it's because the request triggered by setFollowupEvent doesn't match any intent.

If I remove the requirement of the targetContext from the targetIntent, it works.

I think I'm setting the context correctly:

agent.context.set(targetContext, null, null);
agent.setFollowupEvent(targetIntent);

Inspecting the body of the response that dialogflow-fulfillment is sending to dialogflow I see:

{
    "outputContexts": [{ "name": "projects/<myprojectid>/agent/sessions/<mysessionid>/contexts/<targetContext>" }],
    "followupEventInput": { "name": "<targetIntent>", "languageCode": "it" }
}

The context is there, and I think is correct.
Any clues? The only thing I can think of is that we changed the agent type from free to enterprise.

Body:
Obviously, I've found the solution just after asking the question...

The problem was the lifespan of the context, I did not set it, now it works with:

                                 |
                                 V
agent.context.set(targetContext, 1, null);
agent.setFollowupEvent(targetIntent);

So the output become:

{
    "outputContexts": [{ "name": "projects/<myprojectid>/agent/sessions/<mysessionid>/contexts/<targetContext>", "lifespanCount": 1 }],
    "followupEventInput": { "name": "<targetIntent>", "languageCode": "it" }
}

Still I'm quite sure it worked before, maybe not setting the lifespan used to default to 1?


问:
Token Mismatch Exception in VerifyCsrfToken.php
I am getting this error on submit button click.

I already tried to put following code in form tag :

```<code><input type="hidden" name="_token" value="{{ csrf_token() }}">
</code>```

session.php

```<code><div class="title">
    Laravel Session Tutorial

   <form action="about.php" method="post">

       {{ csrf_field() }}
       <input type="text" name="name" value="">
       <button type="submit" name="button">Enter</button>
   </form>
</div>
</code>```

I am just passing input string to another web page. For example, if I input name in textbox. In return, it gives me that input name in another web page like  "Hello , (name)".

答:
Try this,</p>

```<code><div class="title">
    Laravel Session Tutorial
   <form action="about.php" method="post">
       {{ csrf_field() }}
       <input type="text" name="name" value="">
       <button type="submit" name="button">Enter</button>
   </form>
</div>
</code>```

Body:
I am getting this error on submit button click.

I already tried to put following code in form tag :

<input type="hidden" name="_token" value="{{ csrf_token() }}">

session.php

    Laravel Session Tutorial

   <form action="about.php" method="post">

       {{ csrf_field() }}
       <input type="text" name="name" value="">
       <button type="submit" name="button">Enter</button>
   </form>

I am just passing input string to another web page. For example, if I input name in textbox. In return, it gives me that input name in another web page like  "Hello , (name)".

Body:
Try this,

<div class="title">
    Laravel Session Tutorial
   <form action="about.php" method="post">
       {{ csrf_field() }}
       <input type="text" name="name" value="">
       <button type="submit" name="button">Enter</button>
   </form>
</div>


问:
Access service api exposed as clusterIP in kubernete
I have two application, both deployed in same cluster.

Now from web, there is an ajax request to get data from api, but it always return 502 Connection refused.

here is my jquery code (web).

```<code>$.get("http://10.43.244.118/api/users", function (data) {
        console.log(data);
        $('#table').bootstrapTable({
            data: data
        });
    });
</code>```

Note: when I change the service type to LoadBalancer from ClusterIP then it works fine.

答: ClusterIP services (usually) only work within the cluster. You can technically make your CNI address space available externally, but that is rare and you probably shouldn't count on it. The correct way to expose something outside the cluster is either a NodePort service or a LoadBalancer (which is a NodePort plus a cloud load balancer).</p>

Body:
I have two application, both deployed in same cluster.

Now from web, there is an ajax request to get data from api, but it always return 502 Connection refused.

here is my jquery code (web).

$.get("http://10.43.244.118/api/users", function (data) {
        console.log(data);
        $('#table').bootstrapTable({
            data: data
        });
    });

Note: when I change the service type to LoadBalancer from ClusterIP then it works fine.


问:
Add "?XDEBUG_PROFILE=on" at the end of each URL using htaccess
I am using X-debug for memory profiling of my Drupal project and I am getting the logs and able to read them using Kcachegrind. I am getting different cachegrind files whenever I add ?XDEBUG_PROFILE=on at the end of the url. So it is pretty helpful to identify the memory usages.

But now I have to give ?XDEBUG_PROFILE=on manually to the end of desired URLs. Is there any way to add ?XDEBUG_PROFILE=on at the end of each URL with help of .htaccess or some other way?

So if my url is http://localhsot/mysite/home, then the new one will be http://localhsot/mysite/home?XDEBUG_PROFILE=on and if the url is http://localhsot/mysite/settings then the new URL will be http://localhsot/mysite/settings?XDEBUG_PROFILE=on

Please help on this.

答:
I Hope this will help you.

```<code>RewriteEngine on
RewriteCond %{QUERY_STRING} ^(?!XDEBUG_PROFILE)
RewriteRule (.*) /mysite/$1?XDEBUG_PROFILE=on [L,R,QSA]
</code>```

Add the above lines in your Drupal .htaccess

Body:
I Hope this will help you.

RewriteEngine on
RewriteCond %{QUERY_STRING} ^(?!XDEBUG_PROFILE)
RewriteRule (.*) /mysite/$1?XDEBUG_PROFILE=on [L,R,QSA]

Add the above lines in your Drupal .htaccess


问:
log4j how to avoid "unknown source" message
Am using my java application with log4j as logging mechanism

For most of the debug statements of the 3rd party jars am using, am getting filename with line numbers like
com.abc.xyz.GG(doFilter:67)

but for my source code, am getting the following
com.xyz.abc.class (unknown source problem)

Its tough for me to debug my source code since there is no line number info.

Can Someone please help me how do I enable this....

Thanks in advance....

答:
You need to pass -g option when calling the javac command.
From the Oracle documentation:

-g
  Generate all debugging information, including local variables. By default, only line number and source file information is generated.

If you using ant to build your project you need to set the javac task's debug attribute to on, like this:

```<code><javac debug="on">...</javac>
</code>```

Body:
You need to pass -g option when calling the javac command.
From the Oracle documentation:

-g
  Generate all debugging information, including local variables. By default, only line number and source file information is generated.

If you using ant to build your project you need to set the javac task's debug attribute to on, like this:

<javac debug="on">...</javac>


问:
Handlebars If var length is greater than
I'm currently trying to set up some email templates using Foundation email and Handlebars. Im trying to render some headings based on if a value is passed to the component, however I can't seem to get it to work. What am i doing wrong here?

heading-1.html

```<code><h1>{{text}}</h1>
</code>```

paragraph.html

```<code><row class="card">
    <columns>
        <wrapper class="inner-padding">
            {{#if (eq heading-1.length > 0)}}
                {{> heading-1 text="Test"}}
            {{else}}
                <h1>failed</h1>
            {{/if}}
            <p>
                {{text}}
            </p>
        </wrapper>
    </columns>
</row>
</code>```

index.html

```<code><container>
  <row>
    <columns class="content">
      {{> paragraph
        heading-1="test"
        text="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet dolorem molestias nam odit suscipit velit.
        Ab aliquam at autem dignissimos dolorum ipsam magnam molestiae officia, quae quo, veniam veritatis voluptatibus?"
      }}
    </columns>
  </row>
</container>
</code>```

答:
Create Handlebars helper :

```<code>Handlebars.registerHelper('checklength', function (v1, v2, options) {
'use strict';
   if (v1.length>v2) {
     return options.fn(this);
  }
  return options.inverse(this);
});
</code>```

Use :

```<code>{{#checklength Title 0}}   //Title is property and 0 is length
             <p>Heading</p>
      {{else}}
             <h1>failed</h1>
      {{/checklength}}
</code>```

Body:
I'm currently trying to set up some email templates using Foundation email and Handlebars. Im trying to render some headings based on if a value is passed to the component, however I can't seem to get it to work. What am i doing wrong here?

heading-1.html

{{text}}

paragraph.html

<row class="card">
    <columns>
        <wrapper class="inner-padding">
            {{#if (eq heading-1.length > 0)}}
                {{> heading-1 text="Test"}}
            {{else}}

failed

            {{/if}}

                {{text}}

        </wrapper>
    </columns>
</row>

index.html

<container>
  <row>
    <columns class="content">
      {{> paragraph
        heading-1="test"
        text="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet dolorem molestias nam odit suscipit velit.
        Ab aliquam at autem dignissimos dolorum ipsam magnam molestiae officia, quae quo, veniam veritatis voluptatibus?"
      }}
    </columns>
  </row>
</container>

Body:
Create Handlebars helper :

Handlebars.registerHelper('checklength', function (v1, v2, options) {
'use strict';
   if (v1.length>v2) {
     return options.fn(this);
  }
  return options.inverse(this);
});

Use :

{{#checklength Title 0}}   //Title is property and 0 is length
             <p>Heading</p>
      {{else}}
             <h1>failed</h1>
      {{/checklength}}


问:
Gatsby Image with Netlify CMS - Field "image" must not have a selection since type "String" has no subfields
I'm building a blog site with Gatsby and I'm using Netlify CMS to manage my content. Each blog post has a featured image specified in the frontmatter.

But, I'm having some issues with getting those images to display. I keep getting this error:

GraphQL Error Field "image" must not have a selection since type "String" has no subfields.

I tried adding gatsby-remark-relative-images to try to fix this but that's not working - i still get the same error.

Any ideas on how to fix this?

Directory structure

```<code>content
 - articles
public
src
static
 - admin
 - images
</code>```

Post Frontmatter

```<code>---
title: Post 1
image: img.png
---
</code>```

gatsby-config.js

```<code>plugins: [
  {
    resolve: `gatsby-source-filesystem`,
    options: {
      name: `images`,
      path: `${__dirname}/static/images`,
    }
  },
  {
    resolve: `gatsby-source-filesystem`,
    options: {
      name: `content`,
      path: `${__dirname}/content`,
    }
  },
  {
    resolve: `gatsby-transformer-remark`,
    options: {
      plugins: [
        {
          resolve: `gatsby-remark-relative-images`,
        },
        {
          resolve: `gatsby-remark-images`,
          options: {
            maxWidth: 590,
          },
        },
      ],
    },
  },
  `gatsby-transformer-sharp`,
  `gatsby-plugin-sharp`,
  `gatsby-plugin-netlify-cms`,
  `gatsby-plugin-sitemap`
]

</code>```

gatsby-node.js

```<code>const path = require('path');

const { createFilePath } = require(`gatsby-source-filesystem`)
const { fmImagesToRelative } = require('gatsby-remark-relative-images');

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  fmImagesToRelative(node)

  if (node.internal.type === `MarkdownRemark`) {

    const slug = createFilePath({ node, getNode, basePath: `pages` })

    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}

exports.createPages = ({actions, graphql}) => {
  const {createPage} = actions;

  return graphql(`{
    allMarkdownRemark {
      edges {
        node {
          html
          id
          frontmatter {
            title
            date
            templateKey
          }
          fields {
            slug
          }
        }
      }
    }
  }`)
  .then(res => {
    if (res.errors) {
      return Promise.reject(res.errors);
    }

    res.data.allMarkdownRemark.edges.forEach(({node}) => {
      createPage({
        path: node.fields.slug,
        component: path.resolve(
          `src/templates/${String(node.frontmatter.templateKey)}.js`
        ),
        context: {
          // Data passed to context is available
          // in page queries as GraphQL variables.
          slug: node.fields.slug,
        },
      })
    })

  })
}
</code>```

答:
Try clearing the cache using:

```<code>gatsby clean
</code>```

And then running the dev server again.

I often get this error randomly when working with the same setup as you. Clearing the cache and restarting usually fixes it.

Body:
I'm building a blog site with Gatsby and I'm using Netlify CMS to manage my content. Each blog post has a featured image specified in the frontmatter.

But, I'm having some issues with getting those images to display. I keep getting this error:

GraphQL Error Field "image" must not have a selection since type "String" has no subfields.

I tried adding gatsby-remark-relative-images to try to fix this but that's not working - i still get the same error.

Any ideas on how to fix this?

Directory structure

content
 - articles
public
src
static
 - admin
 - images

Post Frontmatter

---
title: Post 1
image: img.png
---

gatsby-config.js

plugins: [
  {
    resolve: `gatsby-source-filesystem`,
    options: {
      name: `images`,
      path: `${__dirname}/static/images`,
    }
  },
  {
    resolve: `gatsby-source-filesystem`,
    options: {
      name: `content`,
      path: `${__dirname}/content`,
    }
  },
  {
    resolve: `gatsby-transformer-remark`,
    options: {
      plugins: [
        {
          resolve: `gatsby-remark-relative-images`,
        },
        {
          resolve: `gatsby-remark-images`,
          options: {
            maxWidth: 590,
          },
        },
      ],
    },
  },
  `gatsby-transformer-sharp`,
  `gatsby-plugin-sharp`,
  `gatsby-plugin-netlify-cms`,
  `gatsby-plugin-sitemap`
]

gatsby-node.js

const path = require('path');

const { createFilePath } = require(`gatsby-source-filesystem`)
const { fmImagesToRelative } = require('gatsby-remark-relative-images');

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  fmImagesToRelative(node)

  if (node.internal.type === `MarkdownRemark`) {

    const slug = createFilePath({ node, getNode, basePath: `pages` })

    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}

exports.createPages = ({actions, graphql}) => {
  const {createPage} = actions;

  return graphql(`{
    allMarkdownRemark {
      edges {
        node {
          html
          id
          frontmatter {
            title
            date
            templateKey
          }
          fields {
            slug
          }
        }
      }
    }
  }`)
  .then(res => {
    if (res.errors) {
      return Promise.reject(res.errors);
    }

    res.data.allMarkdownRemark.edges.forEach(({node}) => {
      createPage({
        path: node.fields.slug,
        component: path.resolve(
          `src/templates/${String(node.frontmatter.templateKey)}.js`
        ),
        context: {
          // Data passed to context is available
          // in page queries as GraphQL variables.
          slug: node.fields.slug,
        },
      })
    })

  })
}

Body:
Try clearing the cache using:

gatsby clean

And then running the dev server again.

I often get this error randomly when working with the same setup as you. Clearing the cache and restarting usually fixes it.


问:
Logout logic is not working with basic authentication
This is my logout code. It is getting redirected to logout.done but, if I again go to hello I'm still able to access it.

```<code>public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user")
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
    .invalidateHttpSession(true);
}
</code>```

What is wrong here?

答:
Add Spring security  and spefic controller

```<code>public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user")
    .and()
    .logout()
    .logoutSuccessUrl("/login?logout").invalidateHttpSession(true).deleteCookies("JSESSIONID");
}

    @RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
public ModelAndView adminLogin(Model model,@RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout,
        @RequestParam(value = "expired", required = false) String expired,
        @RequestParam(value = "accessdenied", required = false) String accessdenied,
        HttpServletRequest request, HttpServletResponse response) {
    if (logout != null) {
        logger.info("logout application");
        SecurityContextHolder.getContext().setAuthentication(null);
        SecurityContextHolder.clearContext();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        HttpSession session = request.getSession(false);
        Enumeration<?> e = session.getAttributeNames();
        while (e.hasMoreElements()) {
            String attr = (String) e.nextElement();
            session.setAttribute(attr, null);
        }
        if (session != null) {
            session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            session.invalidate();
        }
        for (javax.servlet.http.Cookie cookie : request.getCookies()) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            cookie.setPath("/");
        }
        model.addAttribute(MESSAGE, "You have been logged out successfully.");
        model.addAttribute(SUCCESSMSG, true);
    }

    final ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("adminLogin", new AdminLogin());
    modelAndView.setViewName("login");
    return modelAndView;
</code>```

}

Body:
This is my logout code. It is getting redirected to logout.done but, if I again go to hello I'm still able to access it.

public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user")
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
    .invalidateHttpSession(true);
}

What is wrong here?

Body:
Add Spring security  and spefic controller

public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user")
    .and()
    .logout()
    .logoutSuccessUrl("/login?logout").invalidateHttpSession(true).deleteCookies("JSESSIONID");
}

    @RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
public ModelAndView adminLogin(Model model,@RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout,
        @RequestParam(value = "expired", required = false) String expired,
        @RequestParam(value = "accessdenied", required = false) String accessdenied,
        HttpServletRequest request, HttpServletResponse response) {
    if (logout != null) {
        logger.info("logout application");
        SecurityContextHolder.getContext().setAuthentication(null);
        SecurityContextHolder.clearContext();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        HttpSession session = request.getSession(false);
        Enumeration<?> e = session.getAttributeNames();
        while (e.hasMoreElements()) {
            String attr = (String) e.nextElement();
            session.setAttribute(attr, null);
        }
        if (session != null) {
            session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            session.invalidate();
        }
        for (javax.servlet.http.Cookie cookie : request.getCookies()) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            cookie.setPath("/");
        }
        model.addAttribute(MESSAGE, "You have been logged out successfully.");
        model.addAttribute(SUCCESSMSG, true);
    }

    final ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("adminLogin", new AdminLogin());
    modelAndView.setViewName("login");
    return modelAndView;

}


问:
Javafx SimpleStringProperty deserialization throw IllegalStateException: unread block data
Im developing an application using javafx. I have to save my data in a file. Im using serialization, but since im using SimpleStringProperty i have a problem.
SimpleStringProperty  isn't serializable so i created the two methods writeObject and readObject. The write method works well (i think, it write in the file) but the read one dont. When i read the save file i got

```<code>java.lang.IllegalStateException: unread block data throwed.
</code>```

Here is the class diagram of my data. What i try to save is Employee.

```<code>    private void writeObject(ObjectOutputStream s) throws IOException
    {
        s.defaultWriteObject();
        s.writeInt(id);
        s.writeUTF(firstname.get());
        s.writeUTF(lastname.get());
        s.writeUTF(phoneNumber.get());
        s.writeBoolean(gender.get());
    }

    private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
    {
        id = s.readInt();
        firstname.set(s.readUTF());
        lastname.set(s.readUTF());
        phoneNumber.set(s.readUTF());
        gender.set(s.readBoolean());
    }
</code>```

Do you have an idea of what could the problem be ?

```<code>java.lang.IllegalStateException: unread block data
at java.io.ObjectInputStream$BlockDataInputStream.setBlockDataMode(ObjectInputStream.java:2783)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1605)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at java.util.ArrayList.readObject(ArrayList.java:797)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1170)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2178)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at sample.Main.loadData(Main.java:61)
at sample.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
</code>```

答:
You may use normal pojo without javafx properties,
This may even help you to use frameworks . There are simple work arounds. When they need to be converted to properties.
However, this is a working example of deserialising javafx properties
https://gist.github.com/james-d/a7202039b00170256293</p>

Body:
Im developing an application using javafx. I have to save my data in a file. Im using serialization, but since im using SimpleStringProperty i have a problem.
SimpleStringProperty  isn't serializable so i created the two methods writeObject and readObject. The write method works well (i think, it write in the file) but the read one dont. When i read the save file i got

java.lang.IllegalStateException: unread block data throwed.

Here is the class diagram of my data. What i try to save is Employee.

    private void writeObject(ObjectOutputStream s) throws IOException
    {
        s.defaultWriteObject();
        s.writeInt(id);
        s.writeUTF(firstname.get());
        s.writeUTF(lastname.get());
        s.writeUTF(phoneNumber.get());
        s.writeBoolean(gender.get());
    }

    private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
    {
        id = s.readInt();
        firstname.set(s.readUTF());
        lastname.set(s.readUTF());
        phoneNumber.set(s.readUTF());
        gender.set(s.readBoolean());
    }

Do you have an idea of what could the problem be ?

java.lang.IllegalStateException: unread block data
at java.io.ObjectInputStream$BlockDataInputStream.setBlockDataMode(ObjectInputStream.java:2783)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1605)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at java.util.ArrayList.readObject(ArrayList.java:797)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1170)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2178)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at sample.Main.loadData(Main.java:61)
at sample.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)


问:
SocketCAN: Filtering of frames with certain CAN IDs not working
I'm trying to filter CAN frames with certain IDs as described here: https://landlock.io/linux-doc/landlock-v8/networking/can.html#raw-protocol-sockets-with-can-filters-sock-raw

Part of my code:

```<code>struct can_filter rfilter[4];

if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
    fprintf(stderr, "Error while opening socket.\n");
    exit(EXIT_FAILURE);
}
rfilter[0].can_id   = 0x0D6 | CAN_INV_FILTER;
rfilter[0].can_mask = CAN_SFF_MASK;
rfilter[1].can_id   = 0x0D8 | CAN_INV_FILTER;
rfilter[1].can_mask = CAN_SFF_MASK;
rfilter[2].can_id   = 0x0E4 | CAN_INV_FILTER;
rfilter[2].can_mask = CAN_SFF_MASK;
rfilter[3].can_id   = 0x77F | CAN_INV_FILTER;
rfilter[3].can_mask = CAN_SFF_MASK;
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
</code>```

If I use only one of my four filters and comment out the other three, it's working as expected. If I use all four filters, it's not working at all. In that case I'm still receiving everything on the CANbus interface.

So, my guess is that somehow my filters are neutralising each other?! What do I need to change to filter the CAN IDs 0x0D6, 0x0D8, 0x0E4, and 0x77F?

答:
When using CAN_INV_FILTER like you do, you specify "everything goes through except ID_x".

When using CAN_RAW_FILTER, it will check if there is a rule which let the received ID pass. In your case, your rules are contradicting each others, this is why nothing is filtered.

From the documentation:

4.1.6 RAW socket option CAN_RAW_JOIN_FILTERS

The CAN_RAW socket can set multiple CAN identifier specific filters
  that   lead to multiple filters in the af_can.c filter processing.
  These filters   are indenpendent from each other which leads to
  logical OR'ed filters when   applied (see 4.1.1).

This socket option joines the given CAN filters in the way that only
  CAN   frames are passed to user space that matched all given CAN
  filters. The   semantic for the applied filters is therefore changed
  to a logical AND.

This is useful especially when the filterset is a combination of
  filters   where the CAN_INV_FILTER flag is set in order to notch
  single CAN IDs or   CAN ID ranges from the incoming traffic.

To have the expected behavior, you should replace:

```<code>setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
</code>```

by:

```<code>setsockopt(s, SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS, &rfilter, sizeof(rfilter));
</code>```

NB: it is possible that the CAN_RAW_JOIN_FILTERS option isn't supported by your Linux kernel

Body:
I'm trying to filter CAN frames with certain IDs as described here: https://landlock.io/linux-doc/landlock-v8/networking/can.html#raw-protocol-sockets-with-can-filters-sock-raw

Part of my code:

struct can_filter rfilter[4];

if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
    fprintf(stderr, "Error while opening socket.\n");
    exit(EXIT_FAILURE);
}
rfilter[0].can_id   = 0x0D6 | CAN_INV_FILTER;
rfilter[0].can_mask = CAN_SFF_MASK;
rfilter[1].can_id   = 0x0D8 | CAN_INV_FILTER;
rfilter[1].can_mask = CAN_SFF_MASK;
rfilter[2].can_id   = 0x0E4 | CAN_INV_FILTER;
rfilter[2].can_mask = CAN_SFF_MASK;
rfilter[3].can_id   = 0x77F | CAN_INV_FILTER;
rfilter[3].can_mask = CAN_SFF_MASK;
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));

If I use only one of my four filters and comment out the other three, it's working as expected. If I use all four filters, it's not working at all. In that case I'm still receiving everything on the CANbus interface.

So, my guess is that somehow my filters are neutralising each other?! What do I need to change to filter the CAN IDs 0x0D6, 0x0D8, 0x0E4, and 0x77F?

Body:
When using CAN_INV_FILTER like you do, you specify "everything goes through except ID_x".

When using CAN_RAW_FILTER, it will check if there is a rule which let the received ID pass. In your case, your rules are contradicting each others, this is why nothing is filtered.

From the documentation:

4.1.6 RAW socket option CAN_RAW_JOIN_FILTERS

The CAN_RAW socket can set multiple CAN identifier specific filters
  that   lead to multiple filters in the af_can.c filter processing.
  These filters   are indenpendent from each other which leads to
  logical OR'ed filters when   applied (see 4.1.1).

This socket option joines the given CAN filters in the way that only
  CAN   frames are passed to user space that matched all given CAN
  filters. The   semantic for the applied filters is therefore changed
  to a logical AND.

This is useful especially when the filterset is a combination of
  filters   where the CAN_INV_FILTER flag is set in order to notch
  single CAN IDs or   CAN ID ranges from the incoming traffic.

To have the expected behavior, you should replace:

setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));

by:

setsockopt(s, SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS, &rfilter, sizeof(rfilter));

NB: it is possible that the CAN_RAW_JOIN_FILTERS option isn't supported by your Linux kernel


问:
ScintillaNet - Working out what line a user clicks on
I'm using the ScintillaNet text box control to display some search results and I want to be able to detect when the user double clicks / right clicks on a line in the results so that I can work out which hit they are clicking on.

Does anyone have any ideas on the best way of doing this?  I can think of a few ways but they all seem a bit "hacky" to me.

答:
With the new version of ScintillaNET you can use a better function to get the current line number:

```<code>scintilla1.Lines.Current.Number()
</code>```

I was able to attach an event handler to SelectionChanged event and then, get the current line number to do what you've asked.

ContentLicense: CC BY-SA 2.5

Body:
With the new version of ScintillaNET you can use a better function to get the current line number:

scintilla1.Lines.Current.Number()

I was able to attach an event handler to SelectionChanged event and then, get the current line number to do what you've asked.


问:
Gathering multiple data columns currently in factor form
I have a dataset of train carloads. It currently has a number (weekly carload) listed for each company (the row) for each week (the columns) over the course of a couple years (100+ columns). I want to gather this into just two columns: a date and loads.

It currently looks like this:

```<code>3/29/2017  4/5/2017  4/12/2017  4/19/2017
32.7       31.6      32.3       32.5
20.5       21.8      22.0       22.3
24.1       24.1      23.6       23.4
24.9       24.7      24.8       26.5
</code>```

I'm looking for:

```<code>Date        Load
3/29/2017   32.7
3/29/2017   20.5
3/29/2017   24.1
3/29/2017   24.9
4/5/2017    31.6
</code>```

I've been doing various versions of the following:

rail3 <- rail2 %>%
  gather(`3/29/2017`:`1/24/2018`, key = "date", value = "loads")
```

<p>When I do this it makes a dataset called rail3, but it didn't make the new columns I wanted. It only made the dataset 44 times longer than it was. And it gave me the following message: </p>

```Warning message:
attributes are not identical across measure variables;
they will be dropped
```

<p>I'm assuming this is because the date columns are currently coded as factors. But I'm also not sure how to convert 100+ columns from factors to numeric. I've tried the following and various other methods:</p>

<pre class="lang-r prettyprint-override"><code>rail2["3/29/2017":"1/24/2018"] <- lapply(rail2["3/29/2017":"1/24/2018"], as.numeric)
</code>```

None of this has worked. Let me know if you have any advice. Thanks!

答:
If you want to avoid warnings when gathering and want date and numeric output in final df you can do:

```<code>library(tidyr)
library(hablar)

# Data from above but with factors
rail2<-read.table(header=TRUE, text="3/29/2017  4/5/2017  4/12/2017  4/19/2017
32.7       31.6      32.3       32.5
                  20.5       21.8      22.0       22.3
                  24.1       24.1      23.6       23.4
                  24.9       24.7      24.8       26.5", check.names=FALSE) %>%
  as_tibble() %>%
  convert(fct(everything()))

# Code
rail2 %>%
  convert(num(everything())) %>%
  gather("date", "load") %>%
  convert(dte(date, .args = list(format = "%m/%d/%Y")))
</code>```

Gives:

```<code># A tibble: 16 x 2
   date        load
   <date>     <dbl>
 1 2017-03-29  32.7
 2 2017-03-29  20.5
 3 2017-03-29  24.1
 4 2017-03-29  24.9
 5 2017-04-05  31.6
</code>```

Body:
I have a dataset of train carloads. It currently has a number (weekly carload) listed for each company (the row) for each week (the columns) over the course of a couple years (100+ columns). I want to gather this into just two columns: a date and loads.

It currently looks like this:

3/29/2017  4/5/2017  4/12/2017  4/19/2017
32.7       31.6      32.3       32.5
20.5       21.8      22.0       22.3
24.1       24.1      23.6       23.4
24.9       24.7      24.8       26.5

I'm looking for:

Date        Load
3/29/2017   32.7
3/29/2017   20.5
3/29/2017   24.1
3/29/2017   24.9
4/5/2017    31.6

I've been doing various versions of the following:

rail3 <- rail2 %>%
  gather(`3/29/2017`:`1/24/2018`, key = "date", value = "loads")

When I do this it makes a dataset called rail3, but it didn't make the new columns I wanted. It only made the dataset 44 times longer than it was. And it gave me the following message:

Warning message:
attributes are not identical across measure variables;
they will be dropped

I'm assuming this is because the date columns are currently coded as factors. But I'm also not sure how to convert 100+ columns from factors to numeric. I've tried the following and various other methods:

rail2["3/29/2017":"1/24/2018"] <- lapply(rail2["3/29/2017":"1/24/2018"], as.numeric)

None of this has worked. Let me know if you have any advice. Thanks!

Body:
If you want to avoid warnings when gathering and want date and numeric output in final df you can do:

library(tidyr)
library(hablar)

# Data from above but with factors
rail2<-read.table(header=TRUE, text="3/29/2017  4/5/2017  4/12/2017  4/19/2017
32.7       31.6      32.3       32.5
                  20.5       21.8      22.0       22.3
                  24.1       24.1      23.6       23.4
                  24.9       24.7      24.8       26.5", check.names=FALSE) %>%
  as_tibble() %>%
  convert(fct(everything()))

# Code
rail2 %>%
  convert(num(everything())) %>%
  gather("date", "load") %>%
  convert(dte(date, .args = list(format = "%m/%d/%Y")))

Gives:

# A tibble: 16 x 2
   date        load
   <date>     <dbl>
 1 2017-03-29  32.7
 2 2017-03-29  20.5
 3 2017-03-29  24.1
 4 2017-03-29  24.9
 5 2017-04-05  31.6


问:
Selecting all checkboxes in a table when a single checkbox is clicked
I have a table that populates a table row with data when a checkbox in the rows first column is clicked. That part is working correctly. There is a header column with a 'Select All' checkbox. When that checkbox is selected, all rows should be populated and corresponding checkbox selected. This is working correctly on IE, but on Chrome and Firefox the data is populating but the checkboxes are not being selected. Any ideas?</p>

```<code>$('.selectAll input[type="checkbox"]').change(function () {

    var thistable = $(this).parents('table');
    if (this.checked) {

        populateOptions(thistable);
        thistable.find('.hiddenUntilOrder').addClass('showItems');
        thistable.find('tr').each(function () {
            $(this).find('.distribution').rules("add", { required: true, messages: { required: "" } });
        });
        thistable.find('.checkbox').prop("checked", true);

    } else {
        thistable.find('.hiddenUntilOrder').removeClass('showItems').rules("remove");
        thistable.find('tr').each(function () {
            $(this).find('.distribution').rules("remove");
        });
        thistable.find('.checkbox').prop("checked", false);
    }
});
</code>```

答:
I have just coded in fiddle. Please look into it.

```<code>$(document).ready(function(){
  $('#selectAll').click(function(){
        $('.selectRow').prop('checked', true);

      if(!$(this).prop("checked")) {
            $('.selectRow').prop('checked', false);
      }
  });

  $('.selectRow').change(function() {
        if(!$(this).prop("checked")) {
          $('#selectAll').prop('checked', false);
      } else {
         if ($('.selectRow:checked').length === $('.selectRow').length) {
             $('#selectAll').prop('checked', true);
         }
      }
  });
});
</code>```

https://jsfiddle.net/sbwfcxnr/2/

Body:
I have a table that populates a table row with data when a checkbox in the rows first column is clicked. That part is working correctly. There is a header column with a 'Select All' checkbox. When that checkbox is selected, all rows should be populated and corresponding checkbox selected. This is working correctly on IE, but on Chrome and Firefox the data is populating but the checkboxes are not being selected. Any ideas?

$('.selectAll input[type="checkbox"]').change(function () {

    var thistable = $(this).parents('table');
    if (this.checked) {

        populateOptions(thistable);
        thistable.find('.hiddenUntilOrder').addClass('showItems');
        thistable.find('tr').each(function () {
            $(this).find('.distribution').rules("add", { required: true, messages: { required: "" } });
        });
        thistable.find('.checkbox').prop("checked", true);

    } else {
        thistable.find('.hiddenUntilOrder').removeClass('showItems').rules("remove");
        thistable.find('tr').each(function () {
            $(this).find('.distribution').rules("remove");
        });
        thistable.find('.checkbox').prop("checked", false);
    }
});

Body:
I have just coded in fiddle. Please look into it.

$(document).ready(function(){
  $('#selectAll').click(function(){
        $('.selectRow').prop('checked', true);

      if(!$(this).prop("checked")) {
            $('.selectRow').prop('checked', false);
      }
  });

  $('.selectRow').change(function() {
        if(!$(this).prop("checked")) {
          $('#selectAll').prop('checked', false);
      } else {
         if ($('.selectRow:checked').length === $('.selectRow').length) {
             $('#selectAll').prop('checked', true);
         }
      }
  });
});

https://jsfiddle.net/sbwfcxnr/2/


问:
Create a Redirect with additional query params for another plugin
I use the news plugin where I add an another Plugin (lets call it 'Form') as a CE für the Detail view.

When I fill out the Form in the Detail view and submit it, then my redirect inside my Controller only passes the Arguments for my Extension.

$this->redirect('success');

But I would like that he also pass the Arguments for the News extensions, so that I land at the Details view of the news and my Form plugin gets his other action informations from the redirect.

But as far as I can see, the redirect method only takes arguments for one plugin.

Did anyone have an Idea?

答:
The redirect function only allows arguments for the controller/action you are redirecting to. There is no way to add other get parameters.

The only way to do this is to create the URL yourself and use the redirectToUri function. That would make it something like:

```<code>$uriBuilder = $this->getControllerContext()->getUriBuilder();
$uri = $uriBuilder->reset()
  ->setTargetPageUid(1)
  ->setArguments($newsArgs)
  ->uriFor('success');
$this->redirectToUri($uri);
</code>```

Body:
The redirect function only allows arguments for the controller/action you are redirecting to. There is no way to add other get parameters.

The only way to do this is to create the URL yourself and use the redirectToUri function. That would make it something like:

$uriBuilder = $this->getControllerContext()->getUriBuilder();
$uri = $uriBuilder->reset()
  ->setTargetPageUid(1)
  ->setArguments($newsArgs)
  ->uriFor('success');
$this->redirectToUri($uri);


问:
Is a synchronous void method with Func<Task> or Func<Task<T>> arguments practically useful?
I am teaching async-await keyword to my friends and up to now I gave them some examples as follows.

```<code>static async Task Do(Func<Task> job)
{
    // some algorithm depends on job parameter.
    await job();
}
</code>```

I think this example is practically useful in many scenarios.

Question

Is there any usefulness of having void methods with arguments of type Func<Task> or Func<Task<T>>? As far as I think, it does make sense for this kind of method to exist because blocking asynchronous methods are not recommended. Any comments are always welcome!

答:
Yes, having non-asynchronous methods executing delegates can be useful, for example the LINQ queries provided by .Net.

Sometimes you want the application to block until a specific result has been returned by the callee.

Let's take the List.ForEach(Action) method for example.

(NOTE: This is NOT the actual implementation is it would be in .Net!)

```<code>public void ForEach(Action<T> action) {
    if (action is default(Action<T>))
        throw new ArgumentNullException(nameof(action), "Action must not be null!");

    foreach (var element in this) {
        // Execute provided action (delegate)
        action(T);

    }
}
</code>```

In this case, you want the loop to run synchronously, because of thread-safety for example.

Another example would be the public static System.Collections.Generic.IEnumerable<TSource> Where<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate); method, which would also run synchronously, for thread safety reasons and so your results are returned as expected.

You can also always call the methods from a separate thread (or async method) if required. Most console applications run synchronously, as there is no GUI that needs to be responsive.

EDIT

Another example of synchronous methods with Func as the parameter would be a console application. Say you're implementing a console application with a library dependency (which you have no control over). This library only exposes tasks.
In a console application you generally don't use/need asynchronous applications as there's no GUI that can block and/or your application should only continue after the user has given input.

```<code>// External method returning a Task
public Task<int> DoFooAsync(object myParam);

public bool ParseMyFoo(Func<Task<int>> myTask) {
    var result = myTask().Result;

    if (result == 0xbadbeef || result == 0xf00dbabe) {
        Console.WriteLine("Schrödingers takeaway");
    }
}

public static void Main(string[] args) {
    Console.WriteLine("Assesment: {0}", ParseMyFoo(DooFooAsync(Console.ReadLine()));
}
</code>```

Body:
I am teaching async-await keyword to my friends and up to now I gave them some examples as follows.

static async Task Do(Func<Task> job)
{
    // some algorithm depends on job parameter.
    await job();
}

I think this example is practically useful in many scenarios.

Question

Is there any usefulness of having void methods with arguments of type Func<Task> or Func<Task<T>>? As far as I think, it does make sense for this kind of method to exist because blocking asynchronous methods are not recommended. Any comments are always welcome!

Body:
Yes, having non-asynchronous methods executing delegates can be useful, for example the LINQ queries provided by .Net.

Sometimes you want the application to block until a specific result has been returned by the callee.

Let's take the List.ForEach(Action) method for example.

(NOTE: This is NOT the actual implementation is it would be in .Net!)

public void ForEach(Action<T> action) {
    if (action is default(Action<T>))
        throw new ArgumentNullException(nameof(action), "Action must not be null!");

    foreach (var element in this) {
        // Execute provided action (delegate)
        action(T);

    }
}

In this case, you want the loop to run synchronously, because of thread-safety for example.

Another example would be the public static System.Collections.Generic.IEnumerable<TSource> Where<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate); method, which would also run synchronously, for thread safety reasons and so your results are returned as expected.

You can also always call the methods from a separate thread (or async method) if required. Most console applications run synchronously, as there is no GUI that needs to be responsive.

EDIT

Another example of synchronous methods with Func as the parameter would be a console application. Say you're implementing a console application with a library dependency (which you have no control over). This library only exposes tasks.
In a console application you generally don't use/need asynchronous applications as there's no GUI that can block and/or your application should only continue after the user has given input.

// External method returning a Task
public Task<int> DoFooAsync(object myParam);

public bool ParseMyFoo(Func<Task<int>> myTask) {
    var result = myTask().Result;

    if (result == 0xbadbeef || result == 0xf00dbabe) {
        Console.WriteLine("Schrödingers takeaway");
    }
}

public static void Main(string[] args) {
    Console.WriteLine("Assesment: {0}", ParseMyFoo(DooFooAsync(Console.ReadLine()));
}


问:
Nested FormGroups in FormArray not working
I have a simple reactive form with a FormArray that will contain FromGroups.

I know this has been asked many times, but I can't still figure out why it's not working. I've tried many ways. This is are two simplified examples put together with what I've read from the docs and found online.

Component:

@Component({
  selector: 'app-professional-info-form',
  templateUrl: './professional-info-form.component.html',
  styleUrls: ['./professional-info-form.component.scss']
})
export class ProfessionalInfoFormComponent implements OnInit {

  protected professionalInfo: FormGroup;

  constructor() { }

  ngOnInit() {
    this.initForm();
  }

  private initForm() {
    this.professionalInfo = new FormGroup({
      trainings: new FormArray([
        new FormGroup({
          institutionId: new FormControl(null, null),
          title: new FormControl(null, null),
          description: new FormControl(null, null),
          institution: new FormControl(null, Validators.required),
          grade: new FormControl(null, null),
          from: new FormControl(null, Validators.required),
          to: new FormControl(null, null)
        })
      ])
    });

  }

}
```
<p>HTML:</p>
```<form [formGroup]="professionalInfo" (ngSubmit)="onSubmit()" novalidate *ngIf="professionalInfo">

      <input type="text" [formControlName]="title" placeholder="Titolo" />
      <input type="text" [formControlName]="institution" placeholder="Istituto" />
      <input type="text" placeholder="Inizio" [formControlName]="from">
      <input type="text" placeholder="Fine" [formControlName]="to">
      <input type="text" placeholder="Voto" [formControlName]="grade" maxlength="5">

</form>
```
<p>Console error:</p>
```ERROR TypeError: Cannot read property 'controls' of undefined
    at Object.eval [as updateDirectives] (ProfessionalInfoFormComponent.html:19)
```
<p>If I add this method to the component:</p>
<pre class="lang-js prettyprint-override"><code>get trainingsFormArray() {
    return (<FormArray>this.professionalInfo.get('trainings'));
  }
</code>```

And edit the *ngFor like this:

```<code><div *ngFor="let training of trainingsFormArray.controls; index as t" [formGroupName]="t">
</code>```

The console error is:

```<code>ERROR Error: Cannot find control with path: 'trainings -> 0 -> '
</code>```

Which is kind of crazy because if console.log 'trainingsFormArray' after initializing the form the output is the following:

console.log output

Every time I have to work with angular's reactive forms I encounter problems like this one. I can't seem to figure out a consistent way for making them work with dynamic controls like in this case. Please help me.

答:
There's an issue in your template. Angular doesn't know what trainings is. Use professionalInfo.controls['trainings'].controls to have access to the controls in the trainings FormArray instead.

Something like this:

```<code><form
  [formGroup]="professionalInfo"
  (ngSubmit)="onSubmit()"
  novalidate
  *ngIf="professionalInfo">
  <div formArrayName="trainings">
    <div
      *ngFor="let training of professionalInfo.controls['trainings'].controls; index as t"
      [formGroupName]="t">
      <input type="text" formControlName="title" placeholder="Titolo" />
      <input type="text" formControlName="institution" placeholder="Istituto" />
      <input type="text" placeholder="Inizio" formControlName="from">
      <input type="text" placeholder="Fine" formControlName="to">
      <input type="text" placeholder="Voto" formControlName="grade" maxlength="5">
    </div>
  </div>
</form>
</code>```

Here's a Working Sample StackBlitz for your ref.

Body:
I have a simple reactive form with a FormArray that will contain FromGroups.

I know this has been asked many times, but I can't still figure out why it's not working. I've tried many ways. This is are two simplified examples put together with what I've read from the docs and found online.

Component:

@Component({
  selector: 'app-professional-info-form',
  templateUrl: './professional-info-form.component.html',
  styleUrls: ['./professional-info-form.component.scss']
})
export class ProfessionalInfoFormComponent implements OnInit {

  protected professionalInfo: FormGroup;

  constructor() { }

  ngOnInit() {
    this.initForm();
  }

  private initForm() {
    this.professionalInfo = new FormGroup({
      trainings: new FormArray([
        new FormGroup({
          institutionId: new FormControl(null, null),
          title: new FormControl(null, null),
          description: new FormControl(null, null),
          institution: new FormControl(null, Validators.required),
          grade: new FormControl(null, null),
          from: new FormControl(null, Validators.required),
          to: new FormControl(null, null)
        })
      ])
    });

  }

}

HTML:

<form [formGroup]="professionalInfo" (ngSubmit)="onSubmit()" novalidate *ngIf="professionalInfo">

      <input type="text" [formControlName]="title" placeholder="Titolo" />
      <input type="text" [formControlName]="institution" placeholder="Istituto" />
      <input type="text" placeholder="Inizio" [formControlName]="from">
      <input type="text" placeholder="Fine" [formControlName]="to">
      <input type="text" placeholder="Voto" [formControlName]="grade" maxlength="5">

</form>

Console error:

ERROR TypeError: Cannot read property 'controls' of undefined
    at Object.eval [as updateDirectives] (ProfessionalInfoFormComponent.html:19)

If I add this method to the component:

get trainingsFormArray() {
    return (<FormArray>this.professionalInfo.get('trainings'));
  }

And edit the *ngFor like this:

The console error is:

ERROR Error: Cannot find control with path: 'trainings -> 0 -> '

Which is kind of crazy because if console.log 'trainingsFormArray' after initializing the form the output is the following:

console.log output

Every time I have to work with angular's reactive forms I encounter problems like this one. I can't seem to figure out a consistent way for making them work with dynamic controls like in this case. Please help me.

Body:
There's an issue in your template. Angular doesn't know what trainings is. Use professionalInfo.controls['trainings'].controls to have access to the controls in the trainings FormArray instead.

Something like this:

<form
  [formGroup]="professionalInfo"
  (ngSubmit)="onSubmit()"
  novalidate
  *ngIf="professionalInfo">
  <div formArrayName="trainings">
    <div
      *ngFor="let training of professionalInfo.controls['trainings'].controls; index as t"
      [formGroupName]="t">
      <input type="text" formControlName="title" placeholder="Titolo" />
      <input type="text" formControlName="institution" placeholder="Istituto" />
      <input type="text" placeholder="Inizio" formControlName="from">
      <input type="text" placeholder="Fine" formControlName="to">
      <input type="text" placeholder="Voto" formControlName="grade" maxlength="5">
    </div>
  </div>
</form>

Here's a Working Sample StackBlitz for your ref.


问:
WTForms-How to prepopulate a textarea field?
Hi I have been trying to pepopulate a textareafield using something
like this in the template.

```<code>{{form.content(value="please type content")}}
</code>```

This works when the field is textfield primarily because the html
accepts value for <input type="text">
but the same does not work for textarea...
Can someone please help me with this?

答:
Alice there seems to be support built into the form widget to do what you are after but you are right it doesn't work at the moment.

Sean and hilquias post decent work arounds which do work. This is the form (yuk yuk) you might try

```<code> else:
        form.title.data=blog.title
        form.blogdata.data=blog.blogdata
    return render_template('editblog.html',form=form)
</code>```

Body:
Hi I have been trying to pepopulate a textareafield using something
like this in the template.

{{form.content(value="please type content")}}

This works when the field is textfield primarily because the html
accepts value for <input type="text">
but the same does not work for textarea...
Can someone please help me with this?

Body:
Alice there seems to be support built into the form widget to do what you are after but you are right it doesn't work at the moment.

Sean and hilquias post decent work arounds which do work. This is the form (yuk yuk) you might try

 else:
        form.title.data=blog.title
        form.blogdata.data=blog.blogdata
    return render_template('editblog.html',form=form)