问:
Refresh datalist in view after user finishes typing in textbox Angular 7
I am trying to refresh a datalist in the view after waiting for user to finish typing in the textbox and updating results. Tried with angular directives, tried with Observable and various timeouts and debounces and no luck. I ran out of options.

In the html file:

```<code>            <input type="text" class="form-control" id="Other"
            (keyup)="onKeySearch($event)" list="dynamicList" formControlName="Other"/>

            <datalist id="dynamicList">
                <option *ngFor="let employee of employeesList" [value]="employee.Name">
                    {{employee.Name}}</option>
            </datalist>
</code>```

in the .ts file:

```<code>  public employeesList: EmployeeData[] = [];

  timeout: any = null;

  getEmployeesList(name : string) {
      let empList: EmployeeData[] = [];

      // get employees list from service
      this.employeeService.getEmployeesList(name).subscribe((data: any) => {
        empList = data;
        console.log(empList)
      })
      return empList;
    }

  public onKeySearch(event: any) {
    let empListt: EmployeeData[] = [];

    clearTimeout(this.timeout);
    var $this = this;
    this.timeout = setTimeout(() => {
        empListt = $this.getEmployeesList(event.target.value);
        console.log(empListt)
    }, 1000);
    this.employeesList = empListt;
  }
</code>```

The problem is that the datalist is not updates after retrieving the data an populating the list. After it exists the method the list is again empty, thus no data to display.

I have added stackblitz example code with similar code as above (same behavior):

.ts file:

```<code>import { Component, VERSION, OnInit } from "@angular/core";
import { FormControl } from "@angular/forms";
import { distinctUntilChanged, debounceTime, tap } from "rxjs/operators";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  searchControl = new FormControl("");
  message = "";
  public employeesList: string[] = [];

  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(
        tap(() => (this.message = "User is typing...")),
        distinctUntilChanged(),
        debounceTime(1000)
      )
      .subscribe(res => {
        this.message = "User finished typing!";
        this.employeesList.push('1');
        this.employeesList.push('2');
        this.employeesList.push('3');
      });
  }
}
</code>```

.html file:

```<code><input [formControl]="searchControl" list="dynamicList">

<datalist id="dynamicList">
    <option *ngFor="let employee of employeesList">
        {{employee}}</option>
</datalist>

<span> {{message}} </span>
</code>```

答:
Your formControl (called 'Other', for some reason) has an event that is emitted as an Observable on each change. You can subscribe to that event, and use the RxJS operator debounceTime() to specify how many milliseconds should it wait for the user to stop typing until the event is emitted.

I have created a simple DEMO, maybe it's easier to understand.

Good luck!

Body:
I am trying to refresh a datalist in the view after waiting for user to finish typing in the textbox and updating results. Tried with angular directives, tried with Observable and various timeouts and debounces and no luck. I ran out of options.

In the html file:

            <input type="text" class="form-control" id="Other"
            (keyup)="onKeySearch($event)" list="dynamicList" formControlName="Other"/>

            <datalist id="dynamicList">
                <option *ngFor="let employee of employeesList" [value]="employee.Name">
                    {{employee.Name}}</option>
            </datalist>

in the .ts file:

  public employeesList: EmployeeData[] = [];

  timeout: any = null;

  getEmployeesList(name : string) {
      let empList: EmployeeData[] = [];

      // get employees list from service
      this.employeeService.getEmployeesList(name).subscribe((data: any) => {
        empList = data;
        console.log(empList)
      })
      return empList;
    }

  public onKeySearch(event: any) {
    let empListt: EmployeeData[] = [];

    clearTimeout(this.timeout);
    var $this = this;
    this.timeout = setTimeout(() => {
        empListt = $this.getEmployeesList(event.target.value);
        console.log(empListt)
    }, 1000);
    this.employeesList = empListt;
  }

The problem is that the datalist is not updates after retrieving the data an populating the list. After it exists the method the list is again empty, thus no data to display.

I have added stackblitz example code with similar code as above (same behavior):

.ts file:

import { Component, VERSION, OnInit } from "@angular/core";
import { FormControl } from "@angular/forms";
import { distinctUntilChanged, debounceTime, tap } from "rxjs/operators";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  searchControl = new FormControl("");
  message = "";
  public employeesList: string[] = [];

  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(
        tap(() => (this.message = "User is typing...")),
        distinctUntilChanged(),
        debounceTime(1000)
      )
      .subscribe(res => {
        this.message = "User finished typing!";
        this.employeesList.push('1');
        this.employeesList.push('2');
        this.employeesList.push('3');
      });
  }
}

.html file:

<input [formControl]="searchControl" list="dynamicList">

<datalist id="dynamicList">
    <option *ngFor="let employee of employeesList">
        {{employee}}</option>
</datalist>

 {{message}}


来源: stackexchange

问:
Rename remote branch without deleting it
I need your help to rename a remote branch.

I created a PR but now I need to rename the remote branch name.

I don't want to follow the process where I have to rename the local branch then push and delete the old branch because it will clear the PR.

Is there a way to just rename the remote branch and PR should stay as it is. thanks.

答:
Renaming a remote branch in Git is really just creating a new branch with same commits and new name and deleting old branch. Depending on where you have pull request open (you don't mention whether is it Github, Gitlab, Phabricator or something else) you might have some options given to you by tool operating on repository locally where pull request exists. I can say only for Github that there's no option to rename a branch in their interface nor option to change "compare" branch in a pull request.

Best solution (for Github) is probably to create a new branch and new pull request, post a comment to old pull-request that it was "closed in favor of #NEW" and "continuation of #OLD" to new one. Then delete old branch which will also close the old pull-request.

Quick oneliner for deleting old branch and creating a new one with same content is:

```<code>git push <remote> <remote>/<old>:refs/heads/<new> :<old>
</code>```

where remote is obvious - e.g. origin, old and new are names of branches old and new respectively.

ContentLicense: CC BY-SA 4.0

Body:
Renaming a remote branch in Git is really just creating a new branch with same commits and new name and deleting old branch. Depending on where you have pull request open (you don't mention whether is it Github, Gitlab, Phabricator or something else) you might have some options given to you by tool operating on repository locally where pull request exists. I can say only for Github that there's no option to rename a branch in their interface nor option to change "compare" branch in a pull request.

Best solution (for Github) is probably to create a new branch and new pull request, post a comment to old pull-request that it was "closed in favor of #NEW" and "continuation of #OLD" to new one. Then delete old branch which will also close the old pull-request.

Quick oneliner for deleting old branch and creating a new one with same content is:

git push <remote> <remote>/<old>:refs/heads/<new> :<old>

where remote is obvious - e.g. origin, old and new are names of branches old and new respectively.


问:
Vuetify data table in single-select mode, selecting one row selects all others
I am trying to select one row in the table and emit the selected item.

Selecting one selects all but only the first encountered object is saved to the model (as selected variable).

Do you have any ideas, what i'm doing wrong?

<template>
  <v-data-table
    :headers="headers"
    :items="items"
    :search="search"
    :loading="loading"
    v-model="selected"
    single-select
    show-select
    :options="{itemsPerPage:5}"
    @item-selected="itemSelected"
  >
    <template v-slot:top>
      <v-toolbar flat>
        <v-text-field
          v-model="search"
          append-icon="mdi-magnify"
          label="Search"
          single-line
          hide-details
        ></v-text-field>
      </v-toolbar>
    </template>

    <template v-slot:item.name="{ item }">{{ item.name }}</template>
  </v-data-table>
</template>

```

答:
From the example in the docs I can see the following:

1.) selected should be an array, not an object

Selected holds all selected values. single-select property just determines if the length can be bigger than 1.

2.) if you use v-model you should not use @item-selected="itemSelected"

v-model is already 2 way binding. but you trigger an additional event and override the model (which should be an array) with an object or null

Solution

Make selected an array and remove @item-selected="itemSelected".

```<code><template>
  <v-data-table
    :headers="headers"
    :items="items"
    :search="search"
    :loading="loading"
    v-model="selected"
    single-select
    show-select
    :options="{itemsPerPage:5}"
  >
    <template v-slot:top>
      <v-toolbar flat>
        <v-text-field
          v-model="search"
          append-icon="mdi-magnify"
          label="Search"
          single-line
          hide-details
        ></v-text-field>
      </v-toolbar>
    </template>

    <template v-slot:item.name="{ item }">{{ item.name }}</template>
  </v-data-table>
</template>

<script>
export default {
  name: "variable-selector",
  props: ["variables", "map", "index"],
  data() {
    return {
      search: "",
      selected: [],
      loading: false,
      items: [],
      headers: [{ text: "Variable name", value: "name", sortable: true }]
    };
  },
  methods: {
    updateItemsList(variables) {
      this.items = Array.from(variables);
    }
  },

  mounted() {
    this.updateItemsList(this.variables);
  },

  watch: {
    variables(newValue) {
      this.loading = true;
      this.updateItemsList(newValue);
      this.loading = false;
    }
  }
};
</script>
</code>```

Body:
From the example in the docs I can see the following:

1.) selected should be an array, not an object

Selected holds all selected values. single-select property just determines if the length can be bigger than 1.

2.) if you use v-model you should not use @item-selected="itemSelected"

v-model is already 2 way binding. but you trigger an additional event and override the model (which should be an array) with an object or null

Solution

Make selected an array and remove @item-selected="itemSelected".

<template>
  <v-data-table
    :headers="headers"
    :items="items"
    :search="search"
    :loading="loading"
    v-model="selected"
    single-select
    show-select
    :options="{itemsPerPage:5}"
  >
    <template v-slot:top>
      <v-toolbar flat>
        <v-text-field
          v-model="search"
          append-icon="mdi-magnify"
          label="Search"
          single-line
          hide-details
        ></v-text-field>
      </v-toolbar>
    </template>

    <template v-slot:item.name="{ item }">{{ item.name }}</template>
  </v-data-table>
</template>

<script>
export default {
  name: "variable-selector",
  props: ["variables", "map", "index"],
  data() {
    return {
      search: "",
      selected: [],
      loading: false,
      items: [],
      headers: [{ text: "Variable name", value: "name", sortable: true }]
    };
  },
  methods: {
    updateItemsList(variables) {
      this.items = Array.from(variables);
    }
  },

  mounted() {
    this.updateItemsList(this.variables);
  },

  watch: {
    variables(newValue) {
      this.loading = true;
      this.updateItemsList(newValue);
      this.loading = false;
    }
  }
};
</script>


问:
How do I create an array of pointers?
I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it?
What I have now is:

```<code>Student * db = new Student[5];
</code>```

But each element in that array is the student object, not a pointer to the student object.
Thanks.

答:
```<code>#include <vector>
std::vector <Student *> db(5);
// in use
db[2] = & someStudent;
</code>```

<p>The advantage of this is that you don't have to worry about deleting the allocated storage - the vector does it for you. </p>

OwnerDisplayName: chustar

ContentLicense: CC BY-SA 2.5

Title: How do I create an array of pointers?

Body:
I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it?
What I have now is:

Student * db = new Student[5];

But each element in that array is the student object, not a pointer to the student object.
Thanks.

Body:
#include <vector>
std::vector <Student *> db(5);
// in use
db[2] = & someStudent;

The advantage of this is that you don't have to worry about deleting the allocated storage - the vector does it for you.

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
ScrollView moved AdMob ads
Well before my ads were working fine and were always at the bottom of the screen, but now I added a scrollview and the ads move up a little bit to be right under my scrollbar.

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/pattern_carbon_fiber_dark">

<ScrollView android:id="@+id/ScrollView01"
android:layout_width="wrap_content" android:layout_height="339px">

<LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">

<TextView android:text="Silent Mode" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/silent_textview"></TextView>
<ToggleButton android:layout_height="wrap_content" android:text="Silent Mode" android:id="@+id/silentbutton" android:layout_width="wrap_content" android:textOff="OFF" android:textOn="ON"></ToggleButton>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Wifi " android:id="@+id/wifi_textview"></TextView>
<ToggleButton android:layout_width="wrap_content" android:text="ToggleButton" android:layout_height="wrap_content" android:id="@+id/wifibutton"></ToggleButton>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/gps" android:id="@+id/gps_textview"></TextView>
<Button android:text="@string/gpsbutton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/gps"></Button>
<TextView android:layout_width="wrap_content" android:text="@string/bluetooth" android:layout_height="wrap_content" android:id="@+id/bluetooth_textview"></TextView>
<ToggleButton android:layout_width="wrap_content" android:text="ToggleButton" android:id="@+id/bluetooth" android:layout_height="wrap_content"></ToggleButton>
<TextView android:text="@string/brightness" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/screenbrightness_textview"></TextView>
<SeekBar android:layout_height="wrap_content" android:id="@+id/SbBar" android:layout_width="fill_parent" android:max="255"></SeekBar>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content" android:layout_width="wrap_content">

<com.google.ads.AdView
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/adView"
android:layout_width="fill_parent"
ads:adSize="BANNER"
ads:adUnitId="a14ddb1a61b9fb4"
ads:loadAdOnCreate="true"
android:visibility="visible"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:layout_height="wrap_content"
android:layout_alignParentTop="false">
</com.google.ads.AdView>

 </RelativeLayout>
 </LinearLayout>
 </ScrollView>
 </LinearLayout>
</code>```

Please help, thanks!

EDIT: Picture

UI pic http://img52.imageshack.us/img52/9397/unledyv.png

答:
Why don't you try using a relative layout as the root layout.</p>

```<code><RelativeLayout>
<LinearLayout
android:layout_alignParentTop="true">
ETC
</LinearLayout>
<com.google.ads.AdView
android:layout_alignParentBottom="true">
</com.google.ads.AdView>
</RelativeLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Title: ScrollView moved AdMob ads

Body:
Well before my ads were working fine and were always at the bottom of the screen, but now I added a scrollview and the ads move up a little bit to be right under my scrollbar.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/pattern_carbon_fiber_dark">

<ScrollView android:id="@+id/ScrollView01"
android:layout_width="wrap_content" android:layout_height="339px">

<LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">

<TextView android:text="Silent Mode" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/silent_textview"></TextView>
<ToggleButton android:layout_height="wrap_content" android:text="Silent Mode" android:id="@+id/silentbutton" android:layout_width="wrap_content" android:textOff="OFF" android:textOn="ON"></ToggleButton>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Wifi " android:id="@+id/wifi_textview"></TextView>
<ToggleButton android:layout_width="wrap_content" android:text="ToggleButton" android:layout_height="wrap_content" android:id="@+id/wifibutton"></ToggleButton>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/gps" android:id="@+id/gps_textview"></TextView>
<Button android:text="@string/gpsbutton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/gps"></Button>
<TextView android:layout_width="wrap_content" android:text="@string/bluetooth" android:layout_height="wrap_content" android:id="@+id/bluetooth_textview"></TextView>
<ToggleButton android:layout_width="wrap_content" android:text="ToggleButton" android:id="@+id/bluetooth" android:layout_height="wrap_content"></ToggleButton>
<TextView android:text="@string/brightness" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/screenbrightness_textview"></TextView>
<SeekBar android:layout_height="wrap_content" android:id="@+id/SbBar" android:layout_width="fill_parent" android:max="255"></SeekBar>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content" android:layout_width="wrap_content">

<com.google.ads.AdView
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/adView"
android:layout_width="fill_parent"
ads:adSize="BANNER"
ads:adUnitId="a14ddb1a61b9fb4"
ads:loadAdOnCreate="true"
android:visibility="visible"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:layout_height="wrap_content"
android:layout_alignParentTop="false">
</com.google.ads.AdView>

 </RelativeLayout>
 </LinearLayout>
 </ScrollView>
 </LinearLayout>

Please help, thanks!

EDIT: Picture

UI pic http://img52.imageshack.us/img52/9397/unledyv.png

Body:
Why don't you try using a relative layout as the root layout.

<RelativeLayout>
<LinearLayout
android:layout_alignParentTop="true">
ETC
</LinearLayout>
<com.google.ads.AdView
android:layout_alignParentBottom="true">
</com.google.ads.AdView>
</RelativeLayout>


问:
Spatial querydsl - GeometryExpressions. Find entities that range contains given "Point"
Used tools and their versions:

I am using:

spring boot 2.2.6

hibernate/hibernate-spatial 5.3.10 with dialect set to: org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect

querydsl-spatial 4.2.1

com.vividsolutions.jts 1.13

jscience 4.3.1

Problem description:

I have an entity that represents medical-clinic:

```<code>import com.vividsolutions.jts.geom.Polygon;

@Entity
public class Clinic {

    @Column(name = "range", columnDefinition = "Polygon")
    private Polygon range;
}
</code>```

The range is a circle calculated earlier based on the clinic's gps-location and radius. It represents the operating area for that clinic. That means that it treats only patients with their home address lying within that circle. Let's assume that above circle, is correct.

My goal (question):

I have a gps point with a patient location: 45.7602322 4.8444941. I would like to find all clinics that are able to treat that patient. That means, to find all the clinics that their range field contains 45.7602322 4.8444941.

My solution (partially correct (I think))

To get it done, I have created a simple "Predicate"/"BooleanExpression":

```<code>GeometryExpressions.asGeometry(QClinic.clinic.range)
                .contains(Wkt.fromWkt("Point(45.7602322 4.8444941)"))
</code>```

and it actualy works, because I can see proper sql query in console:

```<code>select (...) where
    ST_Contains(clinic0_.range, ?)=1 limit ?
</code>```

first binding param: POINT(45.7602322 4.8444941)

But I have two problems with that:

QClinic.clinic.range is marked as "warning" in intellij as: "Unchecked assignment: 'com.querydsl.spatial.jts.JTSPolygonPath' to 'com.querydsl.core.types.Expression<org.geolatte.geom.Geometry'". Yes, in QClinic  range is com.querydsl.spatial.jts.JTSPolygonPath

Using debugger and intellij's "evaluate" on the above line (that creates the expression) i can see that there is an error message: "unknown operation with operator CONTAINS and args [clinic.range, POINT(45.7602322 4.8444941)]"

答:
You can ignore the second warning. The spatial specific operations are simply not registered in the serializer used for the toString of the operation. They reside in their own module.

The first warning indicates that you're mixing up Geolatte and JTS expressions. From your mapping it seems you intend to use JTS. In that case you need to use com.querydsl.spatial.jts.JTSGeometryExpressions instead of com.querydsl.spatial.jts.GeometryExpressions in order to get rid of that warning.

Body:
Used tools and their versions:

I am using:

spring boot 2.2.6

hibernate/hibernate-spatial 5.3.10 with dialect set to: org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect

querydsl-spatial 4.2.1

com.vividsolutions.jts 1.13

jscience 4.3.1

Problem description:

I have an entity that represents medical-clinic:

import com.vividsolutions.jts.geom.Polygon;

@Entity
public class Clinic {

    @Column(name = "range", columnDefinition = "Polygon")
    private Polygon range;
}

The range is a circle calculated earlier based on the clinic's gps-location and radius. It represents the operating area for that clinic. That means that it treats only patients with their home address lying within that circle. Let's assume that above circle, is correct.

My goal (question):

I have a gps point with a patient location: 45.7602322 4.8444941. I would like to find all clinics that are able to treat that patient. That means, to find all the clinics that their range field contains 45.7602322 4.8444941.

My solution (partially correct (I think))

To get it done, I have created a simple "Predicate"/"BooleanExpression":

GeometryExpressions.asGeometry(QClinic.clinic.range)
                .contains(Wkt.fromWkt("Point(45.7602322 4.8444941)"))

and it actualy works, because I can see proper sql query in console:

select (...) where
    ST_Contains(clinic0_.range, ?)=1 limit ?

first binding param: POINT(45.7602322 4.8444941)

But I have two problems with that:

QClinic.clinic.range is marked as "warning" in intellij as: "Unchecked assignment: 'com.querydsl.spatial.jts.JTSPolygonPath' to 'com.querydsl.core.types.Expression<org.geolatte.geom.Geometry'". Yes, in QClinic  range is com.querydsl.spatial.jts.JTSPolygonPath

Using debugger and intellij's "evaluate" on the above line (that creates the expression) i can see that there is an error message: "unknown operation with operator CONTAINS and args [clinic.range, POINT(45.7602322 4.8444941)]"


问:
Is it possible to build a Qt project using external libraries
I made a project using OpenCV library that works perfectly on my computer when I run the .exe but it doesn't when I open it in other computers. I placed all QT and Opencv dlls used in the same folder but still when I run it stays loading for a while and then nothing happens.

Is there a right way to include/embed an external library in the files?

答:
Check out https://github.com/brechtsanders/pedeps/releases

It contains a tool copypedeps which with the -r parameter recursively copies all of the dependancies along with the executable.

Also, you should probably copy the Qt's plugins folder (the entire folder itself, not its contents) into the folder where your .exe and .dll files are.


问:
java.lang.NoClassDefFoundError exception: gherkin/util/FixJava while running cucumber test using JUnit
I'm trying to run a cucumber test with JUnit and getting exception

```<code>java.lang.NoClassDefFoundError: gherkin/util/FixJava
</code>```

RunnerClass:

```<code>import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;

    @RunWith(Cucumber.class)
    @Cucumber.Options(
            features = ".//FeatureFile", //the path of the feature files
            glue= "StepDfb"
            )

    public class RunTest {

    }
</code>```

Exception stacktrace

```<code>java.lang.NoClassDefFoundError: gherkin/util/FixJava
    at cucumber.runtime.RuntimeOptions.<clinit>(RuntimeOptions.java:25)
    at cucumber.junit.RuntimeOptionsFactory.create(RuntimeOptionsFactory.java:30)
    at cucumber.junit.Cucumber.<init>(Cucumber.java:56)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:87)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:73)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:523)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: java.lang.ClassNotFoundException: gherkin.util.FixJava
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 20 more
</code>```

I have added the below Cucumber jar files to Eclipse and added the cucumber plugin to eclipse

```<code>    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.47.1</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.0.2</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm</artifactId>
        <version>1.2.5</version>
        <type>pom</type>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm-deps</artifactId>
        <version>1.0.5</version>
    </dependency>

    <dependency>
        <groupId>net.masterthought</groupId>
        <artifactId>cucumber-reporting</artifactId>
        <version>1.0.0</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>gherkin</artifactId>
        <version>2.12.2</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.0.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>

</dependencies>
</code>```

Any help to fix this issue is much appreciated

答:
The way is you download gherkin-2.12.2.jar, gherkin-2.12.2-sources.jar
files from https://repo1.maven.org/maven2/info/cukes/gherkin/2.12.2/ and add them in your library.</p>

Body:
I'm trying to run a cucumber test with JUnit and getting exception

java.lang.NoClassDefFoundError: gherkin/util/FixJava

RunnerClass:

import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;

    @RunWith(Cucumber.class)
    @Cucumber.Options(
            features = ".//FeatureFile", //the path of the feature files
            glue= "StepDfb"
            )

    public class RunTest {

    }

Exception stacktrace

java.lang.NoClassDefFoundError: gherkin/util/FixJava
    at cucumber.runtime.RuntimeOptions.<clinit>(RuntimeOptions.java:25)
    at cucumber.junit.RuntimeOptionsFactory.create(RuntimeOptionsFactory.java:30)
    at cucumber.junit.Cucumber.<init>(Cucumber.java:56)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:87)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:73)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:523)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: java.lang.ClassNotFoundException: gherkin.util.FixJava
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 20 more

I have added the below Cucumber jar files to Eclipse and added the cucumber plugin to eclipse

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.47.1</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.0.2</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm</artifactId>
        <version>1.2.5</version>
        <type>pom</type>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm-deps</artifactId>
        <version>1.0.5</version>
    </dependency>

    <dependency>
        <groupId>net.masterthought</groupId>
        <artifactId>cucumber-reporting</artifactId>
        <version>1.0.0</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>gherkin</artifactId>
        <version>2.12.2</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.0.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>

</dependencies>

Any help to fix this issue is much appreciated


问:
I have an error: setOnItemClickListener cannot be used with a spinner, what is wrong?
Kindly This is my code below, and I am pasting the error messages underneath:
I am trying to use setOnItemClickListener on the spinner, is it permissible?

```<code>@Override
public void onItemClick(AdapterView<?> arg0, View v, int index, long arg3) {
    if (quantity[index]=="Meter" ){
        s1="Meter";
        Toast.makeText(v.getContext(), "convert from meter",Toast.LENGTH_SHORT).show();
    }
}

   });

convertto.setOnItemClickListener(new OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> arg, View v1, int index1, long arg4)
    {
        if ((quantity[index1]=="Meter") && (s1.equalsIgnoreCase("Meter")))
        {
            Toast.makeText(v1.getContext(), " to meter",Toast.LENGTH_SHORT).show();
            var2=var1;
            lresult.setText("" + var2);
        }
    }
});

}

}
</code>```

and here are the errors

```<code>FATAL EXCEPTION: main
07-04 09:48:39.912: E/AndroidRuntime(694): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.a2zunitconverter.miniproject/com.a2zunitconverter.miniproject.lenght}: java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.os.Looper.loop(Looper.java:123)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.main(ActivityThread.java:3683)
07-04 09:48:39.912: E/AndroidRuntime(694):  at java.lang.reflect.Method.invokeNative(Native Method)
07-04 09:48:39.912: E/AndroidRuntime(694):  at java.lang.reflect.Method.invoke(Method.java:507)
07-04 09:48:39.912: E/AndroidRuntime(694):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-04 09:48:39.912: E/AndroidRuntime(694):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-04 09:48:39.912: E/AndroidRuntime(694):  at dalvik.system.NativeStart.main(Native Method)
07-04 09:48:39.912: E/AndroidRuntime(694): Caused by: java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.widget.Spinner.setOnItemClickListener(Spinner.java:102)
07-04 09:48:39.912: E/AndroidRuntime(694):  at com.a2zunitconverter.miniproject.lenght.onCreate(lenght.java:31)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-04 09:48:39.912: E/AndroidRuntime(694):  ... 11 more
</code>```

答:
Solved by </p>

```<code> spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int
 i, long l) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
</code>```

Body:
Kindly This is my code below, and I am pasting the error messages underneath:
I am trying to use setOnItemClickListener on the spinner, is it permissible?

@Override
public void onItemClick(AdapterView<?> arg0, View v, int index, long arg3) {
    if (quantity[index]=="Meter" ){
        s1="Meter";
        Toast.makeText(v.getContext(), "convert from meter",Toast.LENGTH_SHORT).show();
    }
}

   });

convertto.setOnItemClickListener(new OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> arg, View v1, int index1, long arg4)
    {
        if ((quantity[index1]=="Meter") && (s1.equalsIgnoreCase("Meter")))
        {
            Toast.makeText(v1.getContext(), " to meter",Toast.LENGTH_SHORT).show();
            var2=var1;
            lresult.setText("" + var2);
        }
    }
});

}

}

and here are the errors

FATAL EXCEPTION: main
07-04 09:48:39.912: E/AndroidRuntime(694): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.a2zunitconverter.miniproject/com.a2zunitconverter.miniproject.lenght}: java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.os.Looper.loop(Looper.java:123)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.main(ActivityThread.java:3683)
07-04 09:48:39.912: E/AndroidRuntime(694):  at java.lang.reflect.Method.invokeNative(Native Method)
07-04 09:48:39.912: E/AndroidRuntime(694):  at java.lang.reflect.Method.invoke(Method.java:507)
07-04 09:48:39.912: E/AndroidRuntime(694):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-04 09:48:39.912: E/AndroidRuntime(694):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-04 09:48:39.912: E/AndroidRuntime(694):  at dalvik.system.NativeStart.main(Native Method)
07-04 09:48:39.912: E/AndroidRuntime(694): Caused by: java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.widget.Spinner.setOnItemClickListener(Spinner.java:102)
07-04 09:48:39.912: E/AndroidRuntime(694):  at com.a2zunitconverter.miniproject.lenght.onCreate(lenght.java:31)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-04 09:48:39.912: E/AndroidRuntime(694):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-04 09:48:39.912: E/AndroidRuntime(694):  ... 11 more

Body:
Solved by

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int
 i, long l) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });


问:
Is there a way to "install" nuget package like the way Visual Studio does, but on a deployment server
Background:

I am reasonably new to packaging and publishing nuget. Long story short, I have a C# project (Let's call it MYAPI project) which depends on a bunch of other nuget packages. Some consumers of MYAPI, expect to reference it as a nuget package and deal with their products' deployment on their own, while some other consumers expect MYAPI dlls to be installed in specific folders from where they will pick it up at runtime.

So I have packaged MYAPI as a nuget and published it onto an internal nuget server.

Issue:

How do I install my nuget package onto the servers in a way that it will have all the required dependencies. I want it to look like how the bin\debug folder looks like i.e. based on the target framework, copy the relevant files from all the dependency nuget packages including the main nuget package (MYAPI in this case)

I know I can achieve this by packaging MYAPI as a zip file or an msi in addition to the nuget package. But I don't want multiple types of packages for MYAPI, and would prefer to stick to just nuget package. I also understand I can reference all the dependency in my <files> section of nuspec, but I think it is a poor man's way of doing it.

Is there a way to do it just like Visual Studio does it i.e. download main nuget package and all its dependencies, extract them and then copy the relevant (framework version based) files from all the extracted nuget packages into the bin\debug folder. If that is not available out of the box, can someone point me to the "intelligence" VS uses to copy the files into bin\debug folder, so i can replicate it in an install script.

EDIT:

This is a regular .NET Framework project, and I am talking of installing on say a production server where development tools like MSBuild, VS won't be available. I can still have the nuget.exe command as it is a single executable.

答: You can use a temporary/publish project. Create the project with whatever TFM you want, add a PackageReference to the package, run dotnet publish, then delete <project_name>.* from the publish directory.


问:
Use Python Imaging Library to isolate a single channel
So say I have an image, and I want to make it so that only the red channel shows up, and the image looks red, how would I do this using PIL? Thanks.</p>

答:
For people who are looking to extract a single channel from an image (as opposed to generating an image with R, G and B channels, but with the G and B channels all zero), you can do:

```<code>img = Image.open("image.jpg")
red = img.getchannel('R')
# OR
red = img.getchannel(0)  # Avoids internal lookup of 'R' in img.getbands()
</code>```

Body:
For people who are looking to extract a single channel from an image (as opposed to generating an image with R, G and B channels, but with the G and B channels all zero), you can do:

img = Image.open("image.jpg")
red = img.getchannel('R')
# OR
red = img.getchannel(0)  # Avoids internal lookup of 'R' in img.getbands()


问:
How to detect where NaN is passing to CoreGraphics API on Mac OS X 10.9
I have very large graphic Mac app and now I receive a lot of the following messages in Console on 10.9 GM.

```<code><Error>: Error: this application, or a library it uses, has passed an invalid numeric value (NaN, or not-a-number) to CoreGraphics API. This is a serious error and contributes to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.
</code>```

I noticed that these messages appear in debugger after calling [NSApp nextEventMatchingMask: untilDate inMode: dequeue] but I think the reasons are in some other places. But I have too many places where I use Cocoa Graphics. I didn't receive this kind of message before 10.9.

How to detect where NaN is passing to CoreGraphics API?

答:
The habit of creating lazy UIView's with a .zero frame played against me when doing it for a PDFView.

This

```<code>var pdfView = PDFView(frame: .zero)
</code>```

will generate lots of the same logs from the question. The reason I used .zero, is because later I set up the view with constraints. This proved to be a problem. The solution was to use an arbitrary, non-zero frame when initializing the PDFView.

```<code>var pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
</code>```

Body:
I have very large graphic Mac app and now I receive a lot of the following messages in Console on 10.9 GM.

<Error>: Error: this application, or a library it uses, has passed an invalid numeric value (NaN, or not-a-number) to CoreGraphics API. This is a serious error and contributes to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

I noticed that these messages appear in debugger after calling [NSApp nextEventMatchingMask: untilDate inMode: dequeue] but I think the reasons are in some other places. But I have too many places where I use Cocoa Graphics. I didn't receive this kind of message before 10.9.

How to detect where NaN is passing to CoreGraphics API?

Body:
The habit of creating lazy UIView's with a .zero frame played against me when doing it for a PDFView.

This

var pdfView = PDFView(frame: .zero)

will generate lots of the same logs from the question. The reason I used .zero, is because later I set up the view with constraints. This proved to be a problem. The solution was to use an arbitrary, non-zero frame when initializing the PDFView.

var pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))


问:
Converting separate month, day and year values into a timestamp
I have a month value (1-12), day value (1-31), and a year value (2010,2011,2012). I also have a hour value and a minute value.

How can I give this to strtotime() in a way it can convert it to a timestamp?

答:
Use it like this strtotime("YYYY-mm-DD HH:MM AM/PM"):

```<code>echo date("d F Y h:i:s A", strtotime("2011-06-01 11:15 PM")) . "\n";
</code>```

OUTPUT

```<code>01 June 2011 11:15:00 PM
</code>```

Body:
Use it like this strtotime("YYYY-mm-DD HH:MM AM/PM"):

echo date("d F Y h:i:s A", strtotime("2011-06-01 11:15 PM")) . "\n";

OUTPUT

01 June 2011 11:15:00 PM


问:
Looping/iterate over the second level nested JSON in go lang
Consider the following code:

```<code>package main

import (
"encoding/json"
"fmt"
"reflect"
)

func main() {
    //Creating the maps for JSON
    m := map[string]interface{}{}

    //Parsing/Unmarshalling JSON encoding/json
    err := json.Unmarshal([]byte(input), &m)

    fmt.Println("\nReflect type of Parsing/Unmarshalling Error Object:\n",reflect.TypeOf(err))
    fmt.Println("\nParsing/Unmarshalling Error Object:\n",err)
    if err != nil {
        panic(err)
    }

    fmt.Println("\nParsed JSON is as follows:\n",m)
    fmt.Println("\nReflect type of parsed json object:\n", reflect.TypeOf(m))

    for firstLvlkey, firstLvlValue := range m {
        fmt.Println("First Level Key:", firstLvlkey)
        fmt.Println("First Level Key reflect type of :", reflect.TypeOf(firstLvlkey))

        fmt.Println("First Level Value:", firstLvlValue)
        fmt.Println("First Level Value reflect type of :", reflect.TypeOf(firstLvlValue))
         // <===============================>
         //Here I want to iterate/loop over innerJSON1, InnerJSON2 then reach to level InnerInnerJSONArray - fld1 and fld2
         // <===============================>

    }
}

const input = `
{
    "outterJSON":{
        "innerJSON1":{
            "value1":10,
            "value2":22
            ,
            "InnerInnerArray": [ "test1" , "test2"],
            "InnerInnerJSONArray": [ {"fld1" : "val1"} , {"fld2" : "val2"} ]
            },
            "InnerJSON2":"NoneValue"
        }
    }
    `
</code>```

I have some requirement like I want to read/get all the Key and value in String type for some processing adn I can't define the struct because I will be getting dynamic JSON input (e.g InnerInnerArray as a string then second level loop will give me index of array and process each JSON having key fld1 and val1).

I wish to iterate over every key/value pair contained within it, what is the most efficient way of going through the map?

Note: I am Newbie for Go-lang, your suggestion/improvement on question is also most welcome.

答:
I have implemented something very similar to https://stackoverflow.com/users/1078890/iamnan solution. The body of parseMap and parseArray is combined into one and it looks something like this.

```<code>func printJson(res1 map[string]interface{}, res2 []interface{}) {
    for k, v := range res1 {
        switch vv := v.(type) {
        case float64, int, string:
            fmt.Println(k, ":", vv)
        case []interface{}:
            fmt.Println(k, ":")
            printJson(nil, vv)
        case map[string]interface{}:
            fmt.Println(k, ":")
            printJson(vv, nil)
        default:
            fmt.Println(k, ":", vv)
        }
    }
    for k, v := range res2 {
        switch vv := v.(type) {
        case float64, int, string:
            fmt.Println(k, ":", vv)
        case []interface{}:
            fmt.Println(k, ":")
            printJson(nil, vv)
        case map[string]interface{}:
            fmt.Println(k, ":")
            printJson(vv, nil)
        default:
            fmt.Println(k, ":", vv)
        }
    }
}
</code>```

Code can be found here https://gist.github.com/sandeep-sarkar/78a0e96461b4dec727386a96404d29b0

Body:
Consider the following code:

package main

import (
"encoding/json"
"fmt"
"reflect"
)

func main() {
    //Creating the maps for JSON
    m := map[string]interface{}{}

    //Parsing/Unmarshalling JSON encoding/json
    err := json.Unmarshal([]byte(input), &m)

    fmt.Println("\nReflect type of Parsing/Unmarshalling Error Object:\n",reflect.TypeOf(err))
    fmt.Println("\nParsing/Unmarshalling Error Object:\n",err)
    if err != nil {
        panic(err)
    }

    fmt.Println("\nParsed JSON is as follows:\n",m)
    fmt.Println("\nReflect type of parsed json object:\n", reflect.TypeOf(m))

    for firstLvlkey, firstLvlValue := range m {
        fmt.Println("First Level Key:", firstLvlkey)
        fmt.Println("First Level Key reflect type of :", reflect.TypeOf(firstLvlkey))

        fmt.Println("First Level Value:", firstLvlValue)
        fmt.Println("First Level Value reflect type of :", reflect.TypeOf(firstLvlValue))
         // <===============================>
         //Here I want to iterate/loop over innerJSON1, InnerJSON2 then reach to level InnerInnerJSONArray - fld1 and fld2
         // <===============================>

    }
}

const input = `
{
    "outterJSON":{
        "innerJSON1":{
            "value1":10,
            "value2":22
            ,
            "InnerInnerArray": [ "test1" , "test2"],
            "InnerInnerJSONArray": [ {"fld1" : "val1"} , {"fld2" : "val2"} ]
            },
            "InnerJSON2":"NoneValue"
        }
    }
    `

I have some requirement like I want to read/get all the Key and value in String type for some processing adn I can't define the struct because I will be getting dynamic JSON input (e.g InnerInnerArray as a string then second level loop will give me index of array and process each JSON having key fld1 and val1).

I wish to iterate over every key/value pair contained within it, what is the most efficient way of going through the map?

Note: I am Newbie for Go-lang, your suggestion/improvement on question is also most welcome.

Body:
I have implemented something very similar to https://stackoverflow.com/users/1078890/iamnan solution. The body of parseMap and parseArray is combined into one and it looks something like this.

func printJson(res1 map[string]interface{}, res2 []interface{}) {
    for k, v := range res1 {
        switch vv := v.(type) {
        case float64, int, string:
            fmt.Println(k, ":", vv)
        case []interface{}:
            fmt.Println(k, ":")
            printJson(nil, vv)
        case map[string]interface{}:
            fmt.Println(k, ":")
            printJson(vv, nil)
        default:
            fmt.Println(k, ":", vv)
        }
    }
    for k, v := range res2 {
        switch vv := v.(type) {
        case float64, int, string:
            fmt.Println(k, ":", vv)
        case []interface{}:
            fmt.Println(k, ":")
            printJson(nil, vv)
        case map[string]interface{}:
            fmt.Println(k, ":")
            printJson(vv, nil)
        default:
            fmt.Println(k, ":", vv)
        }
    }
}

Code can be found here https://gist.github.com/sandeep-sarkar/78a0e96461b4dec727386a96404d29b0


答:
Given the variables $year $month $day $hour $minute you can do:

```<code>strtotime("$year-$month-$day $hour:$minute");
</code>```

Be careful to enclose the variables with ", never in this case with '.

UPDATE (thanks to comments of @Clockwork and @Tadeck):

In case there is a variable $timeofday that represents the time of day (i.e. AM or PM),
then you can parse it this with:

```<code>strtotime("$year-$month-$day $hour:$minute$timeofday");
</code>```

that is to say, just attach that variable to the end of the text.

Title: Converting separate month, day and year values into a timestamp

Body:
I have a month value (1-12), day value (1-31), and a year value (2010,2011,2012). I also have a hour value and a minute value.

How can I give this to strtotime() in a way it can convert it to a timestamp?

Body:
Given the variables $year $month $day $hour $minute you can do:

strtotime("$year-$month-$day $hour:$minute");

Be careful to enclose the variables with ", never in this case with '.

UPDATE (thanks to comments of @Clockwork and @Tadeck):

In case there is a variable $timeofday that represents the time of day (i.e. AM or PM),
then you can parse it this with:

strtotime("$year-$month-$day $hour:$minute$timeofday");

that is to say, just attach that variable to the end of the text.


问:
How to show user specific data on the list based on a many to many relationship using Symfony 5 EasyAdmin Bundle
I am very new to EasyAdmin bundle. I was trying to load user specific content in the list of a logged in user.

So here is my composer.json file:

```<code>{
"type": "project",
"license": "proprietary",
"require": {
    "php": "^7.2.5",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "easycorp/easyadmin-bundle": "^2.3",
    "sensio/framework-extra-bundle": "^5.1",
    "symfony/asset": "5.0.*",
    "symfony/console": "5.0.*",
    "symfony/dotenv": "5.0.*",
    "symfony/expression-language": "5.0.*",
    "symfony/flex": "^1.3.1",
    "symfony/form": "5.0.*",
    "symfony/framework-bundle": "5.0.*",
    "symfony/http-client": "5.0.*",
    "symfony/intl": "5.0.*",
    "symfony/mailer": "5.0.*",
    "symfony/monolog-bundle": "^3.1",
    "symfony/notifier": "5.0.*",
    "symfony/orm-pack": "*",
    "symfony/process": "5.0.*",
    "symfony/security-bundle": "5.0.*",
    "symfony/serializer-pack": "*",
    "symfony/string": "5.0.*",
    "symfony/translation": "5.0.*",
    "symfony/twig-pack": "*",
    "symfony/validator": "5.0.*",
    "symfony/web-link": "5.0.*",
    "symfony/yaml": "5.0.*"
},
</code>```

I have a Project Requirements entity which has a many to many relationship with the User entity like the following:

```<code>/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="User", inversedBy="projectRequirementsHasUserProjectRequirements")
 * @ORM\JoinTable(name="project_requirements_has_user",
 *   joinColumns={
 *     @ORM\JoinColumn(name="project_requirements_has_user_project_requirements_id", referencedColumnName="id")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="project_requirements_has_user_user_id", referencedColumnName="id")
 *   }
 * )
 */
private $projectRequirementsHasUserUser;

/**
 * Constructor
 */
public function __construct()
{
    $this->projectRequirementsHasUserUser = new \Doctrine\Common\Collections\ArrayCollection();
}
</code>```

So when adding requirements I can assign user like this:

You can see that the first requirements has assigned to 2 users:

Now I want to show all the requirements which has assigned to the logged in user.

I came to know that I need to override the default EasyAdminController, so I configured my entity in config/packages/easy_admin.yaml:

```<code>    # Project Planning
    ProjectRequirements:
      controller: App\Controller\ProjectRequirementsController
      class: App\Entity\ProjectRequirements
</code>```

And then create a controller but don't know how to write the filter or query to select only the requirements which has assigned to the logged in user:

```<code><?php
namespace App\Controller;

use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;

class ProjectRequirementsController extends EasyAdminController {

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{

    /** @var QueryBuilder $result  */
    $result = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);

    return $result;

}
</code>```

}

Any help is highly appreciable.

答:
Seems like you've created a ManyToMany unidirectional connection. Try using bidirectional mapping like described in the documentation.

Then you should easily access your logged in user's assignments via the array collection in the user entity.

Body:
I am very new to EasyAdmin bundle. I was trying to load user specific content in the list of a logged in user.

So here is my composer.json file:

{
"type": "project",
"license": "proprietary",
"require": {
    "php": "^7.2.5",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "easycorp/easyadmin-bundle": "^2.3",
    "sensio/framework-extra-bundle": "^5.1",
    "symfony/asset": "5.0.*",
    "symfony/console": "5.0.*",
    "symfony/dotenv": "5.0.*",
    "symfony/expression-language": "5.0.*",
    "symfony/flex": "^1.3.1",
    "symfony/form": "5.0.*",
    "symfony/framework-bundle": "5.0.*",
    "symfony/http-client": "5.0.*",
    "symfony/intl": "5.0.*",
    "symfony/mailer": "5.0.*",
    "symfony/monolog-bundle": "^3.1",
    "symfony/notifier": "5.0.*",
    "symfony/orm-pack": "*",
    "symfony/process": "5.0.*",
    "symfony/security-bundle": "5.0.*",
    "symfony/serializer-pack": "*",
    "symfony/string": "5.0.*",
    "symfony/translation": "5.0.*",
    "symfony/twig-pack": "*",
    "symfony/validator": "5.0.*",
    "symfony/web-link": "5.0.*",
    "symfony/yaml": "5.0.*"
},

I have a Project Requirements entity which has a many to many relationship with the User entity like the following:

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="User", inversedBy="projectRequirementsHasUserProjectRequirements")
 * @ORM\JoinTable(name="project_requirements_has_user",
 *   joinColumns={
 *     @ORM\JoinColumn(name="project_requirements_has_user_project_requirements_id", referencedColumnName="id")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="project_requirements_has_user_user_id", referencedColumnName="id")
 *   }
 * )
 */
private $projectRequirementsHasUserUser;

/**
 * Constructor
 */
public function __construct()
{
    $this->projectRequirementsHasUserUser = new \Doctrine\Common\Collections\ArrayCollection();
}

So when adding requirements I can assign user like this:

You can see that the first requirements has assigned to 2 users:

Now I want to show all the requirements which has assigned to the logged in user.

I came to know that I need to override the default EasyAdminController, so I configured my entity in config/packages/easy_admin.yaml:

    # Project Planning
    ProjectRequirements:
      controller: App\Controller\ProjectRequirementsController
      class: App\Entity\ProjectRequirements

And then create a controller but don't know how to write the filter or query to select only the requirements which has assigned to the logged in user:

<?php
namespace App\Controller;

use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;

class ProjectRequirementsController extends EasyAdminController {

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{

    /** @var QueryBuilder $result  */
    $result = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);

    return $result;

}

}

Any help is highly appreciable.


问:
How to make a type that for all intents and purposes act like a string, since I cannot inherit from a string
I like types.
Like to be able to specify meaning to a string or int etc)

A string or an int can be almost anything,

I enjoy giving a string a meaningful type.
I also prefer that when you have a longish function call. That way people who use it
wont pass in strings in the wrong order.

I often use strings as parameters and I want "MembersName" as a Type derived from string.

I can easily do something like MembersName.Value where string is a property of another class.
I would rather derive my class from String but that is not possible since it is sealed.

I have looked at the System.String source and thought about taking it out use it to make my own String type, but I decided against it.

Then I started creating my own stand in base class that I could derive my other string-like types from StringBase (realy good name).

I am working on implementing
IEquatable, ICloneable, IComparable, IComparable, IConvertible, IEquatable, IEnumerable

In the base type to make it appear as much like a string as possible.

I would prefer to be able to Membername == "Phil Collins".

It is also desirable to mimick other features of String.

Is this the right path? and does anyone have a version of it written already?
I figure the need must have come up before from someone else?

I tried hunting Google and GitHub without much luck so far.

Am I going down the right path?
Or is what I am trying to do nearly impossible?

答:
I think this can be a good design as it provides type safety for different types of strings (enabling better support for overloading methods, refactoring etc.).

I dug up something from an old project that might get you started at least.

In this case I had a strongly typed UserId functioning (almost) as a string.

Maybe if you complete this with implicit operators as 'GuruStron' suggested you will have something to work on, although if I remember correctly I chose not to provide implicit operators as it made the type "less type safe".

```<code>public struct UserId : IStringIdentifier, IEquatable<UserId>
{
    public UserId(string id) : this() => Value = id;

    public string Value { get; set; }

    public static bool operator ==(UserId id1, UserId id2)
        => id1.Value == id2.Value;

    public static bool operator !=(UserId id1, UserId id2)
        => id1.Value != id2.Value;

    public override bool Equals(object obj)
    {
        if (obj is UserId other)
            return Equals(other);

        return false;
    }

    public bool Equals(UserId other) => Value.Equals(other.Value);
    public override string ToString() => Value;
    public override int GetHashCode() => Value.GetHashCode();
}
</code>```

Edit: Cleaned it up a bit.

Body:
I think this can be a good design as it provides type safety for different types of strings (enabling better support for overloading methods, refactoring etc.).

I dug up something from an old project that might get you started at least.

In this case I had a strongly typed UserId functioning (almost) as a string.

Maybe if you complete this with implicit operators as 'GuruStron' suggested you will have something to work on, although if I remember correctly I chose not to provide implicit operators as it made the type "less type safe".

public struct UserId : IStringIdentifier, IEquatable<UserId>
{
    public UserId(string id) : this() => Value = id;

    public string Value { get; set; }

    public static bool operator ==(UserId id1, UserId id2)
        => id1.Value == id2.Value;

    public static bool operator !=(UserId id1, UserId id2)
        => id1.Value != id2.Value;

    public override bool Equals(object obj)
    {
        if (obj is UserId other)
            return Equals(other);

        return false;
    }

    public bool Equals(UserId other) => Value.Equals(other.Value);
    public override string ToString() => Value;
    public override int GetHashCode() => Value.GetHashCode();
}

Edit: Cleaned it up a bit.


问:
Can't update Android gradle plugin version
I'm trying to update Android gradle plugin from 3.5.1 to 3.6.1.

And got error:

```<code>Cannot cast object 'com.android.build.gradle.internal.pipeline.TransformTask$2$1@67833830' with class 'com.android.build.gradle.internal.pipeline.TransformTask$2$1' to class 'com.android.build.gradle.internal.pipeline.TransformTask'
</code>```

There is not this error on 3.5.1 - 3.5.3. It reproduce only on 3.6.0 - 3.6.1

Gradle 6.2.2

Android Studio 3.6

Android SDK Platform-Tools 29.0.6

compileSdkVersion 29

targetSdkVersion 29

答: I encountered the same thing after updating gradle plugin from version 3.5.3 to 4.0.0. It turned out, that there was a problem with AspectJ plugin com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.5. After updating the plugin to version 2.0.10 the problem disappeared.

Body:
I'm trying to update Android gradle plugin from 3.5.1 to 3.6.1.

And got error:

Cannot cast object 'com.android.build.gradle.internal.pipeline.TransformTask$2$1@67833830' with class 'com.android.build.gradle.internal.pipeline.TransformTask$2$1' to class 'com.android.build.gradle.internal.pipeline.TransformTask'

There is not this error on 3.5.1 - 3.5.3. It reproduce only on 3.6.0 - 3.6.1

Gradle 6.2.2

Android Studio 3.6

Android SDK Platform-Tools 29.0.6

compileSdkVersion 29

targetSdkVersion 29


问:
Not called at Start method of USB DriverKit
I am writing a DriverKit dext and can activate it using System Extension framework. I have the entitlements in place for usb which is
com.apple.developer.driverkit is set to true
com.apple.developer.driverkit.transport.usb has been added as dictionary but without any sub values ( it is empty) .

I was expecting getting called at dext's Start method after any USB device being plugged in but I am not seeing any calls.

Any idea whether any step / configuration is missing ?

答:
There are a number of critical pieces of information you haven't shared:

Is SIP disabled on your machine or have you got the necessary entitlements enabled in your signing certificate/provisioning profile?

Why is your USB DriverKit entitlement empty? Apple will normally issue USB entitlements with a specific vendor ID, or a set of them.

Is your dext activation (from the wrapper app) definitely succeeding?

Are you getting any crash reports? (See Console.app)

What exactly do you mean by "after any USB device being plugged in" (emphasis mine)? What is your dext's IOKit matching dictionary in the Info.plist? What devices do you expect it to match?

Is your driver's service object showing up in the I/O Registry? (ioreg or IORegistryExplorer.app)

Those are common causes but to diagnose the problem regardless - have you looked at the system log? Specifically, sysextd and kextd will typically complain in the log when there is something about a dext which makes it not loadable.

Try something like this:

Uninstall your dext

Reboot

/Library/SystemExtensions should not have any remnants of your dext. (in any uuid-named subdirectories) If it does, try running sudo kextcache --invalidate /, wait until that finishes, then reboot again. Zombie dexts cause major problems.

Launch log stream --info --predicate 'process == "kextd" || process == "sysextd" || processID == 0' in a Terminal window (you might want to add your app to the predicate if you're logging via NSLog/os_log there too)

Launch your app, install the dext

Check if the log shows anything relevant

Plug in your device

Check if the log shows anything relevant

You should be seeing some useful information there. Feel free to update your question with the logs you get if you can't make sense of them.


问:
Can I use dynamic properties in dependency array for useEffect?
So I have a question regarding useEffect dependenices

This is from the react docs:

```<code>useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
</code>```

What does this mean exactly, does React keep track of the count variable and its value, and reacts when the value changes, or does React keep track of the first element in the array and its value.

What do I mean by this? Let me explain more. So if we have something like this [name] as dependencies. At the moment of evaluation, the array might result with ['Bob'] or ['Steve']. Clearly this is a change and the useEffect will rerender the component. But how does it check it?

Does it keep track of name or does it keep track of dependencyArray[0]. If we take a look in the previous example, both of these would result to true, name and the first element both changed their values from 'Bob' to 'Steve'. But how does it actually work?

Currently in my code I am using something like this [employees[selectedEmployee].name], where selectedEmployee is something clickable on the UI and it becomes 'Bob' or 'Steve'

ex:

```<code>const employees = {
   Bob: {
      name: 'Bob'
   },
   Steve: {
      name: 'Steve'
   }
}
</code>```

This means that in the end, when evaluated, the dependency array will still result with ['Bob'] --> ['Steve'], and if React is evaluating the dependencyArray[0] then that has clearly changed and component should rerender, but If it keeps track of the reference, then I am changing the reference altogether and it may cause problems.

So what's the correct approach? Can I use dynamic properties like employees[selectedEmployee].name as a dependency?

答:
count is a value, not a reference.

It's just good old Javascript, nothing fancy:

```<code>const myArray = [ count ]; // new array containing the value of variable 'count'
const myFunction = () => {
  document.title = `You clicked ${count} times`;
}

useEffect(
  myFunction,
  myArray
);

// Means actually:
// "Run this function if any value in the array
// is different to what it was last time this useEffect() was called"
</code>```

does React keep track of the ... value, or ... the reference ?

React doesn't really 'keep track' of any of them. It only checks the difference to a previous call, and forgets about everything else.

Can I use dynamic properties as a dependency?

Yes, you can (because they are not as 'dynamic' as you think).

So what's the correct approach?

Better think less of any react-magic going on, but

understand that the component is a function, and believe React calls it when necessary and

think about the variables (properties and state) used inside it, from a plain Javascript perspective.

Then your 'dynamic properties' become 'constant variables during one function call'. No matter which variables change dynamically and how, it will always be one value last time and one value now.

Explaination:

The important 'trick' here is, that the component is just a javascript function, that is called like 'whenever anything might have changed', and consequently useEffect() is also called (as useEffect() is just a function call inside the component).

Only the callback function passed to useEffect is not always called.

useEffect does not render the component, useEffect is called when the component is called, and then just calls the function given to it, or not, depending on if any value in the dependencies array is different to what it was last time useEffect() was called.

React might rerender the component if in the function given to useEffect there are any changes made to the state or something (anything that makes React to think it has to rerender), but that's as a result of this state change, where ever it came from, not because of the useEffect call.

Example:

```<code>const MyComponent = (props) => {

  // I'm assigning many const here to show we are dealing with local constants.
  // Usually you would use this form (using array destructuring):
  // const [ selectedEmployee, setSelectedEmployee ] = useState( someInitialValue );

  const myStateValueAndSetter = useState( 'Bob' );
  const selectedEmployee    = myStateValueAndSetter[0];
  const setSelectedEmployee = myStateValueAndSetter[1];

  const employees = {
    Bob: { name: 'Bob' },
    Steve: { name: 'Steve' }
  };

  const currentName = employees[ selectedEmployee ].name;

  useEffect(() => {
    document.title = 'current name: ' + currentName;
  }, [ currentName ]);

  return <MyClickableComponent onClick={( newValue ) => {
    setSelectedEmployee( newValue )
  }}>;
};
</code>```

click on MyClickableComponent calls the current setSelectedEmployee( newValue ) function.

(The constant selectedEmployee is not changed!)

MyComponent() is called again.

(This is a new function call. All the constants are gone! Only React stores some state in the background.)

useState() is called, the result is stored in a new constant selectedEmployee.

useEffect() is called, and decides if its callback should be called, depending on the previous and the current value of selectedEmployee.

If the callback is not called and nothing else is changed, you might not notice that anything has happened at all.

<MyClickableComponent ... /> is rendered.

Body:
So I have a question regarding useEffect dependenices

This is from the react docs:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

What does this mean exactly, does React keep track of the count variable and its value, and reacts when the value changes, or does React keep track of the first element in the array and its value.

What do I mean by this? Let me explain more. So if we have something like this [name] as dependencies. At the moment of evaluation, the array might result with ['Bob'] or ['Steve']. Clearly this is a change and the useEffect will rerender the component. But how does it check it?

Does it keep track of name or does it keep track of dependencyArray[0]. If we take a look in the previous example, both of these would result to true, name and the first element both changed their values from 'Bob' to 'Steve'. But how does it actually work?

Currently in my code I am using something like this [employees[selectedEmployee].name], where selectedEmployee is something clickable on the UI and it becomes 'Bob' or 'Steve'

ex:

const employees = {
   Bob: {
      name: 'Bob'
   },
   Steve: {
      name: 'Steve'
   }
}

This means that in the end, when evaluated, the dependency array will still result with ['Bob'] --> ['Steve'], and if React is evaluating the dependencyArray[0] then that has clearly changed and component should rerender, but If it keeps track of the reference, then I am changing the reference altogether and it may cause problems.

So what's the correct approach? Can I use dynamic properties like employees[selectedEmployee].name as a dependency?

Body:
count is a value, not a reference.

It's just good old Javascript, nothing fancy:

const myArray = [ count ]; // new array containing the value of variable 'count'
const myFunction = () => {
  document.title = `You clicked ${count} times`;
}

useEffect(
  myFunction,
  myArray
);

// Means actually:
// "Run this function if any value in the array
// is different to what it was last time this useEffect() was called"

does React keep track of the ... value, or ... the reference ?

React doesn't really 'keep track' of any of them. It only checks the difference to a previous call, and forgets about everything else.

Can I use dynamic properties as a dependency?

Yes, you can (because they are not as 'dynamic' as you think).

So what's the correct approach?

Better think less of any react-magic going on, but

understand that the component is a function, and believe React calls it when necessary and

think about the variables (properties and state) used inside it, from a plain Javascript perspective.

Then your 'dynamic properties' become 'constant variables during one function call'. No matter which variables change dynamically and how, it will always be one value last time and one value now.

Explaination:

The important 'trick' here is, that the component is just a javascript function, that is called like 'whenever anything might have changed', and consequently useEffect() is also called (as useEffect() is just a function call inside the component).

Only the callback function passed to useEffect is not always called.

useEffect does not render the component, useEffect is called when the component is called, and then just calls the function given to it, or not, depending on if any value in the dependencies array is different to what it was last time useEffect() was called.

React might rerender the component if in the function given to useEffect there are any changes made to the state or something (anything that makes React to think it has to rerender), but that's as a result of this state change, where ever it came from, not because of the useEffect call.

Example:

const MyComponent = (props) => {

  // I'm assigning many const here to show we are dealing with local constants.
  // Usually you would use this form (using array destructuring):
  // const [ selectedEmployee, setSelectedEmployee ] = useState( someInitialValue );

  const myStateValueAndSetter = useState( 'Bob' );
  const selectedEmployee    = myStateValueAndSetter[0];
  const setSelectedEmployee = myStateValueAndSetter[1];

  const employees = {
    Bob: { name: 'Bob' },
    Steve: { name: 'Steve' }
  };

  const currentName = employees[ selectedEmployee ].name;

  useEffect(() => {
    document.title = 'current name: ' + currentName;
  }, [ currentName ]);

  return <MyClickableComponent onClick={( newValue ) => {
    setSelectedEmployee( newValue )
  }}>;
};

click on MyClickableComponent calls the current setSelectedEmployee( newValue ) function.

(The constant selectedEmployee is not changed!)

MyComponent() is called again.

(This is a new function call. All the constants are gone! Only React stores some state in the background.)

useState() is called, the result is stored in a new constant selectedEmployee.

useEffect() is called, and decides if its callback should be called, depending on the previous and the current value of selectedEmployee.

If the callback is not called and nothing else is changed, you might not notice that anything has happened at all.

<MyClickableComponent ... /> is rendered.


问:
YAML configuration with validity range
I have a YAML file that contains some configuration for my application. Now, some configs need to change in time. For example:

For 2020 Values are:

```<code>tax:
    federal: 9
    provincial: 7
</code>```

But for 2021, what we need is:

```<code>tax:
    federal: 9.5
    provincial: 7.5
</code>```

It would be easy if I could only switch yml files through time, but the yaml file contains many configs that will change at different point in time. Plus, I'm only assigned 1 yml file to configure my application, so this is not really an option.

So my question is, what would be the cleanest way to represent this using YAML ?

The only way I can think of is the following, but I can see this going very messy.

```<code>tax:
    federal: [20200101-20201231]9;[20210101-20211231]9.5
    provincial:  [20200101-20201231]7;[20210101-20211231]7.5;
</code>```

答:
Your syntax is illegal, you would need to enclose that in quotes, parse it as single scalar, and post-process it.

I suggest to use YAML's tag system: You use a tag like !datedep to mark the values, e.g.:

tax:
    federal: !datedep { [20200101, 20210101, 20220101]: [9, 7.5] }
    provincial: !datedep { [20200101, 20210101, 20220101]: [7, 7.5] }
```

<p>I give as value a YAML mapping with a single key-value pair. The key is a list of dates, building up the ranges in between. The value is the list of values which should be mapped to the ranges between the dates.</p>

<p>When loading the YAML, you have to provide a constructor for the tag <code>!datedep</code>. How this works depends on your implementation. The constructor should select the appropriate value based on the current date. You can use YAML anchors and aliases to reference duplicate date ranges, e.g.:</p>

<pre class="lang-yaml prettyprint-override"><code>tax:
    federal: !datedep { &y2021 [20200101, 20210101, 20220101]: [9, 7.5] }
    provincial: !datedep { *y2021 : [7, 7.5] }
</code>```

Title: YAML configuration with validity range

Body:
I have a YAML file that contains some configuration for my application. Now, some configs need to change in time. For example:

For 2020 Values are:

tax:
    federal: 9
    provincial: 7

But for 2021, what we need is:

tax:
    federal: 9.5
    provincial: 7.5

It would be easy if I could only switch yml files through time, but the yaml file contains many configs that will change at different point in time. Plus, I'm only assigned 1 yml file to configure my application, so this is not really an option.

So my question is, what would be the cleanest way to represent this using YAML ?

The only way I can think of is the following, but I can see this going very messy.

tax:
    federal: [20200101-20201231]9;[20210101-20211231]9.5
    provincial:  [20200101-20201231]7;[20210101-20211231]7.5;

Body:
Your syntax is illegal, you would need to enclose that in quotes, parse it as single scalar, and post-process it.

I suggest to use YAML's tag system: You use a tag like !datedep to mark the values, e.g.:

tax:
    federal: !datedep { [20200101, 20210101, 20220101]: [9, 7.5] }
    provincial: !datedep { [20200101, 20210101, 20220101]: [7, 7.5] }

I give as value a YAML mapping with a single key-value pair. The key is a list of dates, building up the ranges in between. The value is the list of values which should be mapped to the ranges between the dates.

When loading the YAML, you have to provide a constructor for the tag !datedep. How this works depends on your implementation. The constructor should select the appropriate value based on the current date. You can use YAML anchors and aliases to reference duplicate date ranges, e.g.:

tax:
    federal: !datedep { &y2021 [20200101, 20210101, 20220101]: [9, 7.5] }
    provincial: !datedep { *y2021 : [7, 7.5] }


问:
Workaround for output=graph with bazel cquery
I'm trying to obtain a dependency graph (either as an image or in text-form) from a bazel cquery. According to the documentation, the option --output=graph is currently only supported by bazel query, but not by cquery. Unfortunately, in our project it's not possible to use query since it fetches some external dependencies with restricted access. Only using a config (with cquery) prevents fetching these restricted dependencies.

Is there a work-around to somehow get a graph-like structure from cquery? The default output is just a flattened list which seems to contain no information on the inter-dependencies between the targets.

If the inter-dependencies can somehow be printed, I guess it would be quite easy to reconstruct an image from it.

答:
The following works: Using query instead of cquery and appending the flag --keep_going to ignore errors caused by external dependencies that cannot be fetched by everybody. Then --output=graph can be used.

Note: The result might be different from a configured cquery, but for our purposes, it doesn't matter much.


问:
MemoryError using Plotly in Python
I try to plot time series with Plotly. Graphs typically contain 200 000 rows and 10 curves resulting in a 80Mo html files. But this 200 000 rows is limited by the MemoryError raised by Plotly, and this is very limiting my studies.

```<code>    py.plot(fig, filename=self.filename, auto_open=True)
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\plotly\offline\offline.py", line 586, in plot
    pio.write_html(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\plotly\io\_html.py", line 508, in write_html
    html_str = to_html(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\plotly\io\_html.py", line 137, in to_html
    jdata = json.dumps(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\_plotly_utils\utils.py", line 60, in encode
    return _json.dumps(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 202, in encode
    return ''.join(chunks)
MemoryError
</code>```

I already implemented downsizing (like this topic suggests), and also rounding values to a limited number of decimals to avoid having to big .html files. But still it is not enough.

Also, for example when plotting 10 curves, even if they share the same X axis, the html file will contain 10 times the same X vector. Is there a way to improve that?

When I look at the memory while Plotly is concatenating data and when it stops working, it seems to be utilizing only 500Mo of RAM while my computer memory is far from being full, with still 1 or 2 Go of RAM free. Thus I don't understand why this MemoryError is raised. Is there a dedicated memory space parameter somewhere in Plotly or Python options?

I am even ready to use any other library that would allow me to draw large graphs as long as they provide sufficient interactivity. For example Matplotlib is able to draw large time series when Plotly cannot, but it is way less interactive. This one seems super light and dedicated to time series, but I did not find any Python package of it and it would require to develop the Python interface from scratch.

答:
https://bcolz.readthedocs.io/en/latest/intro.html#bcolz-at-glance

I did some quick searching on Google based on your issue and this seems like a reasonable solution, although I'm not sure you will be able to utilize it with Plotly. You'll have to give it a shot on your own.

Title: MemoryError using Plotly in Python

Body:
I try to plot time series with Plotly. Graphs typically contain 200 000 rows and 10 curves resulting in a 80Mo html files. But this 200 000 rows is limited by the MemoryError raised by Plotly, and this is very limiting my studies.

    py.plot(fig, filename=self.filename, auto_open=True)
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\plotly\offline\offline.py", line 586, in plot
    pio.write_html(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\plotly\io\_html.py", line 508, in write_html
    html_str = to_html(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\plotly\io\_html.py", line 137, in to_html
    jdata = json.dumps(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\site-packages\_plotly_utils\utils.py", line 60, in encode
    return _json.dumps(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "C:\Users\Max\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 202, in encode
    return ''.join(chunks)
MemoryError

I already implemented downsizing (like this topic suggests), and also rounding values to a limited number of decimals to avoid having to big .html files. But still it is not enough.

Also, for example when plotting 10 curves, even if they share the same X axis, the html file will contain 10 times the same X vector. Is there a way to improve that?

When I look at the memory while Plotly is concatenating data and when it stops working, it seems to be utilizing only 500Mo of RAM while my computer memory is far from being full, with still 1 or 2 Go of RAM free. Thus I don't understand why this MemoryError is raised. Is there a dedicated memory space parameter somewhere in Plotly or Python options?

I am even ready to use any other library that would allow me to draw large graphs as long as they provide sufficient interactivity. For example Matplotlib is able to draw large time series when Plotly cannot, but it is way less interactive. This one seems super light and dedicated to time series, but I did not find any Python package of it and it would require to develop the Python interface from scratch.


问:
Getting first image from html using Python/Django
I am grabbing a bunch of html from a service and parsing it slightly.
I am looking for a way to grab the link from the first image tag.

Something similar like this JQuery code:

```<code>var imagelink = $('img:first', feed.content).attr('src');
</code>```

But of course using only Python/Django (server runs on Google app engine). I rather not use any other libraries, just to grab a simple link.

答:
If I do any more parsing of html I probably will look into one of the libraries suggested. But for now I have solved this by:

```<code>   startImgPos = post.find('<img', 0, len(post)) + 4
    if(startImgPos > -1):
        endImgPos = post.find('>', startImgPos, len(post))
        imageTag = post[startImgPos:endImgPos]
        startSrcPos = imageTag.find('src="', 0, len(post)) +5
        endSrcPos = imageTag.find('"', startSrcPos , len(post))
        linkTag = imageTag[startSrcPos:endSrcPos]
        r['linktag'] = linkTag
</code>```

I'll improve this later, but for now it does the trick. Feel free to suggest any more ideas/improvements to the above code.

Body:
I am grabbing a bunch of html from a service and parsing it slightly.
I am looking for a way to grab the link from the first image tag.

Something similar like this JQuery code:

var imagelink = $('img:first', feed.content).attr('src');

But of course using only Python/Django (server runs on Google app engine). I rather not use any other libraries, just to grab a simple link.

Body:
If I do any more parsing of html I probably will look into one of the libraries suggested. But for now I have solved this by:

   startImgPos = post.find('<img', 0, len(post)) + 4
    if(startImgPos > -1):
        endImgPos = post.find('>', startImgPos, len(post))
        imageTag = post[startImgPos:endImgPos]
        startSrcPos = imageTag.find('src="', 0, len(post)) +5
        endSrcPos = imageTag.find('"', startSrcPos , len(post))
        linkTag = imageTag[startSrcPos:endSrcPos]
        r['linktag'] = linkTag

I'll improve this later, but for now it does the trick. Feel free to suggest any more ideas/improvements to the above code.


问:
Django admin colours
The Django Admin page is different shades of blue by default.
Where do I access how these colours are controlled? I want to change it all to shades of green instead of blue.

Ideas?

答:
@Dominic Rodger is accepted answer. But in this I'm using Inline CSS and override Django base CSS.

Django Base CSS

Customize your AdminSite using Django Official Base CSS according to your need.

You can override Django Official Base CSS

```<code>body {
    margin: 0;
    padding: 0;
    font-size: 14px; # change default color
    font-family: "Roboto","Lucida Grande","DejaVu Sans","Bitstream Vera Sans",Verdana,Arial,sans-serif;
    color: #333;
    background: #fff; # Change color
}
</code>```

Extend the base_site templates to add extra style to AdminSite.

Create directories and base_site.html.

```<code>your_project_root_directory/templates/admin/base_site.html
</code>```

base_site.html

Copy these into your base_site.html.In style tag you can style your AdminSite

```<code>{% extends "admin/base.html" %}

{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}

{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>
{% endblock %}

{% block extrastyle %} # Here you can add your CSS

<style>

.module h2, .module caption, .inline-group h2,#header
{
    margin: 0;
    padding: 2px 5px 3px 5px;
    font-size: 11px;
    text-align: left;
    font-weight: bold;
    background: #7CA0C7 url(../img/default-bg.gif) top left repeat-x;
    color: #fff;
}

</style>

{% endblock %}

{% block nav-global %}{% endblock %}
</code>```

Title: Django admin colours

Body:
@Dominic Rodger is accepted answer. But in this I'm using Inline CSS and override Django base CSS.

Django Base CSS

Customize your AdminSite using Django Official Base CSS according to your need.

You can override Django Official Base CSS

body {
    margin: 0;
    padding: 0;
    font-size: 14px; # change default color
    font-family: "Roboto","Lucida Grande","DejaVu Sans","Bitstream Vera Sans",Verdana,Arial,sans-serif;
    color: #333;
    background: #fff; # Change color
}

Extend the base_site templates to add extra style to AdminSite.

Create directories and base_site.html.

your_project_root_directory/templates/admin/base_site.html

base_site.html

Copy these into your base_site.html.In style tag you can style your AdminSite

{% extends "admin/base.html" %}

{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}

{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>
{% endblock %}

{% block extrastyle %} # Here you can add your CSS

<style>

.module h2, .module caption, .inline-group h2,#header
{
    margin: 0;
    padding: 2px 5px 3px 5px;
    font-size: 11px;
    text-align: left;
    font-weight: bold;
    background: #7CA0C7 url(../img/default-bg.gif) top left repeat-x;
    color: #fff;
}

</style>

{% endblock %}

{% block nav-global %}{% endblock %}