问:
D3js force simulation with specific targeted destination
I'm trying to render a d3js force simulation but I'd like to ensure my nodes don't relay false information.

With the following code used to display the nodes but due to the dynamic nature of force layouts, it occasionally pushes some nodes out of its appropriate x-coordinate location.

```<code> inOrder(){
  this.simulation
    .force("x", d3.forceX(d => this.xScale(d.value)))
    .force("y",  d3.forceY(this.height / 2))
    .alpha(1).restart();
},
</code>```

Here is an egregious example of this happening:
The numbers should be in order from left to right.

I made an attempt to use the fx property on a node to lock the position in place:

```<code>inOrder(){
  this.releases.forEach(x => {
    x.fx = this.xScale(x.value)
  })

  this.simulation
    .force("x", d3.forceX(d => this.xScale(d.value)))
    .force("y",  d3.forceY(this.height / 2))
    .alpha(1).restart();
},
</code>```

This works as intended for preserving the x position but when the inOrder method is called, the nodes instantly jump to their final x position. This ruins the fluid and dynamic nature of the force simulation.

Is there a way to get the best of both worlds? Perhaps by using the .on("end", () => {}) or the .on("tick", () => {})? event handlers?

Mike Bostock (https://stackoverflow.com/users/365814/mbostock) and Shan Carter created some of the work that serves as the inspiration to what I'm trying to do here:

Click between the Changes and Department totals tabs
https://archive.nytimes.com/www.nytimes.com/interactive/2012/02/13/us/politics/2013-budget-proposal-graphic.html?hp

Click betweeen The Overall Picture and the View By Industry tabs
https://archive.nytimes.com/www.nytimes.com/interactive/2013/05/25/sunday-review/corporate-taxes.html

答:
I may be missing something here, but tinkering with the strength of the x positioning force (and the y) can help ensure that your ordering is completed properly. The default strength of forceX or forceY is 0.1, the strength is implemented as follows:

a value of 0.1 indicates that the node should move a tenth of the way from its current x-position to the target x-position with each application. Higher values moves nodes more quickly to the target position, often at the expense of other forces or constraints. A value outside the range [0,1] is not recommended. (docs)

So we could increase the forceX strength, and to allow freer movement of nodes on the x axis we could decrease the forceY - allowing nodes to hop over each other with greater ease - decreasing the collision strength could help too.

I don't label the circle below (instead they are sequentially shaded), but I do run a check to see if they are in order (logs to console on end of simulation), the below snippet modifies only the x and y forces (not the collision force):

var height = 300;
var width = 500;

var data = d3.range(30).map(function(d,i) {
  return { size: Math.random()+1, index: i}
});

var svg = d3.select("body")
  .append("svg")
  .attr("width",width)
  .attr("height",height);

var x = d3.scaleLinear()
  .domain([1,30])
  .range([50,width-50]);

var color = d3.scaleLinear()
  .domain([0,29])
  .range(["#ccc","#000"])

var simulation = d3.forceSimulation()
    .force("x", d3.forceX(d => x(d.index)).strength(0.20))
    .force("y",  d3.forceY(height / 2).strength(0.05))
    .force("collide", d3.forceCollide().radius(d=> d.size*10))
    .alpha(1).restart();

var circles = svg.selectAll(null)
  .data(data)
  .enter()
  .append("circle")
  .attr("r", function(d) { return d.size * 10; })
  .attr("fill", function(d,i) { return color(i); })

simulation.nodes(data)
  .on("tick",tick)
  .on("end",verify);

function tick() {
  circles
  .attr("cx", function(d) { return d.x; })
  .attr("cy", function(d) { return d.y; })
}

function verify() {
  var n = 0;
  for(var i = 0; i < data.length - 1; i++) {
     if(data[i].x > data[i+1].x) n++;
  }
  console.log(n + " out of place");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script></code>```

The snippet places 30 circles in a 500x300 area without much issue: I've tested a handful of times with 0 out of place. Placing 100 circles in here will cause issues: the circles will not be able to change places in such a cramped area: further modification of the forces might be required, but a larger size plot might be preferential (as opposed to a tiny snippet view) too.

Another option would be to modify forces throughout the maturation of the simulation: start with strong x force strength and low collision force strength, then dial up collision slowly so that subsequent jostling is minimized. Here's an example of modifying the forces in the tick function - though, this example is for link length rather than placement on the x - but adaptation shouldn't be too hard.

Yet another possibility would be to keep alpha high until all circles are properly ordered on the x axis and then begin to cool down, again this would have to occur in the tick function.

Body:
I'm trying to render a d3js force simulation but I'd like to ensure my nodes don't relay false information.

With the following code used to display the nodes but due to the dynamic nature of force layouts, it occasionally pushes some nodes out of its appropriate x-coordinate location.

 inOrder(){
  this.simulation
    .force("x", d3.forceX(d => this.xScale(d.value)))
    .force("y",  d3.forceY(this.height / 2))
    .alpha(1).restart();
},

Here is an egregious example of this happening:
The numbers should be in order from left to right.

I made an attempt to use the fx property on a node to lock the position in place:

inOrder(){
  this.releases.forEach(x => {
    x.fx = this.xScale(x.value)
  })

  this.simulation
    .force("x", d3.forceX(d => this.xScale(d.value)))
    .force("y",  d3.forceY(this.height / 2))
    .alpha(1).restart();
},

This works as intended for preserving the x position but when the inOrder method is called, the nodes instantly jump to their final x position. This ruins the fluid and dynamic nature of the force simulation.

Is there a way to get the best of both worlds? Perhaps by using the .on("end", () => {}) or the .on("tick", () => {})? event handlers?

Mike Bostock (https://stackoverflow.com/users/365814/mbostock) and Shan Carter created some of the work that serves as the inspiration to what I'm trying to do here:

Click between the Changes and Department totals tabs
https://archive.nytimes.com/www.nytimes.com/interactive/2012/02/13/us/politics/2013-budget-proposal-graphic.html?hp

Click betweeen The Overall Picture and the View By Industry tabs
https://archive.nytimes.com/www.nytimes.com/interactive/2013/05/25/sunday-review/corporate-taxes.html

Body:
I may be missing something here, but tinkering with the strength of the x positioning force (and the y) can help ensure that your ordering is completed properly. The default strength of forceX or forceY is 0.1, the strength is implemented as follows:

a value of 0.1 indicates that the node should move a tenth of the way from its current x-position to the target x-position with each application. Higher values moves nodes more quickly to the target position, often at the expense of other forces or constraints. A value outside the range [0,1] is not recommended. (docs)

So we could increase the forceX strength, and to allow freer movement of nodes on the x axis we could decrease the forceY - allowing nodes to hop over each other with greater ease - decreasing the collision strength could help too.

I don't label the circle below (instead they are sequentially shaded), but I do run a check to see if they are in order (logs to console on end of simulation), the below snippet modifies only the x and y forces (not the collision force):

var height = 300;
var width = 500;

var data = d3.range(30).map(function(d,i) {
  return { size: Math.random()+1, index: i}
});

var svg = d3.select("body")
  .append("svg")
  .attr("width",width)
  .attr("height",height);

var x = d3.scaleLinear()
  .domain([1,30])
  .range([50,width-50]);

var color = d3.scaleLinear()
  .domain([0,29])
  .range(["#ccc","#000"])

var simulation = d3.forceSimulation()
    .force("x", d3.forceX(d => x(d.index)).strength(0.20))
    .force("y",  d3.forceY(height / 2).strength(0.05))
    .force("collide", d3.forceCollide().radius(d=> d.size*10))
    .alpha(1).restart();

var circles = svg.selectAll(null)
  .data(data)
  .enter()
  .append("circle")
  .attr("r", function(d) { return d.size * 10; })
  .attr("fill", function(d,i) { return color(i); })

simulation.nodes(data)
  .on("tick",tick)
  .on("end",verify);

function tick() {
  circles
  .attr("cx", function(d) { return d.x; })
  .attr("cy", function(d) { return d.y; })
}

function verify() {
  var n = 0;
  for(var i = 0; i < data.length - 1; i++) {
     if(data[i].x > data[i+1].x) n++;
  }
  console.log(n + " out of place");
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

The snippet places 30 circles in a 500x300 area without much issue: I've tested a handful of times with 0 out of place. Placing 100 circles in here will cause issues: the circles will not be able to change places in such a cramped area: further modification of the forces might be required, but a larger size plot might be preferential (as opposed to a tiny snippet view) too.

Another option would be to modify forces throughout the maturation of the simulation: start with strong x force strength and low collision force strength, then dial up collision slowly so that subsequent jostling is minimized. Here's an example of modifying the forces in the tick function - though, this example is for link length rather than placement on the x - but adaptation shouldn't be too hard.

Yet another possibility would be to keep alpha high until all circles are properly ordered on the x axis and then begin to cool down, again this would have to occur in the tick function.


来源: stackexchange

问:
How to save booleans so i can use them when coming back to this activity?
I am making a study choice test app. In this test, where you should be able to go back when you want to change an answer. Each question is a different activity.
In order to go back, and accept different input, my program needs to recognise what button has previously been pressed (if any), hence the code below.

The main thing i don't know how to figure out, is how do i modify this code, so it can save booleans for when you come back to this page.

```<code>//defining the booleans
public boolean Clicked1 = false;
public boolean Clicked2 = false;
public boolean Clicked3 = false;
public boolean Clicked4 = false;

//defining my button
mButtonChoice1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            if (Clicked1 || Clicked2 || Clicked3 || Clicked4){
                if (Clicked1) {
                    NextPage();
                }else if (Clicked2) {
                    Clicked1 = true;
                    Clicked2 = false;
                    NextPage();
                }else if (Clicked3){
                        Clicked1 = true;
                        Clicked3 = false;
                        NextPage();
                }else {
                        Clicked1 = true;
                        Clicked4 = false;
                        NextPage();
                }
            }else {
                Clicked1 = true;
                NextPage();
            }
        }
    });`
</code>```

答:
I think what you're looking for are SharedPreferences. Data in SharedPrefences are saved in your app internal storage. So to start :

Initialize your SharedPreferences in onCreate().

Saving data in SharedPrefences

```<code>// You need a static String variable for identifying your preference
public static final String CHOICE_PREF = "MyOptions";
SharedPreferences.Editor editor = getSharedPreferences(CHOICE_PREF, MODE_PRIVATE).edit();
editor.putBoolean("Clicked1_state", Clicked1); //("Id key", Value)
editor.putBoolean("Clicked2_state", Clicked2);
editor.putBoolean("Clicked3_state", Clicked3);
editor.putBoolean("Clicked4_state", Clicked4);
editor.apply();
</code>```

Getting data from SharedPrefences

```<code>SharedPreferences prefs = getSharedPreferences(CHOICE_PREF, MODE_PRIVATE);
Boolean Clicked1 = prefs.getBoolean("Clicked1_state", false);//This will get the last state of Clicked1
Boolean Clicked2 = prefs.getBoolean("Clicked2_state", false);
Boolean Clicked3 = prefs.getBoolean("Clicked3_state", false);
Boolean Clicked4 = prefs.getBoolean("Clicked4_state", false);

</code>```

So, ideally, when your activity enters onStop(), save your preferences and when your activity onResume(), retrieve your saved preferences.

More info about SharedPrefences : Here

ContentLicense: CC BY-SA 4.0

Body:
I am making a study choice test app. In this test, where you should be able to go back when you want to change an answer. Each question is a different activity.
In order to go back, and accept different input, my program needs to recognise what button has previously been pressed (if any), hence the code below.

The main thing i don't know how to figure out, is how do i modify this code, so it can save booleans for when you come back to this page.

//defining the booleans
public boolean Clicked1 = false;
public boolean Clicked2 = false;
public boolean Clicked3 = false;
public boolean Clicked4 = false;

//defining my button
mButtonChoice1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            if (Clicked1 || Clicked2 || Clicked3 || Clicked4){
                if (Clicked1) {
                    NextPage();
                }else if (Clicked2) {
                    Clicked1 = true;
                    Clicked2 = false;
                    NextPage();
                }else if (Clicked3){
                        Clicked1 = true;
                        Clicked3 = false;
                        NextPage();
                }else {
                        Clicked1 = true;
                        Clicked4 = false;
                        NextPage();
                }
            }else {
                Clicked1 = true;
                NextPage();
            }
        }
    });`

Body:
I think what you're looking for are SharedPreferences. Data in SharedPrefences are saved in your app internal storage. So to start :

Initialize your SharedPreferences in onCreate().

Saving data in SharedPrefences

// You need a static String variable for identifying your preference
public static final String CHOICE_PREF = "MyOptions";
SharedPreferences.Editor editor = getSharedPreferences(CHOICE_PREF, MODE_PRIVATE).edit();
editor.putBoolean("Clicked1_state", Clicked1); //("Id key", Value)
editor.putBoolean("Clicked2_state", Clicked2);
editor.putBoolean("Clicked3_state", Clicked3);
editor.putBoolean("Clicked4_state", Clicked4);
editor.apply();

Getting data from SharedPrefences

SharedPreferences prefs = getSharedPreferences(CHOICE_PREF, MODE_PRIVATE);
Boolean Clicked1 = prefs.getBoolean("Clicked1_state", false);//This will get the last state of Clicked1
Boolean Clicked2 = prefs.getBoolean("Clicked2_state", false);
Boolean Clicked3 = prefs.getBoolean("Clicked3_state", false);
Boolean Clicked4 = prefs.getBoolean("Clicked4_state", false);

So, ideally, when your activity enters onStop(), save your preferences and when your activity onResume(), retrieve your saved preferences.

More info about SharedPrefences : Here


问:
Django: Is it possible to download a csv file from another website and add it to FileField through Django shell?
While using Django, when I need to do something on data from DB, I've always been using Django shell. For this time, I want to do something like the below scenario in Django shell.

I have a model Store with a bunch of stores. In Django shell,
1. import Store model
2. With each of store name, I search each name and download a csv file based on each store name.
3. Add the downloaded csv file to a FileField in Store model.

I know how to #1 and #3, but I'm confused how I can do #2. How can I input the store name and download a csv file from the store name in Django shell?

答:
You can use the requests library to fetch data from the internet. Install it like this:

```<code>pip install requests
</code>```

Then, in Django, you can use ContentFile to save the downloaded data into a FileField. Here's an example:

import requests
from django.core.files.base import ContentFile
from .models import SomeModel

response = requests.get('https://raw.githubusercontent.com/wireservice/csvkit/master/examples/test_geo.csv')

s = SomeModal.objects.get(id=0)
s.file_field.save('data.csv', ContentFile(response.content))
s.save()
```

Body:
You can use the requests library to fetch data from the internet. Install it like this:

pip install requests

Then, in Django, you can use ContentFile to save the downloaded data into a FileField. Here's an example:

import requests
from django.core.files.base import ContentFile
from .models import SomeModel

response = requests.get('https://raw.githubusercontent.com/wireservice/csvkit/master/examples/test_geo.csv')

s = SomeModal.objects.get(id=0)
s.file_field.save('data.csv', ContentFile(response.content))
s.save()


问:
How to find a specific string in .txt file using BufferedReader in Java
I have a task to search all .txt files for a specific word and then print all files containing that word. I have this code which finds all .txt files, and I just need to add check if that word is in, but with using BufferedReader import. I'm new in Java and I'd be happy if you help me.

```<code>package thenewboston.tutorials;
import java.io.File;
import java.io.FilenameFilter;
import java.io.BufferedReader;

public class apples30 {
    public static void main(String[] args) {
        File folder = new File("D:\\test");
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if(name.lastIndexOf('.')>0) {
                      int lastIndex = name.lastIndexOf('.');
                      String str = name.substring(lastIndex);
                      if(str.equals(".txt")) {
                         return true;
                      }
                   }
                return false;
            }
        };
        File[] listOfFiles = folder.listFiles(filter);

        for(File x: listOfFiles) {
            System.out.println(x.getName());
        }
    }
}
</code>```

This is how my code looks now.

答: You could read the files and use .contains("specific word") (a string method that will return true if the string contains that specific word).</p>

Body:
I have a task to search all .txt files for a specific word and then print all files containing that word. I have this code which finds all .txt files, and I just need to add check if that word is in, but with using BufferedReader import. I'm new in Java and I'd be happy if you help me.

package thenewboston.tutorials;
import java.io.File;
import java.io.FilenameFilter;
import java.io.BufferedReader;

public class apples30 {
    public static void main(String[] args) {
        File folder = new File("D:\\test");
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if(name.lastIndexOf('.')>0) {
                      int lastIndex = name.lastIndexOf('.');
                      String str = name.substring(lastIndex);
                      if(str.equals(".txt")) {
                         return true;
                      }
                   }
                return false;
            }
        };
        File[] listOfFiles = folder.listFiles(filter);

        for(File x: listOfFiles) {
            System.out.println(x.getName());
        }
    }
}

This is how my code looks now.


问:
facebook/php-webdriver headless downloads
There are quite a few posts about facebook/php-webdriver successfully downloading files when non-headless, and the same operation failing when headless. I'm looking for a successful implementation of RemoteWebdriver downloading headlessly for this library (facebook/php-webdriver).

The following article suggests that the library does not yet have the flexibility to set a custom command ("Page.setDownloadBehavior"), which may be what's needed for successful headless downloads. But I have not yet seen an example of a working solution in PHP.

https://github.com/facebook/php-webdriver/issues/605

Any working solutions out there? Thank you.

答:
A colleague of mine discovered a beautiful workaround to this shortcoming with Chrome/Chromium browser:

We banged our heads against the wall for weeks trying to get
  --headless to work with downloads. Here is specifically what we did:

Install Xvfb

sudo apt-get install xvfb

Start a screen session

Start Xvfb process to provide a virtual display

Xvfb :1 -screen 5 1024x768x8 &

Add DISPLAY to the environment in the screen session

export DISPLAY=:1.5

Start chromedriver (which will have the DISPLAY in its environment)

chromedriver &

Now any chromium-browser processes started by chromedriver will inherit DISPLAY and will use the Xvfb virtual display.


问:
Assign nil value to double in Objective-C
In my iOS iPhone app I have this method:

```<code>-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;
</code>```

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?

答:
You cannot have a double value of nil.  It's not a reference type, it's a primitive.  What exactly are you trying to accomplish?

Aside:

If you weren't trying to use it in this method, you could utilize [NSNumber numberWithFloat:0.4f] and as any pointer, NSNumber *number = nil; is perfectly valid.  But it won't work in this scenario, since the method requires double.

Body:
In my iOS iPhone app I have this method:

-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?

ContentLicense: CC BY-SA 3.0


问:
@Input() property in angular component returns empty array
I have calendar component with data property decorated as @Input():

```<code>import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: ['./calendar.component.css']
})
export class CalendarComponent implements OnInit, OnChanges {
  @Input() data: CalendarDay[];

  constructor() {
    this.data = [];
  }

  ngOnInit() {
    this.initDays();
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(this.data);
    console.log(changes.data);
  }
}
</code>```

I pass data in from another component like that:

```<code><app-calendar [data]="this.calendarData"></app-calendar>
</code>```

And passed data gets rendered by *ngFor in the calendar component (it renders perfectly and everything works just fine):

```<code><div *ngFor="let item of data">{{item.date}}</div>
</code>```

I want to parse this data first before rendering it into view and whenever i try to console.log data property within the calendar component i get strange array, its shows as empty, i can 'open' it from browser console:

.

And when i try to log value like that:

```<code>console.log(this.data[0])
</code>```

or

```<code>console.log(changes.data.currentValue[0])
</code>```

i get undefined value.

答:
Delete this.data = [] from constructor, avoid change anything when you use dependecy injecton.

And use set and get for each Input() that you want to use in your template, it's a best practice.

  private _data: CalendarDay[];

  @Input() set data(data: CalendarDay[]) {
    if(data) {
     this._data = data;
    }
  }

  get data(): CalendarDay[] {
    return this._data;
  }
```

<p>And in your HTML you should pass it with:</p>

<pre class="lang-html prettyprint-override"><code><app-calendar [data]="calendarData"></app-calendar>
</code>```

In calendar component you can use with

{{item.date}}

```

Body:
I have calendar component with data property decorated as @Input():

import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: ['./calendar.component.css']
})
export class CalendarComponent implements OnInit, OnChanges {
  @Input() data: CalendarDay[];

  constructor() {
    this.data = [];
  }

  ngOnInit() {
    this.initDays();
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(this.data);
    console.log(changes.data);
  }
}

I pass data in from another component like that:

<app-calendar [data]="this.calendarData"></app-calendar>

And passed data gets rendered by *ngFor in the calendar component (it renders perfectly and everything works just fine):

{{item.date}}

I want to parse this data first before rendering it into view and whenever i try to console.log data property within the calendar component i get strange array, its shows as empty, i can 'open' it from browser console:

.

And when i try to log value like that:

console.log(this.data[0])

or

console.log(changes.data.currentValue[0])

i get undefined value.

Body:
Delete this.data = [] from constructor, avoid change anything when you use dependecy injecton.

And use set and get for each Input() that you want to use in your template, it's a best practice.

  private _data: CalendarDay[];

  @Input() set data(data: CalendarDay[]) {
    if(data) {
     this._data = data;
    }
  }

  get data(): CalendarDay[] {
    return this._data;
  }

And in your HTML you should pass it with:

<app-calendar [data]="calendarData"></app-calendar>

In calendar component you can use with

<div *ngFor="let item of data">{{item.date}}</div>


问:
MySQL find gaps in two column sequence
I've searched through and tried to modify some other answers here for a solution, but I am unable to come up with anything that works.

I have a table that has a two column sequence. The first column is, unfortunately, a string, which represents a hex value, e.g. 0x0010. The second column is another counter that goes from 0-15 inclusive.

I am looking for gaps from 0x0000 to 0xFFFF and from 0-15 in each hex space. Some hex spaces can be completely empty, in which case, the query or procedure would report that all 0-15 are blank.

For example, given:

```<code>id    hex_counter    integer_counter
1          0x0000                  0
2          0x0000                  1
3          0x0000                  5
4          0x0001                 10
5          0x0003                  7
</code>```

And only searching from 0x0 to 0x3, I'd expect something like:

```<code>hex_counter    gaps
0x0000         2-4
0x0000         6-15
0x0001         0-9
0x0001         11-15
0x0002         0-15
0x0003         0-6
0x0003         8-15
</code>```

Or the same set with each number in its own row.

I have tried putting this in a stored procedure as follows:

CREATE PROCEDURE find_blanks()
BEGIN
    DECLARE curr INT UNSIGNED DEFAULT 0;
    DECLARE max INT UNSIGNED DEFAULT 65535;

    CREATE TEMPORARY TABLE IF NOT EXISTS unused
    (
        hex_counter VARCHAR(255),
        gap VARCHAR(255)
    );

    WHILE curr < max DO
        INSERT INTO unused (hex_counter, gap)
        SELECT CONCAT( '0x', LPAD(CONV(curr, 10, 16), 4, '0')), m.missing from (
        SELECT CONCAT(z.expected, IF(z.got+1<z.expected, CONCAT('-',z.got+1), '')) AS missing FROM ( SELECT @rownuma:=@rownuma-1 AS expected, IF(@rownuma=int_counter, 16, @rownuma:=int_counter) AS got FROM (SELECT @rownuma:=16) AS a JOIN table WHERE hex_counter = CONCAT( '0x', LPAD(CONV(curr, 10, 16), 4, '0')) ORDER BY int_counter) AS z WHERE z.got >= 0 AND z.got < 16
        UNION
        SELECT CONCAT(z.expected, IF(z.got-1>z.expected, CONCAT('-',z.got-1), '')) AS missing FROM ( SELECT @rownumb:=@rownumb+1 AS expected, IF(@rownumb=int_counter, 0, @rownumb:=int_counter) AS got FROM (SELECT @rownumb:=0) AS a JOIN table WHERE project = project_in AND hex_counter = CONCAT( '0x', LPAD(CONV(curr, 10, 16), 4, '0')) ORDER BY int_counter) AS z WHERE z.got >= 0 AND z.got < 16) as m;
        SET curr = curr + 1;
    END WHILE;

    DROP TABLE IF EXISTS unused;

    SELECT * from unused;
END;
```

This returns incorrect information, such as negative numbers etc. I'm about to implement something in python that will send a query for each hex value, but that will lead to about 65535 queries and I'd like to avoid that if possible.

Thank you!

答:
Exclusively for versions prior to 8.0...</p>

```<code>DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,hex_counter CHAR(6) NOT NULL
,integer_counter INT NOT NULL
);

INSERT INTO my_table VALUES
(1,'0x0000', 0),
(2,'0x0000', 1),
(3,'0x0000', 5),
(4,'0x0001',10),
(5,'0x0003', 7);

DROP TABLE IF EXISTS ints;

CREATE TABLE ints (i INT NOT NULL PRIMARY KEY);

INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);

SELECT hex_counter
     , MIN(int_counter) range_start
     , MAX(int_counter) range_end
  FROM
     ( SELECT hex_counter
            , int_counter
            , CASE WHEN @prev=j THEN @k:=@k ELSE @k:=@k+1 END k
            , @prev:=j b
         FROM
            ( SELECT UNHEX(HEX('0x0000')+h.i) hex_counter
                   , (i2.i*10)+i1.i int_counter
                   , COALESCE(x.integer_counter = (i2.i*10)+i1.i,0) j
                FROM ints h
                JOIN ints i1
                JOIN ints i2
                LEFT
                JOIN my_table x
                  ON x.hex_counter = UNHEX(HEX('0x0000')+h.i)
                 AND x.integer_counter = (i2.i*10)+i1.i
                JOIN (SELECT @j:=0) vars
               WHERE h.i <=3
                 AND (i2.i*10)+i1.i <= 15
               ORDER
                  BY hex_counter
                   , int_counter
            ) a
         JOIN (SELECT @prev:=null,@k:=0) vars
        ORDER
           BY hex_counter
            , int_counter
      ) n
  WHERE b = 0
  GROUP
     BY hex_counter, k;

+-------------+-------------+-----------+
| hex_counter | range_start | range_end |
+-------------+-------------+-----------+
| 0x0000      |           2 |         4 |
| 0x0000      |           6 |        15 |
| 0x0001      |           0 |         9 |
| 0x0001      |          11 |        15 |
| 0x0002      |           0 |        15 |
| 0x0003      |           0 |         6 |
| 0x0003      |           8 |        15 |
+-------------+-------------+-----------+
</code>```

Title: MySQL find gaps in two column sequence

Body:
I've searched through and tried to modify some other answers here for a solution, but I am unable to come up with anything that works.

I have a table that has a two column sequence. The first column is, unfortunately, a string, which represents a hex value, e.g. 0x0010. The second column is another counter that goes from 0-15 inclusive.

I am looking for gaps from 0x0000 to 0xFFFF and from 0-15 in each hex space. Some hex spaces can be completely empty, in which case, the query or procedure would report that all 0-15 are blank.

For example, given:

id    hex_counter    integer_counter
1          0x0000                  0
2          0x0000                  1
3          0x0000                  5
4          0x0001                 10
5          0x0003                  7

And only searching from 0x0 to 0x3, I'd expect something like:

hex_counter    gaps
0x0000         2-4
0x0000         6-15
0x0001         0-9
0x0001         11-15
0x0002         0-15
0x0003         0-6
0x0003         8-15

Or the same set with each number in its own row.

I have tried putting this in a stored procedure as follows:

CREATE PROCEDURE find_blanks()
BEGIN
    DECLARE curr INT UNSIGNED DEFAULT 0;
    DECLARE max INT UNSIGNED DEFAULT 65535;

    CREATE TEMPORARY TABLE IF NOT EXISTS unused
    (
        hex_counter VARCHAR(255),
        gap VARCHAR(255)
    );

    WHILE curr < max DO
        INSERT INTO unused (hex_counter, gap)
        SELECT CONCAT( '0x', LPAD(CONV(curr, 10, 16), 4, '0')), m.missing from (
        SELECT CONCAT(z.expected, IF(z.got+1<z.expected, CONCAT('-',z.got+1), '')) AS missing FROM ( SELECT @rownuma:=@rownuma-1 AS expected, IF(@rownuma=int_counter, 16, @rownuma:=int_counter) AS got FROM (SELECT @rownuma:=16) AS a JOIN table WHERE hex_counter = CONCAT( '0x', LPAD(CONV(curr, 10, 16), 4, '0')) ORDER BY int_counter) AS z WHERE z.got >= 0 AND z.got < 16
        UNION
        SELECT CONCAT(z.expected, IF(z.got-1>z.expected, CONCAT('-',z.got-1), '')) AS missing FROM ( SELECT @rownumb:=@rownumb+1 AS expected, IF(@rownumb=int_counter, 0, @rownumb:=int_counter) AS got FROM (SELECT @rownumb:=0) AS a JOIN table WHERE project = project_in AND hex_counter = CONCAT( '0x', LPAD(CONV(curr, 10, 16), 4, '0')) ORDER BY int_counter) AS z WHERE z.got >= 0 AND z.got < 16) as m;
        SET curr = curr + 1;
    END WHILE;

    DROP TABLE IF EXISTS unused;

    SELECT * from unused;
END;

This returns incorrect information, such as negative numbers etc. I'm about to implement something in python that will send a query for each hex value, but that will lead to about 65535 queries and I'd like to avoid that if possible.

Thank you!

Body:
Exclusively for versions prior to 8.0...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,hex_counter CHAR(6) NOT NULL
,integer_counter INT NOT NULL
);

INSERT INTO my_table VALUES
(1,'0x0000', 0),
(2,'0x0000', 1),
(3,'0x0000', 5),
(4,'0x0001',10),
(5,'0x0003', 7);

DROP TABLE IF EXISTS ints;

CREATE TABLE ints (i INT NOT NULL PRIMARY KEY);

INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);

SELECT hex_counter
     , MIN(int_counter) range_start
     , MAX(int_counter) range_end
  FROM
     ( SELECT hex_counter
            , int_counter
            , CASE WHEN @prev=j THEN @k:=@k ELSE @k:=@k+1 END k
            , @prev:=j b
         FROM
            ( SELECT UNHEX(HEX('0x0000')+h.i) hex_counter
                   , (i2.i*10)+i1.i int_counter
                   , COALESCE(x.integer_counter = (i2.i*10)+i1.i,0) j
                FROM ints h
                JOIN ints i1
                JOIN ints i2
                LEFT
                JOIN my_table x
                  ON x.hex_counter = UNHEX(HEX('0x0000')+h.i)
                 AND x.integer_counter = (i2.i*10)+i1.i
                JOIN (SELECT @j:=0) vars
               WHERE h.i <=3
                 AND (i2.i*10)+i1.i <= 15
               ORDER
                  BY hex_counter
                   , int_counter
            ) a
         JOIN (SELECT @prev:=null,@k:=0) vars
        ORDER
           BY hex_counter
            , int_counter
      ) n
  WHERE b = 0
  GROUP
     BY hex_counter, k;

+-------------+-------------+-----------+
| hex_counter | range_start | range_end |
+-------------+-------------+-----------+
| 0x0000      |           2 |         4 |
| 0x0000      |           6 |        15 |
| 0x0001      |           0 |         9 |
| 0x0001      |          11 |        15 |
| 0x0002      |           0 |        15 |
| 0x0003      |           0 |         6 |
| 0x0003      |           8 |        15 |
+-------------+-------------+-----------+


问:
How to increase the height of column header in ag-grid?

Is there a way to increase the height of the column header like we do for the width. I need this because I've embedded a piechart in header and which is binded but the column is too short to show it completely. is there a way to increase size of a column header.

答:
Header Height property can also be set directly on the grid component in pixels like so:</p>

```<code><ag-grid-vue style="width: 100%;height: 47vh;"
    class="ag-theme-balham"
    :columnDefs="columnDefs"
    :rowData="rowData"
    headerHeight="50">
</ag-grid-vue>
</code>```

Body:
Header Height property can also be set directly on the grid component in pixels like so:

<ag-grid-vue style="width: 100%;height: 47vh;"
    class="ag-theme-balham"
    :columnDefs="columnDefs"
    :rowData="rowData"
    headerHeight="50">
</ag-grid-vue>


答:
The problem is that you are using annonimous class. This is how the new View.OnClickListener(){ construct is called. When you access variables from within annonymous class they need to be final. In your case theClicked1/2/3/4 variables are not final and this is why you are not able to modify and preserve the result.

You have couple of options:

Alternative 1 Use a state pattern. Instead of anonymous class create a real class that extends from View.OnClickListener  create a State class where your shared state is and share it in between the action listener and the class holding the buttons. This way your state will be accessable and modifyable.

Here is an article describing the State pattern https://dzone.com/articles/design-patterns-state

Here is on very detailed implementation of the state pattern using swing. https://hal.inria.fr/inria-00538334/PDF/SwingStates.pdf

Alternative 2 would be to use some sort of storage to hold the state in the form of a file, or a database.

Title: How to save booleans so i can use them when coming back to this activity?


问:
Text Editor in filtered ComboBox does not display text
I adapted Jonathan Stenbackas Answer (JavaFX - Filtered ComboBox) to a ComboBox with a Jooq Record Bean, displaying one of the Beans fields using a custom ListCell/ButtonCell.
The filtering works fine, but I can't get the Editor to show the text of the selected items field.

I added a listener to the combobox' selection and let it print out editors Text. So I get the toString() of the bean, but the Editor is empty. When I use the listener to set the text programmatically, the programmatically set text is printed out, but the editor does not show it.
I also tried a JavaFX bean for testing, with the same result.
Any recommendation would be highly appreciated.

```<code>//retrieving data from database
ObservableList<MyRecord> items = applicationContext.getFetchData().fetchOList();

//wrapping in a FilteredList

FilteredList<MyRecord> filteredItems = new FilteredList<>(items, p -> true);

    ComboBox<MyRecord> cb = new ComboBox<>(filteredItems);
    cb.setEditable(true);
    cb.setCellFactory(c_ -> new NamenCell());
    cb.setButtonCell(new NamenCell());
    TextField editor = cb.getEditor();

    editor.textProperty().addListener((obs, oldValue, newValue) -> {

        final MyRecord selected = cb.getSelectionModel().getSelectedItem();

        Platform.runLater(() -> {
            if (selected == null || !selected.getSurname().equals(editor.getText())) {
                filteredItems.setPredicate(item -> {
                    if (item.getSurname().toLowerCase().contains(newValue.toLowerCase())) {
                        return true;
                    } else {
                        return false;
                    }
                });
            }

        });
    });

    cb.getSelectionModel().selectedItemProperty().addListener(
            (ob, oldValue, newValue) -> {
                if (newValue != null) {
                    cb.getEditor().setText(newValue.getSurname());
                    System.out.println(cb.getEditor().getText());

                }

            });

//The Cell class:

public class NamenCell extends ListCell<MyRecord> {

    public NamenCell() { }
    @Override
    protected void updateItem(MyRecord item, boolean empty) {
        super.updateItem(item, empty);
        setText(item == null ? "" : item.getSurname());

    }
}
</code>```

答:
I found a solution: I extended Combobox.
Perhaps this may be useful to someone:</p>

```<code>

       import javafx.application.Platform;
    import javafx.beans.property.Property;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.collections.transformation.FilteredList;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.TextField;
    import org.jooq.impl.TableRecordImpl;

    public class FilterComboBox extends ComboBox {
        private ObservableList ol;
        private ObservableList items;
        private FilteredList filteredItems;
        private FilteredList filteredOl;
        private String field;
        private Property selectedBeanProperty = new SimpleObjectProperty();

        public FilterComboBox(){

        }

        public FilterComboBox(ObservableList ol, String field) {
          populate(ol,field);
        }

        public Property selectedBeanProperty() {
            return selectedBeanProperty;
        }

        public void setSelectedBeanProperty(T selectedBeanProperty) {
            this.selectedBeanProperty.setValue(selectedBeanProperty);
        }

        private ObservableList createItems(ObservableList ol, String field) {
            this.items = FXCollections.observableArrayList();
            for (T t : ol) items.add(t.get(field).toString());
            return items;
        }

        public void populate(ObservableList ol, String field){
            this.field=field;
            this.ol = ol;
            this.items = createItems(this.ol, field);
            this.filteredItems = new FilteredList(items, p -> true);
            this.filteredOl= new FilteredList(ol, p->true);
            this.setEditable(true);
            this.setItems(filteredItems);

            TextField editor = this.getEditor();
            editor.textProperty().addListener((obs, oldValue, newValue) -> {
                final String selected = this.getSelectionModel().getSelectedItem();

                Platform.runLater(() -> {
                    if (selected == null || !selected.equals(editor.getText())) {
                        filteredItems.setPredicate(item -> {
                            if (item.toLowerCase().contains(newValue.toLowerCase())) {
                                return true;
                            } else {
                                return false;
                            }
                        });
                    }

                });

            });

            this.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
                if (newValue != null &&!newValue.isEmpty() ) {
                    setSelectedBeanProperty(this.ol.get(getOlIndex(newValue, field)));
                }
            });
        }

        public Integer getOlIndex(String s, String field){
            for (T t : ol)
                if(t.get(field).toString().equals(s)){
                return ol.indexOf(t);
            }
            return -1;
        }

    }

</code>```

Body:
I adapted Jonathan Stenbackas Answer (JavaFX - Filtered ComboBox) to a ComboBox with a Jooq Record Bean, displaying one of the Beans fields using a custom ListCell/ButtonCell.
The filtering works fine, but I can't get the Editor to show the text of the selected items field.

I added a listener to the combobox' selection and let it print out editors Text. So I get the toString() of the bean, but the Editor is empty. When I use the listener to set the text programmatically, the programmatically set text is printed out, but the editor does not show it.
I also tried a JavaFX bean for testing, with the same result.
Any recommendation would be highly appreciated.

//retrieving data from database
ObservableList<MyRecord> items = applicationContext.getFetchData().fetchOList();

//wrapping in a FilteredList

FilteredList<MyRecord> filteredItems = new FilteredList<>(items, p -> true);

    ComboBox<MyRecord> cb = new ComboBox<>(filteredItems);
    cb.setEditable(true);
    cb.setCellFactory(c_ -> new NamenCell());
    cb.setButtonCell(new NamenCell());
    TextField editor = cb.getEditor();

    editor.textProperty().addListener((obs, oldValue, newValue) -> {

        final MyRecord selected = cb.getSelectionModel().getSelectedItem();

        Platform.runLater(() -> {
            if (selected == null || !selected.getSurname().equals(editor.getText())) {
                filteredItems.setPredicate(item -> {
                    if (item.getSurname().toLowerCase().contains(newValue.toLowerCase())) {
                        return true;
                    } else {
                        return false;
                    }
                });
            }

        });
    });

    cb.getSelectionModel().selectedItemProperty().addListener(
            (ob, oldValue, newValue) -> {
                if (newValue != null) {
                    cb.getEditor().setText(newValue.getSurname());
                    System.out.println(cb.getEditor().getText());

                }

            });

//The Cell class:

public class NamenCell extends ListCell<MyRecord> {

    public NamenCell() { }
    @Override
    protected void updateItem(MyRecord item, boolean empty) {
        super.updateItem(item, empty);
        setText(item == null ? "" : item.getSurname());

    }
}

Body:
I found a solution: I extended Combobox.
Perhaps this may be useful to someone:

       import javafx.application.Platform;
    import javafx.beans.property.Property;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.collections.transformation.FilteredList;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.TextField;
    import org.jooq.impl.TableRecordImpl;

    public class FilterComboBox extends ComboBox {
        private ObservableList ol;
        private ObservableList items;
        private FilteredList filteredItems;
        private FilteredList filteredOl;
        private String field;
        private Property selectedBeanProperty = new SimpleObjectProperty();

        public FilterComboBox(){

        }

        public FilterComboBox(ObservableList ol, String field) {
          populate(ol,field);
        }

        public Property selectedBeanProperty() {
            return selectedBeanProperty;
        }

        public void setSelectedBeanProperty(T selectedBeanProperty) {
            this.selectedBeanProperty.setValue(selectedBeanProperty);
        }

        private ObservableList createItems(ObservableList ol, String field) {
            this.items = FXCollections.observableArrayList();
            for (T t : ol) items.add(t.get(field).toString());
            return items;
        }

        public void populate(ObservableList ol, String field){
            this.field=field;
            this.ol = ol;
            this.items = createItems(this.ol, field);
            this.filteredItems = new FilteredList(items, p -> true);
            this.filteredOl= new FilteredList(ol, p->true);
            this.setEditable(true);
            this.setItems(filteredItems);

            TextField editor = this.getEditor();
            editor.textProperty().addListener((obs, oldValue, newValue) -> {
                final String selected = this.getSelectionModel().getSelectedItem();

                Platform.runLater(() -> {
                    if (selected == null || !selected.equals(editor.getText())) {
                        filteredItems.setPredicate(item -> {
                            if (item.toLowerCase().contains(newValue.toLowerCase())) {
                                return true;
                            } else {
                                return false;
                            }
                        });
                    }

                });

            });

            this.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
                if (newValue != null &&!newValue.isEmpty() ) {
                    setSelectedBeanProperty(this.ol.get(getOlIndex(newValue, field)));
                }
            });
        }

        public Integer getOlIndex(String s, String field){
            for (T t : ol)
                if(t.get(field).toString().equals(s)){
                return ol.indexOf(t);
            }
            return -1;
        }

    }


问:
Lerping between blue and green produces grey? Unity, 2d Sprite.colour
I'm having trouble to mix 2 colour on touching sprites  (when blue and yellow makes grey )
To lerp or not to lerp....

Combinations that work:

Yellow and red = produces orange

Blue and red = produces purple.

Blue and yellow produces grey

if interpolated colour is not the best way to mix colour to accurately reflect the kind of mixing we would do on a colour-wheel ... then what is the correct way?

```<code>SpriteRenderer tempCol01 = collidedColour.mainColourGO.GetComponent<SpriteRenderer>();
tempCol01.color = Color32.Lerp(col01, col02, 0.5f);
</code>```

--------------------------------Second attempt------------------------------

//next I have also tried as suggested by vislila (thanks dude)
(now mixes blue and yellow) but still doesn't mix some other colours correctly... win some lose some ;)

//New Code using HSBColor.Lerp....

```<code>SpriteRenderer tempCol01 = collidedColour.mainColourGO.GetComponent<SpriteRenderer>();
            tempCol01.color = Slerp(col01, col02, 0.5f);

public static Color Slerp(Color a, Color b, float t)
    {
        return (HSBColor.Lerp(HSBColor.FromColor(a), HSBColor.FromColor(b), t)).ToColor();
    }
</code>```

Am a bit nubie - so maybe im doing it wrong?

//link to scripts
http://wiki.unity3d.com/index.php/Colorx

download:
HSBColor.unityPackage.zip
"helper function to tie in with HSBColor that will let you slerp between two Unity Colors. The slerp function provides much more pleasing visual results than Color.Lerp"

答:
There's a useful HSBColor struct on the unity wiki that handles lerping in HSV/HSB space:

With it, you can lerp between two Colors in HSB space:

```<code>public Color LerpViaHSB(Color a, Color b, float t)
{
     return HSBColor.Lerp(HSBColor.FromColor(a), HSBColor.FromColor(b), t).ToColor();
}
</code>```

Here's the HSBColor struct as shown on the unity wiki:

```<code>using UnityEngine;

[System.Serializable]
public struct HSBColor
{
    public float h;
    public float s;
    public float b;
    public float a;

    public HSBColor(float h, float s, float b, float a)
    {
        this.h = h;
        this.s = s;
        this.b = b;
        this.a = a;
    }

    public HSBColor(float h, float s, float b)
    {
        this.h = h;
        this.s = s;
        this.b = b;
        this.a = 1f;
    }

    public HSBColor(Color col)
    {
        HSBColor temp = FromColor(col);
        h = temp.h;
        s = temp.s;
        b = temp.b;
        a = temp.a;
    }

    public static HSBColor FromColor(Color color)
    {
        HSBColor ret = new HSBColor(0f, 0f, 0f, color.a);

        float r = color.r;
        float g = color.g;
        float b = color.b;

        float max = Mathf.Max(r, Mathf.Max(g, b));

        if (max <= 0)
        {
            return ret;
        }

        float min = Mathf.Min(r, Mathf.Min(g, b));
        float dif = max - min;

        if (max > min)
        {
            if (g == max)
            {
                ret.h = (b - r) / dif * 60f + 120f;
            }
            else if (b == max)
            {
                ret.h = (r - g) / dif * 60f + 240f;
            }
            else if (b > g)
            {
                ret.h = (g - b) / dif * 60f + 360f;
            }
            else
            {
                ret.h = (g - b) / dif * 60f;
            }
            if (ret.h < 0)
            {
                ret.h = ret.h + 360f;
            }
        }
        else
        {
            ret.h = 0;
        }

        ret.h *= 1f / 360f;
        ret.s = (dif / max) * 1f;
        ret.b = max;

        return ret;
    }

    public static Color ToColor(HSBColor hsbColor)
    {
        float r = hsbColor.b;
        float g = hsbColor.b;
        float b = hsbColor.b;
        if (hsbColor.s != 0)
        {
            float max = hsbColor.b;
            float dif = hsbColor.b * hsbColor.s;
            float min = hsbColor.b - dif;

            float h = hsbColor.h * 360f;

            if (h < 60f)
            {
                r = max;
                g = h * dif / 60f + min;
                b = min;
            }
            else if (h < 120f)
            {
                r = -(h - 120f) * dif / 60f + min;
                g = max;
                b = min;
            }
            else if (h < 180f)
            {
                r = min;
                g = max;
                b = (h - 120f) * dif / 60f + min;
            }
            else if (h < 240f)
            {
                r = min;
                g = -(h - 240f) * dif / 60f + min;
                b = max;
            }
            else if (h < 300f)
            {
                r = (h - 240f) * dif / 60f + min;
                g = min;
                b = max;
            }
            else if (h <= 360f)
            {
                r = max;
                g = min;
                b = -(h - 360f) * dif / 60 + min;
            }
            else
            {
                r = 0;
                g = 0;
                b = 0;
            }
        }

        return new Color(Mathf.Clamp01(r),Mathf.Clamp01(g),Mathf.Clamp01(b),hsbColor.a);
    }

    public Color ToColor()
    {
        return ToColor(this);
    }

    public override string ToString()
    {
        return "H:" + h + " S:" + s + " B:" + b;
    }

    public static HSBColor Lerp(HSBColor a, HSBColor b, float t)
    {
        float h,s;

        //check special case black (color.b==0): interpolate neither hue nor saturation!
        //check special case grey (color.s==0): don't interpolate hue!
        if(a.b==0){
            h=b.h;
            s=b.s;
        }else if(b.b==0){
            h=a.h;
            s=a.s;
        }else{
            if(a.s==0){
                h=b.h;
            }else if(b.s==0){
                h=a.h;
            }else{
                // works around bug with LerpAngle
                float angle = Mathf.LerpAngle(a.h * 360f, b.h * 360f, t);
                while (angle < 0f)
                    angle += 360f;
                while (angle > 360f)
                    angle -= 360f;
                h=angle/360f;
            }
            s=Mathf.Lerp(a.s,b.s,t);
        }
        return new HSBColor(h, s, Mathf.Lerp(a.b, b.b, t), Mathf.Lerp(a.a, b.a, t));
    }

    public static void Test()
    {
        HSBColor color;

        color = new HSBColor(Color.red);
        Debug.Log("red: " + color);

        color = new HSBColor(Color.green);
        Debug.Log("green: " + color);

        color = new HSBColor(Color.blue);
        Debug.Log("blue: " + color);

        color = new HSBColor(Color.grey);
        Debug.Log("grey: " + color);

        color = new HSBColor(Color.white);
        Debug.Log("white: " + color);

        color = new HSBColor(new Color(0.4f, 1f, 0.84f, 1f));
        Debug.Log("0.4, 1f, 0.84: " + color);

        Debug.Log("164,82,84   .... 0.643137f, 0.321568f, 0.329411f  :" + ToColor(new HSBColor(new Color(0.643137f, 0.321568f, 0.329411f))));
    }
}
</code>```

Body:
I'm having trouble to mix 2 colour on touching sprites  (when blue and yellow makes grey )
To lerp or not to lerp....

Combinations that work:

Yellow and red = produces orange

Blue and red = produces purple.

Blue and yellow produces grey

if interpolated colour is not the best way to mix colour to accurately reflect the kind of mixing we would do on a colour-wheel ... then what is the correct way?

SpriteRenderer tempCol01 = collidedColour.mainColourGO.GetComponent<SpriteRenderer>();
tempCol01.color = Color32.Lerp(col01, col02, 0.5f);

--------------------------------Second attempt------------------------------

//next I have also tried as suggested by vislila (thanks dude)
(now mixes blue and yellow) but still doesn't mix some other colours correctly... win some lose some ;)

//New Code using HSBColor.Lerp....

SpriteRenderer tempCol01 = collidedColour.mainColourGO.GetComponent<SpriteRenderer>();
            tempCol01.color = Slerp(col01, col02, 0.5f);

public static Color Slerp(Color a, Color b, float t)
    {
        return (HSBColor.Lerp(HSBColor.FromColor(a), HSBColor.FromColor(b), t)).ToColor();
    }

Am a bit nubie - so maybe im doing it wrong?

//link to scripts
http://wiki.unity3d.com/index.php/Colorx

download:
HSBColor.unityPackage.zip
"helper function to tie in with HSBColor that will let you slerp between two Unity Colors. The slerp function provides much more pleasing visual results than Color.Lerp"

Body:
There's a useful HSBColor struct on the unity wiki that handles lerping in HSV/HSB space:

With it, you can lerp between two Colors in HSB space:

public Color LerpViaHSB(Color a, Color b, float t)
{
     return HSBColor.Lerp(HSBColor.FromColor(a), HSBColor.FromColor(b), t).ToColor();
}

Here's the HSBColor struct as shown on the unity wiki:

using UnityEngine;

[System.Serializable]
public struct HSBColor
{
    public float h;
    public float s;
    public float b;
    public float a;

    public HSBColor(float h, float s, float b, float a)
    {
        this.h = h;
        this.s = s;
        this.b = b;
        this.a = a;
    }

    public HSBColor(float h, float s, float b)
    {
        this.h = h;
        this.s = s;
        this.b = b;
        this.a = 1f;
    }

    public HSBColor(Color col)
    {
        HSBColor temp = FromColor(col);
        h = temp.h;
        s = temp.s;
        b = temp.b;
        a = temp.a;
    }

    public static HSBColor FromColor(Color color)
    {
        HSBColor ret = new HSBColor(0f, 0f, 0f, color.a);

        float r = color.r;
        float g = color.g;
        float b = color.b;

        float max = Mathf.Max(r, Mathf.Max(g, b));

        if (max <= 0)
        {
            return ret;
        }

        float min = Mathf.Min(r, Mathf.Min(g, b));
        float dif = max - min;

        if (max > min)
        {
            if (g == max)
            {
                ret.h = (b - r) / dif * 60f + 120f;
            }
            else if (b == max)
            {
                ret.h = (r - g) / dif * 60f + 240f;
            }
            else if (b > g)
            {
                ret.h = (g - b) / dif * 60f + 360f;
            }
            else
            {
                ret.h = (g - b) / dif * 60f;
            }
            if (ret.h < 0)
            {
                ret.h = ret.h + 360f;
            }
        }
        else
        {
            ret.h = 0;
        }

        ret.h *= 1f / 360f;
        ret.s = (dif / max) * 1f;
        ret.b = max;

        return ret;
    }

    public static Color ToColor(HSBColor hsbColor)
    {
        float r = hsbColor.b;
        float g = hsbColor.b;
        float b = hsbColor.b;
        if (hsbColor.s != 0)
        {
            float max = hsbColor.b;
            float dif = hsbColor.b * hsbColor.s;
            float min = hsbColor.b - dif;

            float h = hsbColor.h * 360f;

            if (h < 60f)
            {
                r = max;
                g = h * dif / 60f + min;
                b = min;
            }
            else if (h < 120f)
            {
                r = -(h - 120f) * dif / 60f + min;
                g = max;
                b = min;
            }
            else if (h < 180f)
            {
                r = min;
                g = max;
                b = (h - 120f) * dif / 60f + min;
            }
            else if (h < 240f)
            {
                r = min;
                g = -(h - 240f) * dif / 60f + min;
                b = max;
            }
            else if (h < 300f)
            {
                r = (h - 240f) * dif / 60f + min;
                g = min;
                b = max;
            }
            else if (h <= 360f)
            {
                r = max;
                g = min;
                b = -(h - 360f) * dif / 60 + min;
            }
            else
            {
                r = 0;
                g = 0;
                b = 0;
            }
        }

        return new Color(Mathf.Clamp01(r),Mathf.Clamp01(g),Mathf.Clamp01(b),hsbColor.a);
    }

    public Color ToColor()
    {
        return ToColor(this);
    }

    public override string ToString()
    {
        return "H:" + h + " S:" + s + " B:" + b;
    }

    public static HSBColor Lerp(HSBColor a, HSBColor b, float t)
    {
        float h,s;

        //check special case black (color.b==0): interpolate neither hue nor saturation!
        //check special case grey (color.s==0): don't interpolate hue!
        if(a.b==0){
            h=b.h;
            s=b.s;
        }else if(b.b==0){
            h=a.h;
            s=a.s;
        }else{
            if(a.s==0){
                h=b.h;
            }else if(b.s==0){
                h=a.h;
            }else{
                // works around bug with LerpAngle
                float angle = Mathf.LerpAngle(a.h * 360f, b.h * 360f, t);
                while (angle < 0f)
                    angle += 360f;
                while (angle > 360f)
                    angle -= 360f;
                h=angle/360f;
            }
            s=Mathf.Lerp(a.s,b.s,t);
        }
        return new HSBColor(h, s, Mathf.Lerp(a.b, b.b, t), Mathf.Lerp(a.a, b.a, t));
    }

    public static void Test()
    {
        HSBColor color;

        color = new HSBColor(Color.red);
        Debug.Log("red: " + color);

        color = new HSBColor(Color.green);
        Debug.Log("green: " + color);

        color = new HSBColor(Color.blue);
        Debug.Log("blue: " + color);

        color = new HSBColor(Color.grey);
        Debug.Log("grey: " + color);

        color = new HSBColor(Color.white);
        Debug.Log("white: " + color);

        color = new HSBColor(new Color(0.4f, 1f, 0.84f, 1f));
        Debug.Log("0.4, 1f, 0.84: " + color);

        Debug.Log("164,82,84   .... 0.643137f, 0.321568f, 0.329411f  :" + ToColor(new HSBColor(new Color(0.643137f, 0.321568f, 0.329411f))));
    }
}


问:
Unable to create add migrations with EntityFrameworkCore.Tools and AzureFunctions
I have been trying for hours to run migrations on Azure Functions with EntityFramework.Core. It throws an error:

```<code>PM> add-migration newmigration
Error:
  An assembly specified in the application dependencies manifest (Test.API.deps.json) was not found:
    package: 'Test.API', version: '1.0.0'
    path: 'Test.API.dll'
</code>```

To try to solve the problem, I updated the .net core version to 2.2.300(currently the latest) from 2.2.104.Updated the Azure functions SDK and EntityFramework to the latest too. Tried with different sql servers but still no progress. Deleted the bin and obj folders - no luck. And even delete the packet manager cache...

UPDATE:
The problem is than in the folder bin/debug/netcoreapp2.2 I have another folder bin where the Test.API.dll is but the manifest file is in folder  bin/debug/netcoreapp2.2.
If you cut and paste everything from the inner bin in bin/debug/netcoreapp2.2, everything works fine. Also if you go to the manifest file and explicitly add the whole path to Test.API.dll, it works.
But it still needs manual work, any thoughts how to make it automatically recognize the right path to Test.API.dll?

答:
@jeffhollan found a solution available here:
https://github.com/jeffhollan/functions-csharp-entityframeworkcore/blob/master/functions-csharp-entityframeworkcore/functions-csharp-entityframeworkcore.csproj

In your csproj, add theses lines:

```<code>   <Target Name="PostBuild" AfterTargets="PostBuildEvent">
     <Exec Command="copy /Y "$(TargetDir)bin\$(ProjectName).dll"
 "$(TargetDir)$(ProjectName).dll"" />
 </Target>
</code>```

Hope it will help!

Body:
I have been trying for hours to run migrations on Azure Functions with EntityFramework.Core. It throws an error:

PM> add-migration newmigration
Error:
  An assembly specified in the application dependencies manifest (Test.API.deps.json) was not found:
    package: 'Test.API', version: '1.0.0'
    path: 'Test.API.dll'

To try to solve the problem, I updated the .net core version to 2.2.300(currently the latest) from 2.2.104.Updated the Azure functions SDK and EntityFramework to the latest too. Tried with different sql servers but still no progress. Deleted the bin and obj folders - no luck. And even delete the packet manager cache...

UPDATE:
The problem is than in the folder bin/debug/netcoreapp2.2 I have another folder bin where the Test.API.dll is but the manifest file is in folder  bin/debug/netcoreapp2.2.
If you cut and paste everything from the inner bin in bin/debug/netcoreapp2.2, everything works fine. Also if you go to the manifest file and explicitly add the whole path to Test.API.dll, it works.
But it still needs manual work, any thoughts how to make it automatically recognize the right path to Test.API.dll?

Body:
@jeffhollan found a solution available here:
https://github.com/jeffhollan/functions-csharp-entityframeworkcore/blob/master/functions-csharp-entityframeworkcore/functions-csharp-entityframeworkcore.csproj

In your csproj, add theses lines:

   <Target Name="PostBuild" AfterTargets="PostBuildEvent">
     <Exec Command="copy /Y &quot;$(TargetDir)bin\$(ProjectName).dll&quot;
 &quot;$(TargetDir)$(ProjectName).dll&quot;" />
 </Target>

Hope it will help!


问:
How to select and show thousands of records
I have an SQLite query that, potentially, returns thousands of records. I need to show these records in a ListView but, obviously, I cannot show them all together. Which is the Android-way to solve this problem?</p>

答: I don't think you'll have a problem with thousands of records in a ListView unless you don't use a Cursor.</p>


问:
Unable to find Alexa-skill-kit-sdk-factskill blueprint on aws lamda
I'm quite a beginner to Alexa skill set. Trying to add a node.js skill to Alexa following few nuggets from the internet. I have created skill on amazon developer console and trying to create aws lambda function on aws console. Surprisingly, when I tried creating a lambda function, I could not find any blueprint matching to "Alexa" keyword.

Here are the steps -:
    1.Got to aws.amazon.com and log in
    2. Search for the Lambda service and go to it
    3. Click on Create a function
    4. Click on Blueprints
    5. Search for “Alexa”

I did some research and it says, changing to North. Virginia region could help but no luck so far.

Any such leads would be really appreciated.

答: Use cloudformation application templates instead. Though they are still outdated (like the blueprints out there). My advice is that you create an Alexa Hosted Skill instead</p>


问:
How to update records on production environment?
Ruby on Rails
We recently added a field to a table and that field is populated when a record is created. However, we have older records in the table. Meaning the newly added fields are not populated in those records. Now I need to update them.
So,.what is the best way to update the older records? The value to populate needs some computation before storing.
The server is hosted on AWS.
I know rake task is one option. But are there any other efficient ways?</p>

答: Ideally you'll put these updates in your migrations file. Not helpful for migrations you've already done, but for any database modification which will affect older records, always put the required changes in the migration file.</p>


答: Nil is just 0. Setting them to 0 will do the same thing that setting them to nil would do.</p>

Title: Assign nil value to double in Objective-C


问:
When is the @JsonProperty property used and what is it used for?
This bean 'State' :

```<code>public class State {

    private boolean isSet;

    @JsonProperty("isSet")
    public boolean isSet() {
        return isSet;
    }

    @JsonProperty("isSet")
    public void setSet(boolean isSet) {
        this.isSet = isSet;
    }

}
</code>```

is sent over the wire using the ajax ' success' callback :

```<code>        success : function(response) {
            if(response.State.isSet){
                alert('success called successfully)
            }
</code>```

Is the annotation @JsonProperty required here ? What is the advantage of using it ?
I think I can remove this annotation without causing any side effects.

Reading about this annotion on https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations I don't know when this is required to be used ?

答:
In addition to all the answers above, don't forget the part of the documentation that says

Marker annotation that can be used to define a non-static method as a
  "setter" or "getter" for a logical property (depending on its
  signature), or non-static object field to be used (serialized,
  deserialized) as a logical property.

If you have a non-static method in your class that is not a conventional getter or setter then you can make it act like a getter and setter by using the annotation on it. See the example below

```<code>public class Testing {
    private Integer id;
    private String username;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getIdAndUsername() {
        return id + "." + username;
    }

    public String concatenateIdAndUsername() {
        return id + "." + username;
    }
}
</code>```

When the above object is serialized, then response will contain

username from getUsername()

id from getId()

idAndUsername from getIdAndUsername*

Since the method getIdAndUsername starts with get then it's treated as normal getter hence, why you could annotate such with @JsonIgnore.

If you have noticed the concatenateIdAndUsername is not returned and that's because it name does not start with get and if you wish the result of that method to be included in the response then you can use @JsonProperty("...") and it would be treated as normal getter/setter as mentioned in the above highlighted documentation.

Body:
This bean 'State' :

public class State {

    private boolean isSet;

    @JsonProperty("isSet")
    public boolean isSet() {
        return isSet;
    }

    @JsonProperty("isSet")
    public void setSet(boolean isSet) {
        this.isSet = isSet;
    }

}

is sent over the wire using the ajax ' success' callback :

        success : function(response) {
            if(response.State.isSet){
                alert('success called successfully)
            }

Is the annotation @JsonProperty required here ? What is the advantage of using it ?
I think I can remove this annotation without causing any side effects.

Reading about this annotion on https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations I don't know when this is required to be used ?

Body:
In addition to all the answers above, don't forget the part of the documentation that says

Marker annotation that can be used to define a non-static method as a
  "setter" or "getter" for a logical property (depending on its
  signature), or non-static object field to be used (serialized,
  deserialized) as a logical property.

If you have a non-static method in your class that is not a conventional getter or setter then you can make it act like a getter and setter by using the annotation on it. See the example below

public class Testing {
    private Integer id;
    private String username;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getIdAndUsername() {
        return id + "." + username;
    }

    public String concatenateIdAndUsername() {
        return id + "." + username;
    }
}

When the above object is serialized, then response will contain

username from getUsername()

id from getId()

idAndUsername from getIdAndUsername*

Since the method getIdAndUsername starts with get then it's treated as normal getter hence, why you could annotate such with @JsonIgnore.

If you have noticed the concatenateIdAndUsername is not returned and that's because it name does not start with get and if you wish the result of that method to be included in the response then you can use @JsonProperty("...") and it would be treated as normal getter/setter as mentioned in the above highlighted documentation.


问:
Issue on delete record from SQL Server database through C# program
I'm new to C# programming. I've written a program in C# which has been connected to a SQL Server database through LINQ connector. Everything ran smoothly. But now I get below error when I want to delete a record from program with a specific condition:

An unhandled exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll

Additional information: Value cannot be null.

This is my C# code:

```<code>private void btnDel_Click(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show("Sales system ", "Are you sure to delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (result == DialogResult.Yes)
    {
        string photo = txtPhoto.ToString();

        var edit = db.tblPersons.Where(c => c.PhotoNo == photo || c.ReceiptNo == photo).FirstOrDefault();
        db.tblPersons.Remove(edit);
        db.SaveChanges();

        MessageBox.Show("Info deleted");
    }
}
</code>```

Does anyone know about my issue in this occasion?

答:
I believe that control is a textbox, however, get the text.

example:

```<code>string photo = txtPhoto.Text;
</code>```

Body:
I'm new to C# programming. I've written a program in C# which has been connected to a SQL Server database through LINQ connector. Everything ran smoothly. But now I get below error when I want to delete a record from program with a specific condition:

An unhandled exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll

Additional information: Value cannot be null.

This is my C# code:

private void btnDel_Click(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show("Sales system ", "Are you sure to delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (result == DialogResult.Yes)
    {
        string photo = txtPhoto.ToString();

        var edit = db.tblPersons.Where(c => c.PhotoNo == photo || c.ReceiptNo == photo).FirstOrDefault();
        db.tblPersons.Remove(edit);
        db.SaveChanges();

        MessageBox.Show("Info deleted");
    }
}

Does anyone know about my issue in this occasion?

Body:
I believe that control is a textbox, however, get the text.

example:

string photo = txtPhoto.Text;


问:
Generating CSV/Excel file for 100 Million of records in Ruby on rails?
Requirement is like

We get the huge dataset from the database( > 1 billion records) and need to export it to the csv file or excel.

Currently implementation use CSV class CSV.generate

```<code> CSV.generate(headers: true) do |csv|
    csv << header
    @obj.find_each do |c|
     arr = [c.id,c.name,soon]
     csv << array
    end
 end
</code>```

and sending the output to

```<code>Zip::File.open(file, Zip::File::CREATE) do |zip|
        zip.get_output_stream("test.#{@format}") { |f| f.puts(convert_to_csv) }
      end
</code>```

All this operation is done other delayed jobs
This works good when record is < 20,000
But when rows starts growing it gets some memory issues.

What i was thinking is to chunk the record to pieces say 1 million rows into 50 files (1million/20000)(csv1.csv,csv2.csv,csv3.csv,csv4.csv,csv5.csv) and then concat them into single file or zip all files together(faster way)

Can any one give me idea how can I start on it.

答:
Write to the CSV in chunks and find_in_batches and pluck. Something like:

```<code>Model.pluck(:id, :name, ...).find_in_batches(10_000) do |ary|
  CSV.open("tmp.csv", "ab") do |csv|
    csv << ary.map{|a| a.join ','}.join("\n")
  end
end
</code>```

Body:
Requirement is like

We get the huge dataset from the database( > 1 billion records) and need to export it to the csv file or excel.

Currently implementation use CSV class CSV.generate

 CSV.generate(headers: true) do |csv|
    csv << header
    @obj.find_each do |c|
     arr = [c.id,c.name,soon]
     csv << array
    end
 end

and sending the output to

Zip::File.open(file, Zip::File::CREATE) do |zip|
        zip.get_output_stream("test.#{@format}") { |f| f.puts(convert_to_csv) }
      end

All this operation is done other delayed jobs
This works good when record is < 20,000
But when rows starts growing it gets some memory issues.

What i was thinking is to chunk the record to pieces say 1 million rows into 50 files (1million/20000)(csv1.csv,csv2.csv,csv3.csv,csv4.csv,csv5.csv) and then concat them into single file or zip all files together(faster way)

Can any one give me idea how can I start on it.

Body:
Write to the CSV in chunks and find_in_batches and pluck. Something like:

Model.pluck(:id, :name, ...).find_in_batches(10_000) do |ary|
  CSV.open("tmp.csv", "ab") do |csv|
    csv << ary.map{|a| a.join ','}.join("\n")
  end
end


问:
ORA-00936: missing expression when using pyodbc to extract specific data from a SQL server
Unable to understand why my sql query is throwing an exception of [Oracle][ODBC][Ora]ORA-00936: missing expression.

The case is that the code seems to be working fine when I'm using
select* from reports.ORDERS_NOW.
So it's letting me pull all the data, but for my case, I want only specific columns for which I'm writing the query. Please look at the code below and let me know what's wrong with it.

```<code>import pyodbc
import pandas as pd

conn = conn = pyodbc.connect('DSN=abcd;UID=xxxxxx;PWD=xxxxxx')

if conn:
    print("Connection is successful")
</code>```

db query

```<code>sql = '''

select [QUANTITY] from reports.ORDERS_NOW

'''

df = pd.read_sql(sql,conn)
</code>```

答:
i  think [] is not allowed in oracle so remove it</p>

```<code>select QUANTITY from reports.ORDERS_NOW
</code>```

Body:
Unable to understand why my sql query is throwing an exception of [Oracle][ODBC][Ora]ORA-00936: missing expression.

The case is that the code seems to be working fine when I'm using
select* from reports.ORDERS_NOW.
So it's letting me pull all the data, but for my case, I want only specific columns for which I'm writing the query. Please look at the code below and let me know what's wrong with it.

import pyodbc
import pandas as pd

conn = conn = pyodbc.connect('DSN=abcd;UID=xxxxxx;PWD=xxxxxx')

if conn:
    print("Connection is successful")

db query

sql = '''

select [QUANTITY] from reports.ORDERS_NOW

'''

df = pd.read_sql(sql,conn)

Body:
i  think [] is not allowed in oracle so remove it

select QUANTITY from reports.ORDERS_NOW


问:
How can I do a function that outputs the not of another function in bash shell?
I have an existing function is_active_instance, which determines if a database instance is running (true) or not. I am working in a new function called is_inactive_instance which needs to return true if is_active_instance returns false.

How can I call is_active_instance from is_inactive_instance and negate its return to return True to main program?

I already tried to call is_instance_active with ! to change the result of the original function.

```<code>is_active_instance(){
    dbservice=""
    if is_mysql_db
    then
        dbservice="mysqld"
    elif is_mariadb_db
    then
        dbservice="mysqld"
    elif is_postgre_db
    then
        dbservice='postgresql'
    fi
    [ $(ps -ef | grep -v grep | grep $dbservice* | wc -l) > 0 ]
}

is_inactive_instance(){
    [ [ ! is_active_instance ] ]
}

if is_active_instance
then
        echo "Is active instance"
elif is_inactive_instance
then
        echo "Is inactive instance"
else
        echo "Other result"
fi

</code>```

In Main body I will need to be able to detect if the instance is running, stopped or other for my purposes.

答:
Don't use any [s:

```<code>is_inactive_instance(){
    ! is_active_instance
}
</code>```

Also see Comparing numbers in Bash for how to make your is_active_instance work.

Body:
I have an existing function is_active_instance, which determines if a database instance is running (true) or not. I am working in a new function called is_inactive_instance which needs to return true if is_active_instance returns false.

How can I call is_active_instance from is_inactive_instance and negate its return to return True to main program?

I already tried to call is_instance_active with ! to change the result of the original function.

is_active_instance(){
    dbservice=""
    if is_mysql_db
    then
        dbservice="mysqld"
    elif is_mariadb_db
    then
        dbservice="mysqld"
    elif is_postgre_db
    then
        dbservice='postgresql'
    fi
    [ $(ps -ef | grep -v grep | grep $dbservice* | wc -l) > 0 ]
}

is_inactive_instance(){
    [ [ ! is_active_instance ] ]
}

if is_active_instance
then
        echo "Is active instance"
elif is_inactive_instance
then
        echo "Is inactive instance"
else
        echo "Other result"
fi

In Main body I will need to be able to detect if the instance is running, stopped or other for my purposes.

Body:
Don't use any [s:

is_inactive_instance(){
    ! is_active_instance
}

Also see Comparing numbers in Bash for how to make your is_active_instance work.


问:
html question want to move a table beside another
I have two tables. One above the other. I want to move the bottom table to the right of the top table. Right now when I run the server, the top table is positioned above the bottom table. Is there a way to move the bottom table to the right side of the top table?</p>

```<code><table>
        <tr><th>Type</th><th>Quantity</th></tr>
        </tr><td>Tape + Film</td><td>{{total_tape_and_film_items}}</td></tr>
        </tr><td>Electrical Equipment</td><td>{{total_electrical_equipment_items}}</td></tr>
</tables>

<table>
        <tr><th></th><th>Status</th><th>Quantity</th></tr>
        <tr><td><a id="new_client" href='{% url tiptop.views.in_items client.pk%}'/>View</a></td><td>In</td><td>{{in_items|length}}</td</tr>
        <tr><td><a id="new_client" href='{% url tiptop.views.out_items client.pk%}'/>View</a></td><td>Out</td><td>{{out_items|length}}</td</tr>
        <tr><td><a id="new_client" href='{% url tiptop.views.empty_items client.pk%}'/>View</a></td><td>Empty</td><td>{{empty_items|length}}</td</tr>
</table>
</code>```

答:
Change
 to

After the last
 add

. This is to make sure nothing goes to the right of the second table.

Body:
I have two tables. One above the other. I want to move the bottom table to the right of the top table. Right now when I run the server, the top table is positioned above the bottom table. Is there a way to move the bottom table to the right side of the top table?

Type	Quantity

Tape + Film	{{total_tape_and_film_items}}

Electrical Equipment	{{total_electrical_equipment_items}}

</tables>

	Status	Quantity

View	In	{{in_items|length}}</td

View	Out	{{out_items|length}}</td

View	Empty	{{empty_items|length}}</td

Body:
Change <table> to <table style="float: left">

After the last </table> add <div style="clear: both"></div>. This is to make sure nothing goes to the right of the second table.


问:
How to autoload Service provider in Laravel package development
I'm trying to develop a very simple Laravel package for learning purpose. I want to display a simple message like 'Hello World' when I call /demo route. I've installed my package in a Laravel project with the following command:

```<code>composer require onbiponi/message:dev-master
</code>```

And then,

```<code>composer dump-autoload
</code>```

Now,  I can't access /demo route. I get the error:

Sorry, the page you are looking for could not be found.

I noticed the boot method of MessageServiceProvider is not being triggered. Do I need to manually add this service provider to config/app.php or do I need need to add something manually? But I want to do everything automatically after installation.
Here is my package in github: https://github.com/rejauldu/message

答:
Autoload service provider only exist from Laravel 5.5.
It will not work with 5.4</p>

Body:
I'm trying to develop a very simple Laravel package for learning purpose. I want to display a simple message like 'Hello World' when I call /demo route. I've installed my package in a Laravel project with the following command:

composer require onbiponi/message:dev-master

And then,

composer dump-autoload

Now,  I can't access /demo route. I get the error:

Sorry, the page you are looking for could not be found.

I noticed the boot method of MessageServiceProvider is not being triggered. Do I need to manually add this service provider to config/app.php or do I need need to add something manually? But I want to do everything automatically after installation.
Here is my package in github: https://github.com/rejauldu/message


问:
How to create this signup form - NativeScript GridView
I am new to NativeScript, and am overwhelmed at the moment.

I am trying to get this layout (pictured below) just in a skeleton form, so I can learn and fill in the details.

Starting at the top, it appears I need a grid of 8 rows, and 2 columns.

```<code>  <GridLayout rows="*, auto" columns="250, *">
    <Label text="First Name" />
    <Label text="Middle Initial" col="1" />

<TextField hint="First Name"
        secure="false"
        autocorrect="false"
        maxLength="10"
        class="input input-border"/>

    <TextField hint="Middle Initial"
        secure="false"
        autocorrect="false"
        maxLength="1"
        class="input input-border"/>

<!-- continue... -->

    <Label text="This is Label in row 0, col 0" rowSpan="2" colSpan="2" />
  </GridLayout>
</Page>
</code>```

This method is not working. The layout does not reflect what I need in the image.

Can you please help me to at least rough out this layout? I am having a heck of a time.

Thank you for looking.

答:
for something like this I would wrap the outermost element with

```<code><ScrollView>
  <StackLayout>
  <!-- Main form component wrapper -->
  <!-- Green component wrapper -->
  </StackLayout>
</ScrollView>
</code>```

That will make your layout scrollable and the elements will be placed on top of one another without needing to specify a fixed size.

For the main form area I would use a layout something like this

```<code><GridLayout rows="*" columns="*">
  <!-- this stackLayout is the lefthand side of form -->
  <StackLayout row="0" col="0">
    <TextField ... />
    <TextField ... />
  </StackLayout>

  <!-- this stackLayout is the righthand side of form -->
  <StackLayout row="0" col="1">
    <Switch .../>
    <Birthday stuff... />
  </StackLayout>
</GridLayout>
</code>```

This would split the upper area into two columns and stack the fields on top of one another.

The green area is probably easiest as one StackLayout with backgroundColor="someGreenColor" and then using either GridLayout or AbsoluteLayout I would code in the three boxes with a lot of css.

Hope that helps!

Body:
I am new to NativeScript, and am overwhelmed at the moment.

I am trying to get this layout (pictured below) just in a skeleton form, so I can learn and fill in the details.

Starting at the top, it appears I need a grid of 8 rows, and 2 columns.

  <GridLayout rows="*, auto" columns="250, *">

<TextField hint="First Name"
        secure="false"
        autocorrect="false"
        maxLength="10"
        class="input input-border"/>

    <TextField hint="Middle Initial"
        secure="false"
        autocorrect="false"
        maxLength="1"
        class="input input-border"/>

  </GridLayout>
</Page>

This method is not working. The layout does not reflect what I need in the image.

Can you please help me to at least rough out this layout? I am having a heck of a time.

Thank you for looking.

Body:
for something like this I would wrap the outermost element with

<ScrollView>
  <StackLayout>
  <!-- Main form component wrapper -->
  <!-- Green component wrapper -->
  </StackLayout>
</ScrollView>

That will make your layout scrollable and the elements will be placed on top of one another without needing to specify a fixed size.

For the main form area I would use a layout something like this

<GridLayout rows="*" columns="*">
  <!-- this stackLayout is the lefthand side of form -->
  <StackLayout row="0" col="0">
    <TextField ... />
    <TextField ... />
  </StackLayout>

  <!-- this stackLayout is the righthand side of form -->
  <StackLayout row="0" col="1">
    <Switch .../>
    <Birthday stuff... />
  </StackLayout>
</GridLayout>

This would split the upper area into two columns and stack the fields on top of one another.

The green area is probably easiest as one StackLayout with backgroundColor="someGreenColor" and then using either GridLayout or AbsoluteLayout I would code in the three boxes with a lot of css.

Hope that helps!


问:
How to change the application launcher icon on Flutter?
When I create an app with a flutter create command, the flutter logo is used as an application icon for both platforms.

If I want to change the app icon, shall I go to both platforms directories and replace images there?, by platforms directories I mean  myapp/ios/Runner/Assets.xcassets/AppIcon.appiconset for iOS and myapp/android/app/src/main/res for Android.

Or is it possible to define an image as a Flutter Asset and the icons are generated somehow?.

答:
I would suggest You to use this website Linked Below

App Icon Creator

Step-1: upload The Image,

Step-2: Make necessary Changes And Click on download(dont change the file name)

Step-3: Extract the Downloaded Zip File In the respective folder

```<code>android/app/src/main/res
</code>```

Body:
I would suggest You to use this website Linked Below

App Icon Creator

Step-1: upload The Image,

Step-2: Make necessary Changes And Click on download(dont change the file name)

Step-3: Extract the Downloaded Zip File In the respective folder

android/app/src/main/res


问:
AWS Lambda with Knex JS and RDS Postgres
I have been doing some research and I'm not able to find a good answer about using Knex JS within a Lambda function:

How do I use Knex with AWS Lambda? #1875

Serverless URL Shortener with Apex and AWS Lambda

Use Promise.all() in AWS lambda

Here is what I have in my index.js:

```<code>const knex = require('knex')({
  client: 'pg',
  connection: {...},
});

exports.handler = (event, context, callback) => {
  console.log('event received: ', event);
  console.log('knex connection: ', knex);

  knex('goals')
    .then((goals) => {
      console.log('received goals: ', goals);
      knex.client.destroy();
      return callback(null, goals);
    })
    .catch((err) => {
      console.log('error occurred: ', err);
      knex.client.destroy();
      return callback(err);
    });
};
</code>```

I am able to connect and execute my code fine locally, but I'm running into an interesting error when it's deployed to AWS - the first call is always successful, but anything after fails. I think this is related to the knex client being destroyed, but then trying to be used again on the next call. If I re-upload my index.js, it goes back to working for one call, and then failing.

I believe this can be resolved somehow using promises but this my first time working with Lambda so I'm not familiar with how it's managing the connection to RDS on subsequent calls. Thanks in advance for any suggestions!

答:
For me, it worked on my local machine but not after deploying. I was kind of be mislead.

It turns out the RDS inbound source is not open to my Lambda function. Found solution at AWS Lambda can't connect to RDS instance, but I can locally?: either changing RDS inbound source to 0.0.0.0/0 or use VPC.

After updating RDS inbound source, I can use Lambda with Knex successfully.

The Lambda runtime I am using is Node.js 8.10 with packages:

```<code>knex: 0.17.0
pg: 7.11.0
</code>```

The code below using async also just works for me

const Knex = require('knex');

const pg = Knex({ ... });

module.exports.submitForm = async (event) => {
  const {
    fields,
  } = event['body-json'] || {};

  return pg('surveys')
    .insert(fields)
    .then(() => {
      return {
        status: 200
      };
    })
    .catch(err => {
      return {
        status: 500
      };
    });
};
```

Hopefully it will help people who might meet same issue in future.

Body:
I have been doing some research and I'm not able to find a good answer about using Knex JS within a Lambda function:

How do I use Knex with AWS Lambda? #1875

Serverless URL Shortener with Apex and AWS Lambda

Use Promise.all() in AWS lambda

Here is what I have in my index.js:

const knex = require('knex')({
  client: 'pg',
  connection: {...},
});

exports.handler = (event, context, callback) => {
  console.log('event received: ', event);
  console.log('knex connection: ', knex);

  knex('goals')
    .then((goals) => {
      console.log('received goals: ', goals);
      knex.client.destroy();
      return callback(null, goals);
    })
    .catch((err) => {
      console.log('error occurred: ', err);
      knex.client.destroy();
      return callback(err);
    });
};

I am able to connect and execute my code fine locally, but I'm running into an interesting error when it's deployed to AWS - the first call is always successful, but anything after fails. I think this is related to the knex client being destroyed, but then trying to be used again on the next call. If I re-upload my index.js, it goes back to working for one call, and then failing.

I believe this can be resolved somehow using promises but this my first time working with Lambda so I'm not familiar with how it's managing the connection to RDS on subsequent calls. Thanks in advance for any suggestions!

Body:
For me, it worked on my local machine but not after deploying. I was kind of be mislead.

It turns out the RDS inbound source is not open to my Lambda function. Found solution at AWS Lambda can't connect to RDS instance, but I can locally?: either changing RDS inbound source to 0.0.0.0/0 or use VPC.

After updating RDS inbound source, I can use Lambda with Knex successfully.

The Lambda runtime I am using is Node.js 8.10 with packages:

knex: 0.17.0
pg: 7.11.0

The code below using async also just works for me

const Knex = require('knex');

const pg = Knex({ ... });

module.exports.submitForm = async (event) => {
  const {
    fields,
  } = event['body-json'] || {};

  return pg('surveys')
    .insert(fields)
    .then(() => {
      return {
        status: 200
      };
    })
    .catch(err => {
      return {
        status: 500
      };
    });
};

Hopefully it will help people who might meet same issue in future.


问:
How to run a simple JUnit test in eclipse
So here's my code:

```<code>package tests;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

class StatementTester extends TestCase {
    public StatementTester (String name) {
        super(name);
    }

    protected void setUp() {
    }

    protected void tearDown() {
    }

    public void test1() {
        System.out.println("testing");
        assert(true);
    }

    public static Test suite() {
        TestSuite suite= new TestSuite();
        suite.addTest(new StatementTester("test1"));
        return suite;
    }

    public static void main (String[] args) {
        junit.textui.TestRunner.run (suite());
  }
}
</code>```

When I try to run this I get the following error message:

```<code>.E
Time: 0.001
There was 1 error:
1) test1(tests.StatementTester) at tests.StatementTester.main(StatementTester.java:30)

FAILURES!!!
Tests run: 1,  Failures: 0,  Errors: 1
</code>```

I based my code on the example given in Chapter 4 of Martin Fowler's "Refactoring: Improving the design of existing code" (although I simplified it, but the base structure is the same). Also, I run eclipse 3.5.1 and use the JUnit 3 library (don't know how relevant it is, but anyway...)

Can you give me any hints on what I'm doing wrong?

答: With your file currently in the editor, ALT-SHIFT-X, T.  Or right click->Run As->JUnit Test.

Body:
So here's my code:

package tests;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

class StatementTester extends TestCase {
    public StatementTester (String name) {
        super(name);
    }

    protected void setUp() {
    }

    protected void tearDown() {
    }

    public void test1() {
        System.out.println("testing");
        assert(true);
    }

    public static Test suite() {
        TestSuite suite= new TestSuite();
        suite.addTest(new StatementTester("test1"));
        return suite;
    }

    public static void main (String[] args) {
        junit.textui.TestRunner.run (suite());
  }
}

When I try to run this I get the following error message:

.E
Time: 0.001
There was 1 error:
1) test1(tests.StatementTester) at tests.StatementTester.main(StatementTester.java:30)

FAILURES!!!
Tests run: 1,  Failures: 0,  Errors: 1

I based my code on the example given in Chapter 4 of Martin Fowler's "Refactoring: Improving the design of existing code" (although I simplified it, but the base structure is the same). Also, I run eclipse 3.5.1 and use the JUnit 3 library (don't know how relevant it is, but anyway...)

Can you give me any hints on what I'm doing wrong?