问:
ggplot: How to Manually Sort Stacked Bars Differently at Each X?
I want to plot a week-view calendar/timetable/timesheet/waterfall with ggplot. A sample data looks as follows (sampleData.csv):

```<code>date, start, end, duration, name, color
2016-08-04, 00:00:00, 08:00:00, 8.00, idle, #00000000
2016-08-04, 08:00:00, 10:00:00, 2.00, Coding, red
2016-08-04, 10:00:00, 14:00:00, 4.00, idle, #00000000
2016-08-04, 14:00:00, 17:30:00, 3.50, Laundry, green
2016-08-04, 17:30:00, 20:00:00, 2.50, Cooking, blue
2016-08-04, 20:00:00, 24:00:00, 4.00, idle, #00000000
2016-08-05, 00:00:00, 06:00:00, 6.00, idle, #00000000
2016-08-05, 06:00:00, 09:00:00, 3.00, Cooking, blue
2016-08-05, 09:00:00, 10:00:00, 1.00, Laundry, green
2016-08-05, 10:00:00, 12:30:00, 2.50, idle, #00000000
2016-08-05, 12:30:00, 16:00:00, 3.50, Coding, red
2016-08-05, 16:00:00, 22:00:00, 6.00, Basketball, brown
2016-08-05, 22:00:00, 24:00:00, 2.00, idle, #00000000
</code>```

Currently, I am able to plot them like this:

However, there are 2 disadvantages:

I cannot make a legend, since I didn't tell legend how to group these bars.

Colors had to be given row-by-row. It is indeed awkward to hard-code the style into the data.

To enable the legend and to leave the coloring job to ggplot, I used the aes(fill=name) command. However, ggplot automatically sorted bars at each date according to their "name" values, which ruined my timetable:

Please note in the sample data that:

I want to get rid of the "color" column, and let ggplot automatically assign colors to each name.

At each date, the sum of "duration" is 24 (hours). This is how I position bars at specific Ys for now. I am open to suggestions about how to "float" bars above the X-axis.

At each date, multiple entries with identical "name" field can exist. For example, the "idle" entries starting at 00:00, 10:00 and 20:00. This is one reason why I don't want the bars automatically sorted by the field "name".

Between different dates, the order of entries with different "names" can alter -- another reason to NOT automatically sort.

Here is the code generating the two plots above:

```<code>library(readr)
data <- read_csv("sampleData.csv",
                 col_types = cols(date = col_date(format = "%Y-%m-%d"),
                                  end = col_time(format = "%H:%M:%S"),
                                  start = col_time(format = "%H:%M:%S")))
library(ggplot2)
# The first way to plot it:
ggplot(data, aes(x = date, y = duration, fill=name)) +
  geom_bar(stat = "identity") +
  scale_y_reverse(breaks=0:24)+#function(x) seconds_to_period(x))#strftime(chron(times=c(x/86400)), "%H:%M"))#+coord_flip()
  coord_cartesian(ylim = c(0, 24), expand = FALSE)+
  labs( x = "Date", y = "Time (Hour)",
        title = "Timetable",
        subtitle = "using aes(fill=name)",
        caption = "Legend is plotted and colors are well chosen, but bars at each date are sorted by \"name\" (unwanted).")+
  scale_x_date(date_breaks = "2 month", date_labels = "%b %Y")
# The second way to plot it:
ggplot(data, aes(x = date, y = duration)) +
  geom_bar(stat = "identity", fill = data$color) +
  scale_y_reverse(breaks=0:24)+#function(x) seconds_to_period(x))#strftime(chron(times=c(x/86400)), "%H:%M"))#+coord_flip()
  coord_cartesian(ylim = c(0, 24), expand = FALSE)+
  labs( x = "Date", y = "Time (Hour)",
        title = "Timetable",
        subtitle = "using geom_bar(fill=data$color)",
        caption = "Bars at each date are correctly positioned, but legend is not available.")+
  scale_x_date(date_breaks = "2 month", date_labels = "%b %Y")
</code>```

To state my question in a different way: how can I make a timetable with legend?

Body:
I want to plot a week-view calendar/timetable/timesheet/waterfall with ggplot. A sample data looks as follows (sampleData.csv):

date, start, end, duration, name, color
2016-08-04, 00:00:00, 08:00:00, 8.00, idle, #00000000
2016-08-04, 08:00:00, 10:00:00, 2.00, Coding, red
2016-08-04, 10:00:00, 14:00:00, 4.00, idle, #00000000
2016-08-04, 14:00:00, 17:30:00, 3.50, Laundry, green
2016-08-04, 17:30:00, 20:00:00, 2.50, Cooking, blue
2016-08-04, 20:00:00, 24:00:00, 4.00, idle, #00000000
2016-08-05, 00:00:00, 06:00:00, 6.00, idle, #00000000
2016-08-05, 06:00:00, 09:00:00, 3.00, Cooking, blue
2016-08-05, 09:00:00, 10:00:00, 1.00, Laundry, green
2016-08-05, 10:00:00, 12:30:00, 2.50, idle, #00000000
2016-08-05, 12:30:00, 16:00:00, 3.50, Coding, red
2016-08-05, 16:00:00, 22:00:00, 6.00, Basketball, brown
2016-08-05, 22:00:00, 24:00:00, 2.00, idle, #00000000

Currently, I am able to plot them like this:

However, there are 2 disadvantages:

I cannot make a legend, since I didn't tell legend how to group these bars.

Colors had to be given row-by-row. It is indeed awkward to hard-code the style into the data.

To enable the legend and to leave the coloring job to ggplot, I used the aes(fill=name) command. However, ggplot automatically sorted bars at each date according to their "name" values, which ruined my timetable:

Please note in the sample data that:

I want to get rid of the "color" column, and let ggplot automatically assign colors to each name.

At each date, the sum of "duration" is 24 (hours). This is how I position bars at specific Ys for now. I am open to suggestions about how to "float" bars above the X-axis.

At each date, multiple entries with identical "name" field can exist. For example, the "idle" entries starting at 00:00, 10:00 and 20:00. This is one reason why I don't want the bars automatically sorted by the field "name".

Between different dates, the order of entries with different "names" can alter -- another reason to NOT automatically sort.

Here is the code generating the two plots above:

library(readr)
data <- read_csv("sampleData.csv",
                 col_types = cols(date = col_date(format = "%Y-%m-%d"),
                                  end = col_time(format = "%H:%M:%S"),
                                  start = col_time(format = "%H:%M:%S")))
library(ggplot2)
# The first way to plot it:
ggplot(data, aes(x = date, y = duration, fill=name)) +
  geom_bar(stat = "identity") +
  scale_y_reverse(breaks=0:24)+#function(x) seconds_to_period(x))#strftime(chron(times=c(x/86400)), "%H:%M"))#+coord_flip()
  coord_cartesian(ylim = c(0, 24), expand = FALSE)+
  labs( x = "Date", y = "Time (Hour)",
        title = "Timetable",
        subtitle = "using aes(fill=name)",
        caption = "Legend is plotted and colors are well chosen, but bars at each date are sorted by \"name\" (unwanted).")+
  scale_x_date(date_breaks = "2 month", date_labels = "%b %Y")
# The second way to plot it:
ggplot(data, aes(x = date, y = duration)) +
  geom_bar(stat = "identity", fill = data$color) +
  scale_y_reverse(breaks=0:24)+#function(x) seconds_to_period(x))#strftime(chron(times=c(x/86400)), "%H:%M"))#+coord_flip()
  coord_cartesian(ylim = c(0, 24), expand = FALSE)+
  labs( x = "Date", y = "Time (Hour)",
        title = "Timetable",
        subtitle = "using geom_bar(fill=data$color)",
        caption = "Bars at each date are correctly positioned, but legend is not available.")+
  scale_x_date(date_breaks = "2 month", date_labels = "%b %Y")

To state my question in a different way: how can I make a timetable with legend?

Body:
geom_rect() is a better choice on this case than geom_bar():

library(ggplot2)
ggplot(df) +
    geom_rect(aes(xmin = date, xmax = date + .8,
                  ymin = start, ymax = end,
                  fill = name),
              color = 'black') +
    scale_y_datetime(date_labels = "%H:%M") +
    scale_x_date(date_breaks = "2 months", date_labels = "%b %Y") +
    labs(x = "Date",
         y = "Time (Hour)",
          title = "Timetable"
          )

Data:

df <- read.table(text = 'date, start, end, duration, name, color
                2016-08-04, 00:00:00, 08:00:00, 8.00, idle, #00000000
                 2016-08-04, 08:00:00, 10:00:00, 2.00, Coding, red
                 2016-08-04, 10:00:00, 14:00:00, 4.00, idle, #00000000
                 2016-08-04, 14:00:00, 17:30:00, 3.50, Laundry, green
                 2016-08-04, 17:30:00, 20:00:00, 2.50, Cooking, blue
                 2016-08-04, 20:00:00, 24:00:00, 4.00, idle, #00000000
                 2016-08-05, 00:00:00, 06:00:00, 6.00, idle, #00000000
                 2016-08-05, 06:00:00, 09:00:00, 3.00, Cooking, blue
                 2016-08-05, 09:00:00, 10:00:00, 1.00, Laundry, green
                 2016-08-05, 10:00:00, 12:30:00, 2.50, idle, #00000000
                 2016-08-05, 12:30:00, 16:00:00, 3.50, Coding, red
                 2016-08-05, 16:00:00, 22:00:00, 6.00, Basketball, brown
                 2016-08-05, 22:00:00, 24:00:00, 2.00, idle, #00000000', header = TRUE, sep = ',')
df$date <- as.Date(df$date)
df$start <- as.POSIXct(df$start, format = "%H:%M:%S")
df$end <- as.POSIXct(df$end, format = "%H:%M:%S")


来源: stackexchange

问:
Better way of finding combination for 3 boolean variables
I have 3 bool variables x,y,z. Now at any given moment I can have one out of 2^3=8 combinations as below.

e.g. x=true, y=false and z=false or
x=false, y=true and z=true  and so on.

If I see from programming perspective there are 8 cases or may be 8 or greater if else statement to determine what is the combination at that moment.
At any given moment if I want to know what combination is present(given the values of x,y,z) How can I know without using if-else ladder, which makes code logic little bulky. Is there any better/simple logic/way to do it.

答:
It might be worth using bitwise operators, rather than the numeric value to determine which boolean variables are on or off.

```<code>// Assign the bitwise value of each variable
X = 4
Y = 2
Z = 1

// Setting X and Z as true using the bitwise OR operator.
v = X | Z // v = 4 + 1 = 5

// Checking if any of the variables are true using the bitwise OR operator
if (v | X+Y+Z) // v = 4 + 2 + 1 = 7

// Checking if ALL of the variables are true using the bitwise AND operator
if (v & X+Y+Z)

// Checking if variable Y is true using the bitwise OR operator
if (v | Y)

// Checking if variable Y is false using the bitwise OR operator
if (v | Y == false)

// Checking if ONLY variable Y is true using the bitwise AND operator
if (v & Y)

// Checking if ONLY variable Y is false using the bitwise AND operator
if (v & Y == false)
</code>```

This saves you from messing up the resulting number of a combination of values X, Y, Z. It is also more readable.

ContentLicense: CC BY-SA 3.0

Body:
It might be worth using bitwise operators, rather than the numeric value to determine which boolean variables are on or off.

// Assign the bitwise value of each variable
X = 4
Y = 2
Z = 1

// Setting X and Z as true using the bitwise OR operator.
v = X | Z // v = 4 + 1 = 5

// Checking if any of the variables are true using the bitwise OR operator
if (v | X+Y+Z) // v = 4 + 2 + 1 = 7

// Checking if ALL of the variables are true using the bitwise AND operator
if (v & X+Y+Z)

// Checking if variable Y is true using the bitwise OR operator
if (v | Y)

// Checking if variable Y is false using the bitwise OR operator
if (v | Y == false)

// Checking if ONLY variable Y is true using the bitwise AND operator
if (v & Y)

// Checking if ONLY variable Y is false using the bitwise AND operator
if (v & Y == false)

This saves you from messing up the resulting number of a combination of values X, Y, Z. It is also more readable.


问:
SqlServer Random Data Generation Observation
I have a question on why the output of these two queries differ.  I would have expected them to work the same.

Query 1:

```<code>declare @cache table(originalValue nvarchar(255), obfuscateValue nvarchar(255));

declare @table1 table(c char(1));
declare @i1 int;
set @i1 = ASCII('0');

while @i1 <= ASCII('9')
begin
    insert into @table1 (c)
    select (CHAR(@i1))

    set @i1 = @i1 +1;
end

insert into @cache (originalValue, obfuscateValue)
select [firstname],
        (select top 1 c from @table1 order by NEWID()) +
        (select top 1 c from @table1 order by NEWID())
from Customer
where [firstname] is not null

select * from @cache;
</code>```

Query 2:

```<code>declare @cache table(originalValue nvarchar(255), obfuscateValue nvarchar(255));

declare @table1 table(c char(1));
declare @i1 int;
set @i1 = ASCII('0');

while @i1 <= ASCII('9')
begin
    insert into @table1 (c)
    select (CHAR(@i1))

    set @i1 = @i1 +1;
end

insert into @cache (originalValue)
select [firstname]
from Customer
where [firstname] is not null

update c
set c.obfuscateValue = t.Value
from @cache c
join
(
    select originalValue,
    (
        (select top 1 c from @table1 order by NEWID()) +
        (select top 1 c from @table1 order by NEWID())
    ) as Value
    from @cache
) t on t.originalValue = c.originalValue

select * from @cache;
</code>```

They should do the same, but first query returns following results:

```<code>Jonathon    73
Everett 73
Janet   73
Andy    73
Shauna  73
</code>```

And second:

```<code>Jonathon    82
Everett 40
Janet   68
Andy    79
Shauna  29
</code>```

As you noticed, the second column in second result has different values, while first - same values.

It looks like in first query the

```<code>(select top 1 c from @table1 order by NEWID()) +
        (select top 1 c from @table1 order by NEWID())
</code>```

is called only once.

Can someone explain this mystery?

答:
You are correct in your assumption that the first query is only running the ‘select top’ once.  The behavior is happening because of how the optimizer chose to optimize the query.  It decided because the subqueries (the select top queries) are self-contained and are not correlated with the outside select query it uses a Tablespool (Lazy Spool) operator in the execution plan.  This causes the select top value to be placed in the tempdb for reuse.

Because the optimizer chooses to use a Nested Loops operator to bring all the data together no rebinding is needed, the spooled value is used instead of reapplying the queries for each input outer row.

During the second query the optimizer chose not to use a Tablespool operator (I believe do to fact the input table being from tempdb).  So you have the select top subqueries being reapplied for each input row from the temporary table.

If needed, you may be able to use a table/query hints if you want to force the execution plan to perform as desired.

ContentLicense: CC BY-SA 2.5

Body:
I have a question on why the output of these two queries differ.  I would have expected them to work the same.

Query 1:

declare @cache table(originalValue nvarchar(255), obfuscateValue nvarchar(255));

declare @table1 table(c char(1));
declare @i1 int;
set @i1 = ASCII('0');

while @i1 <= ASCII('9')
begin
    insert into @table1 (c)
    select (CHAR(@i1))

    set @i1 = @i1 +1;
end

insert into @cache (originalValue, obfuscateValue)
select [firstname],
        (select top 1 c from @table1 order by NEWID()) +
        (select top 1 c from @table1 order by NEWID())
from Customer
where [firstname] is not null

select * from @cache;

Query 2:

declare @cache table(originalValue nvarchar(255), obfuscateValue nvarchar(255));

declare @table1 table(c char(1));
declare @i1 int;
set @i1 = ASCII('0');

while @i1 <= ASCII('9')
begin
    insert into @table1 (c)
    select (CHAR(@i1))

    set @i1 = @i1 +1;
end

insert into @cache (originalValue)
select [firstname]
from Customer
where [firstname] is not null

update c
set c.obfuscateValue = t.Value
from @cache c
join
(
    select originalValue,
    (
        (select top 1 c from @table1 order by NEWID()) +
        (select top 1 c from @table1 order by NEWID())
    ) as Value
    from @cache
) t on t.originalValue = c.originalValue

select * from @cache;

They should do the same, but first query returns following results:

Jonathon    73
Everett 73
Janet   73
Andy    73
Shauna  73

And second:

Jonathon    82
Everett 40
Janet   68
Andy    79
Shauna  29

As you noticed, the second column in second result has different values, while first - same values.

It looks like in first query the

(select top 1 c from @table1 order by NEWID()) +
        (select top 1 c from @table1 order by NEWID())

is called only once.

Can someone explain this mystery?


问:
how to get the particular value from Json?
I am having the Json data as shown below in this I need to get the data that which key value pair for default is 1 then i need to get the remaining dictionaries data and need to be passed to the user to display can any one tell me how to implement this ?

And my code is as shown below

```<code>            if let addressArray = jsonObj!.value(forKey: "address") as? NSArray{
                    for array in addressArray {
                        if let addressDict = array as? NSDictionary{
                            if let Default = addressDict.value(forKey: "default"){

                            }
                        }
                    }
                }
 "address": [
    {
      "default": 0,
      "number": 9123456711,
      "name": "Ramesh",
      "address": "No:11/111 ,cross street,Nungambakkam,mylapore,chennai :600088"
    },
    {
      "default": 1,
      "number": 8123456722,
      "name": "Vignesh",
      "address": "No:22/222 ,cross street,Perambur,chennai :600012"
    },
    {
      "default": 0,
      "number": 7123456733,
      "name": "Rajesh",
      "address": "No:33/333 ,cross street,Villivakkam,chennai :600045"
    }
  ]
</code>```

答:
You can check if Default equals 1 and add those values to an array.</p>

```<code>var defaultArray = [NSDictionary]()
if let addressArray = jsonObj!.value(forKey: "address") as? NSArray{
                    for array in addressArray {
                        if let addressDict = array as? NSDictionary{
                            if let Default = addressDict.value(forKey: "default"){
                               if Default == 1 {
                               defaultArray.append(addressDict)
                              }
                            }
                        }
                    }
                }
</code>```

Body:
I am having the Json data as shown below in this I need to get the data that which key value pair for default is 1 then i need to get the remaining dictionaries data and need to be passed to the user to display can any one tell me how to implement this ?

And my code is as shown below

            if let addressArray = jsonObj!.value(forKey: "address") as? NSArray{
                    for array in addressArray {
                        if let addressDict = array as? NSDictionary{
                            if let Default = addressDict.value(forKey: "default"){

                            }
                        }
                    }
                }
 "address": [
    {
      "default": 0,
      "number": 9123456711,
      "name": "Ramesh",
      "address": "No:11/111 ,cross street,Nungambakkam,mylapore,chennai :600088"
    },
    {
      "default": 1,
      "number": 8123456722,
      "name": "Vignesh",
      "address": "No:22/222 ,cross street,Perambur,chennai :600012"
    },
    {
      "default": 0,
      "number": 7123456733,
      "name": "Rajesh",
      "address": "No:33/333 ,cross street,Villivakkam,chennai :600045"
    }
  ]

Body:
You can check if Default equals 1 and add those values to an array.

var defaultArray = [NSDictionary]()
if let addressArray = jsonObj!.value(forKey: "address") as? NSArray{
                    for array in addressArray {
                        if let addressDict = array as? NSDictionary{
                            if let Default = addressDict.value(forKey: "default"){
                               if Default == 1 {
                               defaultArray.append(addressDict)
                              }
                            }
                        }
                    }
                }


问:
How to parse Json object in ReactJS
I want to parse through a JSON list in reactJS.
Here is the model that I am using

```<code>public class ModelEmployee
{
    public List<Employeelist> Employees { get; set; }
    public int count { get; set; }
    public int Pagenumber { get; set; }
}
public class Employeelist
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<string> Roles { get; set; }
}
</code>```

And my controller is

```<code> public ActionResult Index(int pageNum = 1)
    {
        ModelEmployee model = new ModelEmployee();
            model = new ModelEmployee();
            model.Employees = FetchAllDevices(pageNum, 10);
            model.count = (int)Math.Ceiling((float)_empService.TotalCount() / _pageSize);
            model.Pagenumber = pageNum;
            return Json(model,JsonRequestBehavior.AllowGet);
    }
</code>```

This is what i have tried in ReactJS code to extract each values

```<code> componentWillMount: function(){

    var xhr = new XMLHttpRequest();
    xhr.open('get', this.props.url, true);
    xhr.onload = function () {
        var response = JSON.parse(xhr.responseText);
        this.setState({ result: response });

    }.bind(this);
    xhr.send();
},
render: function(){
    var rows = [];
    this.state.result.Employees.forEach(function (item) {
        rows.push(<EmployeeRow  key={item.EmployeeID} item={item }/>);
});
</code>```

Its not working. But when I change the setState with this,

```<code>this.setState({ result: response.Employees });
</code>```

it will work fine and can go through the Employees list. But cant access the pagenumber and count variables. Can you please help me to sort out this?
Thanks in advance.

答:
In your onLoad callback for the XHR, you should be sure to check the readyState, to ensure the response has completed:

```<code>xhr.onload = function () {
    if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) { // optionally check the status
            var response = JSON.parse(xhr.responseText);
            this.setState({ result: response });
        }
    }

}.bind(this);
</code>```

This ensures you're reading the completed response. Try this and see if this solved the problem

Title: How to parse Json object in ReactJS

Body:
I want to parse through a JSON list in reactJS.
Here is the model that I am using

public class ModelEmployee
{
    public List<Employeelist> Employees { get; set; }
    public int count { get; set; }
    public int Pagenumber { get; set; }
}
public class Employeelist
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<string> Roles { get; set; }
}

And my controller is

 public ActionResult Index(int pageNum = 1)
    {
        ModelEmployee model = new ModelEmployee();
            model = new ModelEmployee();
            model.Employees = FetchAllDevices(pageNum, 10);
            model.count = (int)Math.Ceiling((float)_empService.TotalCount() / _pageSize);
            model.Pagenumber = pageNum;
            return Json(model,JsonRequestBehavior.AllowGet);
    }

This is what i have tried in ReactJS code to extract each values

 componentWillMount: function(){

    var xhr = new XMLHttpRequest();
    xhr.open('get', this.props.url, true);
    xhr.onload = function () {
        var response = JSON.parse(xhr.responseText);
        this.setState({ result: response });

    }.bind(this);
    xhr.send();
},
render: function(){
    var rows = [];
    this.state.result.Employees.forEach(function (item) {
        rows.push(<EmployeeRow  key={item.EmployeeID} item={item }/>);
});

Its not working. But when I change the setState with this,

this.setState({ result: response.Employees });

it will work fine and can go through the Employees list. But cant access the pagenumber and count variables. Can you please help me to sort out this?
Thanks in advance.

Body:
In your onLoad callback for the XHR, you should be sure to check the readyState, to ensure the response has completed:

xhr.onload = function () {
    if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) { // optionally check the status
            var response = JSON.parse(xhr.responseText);
            this.setState({ result: response });
        }
    }

}.bind(this);

This ensures you're reading the completed response. Try this and see if this solved the problem


问:
Need single data from multiple similar DATA in database
I want to find out the data in showing in multiple entries like this

```<code>5   296 19  7   887 DAAS    GAGO    {"password":""}     2017-06-24 13:33:15 2017-06-23 13:33:09 9   10  fuel        4   1   N125XP  DAAS    Requested
5   296 19  7   887 DAAS    GAGO    {"password":""}     2017-06-24 13:33:15 2017-06-23 13:33:09 9   10  fuel        4   1   N125XP  DAAS    Requested
</code>```

I want to see this data once how to do it ?

I am using this Sql Statement to do so :

```<code>SELECT t1.trip_id,
       t1.server_trip_id,
       t1.aircraft_id,
       t2.flight_id,
       t3.server_fid,
       t3.dep,
       t3.dest,
       t3.service_provider,
       t3.flight_name,
       t3.sta,
       t3.std,
       t4.booking_id,
       t5.server_booking_id,
       t5.type,
       t5.trip_number,
       t5.company_id,
       t5.user_id,
       t5.aircraft_registration,
       t5.icao,
       t6.status
FROM trip t1
    JOIN trip_flight t2 ON t2.trip_id = t1.trip_id
    JOIN flight t3 ON t3.fid = t2.flight_id
    JOIN trip_flight_booking t4 ON t4.flight_id = t2.flight_id
    JOIN booking t5 ON t5.booking_id = t4.booking_id OR t5.booking_id != t4.booking_id
    JOIN booking_status t6 ON t6.booking_id = t5.booking_id OR t6.booking_id != t5.booking_id
where t1.aircraft_id="19"
</code>```

答:
Are you sure your joins are correct... this seems to match any row;

```<code>t5.booking_id = t4.booking_id OR t5.booking_id != t4.booking_id
</code>```

as you have = or != with the same values....

That said, you can use DISTINCT

```<code>SELECT DISTINCT t1.trip_id , t1.server_trip_id, t1.aircraft_id,
t2.flight_id,
t3.server_fid,t3.dep,t3.dest,t3.service_provider,t3.flight_name,t3.sta,t3.std,
t4.booking_id,
t5.server_booking_id,t5.type,t5.trip_number,t5.company_id,t5.user_id,t5.aircraft_registration,t5.icao,
t6.status
    FROM trip t1
    JOIN trip_flight t2 ON t2.trip_id = t1.trip_id
    JOIN flight t3 ON t3.fid = t2.flight_id
    JOIN trip_flight_booking t4 ON t4.flight_id = t2.flight_id
    JOIN booking t5 ON t5.booking_id = t4.booking_id OR t5.booking_id != t4.booking_id
    JOIN booking_status t6 ON t6.booking_id = t5.booking_id OR t6.booking_id != t5.booking_id
    where t1.aircraft_id="19"
</code>```

Body:
I want to find out the data in showing in multiple entries like this

5   296 19  7   887 DAAS    GAGO    {"password":""}     2017-06-24 13:33:15 2017-06-23 13:33:09 9   10  fuel        4   1   N125XP  DAAS    Requested
5   296 19  7   887 DAAS    GAGO    {"password":""}     2017-06-24 13:33:15 2017-06-23 13:33:09 9   10  fuel        4   1   N125XP  DAAS    Requested

I want to see this data once how to do it ?

I am using this Sql Statement to do so :

SELECT t1.trip_id,
       t1.server_trip_id,
       t1.aircraft_id,
       t2.flight_id,
       t3.server_fid,
       t3.dep,
       t3.dest,
       t3.service_provider,
       t3.flight_name,
       t3.sta,
       t3.std,
       t4.booking_id,
       t5.server_booking_id,
       t5.type,
       t5.trip_number,
       t5.company_id,
       t5.user_id,
       t5.aircraft_registration,
       t5.icao,
       t6.status
FROM trip t1
    JOIN trip_flight t2 ON t2.trip_id = t1.trip_id
    JOIN flight t3 ON t3.fid = t2.flight_id
    JOIN trip_flight_booking t4 ON t4.flight_id = t2.flight_id
    JOIN booking t5 ON t5.booking_id = t4.booking_id OR t5.booking_id != t4.booking_id
    JOIN booking_status t6 ON t6.booking_id = t5.booking_id OR t6.booking_id != t5.booking_id
where t1.aircraft_id="19"

Body:
Are you sure your joins are correct... this seems to match any row;

t5.booking_id = t4.booking_id OR t5.booking_id != t4.booking_id

as you have = or != with the same values....

That said, you can use DISTINCT

SELECT DISTINCT t1.trip_id , t1.server_trip_id, t1.aircraft_id,
t2.flight_id,
t3.server_fid,t3.dep,t3.dest,t3.service_provider,t3.flight_name,t3.sta,t3.std,
t4.booking_id,
t5.server_booking_id,t5.type,t5.trip_number,t5.company_id,t5.user_id,t5.aircraft_registration,t5.icao,
t6.status
    FROM trip t1
    JOIN trip_flight t2 ON t2.trip_id = t1.trip_id
    JOIN flight t3 ON t3.fid = t2.flight_id
    JOIN trip_flight_booking t4 ON t4.flight_id = t2.flight_id
    JOIN booking t5 ON t5.booking_id = t4.booking_id OR t5.booking_id != t4.booking_id
    JOIN booking_status t6 ON t6.booking_id = t5.booking_id OR t6.booking_id != t5.booking_id
    where t1.aircraft_id="19"


问:
Find all grouped records where a records are newer than a certain type of record
That would be the intermediary output I need:

```<code>Id1, Id2, Type,   Date
1,   2,    test,  2010-10-10
1,   3,    stage, 2010-05-05
1,   2,    stage, 2010-12-12
1,   3,    test,  2010-04-04
1,   3,    prod,  2010-12-31
</code>```

From that point I want to know how many grouped (Id1,Id2) records do exist after the record with Type = 'test'.

for the above I would get this final output:

```<code>Id1, Id2, Count
1,   2,   1
1,   3,   2
</code>```

What sql query would that be?

The use case would be to find all those records who never made it to a later stage than type = "test"

答:
```<code>SELECT x.Id1, x.Id2, x.[Date],
       CountAfter = (
           SELECT COUNT(*) FROM dbo.Table1 AS y
           WHERE x.Id1=y.Id1 AND x.Id2=y.Id2
           AND y.[Date]>x.[Date]) -- After
FROM dbo.Table1 AS x
WHERE x.[Type]='test'
</code>```

Note: I've assumed that every {Id1, Id2} pair of values have only one row with Type='test'.

Edit 1: If you want to filter all rows with CountAfter = 0 then

```<code>SELECT x.Id1, x.Id2, x.[Date]
FROM dbo.Table1 AS x
WHERE x.[Type]='test'
AND NOT EXISTS (
     SELECT * FROM dbo.Table1 AS y
     WHERE x.Id1=y.Id1 AND x.Id2=y.Id2
     AND y.[Date]>x.[Date])
</code>```

or (but it isn't an optimal solution)

```<code>SELECT ...
FROM (
... insert main query ...
) AS mq
WHERE mq.CountAfter = 0
</code>```

Body:
That would be the intermediary output I need:

Id1, Id2, Type,   Date
1,   2,    test,  2010-10-10
1,   3,    stage, 2010-05-05
1,   2,    stage, 2010-12-12
1,   3,    test,  2010-04-04
1,   3,    prod,  2010-12-31

From that point I want to know how many grouped (Id1,Id2) records do exist after the record with Type = 'test'.

for the above I would get this final output:

Id1, Id2, Count
1,   2,   1
1,   3,   2

What sql query would that be?

The use case would be to find all those records who never made it to a later stage than type = "test"

Body:
SELECT x.Id1, x.Id2, x.[Date],
       CountAfter = (
           SELECT COUNT(*) FROM dbo.Table1 AS y
           WHERE x.Id1=y.Id1 AND x.Id2=y.Id2
           AND y.[Date]>x.[Date]) -- After
FROM dbo.Table1 AS x
WHERE x.[Type]='test'

Note: I've assumed that every {Id1, Id2} pair of values have only one row with Type='test'.

Edit 1: If you want to filter all rows with CountAfter = 0 then

SELECT x.Id1, x.Id2, x.[Date]
FROM dbo.Table1 AS x
WHERE x.[Type]='test'
AND NOT EXISTS (
     SELECT * FROM dbo.Table1 AS y
     WHERE x.Id1=y.Id1 AND x.Id2=y.Id2
     AND y.[Date]>x.[Date])

or (but it isn't an optimal solution)

SELECT ...
FROM (
... insert main query ...
) AS mq
WHERE mq.CountAfter = 0


问:
Yii2 and postgres connecttion
I tried yii2 and postgres database but when I try to query my table i got an error . How to fix this?

LINK for my error:

LINK for my database connection:

答:
maybe you don't set defaultSchema on connection string

```<code>    return [
    'class' => 'yii\db\Connection',
    'dsn' => 'pgsql:host=localhost;dbname=db_name',
    'username' => 'db_username',
    'password' => 'db_password',
    'charset' => 'utf8',
    'schemaMap' => [
      'pgsql'=> [
        'class'=>'yii\db\pgsql\Schema',
        'defaultSchema' => 'public' //specify your schema here
      ]
    ], // PostgreSQL
];
</code>```

see to here

OR
change your tableName() function in model like this

```<code>/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'schemaName.table_name';
}
</code>```

Title: Yii2 and postgres connecttion

Body:
maybe you don't set defaultSchema on connection string

    return [
    'class' => 'yii\db\Connection',
    'dsn' => 'pgsql:host=localhost;dbname=db_name',
    'username' => 'db_username',
    'password' => 'db_password',
    'charset' => 'utf8',
    'schemaMap' => [
      'pgsql'=> [
        'class'=>'yii\db\pgsql\Schema',
        'defaultSchema' => 'public' //specify your schema here
      ]
    ], // PostgreSQL
];

see to here

OR
change your tableName() function in model like this

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'schemaName.table_name';
}


问:
When to use `use` or the fully qualified name
I'm wondering when to use the fully qualified class name or when to put a use statement on top of the class.
For example:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class ImageStatus extends Model {
    public function image(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
        return $this->belongsTo( \App\Image::class, 'id' );
    }

    public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
        return $this->belongsTo( \App\User::class, 'id' );
    }
}
</code>```

At the moment I have this piece of code and my PHPStorm tells me Unnecessary fully qualified name. This hint disappears when I change it to:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImageStatus extends Model {
    public function image(): BelongsTo {
        return $this->belongsTo( \App\Image::class, 'id' );
    }

    public function user(): BelongsTo {
        return $this->belongsTo( \App\User::class, 'id' );
    }
}
</code>```

So I'm wondering what the difference is, performance wise, code readability and if one is better than the other.

答:
When you do use SomeNamespace\ClassName than you do not have later append \SomeNamespace to ClassName. So your example should be

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImageStatus extends Model {
    public function image(): BelongsTo {
        return $this->belongsTo(Image::class, 'id' );
    }

    public function user(): BelongsTo {
        return $this->belongsTo(User::class, 'id' );
    }
}
</code>```

Please note that when you are in same namespace, than you do not need to add namespace to class name. When namespace App; then User::class instead of \App\User::class

Body:
I'm wondering when to use the fully qualified class name or when to put a use statement on top of the class.
For example:

namespace App;

use Illuminate\Database\Eloquent\Model;

class ImageStatus extends Model {
    public function image(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
        return $this->belongsTo( \App\Image::class, 'id' );
    }

    public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
        return $this->belongsTo( \App\User::class, 'id' );
    }
}

At the moment I have this piece of code and my PHPStorm tells me Unnecessary fully qualified name. This hint disappears when I change it to:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImageStatus extends Model {
    public function image(): BelongsTo {
        return $this->belongsTo( \App\Image::class, 'id' );
    }

    public function user(): BelongsTo {
        return $this->belongsTo( \App\User::class, 'id' );
    }
}

So I'm wondering what the difference is, performance wise, code readability and if one is better than the other.

Body:
When you do use SomeNamespace\ClassName than you do not have later append \SomeNamespace to ClassName. So your example should be

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImageStatus extends Model {
    public function image(): BelongsTo {
        return $this->belongsTo(Image::class, 'id' );
    }

    public function user(): BelongsTo {
        return $this->belongsTo(User::class, 'id' );
    }
}

Please note that when you are in same namespace, than you do not need to add namespace to class name. When namespace App; then User::class instead of \App\User::class


问:
how to add treeview class to listbox
I have a wpf add treeview item to listbox like follows:

```<code>    private void MenuItem_OnClick(object sender, RoutedEventArgs e)
    {
        var itemToAdd = this.tv_Project.SelectedItem as Product;
        if(itemToAdd != null)
        {
            lb_Configuration.Items.Add(itemToAdd);
        }
        else
        {
            ...
        }
    }
</code>```

the listbox binding to ItemsSource like:

```<code><ListBox x:Name="lb_Configuration" SelectionMode="Single" ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct}">
</code>```

The above code works fine. Now when I detect the RegisterLowByte has the same ModelNumber as Products, I want to add the corresponding Product to the listbox automaticlly, so I tried this:

```<code>    private void FindDevice_Executed(object sender, ExecutedRoutedEventArgs e)
    {

        var RegisterLowByte = BitConverter.GetBytes(infoRegisters[j])[0];
        var hasItem = sdb.GetProductFilteredWithLinq(RegisterLowByte) as Product;
        if (hasItem != null)
        {
            lb_Configuration.Items.Add(hasItem);
        }
        else
        {
            ...
        }
    }
</code>```

The method to get product:

```<code>    public ICollection<Product> GetProductFilteredWithLinq(UInt16 modelNumber)
    {
        ICollection<Product> products = GetProducts();

        IEnumerable<Product> matches = from product in products
                                       where product.ModelNumber == modelNumber
                                       select product;

        return new ObservableCollection<Product>(matches.ToList());
    }
</code>```

After I tried this, the hasItem always be null, but if I try to define hasItem like

```<code>var hasItem = sdb.GetProductFilteredWithLinq(RegisterLow).Cast<Product>();
</code>```

I can get the Product which has the same ModelNumber as RegisterLowByte but I can't add this to listbox as Product, any one knows how to fix this? Thanks in advance!

答:
GetProductFilteredWithLinq returning the collection so you need to use AddRange method instead of Add.</p>

```<code> private void FindDevice_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        var RegisterLowByte = BitConverter.GetBytes(infoRegisters[j])[0];
        var hasItem = sdb.GetProductFilteredWithLinq(RegisterLow);
        if (hasItem != null)
        {
            foreach (var item in hasItem)
            {
              lb_Configuration.Items.Add(item);
            }
        }
        else
        {
            ...
        }
    }
</code>```

Title: how to add treeview class to listbox

Body:
I have a wpf add treeview item to listbox like follows:

    private void MenuItem_OnClick(object sender, RoutedEventArgs e)
    {
        var itemToAdd = this.tv_Project.SelectedItem as Product;
        if(itemToAdd != null)
        {
            lb_Configuration.Items.Add(itemToAdd);
        }
        else
        {
            ...
        }
    }

the listbox binding to ItemsSource like:

<ListBox x:Name="lb_Configuration" SelectionMode="Single" ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct}">

The above code works fine. Now when I detect the RegisterLowByte has the same ModelNumber as Products, I want to add the corresponding Product to the listbox automaticlly, so I tried this:

    private void FindDevice_Executed(object sender, ExecutedRoutedEventArgs e)
    {

        var RegisterLowByte = BitConverter.GetBytes(infoRegisters[j])[0];
        var hasItem = sdb.GetProductFilteredWithLinq(RegisterLowByte) as Product;
        if (hasItem != null)
        {
            lb_Configuration.Items.Add(hasItem);
        }
        else
        {
            ...
        }
    }

The method to get product:

    public ICollection<Product> GetProductFilteredWithLinq(UInt16 modelNumber)
    {
        ICollection<Product> products = GetProducts();

        IEnumerable<Product> matches = from product in products
                                       where product.ModelNumber == modelNumber
                                       select product;

        return new ObservableCollection<Product>(matches.ToList());
    }

After I tried this, the hasItem always be null, but if I try to define hasItem like

var hasItem = sdb.GetProductFilteredWithLinq(RegisterLow).Cast<Product>();

I can get the Product which has the same ModelNumber as RegisterLowByte but I can't add this to listbox as Product, any one knows how to fix this? Thanks in advance!

Body:
GetProductFilteredWithLinq returning the collection so you need to use AddRange method instead of Add.

 private void FindDevice_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        var RegisterLowByte = BitConverter.GetBytes(infoRegisters[j])[0];
        var hasItem = sdb.GetProductFilteredWithLinq(RegisterLow);
        if (hasItem != null)
        {
            foreach (var item in hasItem)
            {
              lb_Configuration.Items.Add(item);
            }
        }
        else
        {
            ...
        }
    }


答:
I think the query will be,</p>

```<code>SELECT Id1, Id2, count(Id1) from <table_name> where Type = 'test' group by Id1, Id2;
</code>```

Title: Find all grouped records where a records are newer than a certain type of record

Body:
I think the query will be,

SELECT Id1, Id2, count(Id1) from <table_name> where Type = 'test' group by Id1, Id2;


答:
You can do it this way:

```<code>SELECT
    t.Id1,
    t.Id2,
    COUNT(*) AS Count
FROM (SELECT Id1, Id2, Date FROM Table WHERE TYPE = 'test') t
LEFT JOIN Table tt
    ON tt.Id1 = t.Id1 AND tt.Id2 = t.Id2 AND t.Date <= tt.Date
    AND tt.Type <> 'Test'
GROUP BY t.Id1, t.Id2
</code>```

Example:

```<code>DECLARE @table TABLE (Id1 int, Id2 int, [Type] varchar(10),[Date] date)
INSERT INTO @table VALUES (1,   2,    'test',  '2010-10-10'),
(1,   3,    'stage', '2010-05-05'),
(1,   2,    'stage', '2010-12-12'),
(1,   3,    'test',  '2010-04-04'),
(1,   3,    'prod',  '2010-12-31')

SELECT
    t.Id1,
    t.Id2,
    COUNT(*) AS Count
FROM (SELECT Id1, Id2, Date FROM @Table WHERE TYPE = 'test') t
LEFT JOIN @Table tt
    ON tt.Id1 = t.Id1 AND tt.Id2 = t.Id2 AND t.Date <= tt.Date
    AND tt.Type <> 'Test'
GROUP BY t.Id1, t.Id2
</code>```

Body:
You can do it this way:

SELECT
    t.Id1,
    t.Id2,
    COUNT(*) AS Count
FROM (SELECT Id1, Id2, Date FROM Table WHERE TYPE = 'test') t
LEFT JOIN Table tt
    ON tt.Id1 = t.Id1 AND tt.Id2 = t.Id2 AND t.Date <= tt.Date
    AND tt.Type <> 'Test'
GROUP BY t.Id1, t.Id2

Example:

DECLARE @table TABLE (Id1 int, Id2 int, [Type] varchar(10),[Date] date)
INSERT INTO @table VALUES (1,   2,    'test',  '2010-10-10'),
(1,   3,    'stage', '2010-05-05'),
(1,   2,    'stage', '2010-12-12'),
(1,   3,    'test',  '2010-04-04'),
(1,   3,    'prod',  '2010-12-31')

SELECT
    t.Id1,
    t.Id2,
    COUNT(*) AS Count
FROM (SELECT Id1, Id2, Date FROM @Table WHERE TYPE = 'test') t
LEFT JOIN @Table tt
    ON tt.Id1 = t.Id1 AND tt.Id2 = t.Id2 AND t.Date <= tt.Date
    AND tt.Type <> 'Test'
GROUP BY t.Id1, t.Id2


问:
jQuery ui close button is not shown but it works properly
I am using the jQuery-ui dialog and I have added the libraries:

```<code><link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">

<script src="../js/jquery-3.2.1.min.js"></script>
<script src="../js/tether.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery-ui.js"></script>
</code>```

But when the dialog box appears, you can not see the close button X.

I can see it as this:

And I have these errors at the console:

Failed to load resource: the server responded with a status of 404
  (Not Found)

答: When you download the Jquery UI zip file and unzip it, there is a images folder. Copy and paste in your project folder. Then, it will work flawlessly. </p>

Body:
I am using the jQuery-ui dialog and I have added the libraries:

<link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">

But when the dialog box appears, you can not see the close button X.

I can see it as this:

And I have these errors at the console:

Failed to load resource: the server responded with a status of 404
  (Not Found)


问:
Decrease bootstrap datepicker end date
I am using bootstrap datepicker for one on my project and set endDate like this

```<code>$('#daterange').data('daterangepicker').setEndDate('2017/03/12');
</code>```

EndDate is somthign that i get from database, only problem is that on datepicker i have to set endDate but decrease one date, it measn if i have something from server like this

2017/03/12

I need to bind datepicker like this

```<code>$('#daterange').data('daterangepicker').setEndDate('2017/03/11');
</code>```

is it possible to do that in frontend or i must go to server to correct, any simple solution?

答:
What i will do:

1. get date from database ( 2017/03712)
2. change it to datetime format
3. decrease one day
4. setEndDate with correct format

Title: Decrease bootstrap datepicker end date

Body:
I am using bootstrap datepicker for one on my project and set endDate like this

$('#daterange').data('daterangepicker').setEndDate('2017/03/12');

EndDate is somthign that i get from database, only problem is that on datepicker i have to set endDate but decrease one date, it measn if i have something from server like this

2017/03/12

I need to bind datepicker like this

$('#daterange').data('daterangepicker').setEndDate('2017/03/11');

is it possible to do that in frontend or i must go to server to correct, any simple solution?


问:
JointJS Link with same source and target
In some cases I have links where source and target are the same element. (same ID).

```<code>  this.lastLink = this.link.clone().set({
    source: {id: ele1Id},
    target: {id: ele2Id},
    ...
</code>```

It currently looks like this. Links have labels so don't be confused about it. (LINK_TABLE is a link label).

What I would like to achieve is that whenever source and target are the same, the link should look something like this.

My initial try was to get the position of target and then increment it for some value.

```<code>    var targetPositionX = ele2.attributes.position.x;
    var targetPositionY = ele2.attributes.position.y;

    source: {id: ele1Id},
    target: {x: targetPositionX+50, y:targetPositionY+50},
    ...
</code>```

But that try didn't work as I encountered problems while trying to get the target position. If I would console.log(ele2), and then look for position, it would be fine. But If I would console.log(ele2.attributes.position) it would log {x:0, y:0} for some reason. But it's not related to this question.

So what else can I try?

答:
I managed to solve this by adding two ports to my element.

```<code>  var port = {
    id: 'port2',
    position:{
      name: 'right'
    },
    markup: '<rect width="0"  height="1"/>'
  };
  var port2 = {
    id: 'port1',
    position:{
      name: 'right'
    },
    markup: '<rect width="0" height="1"/>'
  };
  ele1Id.addPort(port);
  ele1Id.addPort(port2);
</code>```

After adding the links I had to make sure that I also add ports to my source and target.

```<code>source: {id: ele1Id.id, port: "port1"},
target: {id: ele2Id.id, port: "port2"}
</code>```

And another thing I added for that 'spinal' link look is this:

```<code>connector: { name: 'rounded' },
router: { name: 'manhattan' }
</code>```

Body:
In some cases I have links where source and target are the same element. (same ID).

  this.lastLink = this.link.clone().set({
    source: {id: ele1Id},
    target: {id: ele2Id},
    ...

It currently looks like this. Links have labels so don't be confused about it. (LINK_TABLE is a link label).

What I would like to achieve is that whenever source and target are the same, the link should look something like this.

My initial try was to get the position of target and then increment it for some value.

    var targetPositionX = ele2.attributes.position.x;
    var targetPositionY = ele2.attributes.position.y;

    source: {id: ele1Id},
    target: {x: targetPositionX+50, y:targetPositionY+50},
    ...

But that try didn't work as I encountered problems while trying to get the target position. If I would console.log(ele2), and then look for position, it would be fine. But If I would console.log(ele2.attributes.position) it would log {x:0, y:0} for some reason. But it's not related to this question.

So what else can I try?

Body:
I managed to solve this by adding two ports to my element.

  var port = {
    id: 'port2',
    position:{
      name: 'right'
    },
    markup: '<rect width="0"  height="1"/>'
  };
  var port2 = {
    id: 'port1',
    position:{
      name: 'right'
    },
    markup: '<rect width="0" height="1"/>'
  };
  ele1Id.addPort(port);
  ele1Id.addPort(port2);

After adding the links I had to make sure that I also add ports to my source and target.

source: {id: ele1Id.id, port: "port1"},
target: {id: ele2Id.id, port: "port2"}

And another thing I added for that 'spinal' link look is this:

connector: { name: 'rounded' },
router: { name: 'manhattan' }


问:
Access other post fields to create a complex validation condition
I'm sending request data with parent/child relationships (1 level max depth). So parent_id references itself in the table as a fk.

debug($this->request->getData()) yields:

```<code>[
    "activities": [
        [
            "name": "Parent Activity",
            "id": 3,
            "parent_id": null,
            "quantity": null,
        ],

        [
            "name": "Child Activity",
            "id": 4,
            "parent_id": 3,
            "quantity" :5
        ],

        [
            "name": "Parent Activity 2",
            "id": 7,
            "parent_id": null,
            "quantity": null,
        ],

    ]
]
</code>```

I want to create a Validation rule that will force parent activities who have no children ( nodes with parent_id pointing to them ) to have quantity" filled in (this can be any arbitrary field, I have a few others).

The most straight forward way I can think is by looping/manipulating the request data and marking it, but is there a nice Cake way of doing this and possibly in the Validation?

```<code>$data = $this->request->getData();
$collection = new \Cake\Collection\Collection($data);
</code>```

// filter/map so I can create a new key to count the # of children, thus manipulating the data as such:

```<code>[
    "activities": [
        [
            "name": "Parent Activity",
            "id": 3,
            "parent_id": null,
            "quantity": null,
            "children": 1
        ],

        [
            "name": "Child Activity",
            "id": 4,
            "parent_id": 3,
            "quantity" :5
        ],

        [
            "name": "Parent Activity 2",
            "id": 7,
            "parent_id": null,
            "quantity": null,
            "children": 0
        ],

    ]
]
</code>```

Then I could use the children as a condition in Validation rather than something more complicated. Though manipulating the request data doesn't seem that clean. Open to any other suggestions.

Using Cake3.

答:
Use conditional validation.

Example taken from the link above:

```<code>$validator->add('picture', 'file', [
    'rule' => ['mimeType', ['image/jpeg', 'image/png']],
    'on' => function ($context) {
        return !empty($context['data']['show_profile_picture']);
    }
]);
</code>```

$context is the data, just add your logic to check $context in the closure.

Body:
I'm sending request data with parent/child relationships (1 level max depth). So parent_id references itself in the table as a fk.

debug($this->request->getData()) yields:

[
    "activities": [
        [
            "name": "Parent Activity",
            "id": 3,
            "parent_id": null,
            "quantity": null,
        ],

        [
            "name": "Child Activity",
            "id": 4,
            "parent_id": 3,
            "quantity" :5
        ],

        [
            "name": "Parent Activity 2",
            "id": 7,
            "parent_id": null,
            "quantity": null,
        ],

    ]
]

I want to create a Validation rule that will force parent activities who have no children ( nodes with parent_id pointing to them ) to have quantity" filled in (this can be any arbitrary field, I have a few others).

The most straight forward way I can think is by looping/manipulating the request data and marking it, but is there a nice Cake way of doing this and possibly in the Validation?

$data = $this->request->getData();
$collection = new \Cake\Collection\Collection($data);

// filter/map so I can create a new key to count the # of children, thus manipulating the data as such:

[
    "activities": [
        [
            "name": "Parent Activity",
            "id": 3,
            "parent_id": null,
            "quantity": null,
            "children": 1
        ],

        [
            "name": "Child Activity",
            "id": 4,
            "parent_id": 3,
            "quantity" :5
        ],

        [
            "name": "Parent Activity 2",
            "id": 7,
            "parent_id": null,
            "quantity": null,
            "children": 0
        ],

    ]
]

Then I could use the children as a condition in Validation rather than something more complicated. Though manipulating the request data doesn't seem that clean. Open to any other suggestions.

Using Cake3.

Body:
Use conditional validation.

Example taken from the link above:

$validator->add('picture', 'file', [
    'rule' => ['mimeType', ['image/jpeg', 'image/png']],
    'on' => function ($context) {
        return !empty($context['data']['show_profile_picture']);
    }
]);

$context is the data, just add your logic to check $context in the closure.


问:
get value DIV in PHP
I want to get DIV contents in PHP to submit a form.

```<code><div id="hello"></div>
</code>```

In my search, I was advised to use <input type="hidden" but I do not know how to do.

答:
If you are obtaining the HTML as a string, or even if its a remote web page, you will need a HTML parser. There are lots of these for PHP and the question has already been asked and answered. How do you parse and process HTML/XML in PHP?

If you are looking to do this on click or some other page event when a user does something, you need to use javascript instead of PHP. PHP is a server side language and cant be used to access elements in the users web browser, you need to use javascript for this.

Title: get value DIV in PHP

Body:
I want to get DIV contents in PHP to submit a form.

In my search, I was advised to use <input type="hidden" but I do not know how to do.


问:
MySQLdb fetcall,AttributeError: 'int' object has no attribute 'fetchall'
I want to check if I have managed to import my csv file into MySQL db in proper manner.My code

```<code>import MySQLdb

mydb = MySQLdb.connect(host = 'localhost',user = 'milenko',passwd = 'nuklear',db = 'mm')
cur = mydb.cursor()
command = cur.execute('SELECT * FROM jul')
results = command.fetchall()

print (results)
</code>```

But I got this

```<code>File "b12.py", line 6, in <module>
    results = command.fetchall()
AttributeError: 'int' object has no attribute 'fetchall'
</code>```

I have seen previous SO posts,where people claim that number objects do not have fetcall object.I have copied this code from Python for MySQL from Albert Lukaszewski.
How to pull down db content in one go?

答:
You can't call fetchall() on the result of a cursor.execute(), in fact, according to MySQLdb documentation, cursor.execute() return the number of affected rows by the query executed.
To retrieve data you have to access to cursor results directly:

```<code>cur = mydb.cursor()
cur.execute('SELECT * FROM jul')
results = cur.fetchall()
</code>```

Body:
I want to check if I have managed to import my csv file into MySQL db in proper manner.My code

import MySQLdb

mydb = MySQLdb.connect(host = 'localhost',user = 'milenko',passwd = 'nuklear',db = 'mm')
cur = mydb.cursor()
command = cur.execute('SELECT * FROM jul')
results = command.fetchall()

print (results)

But I got this

File "b12.py", line 6, in <module>
    results = command.fetchall()
AttributeError: 'int' object has no attribute 'fetchall'

I have seen previous SO posts,where people claim that number objects do not have fetcall object.I have copied this code from Python for MySQL from Albert Lukaszewski.
How to pull down db content in one go?

Body:
You can't call fetchall() on the result of a cursor.execute(), in fact, according to MySQLdb documentation, cursor.execute() return the number of affected rows by the query executed.
To retrieve data you have to access to cursor results directly:

cur = mydb.cursor()
cur.execute('SELECT * FROM jul')
results = cur.fetchall()


问:
Change checkbox toggle function from click to touchstart
I am developing a cordova app. Because of the 300ms delay with the click event I don't want to use that. How do I change the event a <input type='checkbox'> element listens to for toggeling it's checkmark from click to e.g. touchstart?

The closest I got was making the checkbox disabled and adding this code:

```<code>$(':checkbox').each(function(){
        $(this).bind('touchstart', function(){
            if(this.checked) {
                this.checked = true;
            } else {
                this.checked = false;
            }
        })
    });
</code>```

Unfortunately touchstart does not trigger.

答:
With that code checkbox event will called twice. First touchstart event will called and then after 300ms delay click event will called real event checkbox. Let's try this code</p>

```<code>$(':checkbox').each(function(){
    $(this).bind('touchstart', function(){
        if(this.checked) {
            this.checked = true;
        } else {
            this.checked = false;
        }
    }).bind('click', function(e) {
        e.preventDefault();
    });
});
</code>```

Body:
I am developing a cordova app. Because of the 300ms delay with the click event I don't want to use that. How do I change the event a <input type='checkbox'> element listens to for toggeling it's checkmark from click to e.g. touchstart?

The closest I got was making the checkbox disabled and adding this code:

$(':checkbox').each(function(){
        $(this).bind('touchstart', function(){
            if(this.checked) {
                this.checked = true;
            } else {
                this.checked = false;
            }
        })
    });

Unfortunately touchstart does not trigger.

Body:
With that code checkbox event will called twice. First touchstart event will called and then after 300ms delay click event will called real event checkbox. Let's try this code

$(':checkbox').each(function(){
    $(this).bind('touchstart', function(){
        if(this.checked) {
            this.checked = true;
        } else {
            this.checked = false;
        }
    }).bind('click', function(e) {
        e.preventDefault();
    });
});


答:
you can use momentjs
moment("your date", "YYYY/MM/DD").subtract(1, 'days').format('YYYY/MM/DD');

Title: Decrease bootstrap datepicker end date


问:
How to query a bag with Nhibernate
I need to get publications which the country list doesn't contain a country (research on IsoCode2)

The sql query is :

```<code>select * from pub_head ph
where not exists
(select 1 from pub_head_forbidden_country phfc , country c
                where phfc.pub_head_id = ph.pub_head_id
                and phfc.country_id = c.country_id
                and c.iso_code2 = 'CA');
</code>```

And the model :

```<code><class name="Publication" table="PUB_HEAD">

  <id name="Id" column="PUB_HEAD_ID">
   <generator class="native">
    <param name="sequence">SEQ_PUB_HEAD</param>
   </generator>
  </id>

  <idbag name="Countries" table="PUB_HEAD_COUNTRY" lazy="true">
   <collection-id column="PUB_HEAD_COUNTRY_ID">
    <generator class="native">
     <param name="sequence">SEQ_PUB_HEAD_COUNTRY</param>
    </generator>
   </collection-id>

   <key column ="PUB_HEAD_ID"  />
   <many-to-many class="Model.Referential.Country, Model" column="COUNTRY_ID"/>
  </idbag>
</class>

<class name="Country" table="Country">
  <id name="Id" column="COUNTRY_ID">
   <generator class="native">
   </generator>
  </id>
  <property name="Name">
   <column name="NAME"></column>
  </property>
  <property name="IsoCode2">
   <column name="ISO_CODE2"></column>
  </property>
  <property name="IsoCode3">
   <column name="ISO_CODE3"></column>
  </property>

 </class>
</code>```

I began with SubQueries, but I didn't success to do it.

Thanks

答:
Allergic to joins? That SQL is very hard to understand.

Does it mean this?

```<code>SELECT *
FROM pub_head
WHERE id not IN (
  SELECT phfc.pub_head_id
  FROM pub_head_forbidden_country as phfc
    INNER JOIN country AS c ON phfc.country_id = c.country_id
  WHERE c.iso_code2 = 'CA'
)
</code>```

[Posting as answer because this SQL would be awful in a comment.]

Title: How to query a bag with Nhibernate

Body:
I need to get publications which the country list doesn't contain a country (research on IsoCode2)

The sql query is :

select * from pub_head ph
where not exists
(select 1 from pub_head_forbidden_country phfc , country c
                where phfc.pub_head_id = ph.pub_head_id
                and phfc.country_id = c.country_id
                and c.iso_code2 = 'CA');

And the model :

<class name="Publication" table="PUB_HEAD">

  <id name="Id" column="PUB_HEAD_ID">
   <generator class="native">
    <param name="sequence">SEQ_PUB_HEAD</param>
   </generator>
  </id>

  <idbag name="Countries" table="PUB_HEAD_COUNTRY" lazy="true">
   <collection-id column="PUB_HEAD_COUNTRY_ID">
    <generator class="native">
     <param name="sequence">SEQ_PUB_HEAD_COUNTRY</param>
    </generator>
   </collection-id>

   <key column ="PUB_HEAD_ID"  />
   <many-to-many class="Model.Referential.Country, Model" column="COUNTRY_ID"/>
  </idbag>
</class>

<class name="Country" table="Country">
  <id name="Id" column="COUNTRY_ID">
   <generator class="native">
   </generator>
  </id>
  <property name="Name">
   <column name="NAME"></column>
  </property>
  <property name="IsoCode2">
   <column name="ISO_CODE2"></column>
  </property>
  <property name="IsoCode3">
   <column name="ISO_CODE3"></column>
  </property>

 </class>

I began with SubQueries, but I didn't success to do it.

Thanks

Body:
Allergic to joins? That SQL is very hard to understand.

Does it mean this?

SELECT *
FROM pub_head
WHERE id not IN (
  SELECT phfc.pub_head_id
  FROM pub_head_forbidden_country as phfc
    INNER JOIN country AS c ON phfc.country_id = c.country_id
  WHERE c.iso_code2 = 'CA'
)

[Posting as answer because this SQL would be awful in a comment.]


问:
run qemu with both kvm & icount options
I'm running qemu which emulates x86_64 processor  on top of x86 host machine, and I'm interesting in achieving the following:

1) better execution time, so KVM is a better way to achieve that, as the guest and host machines share the same architecture.

2) counting the number of instruction generated by the guest machine(qemu), and virtual clock (-icount option) achieved that

I was trying to run the qemu including both kvm & icount options  (-enable-kvm -icount 0)
and I got this message
"-icount is not allowed with kvm or xen"

is it possible to run the qemu including both options?
thanks .

答:
As far as I know from reading the source code and debugging QEMU, -icount works by adding code to count the instructions and decrease a counter after every basic block translated by TCG, utilizing a small check at the beginning of each basic block to interrupt execution after each N guest instructions.

This approach cannot work with kvm or xen, as there is no code translation performed in this case that could add the additional instrumentation. So no, this is not possible, without a signficant change to QEMU.

Title: run qemu with both kvm & icount options


问:
Remove attributes based on a the first numeric value XML
Complete noob here, need to edit some XML code for work.

I need to remove the "Value for" and "Range for" rows where the number beings with the digit 8, what would be the best way of going about this? Any help would be appreciated!

Cheers

The Code

?xml version="1.0" encoding="UTF-8" ?>

```<code>        <Theme  xmlns="SOME SITE" id="t59" name="I LOVE TIM TAMS">

            <Indicator id="i564" name="I LOVE TIM TAMS" type="numeric" precision="1"  href="SOME SITE">

                <Value for="80200">53.1</Value>

                <Value for="80420">^</Value>

                <Value for="80540">^</Value>

                <Value for="80620">^</Value>

                <Value for="70700">^</Value>

                <Value for="71000">62.3</Value>

                <Value for="71300">^</Value>

                <Value for="72200">47.9</Value>

                <Value for="72300">63.8</Value>

                <Value for="72330">^</Value>

                <Value for="72800">56.9</Value>

                <Value for="73600">^</Value>

                <Value for="74050">^</Value>

                <Value for="74500">^</Value>

                <Value for="74560">^</Value>

                <Value for="74660">^</Value>

                <Value for="79399">^</Value>

                <ComparisonValue for="1">52.1</ComparisonValue>

                <ComparisonValue for="2">56.3</ComparisonValue>

                <ComparisonValue for="3">43.3</ComparisonValue>

                <ComparisonValue for="4">51.5</ComparisonValue>

                <ComparisonValue for="5">56.0</ComparisonValue>

                <ComparisonValue for="6">43.3</ComparisonValue>

                <ComparisonValue for="7">51.6</ComparisonValue>

                <ComparisonValue for="8">54.8</ComparisonValue>

                <ComparisonValue for="9">41.2</ComparisonValue>

                <ComparisonValue for="10">47.9</ComparisonValue>

                <ComparisonValue for="11">51.7</ComparisonValue>

                <ComparisonValue for="12">44.3</ComparisonValue>

                <ComparisonValue for="13">52.7</ComparisonValue>

                <ComparisonValue for="14">57.4</ComparisonValue>

                <ComparisonValue for="15">33.8</ComparisonValue>

                <ComparisonValue for="16">61.9</ComparisonValue>

                <ComparisonValue for="17">63.6</ComparisonValue>

                <ComparisonValue for="18">54.2</ComparisonValue>

                <ComparisonValue for="19">44.5</ComparisonValue>

                <ComparisonValue for="20">55.1</ComparisonValue>

                <ComparisonValue for="21">36.9</ComparisonValue>

                <ComparisonValue for="22">59.3</ComparisonValue>

                <ComparisonValue for="23">61.3</ComparisonValue>

                <ComparisonValue for="24">51.7</ComparisonValue>

                <ComparisonValue for="25">59.5</ComparisonValue>

                <ComparisonValue for="26">59.5</ComparisonValue>

                <ComparisonValue for="27">..</ComparisonValue>

                <Limits>

                    <Range for="80200" upper="59.7" lower="46.6" />

                    <Range for="80420" upper="NaN" lower="NaN" />

                    <Range for="80540" upper="NaN" lower="NaN" />

                    <Range for="80620" upper="NaN" lower="NaN" />

                    <Range for="70700" upper="NaN" lower="NaN" />

                    <Range for="71000" upper="66.9" lower="57.7" />

                    <Range for="71300" upper="NaN" lower="NaN" />

                    <Range for="72200" upper="60.6" lower="35.3" />

                    <Range for="72300" upper="72.5" lower="55.2" />

                    <Range for="72330" upper="NaN" lower="NaN" />

                    <Range for="72800" upper="63.1" lower="50.6" />

                    <Range for="73600" upper="NaN" lower="NaN" />

                    <Range for="74050" upper="NaN" lower="NaN" />

                    <Range for="74500" upper="NaN" lower="NaN" />

                    <Range for="74560" upper="NaN" lower="NaN" />

                    <Range for="74660" upper="NaN" lower="NaN" />

                    <Range for="79399" upper="NaN" lower="NaN" />

                    <Range for="1" upper="52.4" lower="51.7" />

                    <Range for="2" upper="56.7" lower="55.8" />

                    <Range for="3" upper="43.8" lower="42.7" />

                    <Range for="4" upper="52.1" lower="50.9" />

                    <Range for="5" upper="56.8" lower="55.2" />

                    <Range for="6" upper="44.1" lower="42.4" />

                    <Range for="7" upper="52.3" lower="50.9" />

                    <Range for="8" upper="55.6" lower="53.9" />

                    <Range for="9" upper="42.5" lower="39.9" />

                    <Range for="10" upper="48.6" lower="47.2" />

                    <Range for="11" upper="52.7" lower="50.7" />

                    <Range for="12" upper="45.3" lower="43.3" />

                    <Range for="13" upper="53.8" lower="51.5" />

                    <Range for="14" upper="58.7" lower="56.1" />

                    <Range for="15" upper="35.9" lower="31.7" />

                    <Range for="16" upper="62.9" lower="60.9" />

                    <Range for="17" upper="64.8" lower="62.5" />

                    <Range for="18" upper="56.2" lower="52.3" />

                    <Range for="19" upper="45.9" lower="43.1" />

                    <Range for="20" upper="57.3" lower="52.8" />

                    <Range for="21" upper="38.7" lower="35.1" />

                    <Range for="22" upper="62.3" lower="56.3" />

                    <Range for="23" upper="64.7" lower="57.9" />

                    <Range for="24" upper="57.6" lower="45.8" />

                    <Range for="25" upper="61.4" lower="57.7" />

                    <Range for="26" upper="61.4" lower="57.7" />

                    <Range for="27" upper="NaN" lower="NaN" />

                </Limits>

                <Associate name="NUMBER" type="numeric"  precision="0"  >

                    <Value for="80200">10651</Value>

                    <Value for="80420">^</Value>

                    <Value for="80540">^</Value>

                    <Value for="80620">^</Value>

                    <Value for="70700">^</Value>

                    <Value for="71000">38483</Value>

                    <Value for="71300">^</Value>

                    <Value for="72200">3607</Value>

                    <Value for="72300">11182</Value>

                    <Value for="72330">^</Value>

                    <Value for="72800">13265</Value>

                    <Value for="73600">^</Value>

                    <Value for="74050">^</Value>

                    <Value for="74500">^</Value>

                    <Value for="74560">^</Value>

                    <Value for="74660">^</Value>

                    <Value for="79399">^</Value>

                    <ComparisonValue for="1">9214658</ComparisonValue>

                    <ComparisonValue for="2">6738633</ComparisonValue>

                    <ComparisonValue for="3">2471615</ComparisonValue>

                    <ComparisonValue for="4">2961214</ComparisonValue>

                    <ComparisonValue for="5">2087722</ComparisonValue>

                    <ComparisonValue for="6">873492</ComparisonValue>

                    <ComparisonValue for="7">2312577</ComparisonValue>

                    <ComparisonValue for="8">1885964</ComparisonValue>

                    <ComparisonValue for="9">426613</ComparisonValue>

                    <ComparisonValue for="10">1665325</ComparisonValue>

                    <ComparisonValue for="11">872238</ComparisonValue>

                    <ComparisonValue for="12">793087</ComparisonValue>

                    <ComparisonValue for="13">677071</ComparisonValue>

                    <ComparisonValue for="14">589665</ComparisonValue>

                    <ComparisonValue for="15">87406</ComparisonValue>

                    <ComparisonValue for="16">1166801</ComparisonValue>

                    <ComparisonValue for="17">974713</ComparisonValue>

                    <ComparisonValue for="18">192088</ComparisonValue>

                    <ComparisonValue for="19">176365</ComparisonValue>

                    <ComparisonValue for="20">91703</ComparisonValue>

                    <ComparisonValue for="21">84662</ComparisonValue>

                    <ComparisonValue for="22">77628</ComparisonValue>

                    <ComparisonValue for="23">63361</ComparisonValue>

                    <ComparisonValue for="24">14267</ComparisonValue>

                    <ComparisonValue for="25">173267</ComparisonValue>

                    <ComparisonValue for="26">173267</ComparisonValue>

                    <ComparisonValue for="27">..</ComparisonValue>

                </Associate>

                <Associate name="THE ONE" type="numeric"  >

                    <Value for="80200">reliable</Value>

                    <Value for="80420">..</Value>

                    <Value for="80540">..</Value>

                    <Value for="80620">..</Value>

                    <Value for="70700">..</Value>

                    <Value for="71000">reliable</Value>

                    <Value for="71300">..</Value>

                    <Value for="72200">reliable</Value>

                    <Value for="72300">reliable</Value>

                    <Value for="72330">..</Value>

                    <Value for="72800">reliable</Value>

                    <Value for="73600">..</Value>

                    <Value for="74050">..</Value>

                    <Value for="74500">..</Value>

                    <Value for="74560">..</Value>

                    <Value for="74660">..</Value>

                    <Value for="79399">..</Value>

                    <ComparisonValue for="1">reliable</ComparisonValue>

                    <ComparisonValue for="2">reliable</ComparisonValue>

                    <ComparisonValue for="3">reliable</ComparisonValue>

                    <ComparisonValue for="4">reliable</ComparisonValue>

                    <ComparisonValue for="5">reliable</ComparisonValue>

                    <ComparisonValue for="6">reliable</ComparisonValue>

                    <ComparisonValue for="7">reliable</ComparisonValue>

                    <ComparisonValue for="8">reliable</ComparisonValue>

                    <ComparisonValue for="9">reliable</ComparisonValue>

                    <ComparisonValue for="10">reliable</ComparisonValue>

                    <ComparisonValue for="11">reliable</ComparisonValue>

                    <ComparisonValue for="12">reliable</ComparisonValue>

                    <ComparisonValue for="13">reliable</ComparisonValue>

                    <ComparisonValue for="14">reliable</ComparisonValue>

                    <ComparisonValue for="15">reliable</ComparisonValue>

                    <ComparisonValue for="16">reliable</ComparisonValue>

                    <ComparisonValue for="17">reliable</ComparisonValue>

                    <ComparisonValue for="18">reliable</ComparisonValue>

                    <ComparisonValue for="19">reliable</ComparisonValue>

                    <ComparisonValue for="20">reliable</ComparisonValue>

                    <ComparisonValue for="21">reliable</ComparisonValue>

                    <ComparisonValue for="22">reliable</ComparisonValue>

                    <ComparisonValue for="23">reliable</ComparisonValue>

                    <ComparisonValue for="24">reliable</ComparisonValue>

                    <ComparisonValue for="25">reliable</ComparisonValue>

                    <ComparisonValue for="26">reliable</ComparisonValue>

                    <ComparisonValue for="27">..</ComparisonValue>

                </Associate>                    <Property name="alias_indicator" value="CHOCOLATE"/>

                <Property name="metatext" value="Note: THEY TASTE YUMMY"/>

                <Property name="precision" value="1"/>

            </Indicator></Theme>
</code>```

答:
Here's an XSLT 3.0 stylesheet (use for example with Saxon 9.8):

```<code><xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="(Value|Range)[starts-with(@for, '8')]"/>

</xsl:stylesheet>
</code>```

It can also be done with XSLT 1.0 or 2.0 but the code gets more verbose.

Body:
Complete noob here, need to edit some XML code for work.

I need to remove the "Value for" and "Range for" rows where the number beings with the digit 8, what would be the best way of going about this? Any help would be appreciated!

Cheers

The Code

?xml version="1.0" encoding="UTF-8" ?>

        <Theme  xmlns="SOME SITE" id="t59" name="I LOVE TIM TAMS">

            <Indicator id="i564" name="I LOVE TIM TAMS" type="numeric" precision="1"  href="SOME SITE">

                <Value for="80200">53.1</Value>

                <Value for="80420">^</Value>

                <Value for="80540">^</Value>

                <Value for="80620">^</Value>

                <Value for="70700">^</Value>

                <Value for="71000">62.3</Value>

                <Value for="71300">^</Value>

                <Value for="72200">47.9</Value>

                <Value for="72300">63.8</Value>

                <Value for="72330">^</Value>

                <Value for="72800">56.9</Value>

                <Value for="73600">^</Value>

                <Value for="74050">^</Value>

                <Value for="74500">^</Value>

                <Value for="74560">^</Value>

                <Value for="74660">^</Value>

                <Value for="79399">^</Value>

                <ComparisonValue for="1">52.1</ComparisonValue>

                <ComparisonValue for="2">56.3</ComparisonValue>

                <ComparisonValue for="3">43.3</ComparisonValue>

                <ComparisonValue for="4">51.5</ComparisonValue>

                <ComparisonValue for="5">56.0</ComparisonValue>

                <ComparisonValue for="6">43.3</ComparisonValue>

                <ComparisonValue for="7">51.6</ComparisonValue>

                <ComparisonValue for="8">54.8</ComparisonValue>

                <ComparisonValue for="9">41.2</ComparisonValue>

                <ComparisonValue for="10">47.9</ComparisonValue>

                <ComparisonValue for="11">51.7</ComparisonValue>

                <ComparisonValue for="12">44.3</ComparisonValue>

                <ComparisonValue for="13">52.7</ComparisonValue>

                <ComparisonValue for="14">57.4</ComparisonValue>

                <ComparisonValue for="15">33.8</ComparisonValue>

                <ComparisonValue for="16">61.9</ComparisonValue>

                <ComparisonValue for="17">63.6</ComparisonValue>

                <ComparisonValue for="18">54.2</ComparisonValue>

                <ComparisonValue for="19">44.5</ComparisonValue>

                <ComparisonValue for="20">55.1</ComparisonValue>

                <ComparisonValue for="21">36.9</ComparisonValue>

                <ComparisonValue for="22">59.3</ComparisonValue>

                <ComparisonValue for="23">61.3</ComparisonValue>

                <ComparisonValue for="24">51.7</ComparisonValue>

                <ComparisonValue for="25">59.5</ComparisonValue>

                <ComparisonValue for="26">59.5</ComparisonValue>

                <ComparisonValue for="27">..</ComparisonValue>

                <Limits>

                    <Range for="80200" upper="59.7" lower="46.6" />

                    <Range for="80420" upper="NaN" lower="NaN" />

                    <Range for="80540" upper="NaN" lower="NaN" />

                    <Range for="80620" upper="NaN" lower="NaN" />

                    <Range for="70700" upper="NaN" lower="NaN" />

                    <Range for="71000" upper="66.9" lower="57.7" />

                    <Range for="71300" upper="NaN" lower="NaN" />

                    <Range for="72200" upper="60.6" lower="35.3" />

                    <Range for="72300" upper="72.5" lower="55.2" />

                    <Range for="72330" upper="NaN" lower="NaN" />

                    <Range for="72800" upper="63.1" lower="50.6" />

                    <Range for="73600" upper="NaN" lower="NaN" />

                    <Range for="74050" upper="NaN" lower="NaN" />

                    <Range for="74500" upper="NaN" lower="NaN" />

                    <Range for="74560" upper="NaN" lower="NaN" />

                    <Range for="74660" upper="NaN" lower="NaN" />

                    <Range for="79399" upper="NaN" lower="NaN" />

                    <Range for="1" upper="52.4" lower="51.7" />

                    <Range for="2" upper="56.7" lower="55.8" />

                    <Range for="3" upper="43.8" lower="42.7" />

                    <Range for="4" upper="52.1" lower="50.9" />

                    <Range for="5" upper="56.8" lower="55.2" />

                    <Range for="6" upper="44.1" lower="42.4" />

                    <Range for="7" upper="52.3" lower="50.9" />

                    <Range for="8" upper="55.6" lower="53.9" />

                    <Range for="9" upper="42.5" lower="39.9" />

                    <Range for="10" upper="48.6" lower="47.2" />

                    <Range for="11" upper="52.7" lower="50.7" />

                    <Range for="12" upper="45.3" lower="43.3" />

                    <Range for="13" upper="53.8" lower="51.5" />

                    <Range for="14" upper="58.7" lower="56.1" />

                    <Range for="15" upper="35.9" lower="31.7" />

                    <Range for="16" upper="62.9" lower="60.9" />

                    <Range for="17" upper="64.8" lower="62.5" />

                    <Range for="18" upper="56.2" lower="52.3" />

                    <Range for="19" upper="45.9" lower="43.1" />

                    <Range for="20" upper="57.3" lower="52.8" />

                    <Range for="21" upper="38.7" lower="35.1" />

                    <Range for="22" upper="62.3" lower="56.3" />

                    <Range for="23" upper="64.7" lower="57.9" />

                    <Range for="24" upper="57.6" lower="45.8" />

                    <Range for="25" upper="61.4" lower="57.7" />

                    <Range for="26" upper="61.4" lower="57.7" />

                    <Range for="27" upper="NaN" lower="NaN" />

                </Limits>

                <Associate name="NUMBER" type="numeric"  precision="0"  >

                    <Value for="80200">10651</Value>

                    <Value for="80420">^</Value>

                    <Value for="80540">^</Value>

                    <Value for="80620">^</Value>

                    <Value for="70700">^</Value>

                    <Value for="71000">38483</Value>

                    <Value for="71300">^</Value>

                    <Value for="72200">3607</Value>

                    <Value for="72300">11182</Value>

                    <Value for="72330">^</Value>

                    <Value for="72800">13265</Value>

                    <Value for="73600">^</Value>

                    <Value for="74050">^</Value>

                    <Value for="74500">^</Value>

                    <Value for="74560">^</Value>

                    <Value for="74660">^</Value>

                    <Value for="79399">^</Value>

                    <ComparisonValue for="1">9214658</ComparisonValue>

                    <ComparisonValue for="2">6738633</ComparisonValue>

                    <ComparisonValue for="3">2471615</ComparisonValue>

                    <ComparisonValue for="4">2961214</ComparisonValue>

                    <ComparisonValue for="5">2087722</ComparisonValue>

                    <ComparisonValue for="6">873492</ComparisonValue>

                    <ComparisonValue for="7">2312577</ComparisonValue>

                    <ComparisonValue for="8">1885964</ComparisonValue>

                    <ComparisonValue for="9">426613</ComparisonValue>

                    <ComparisonValue for="10">1665325</ComparisonValue>

                    <ComparisonValue for="11">872238</ComparisonValue>

                    <ComparisonValue for="12">793087</ComparisonValue>

                    <ComparisonValue for="13">677071</ComparisonValue>

                    <ComparisonValue for="14">589665</ComparisonValue>

                    <ComparisonValue for="15">87406</ComparisonValue>

                    <ComparisonValue for="16">1166801</ComparisonValue>

                    <ComparisonValue for="17">974713</ComparisonValue>

                    <ComparisonValue for="18">192088</ComparisonValue>

                    <ComparisonValue for="19">176365</ComparisonValue>

                    <ComparisonValue for="20">91703</ComparisonValue>

                    <ComparisonValue for="21">84662</ComparisonValue>

                    <ComparisonValue for="22">77628</ComparisonValue>

                    <ComparisonValue for="23">63361</ComparisonValue>

                    <ComparisonValue for="24">14267</ComparisonValue>

                    <ComparisonValue for="25">173267</ComparisonValue>

                    <ComparisonValue for="26">173267</ComparisonValue>

                    <ComparisonValue for="27">..</ComparisonValue>

                </Associate>

                <Associate name="THE ONE" type="numeric"  >

                    <Value for="80200">reliable</Value>

                    <Value for="80420">..</Value>

                    <Value for="80540">..</Value>

                    <Value for="80620">..</Value>

                    <Value for="70700">..</Value>

                    <Value for="71000">reliable</Value>

                    <Value for="71300">..</Value>

                    <Value for="72200">reliable</Value>

                    <Value for="72300">reliable</Value>

                    <Value for="72330">..</Value>

                    <Value for="72800">reliable</Value>

                    <Value for="73600">..</Value>

                    <Value for="74050">..</Value>

                    <Value for="74500">..</Value>

                    <Value for="74560">..</Value>

                    <Value for="74660">..</Value>

                    <Value for="79399">..</Value>

                    <ComparisonValue for="1">reliable</ComparisonValue>

                    <ComparisonValue for="2">reliable</ComparisonValue>

                    <ComparisonValue for="3">reliable</ComparisonValue>

                    <ComparisonValue for="4">reliable</ComparisonValue>

                    <ComparisonValue for="5">reliable</ComparisonValue>

                    <ComparisonValue for="6">reliable</ComparisonValue>

                    <ComparisonValue for="7">reliable</ComparisonValue>

                    <ComparisonValue for="8">reliable</ComparisonValue>

                    <ComparisonValue for="9">reliable</ComparisonValue>

                    <ComparisonValue for="10">reliable</ComparisonValue>

                    <ComparisonValue for="11">reliable</ComparisonValue>

                    <ComparisonValue for="12">reliable</ComparisonValue>

                    <ComparisonValue for="13">reliable</ComparisonValue>

                    <ComparisonValue for="14">reliable</ComparisonValue>

                    <ComparisonValue for="15">reliable</ComparisonValue>

                    <ComparisonValue for="16">reliable</ComparisonValue>

                    <ComparisonValue for="17">reliable</ComparisonValue>

                    <ComparisonValue for="18">reliable</ComparisonValue>

                    <ComparisonValue for="19">reliable</ComparisonValue>

                    <ComparisonValue for="20">reliable</ComparisonValue>

                    <ComparisonValue for="21">reliable</ComparisonValue>

                    <ComparisonValue for="22">reliable</ComparisonValue>

                    <ComparisonValue for="23">reliable</ComparisonValue>

                    <ComparisonValue for="24">reliable</ComparisonValue>

                    <ComparisonValue for="25">reliable</ComparisonValue>

                    <ComparisonValue for="26">reliable</ComparisonValue>

                    <ComparisonValue for="27">..</ComparisonValue>

                </Associate>                    <Property name="alias_indicator" value="CHOCOLATE"/>

                <Property name="metatext" value="Note: THEY TASTE YUMMY"/>

                <Property name="precision" value="1"/>

            </Indicator></Theme>

Body:
Here's an XSLT 3.0 stylesheet (use for example with Saxon 9.8):

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="(Value|Range)[starts-with(@for, '8')]"/>

</xsl:stylesheet>

It can also be done with XSLT 1.0 or 2.0 but the code gets more verbose.


问:
All my fields are tabindex=-1 in my editview
I've created a custom module based on people template.

i've customised the editView (which is synced with the detailView) and I have assigned a tabindex value for every field.

But when I use that editView almost every field has tabindex=-1 so I only can't get to them using my mouse, which is very slow.

I was changing include/EditView/EditView.tpl but it looks the changes there has no effect on the generated code.

I changed all tabindex=$tabindex for a tabindex="-3", "-4", "5" in every tabindex assignment, but I couldn't see it in my html page, I also tried making a QRR previously.

So my question is where can I fix that -1 issue or, at least, where is really being generated my editView.

Thanks in advance!!!

答:
Well, I finally found where this fields, and tabindex values of course, were generated.

The include/EditView/EditView.tpl has been overwritten by the themes/suiteP/include/EditView/EditView.tpl.

This SmartyTemplate calls tab_panel_content.tpl in the same folder... Well, as I'm using SuitePImproved this wasn't true, suitePImproved/include/EditView/EditView.tpl was loading suiteP/include/EditView/tab_panel_content.tpl so that had to be fixed.

Anyway, in the tab_panel_content.tpl file you find tabindex=$tabindex 4 times, that $tabindexare replaced by:

$subfields.tabindex

$colData.field.tabindex

$colData.field.tabindex

$colData.field.tabindex

And this is working everywhere for me.

This change is not upgrade-safe because I didn't get loaded that tpl from the custom/themes... I'll come back later to fix that


问:
How can I build a two or multidimensional list from already available one dimension list in python?
I have a list below.  I would like to create a two or multidimensional list from one dimension normal list

x= [ light, double , motor , boolean , brakes , unit 8]

I would like to see like that

x= [ [light, double] , [motor , boolean] , [brakes , unit 8]]

in this way I can select and check the type of specific signal

答:
Another way using numpy array

```<code>import numpy as np
x= [ 'light', 'double' , 'motor' , 'boolean' , 'brakes' , 'unit 8']
a = np.array(x).reshape(3,2)
# print(a) will print as numpy array
# for printing as a list
print(a.tolist())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Another way using numpy array

import numpy as np
x= [ 'light', 'double' , 'motor' , 'boolean' , 'brakes' , 'unit 8']
a = np.array(x).reshape(3,2)
# print(a) will print as numpy array
# for printing as a list
print(a.tolist())


问:
Search a whole table in mySQL for a string
I'm trying to search a whole table in mySQL for a string.

I want to search all fields and all entrees of a table, returning each full entry that contains the specified text.

I can't figure out how to search multiple fields easily; here are the details:

The table is "clients". It has about 30 fields and 800 entries, too much to show all at once in a browser. I would like to search for a name (i.e. "Mary"), but it could be in the shipping_name field or the billing_name field, or the email field, etc.

I would like to search all fields for any entries that contain the string "Mary". This is what I think should work but doesn't:

```<code>SELECT * FROM `clients` IN 'Mary'
</code>```

答:
for specific requirement the following will work for search:

```<code>select * from table_name where (column_name1='%var1%' or column_name2='var2' or column_name='%var3%') and column_name='var';
</code>```

if you want to query for searching data from the database this will work perfectly.

Body:
I'm trying to search a whole table in mySQL for a string.

I want to search all fields and all entrees of a table, returning each full entry that contains the specified text.

I can't figure out how to search multiple fields easily; here are the details:

The table is "clients". It has about 30 fields and 800 entries, too much to show all at once in a browser. I would like to search for a name (i.e. "Mary"), but it could be in the shipping_name field or the billing_name field, or the email field, etc.

I would like to search all fields for any entries that contain the string "Mary". This is what I think should work but doesn't:

SELECT * FROM `clients` IN 'Mary'

Body:
for specific requirement the following will work for search:

select * from table_name where (column_name1='%var1%' or column_name2='var2' or column_name='%var3%') and column_name='var';

if you want to query for searching data from the database this will work perfectly.


问:
Redirect to /admin/auth/user/ since my Django app
I'm looking for add a new reverse url in order to redirect to /admin/auth/user/ in my Django Admin page.

In my template, I already have : href="{% url "admin:index" %}" line which let to overcome to the admin page.

I would like to go directly to the users manage page and groups manage page respectively admin/auth/user/ and admin/auth/group.

My urls.py file looks like :

```<code>urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name=os.path.join(settings.BASE_DIR, 'Accueil/templates/Choice.html')),
        name='choice'),
    url(r'^admin/', admin.site.urls),
    url(r'^Identity/', include('Identity.urls')),
    url(r'^Accueil/', include('Accueil.urls')),
    url(r'^Home/', include('log.urls')),
    url(r'^Informations/', include('Informations.urls')),
    url(r'^Configurations/', include('Configurations.urls')),
    url(r'^__debug__/', include(debug_toolbar.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

How I can write href="{% url "admin:index" %}" in order to add user and group ? Up to now, I don't find a way to do that.

Thank you by advance

答:
You can reverse the user and group changelist urls with:

```<code>{% url "admin:auth_user_changelist" %}
{% url "admin:auth_group_changelist" %}
</code>```

See the docs on reversing admin urls for more info.

Body:
I'm looking for add a new reverse url in order to redirect to /admin/auth/user/ in my Django Admin page.

In my template, I already have : href="{% url "admin:index" %}" line which let to overcome to the admin page.

I would like to go directly to the users manage page and groups manage page respectively admin/auth/user/ and admin/auth/group.

My urls.py file looks like :

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name=os.path.join(settings.BASE_DIR, 'Accueil/templates/Choice.html')),
        name='choice'),
    url(r'^admin/', admin.site.urls),
    url(r'^Identity/', include('Identity.urls')),
    url(r'^Accueil/', include('Accueil.urls')),
    url(r'^Home/', include('log.urls')),
    url(r'^Informations/', include('Informations.urls')),
    url(r'^Configurations/', include('Configurations.urls')),
    url(r'^__debug__/', include(debug_toolbar.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

How I can write href="{% url "admin:index" %}" in order to add user and group ? Up to now, I don't find a way to do that.

Thank you by advance

Body:
You can reverse the user and group changelist urls with:

{% url "admin:auth_user_changelist" %}
{% url "admin:auth_group_changelist" %}

See the docs on reversing admin urls for more info.