问:
R: ggplot: Error: Unknown parameters: binwidth, bins, pad
I want to do a very simple histogram with ggplot2. I have the following MWE:

```<code>library(ggplot2)
mydf <- data.frame(
                  Gene=c("APC","FAT4","XIRP2","TP53","CSMD3","BAI3","LRRK2","MACF1",
                  "TRIO","SETD2","AKAP9","CENPF","ERBB4","FBXW7","NF1","PDE4DIP",
                  "PTPRT","SPEN","ATM","FAT1","SDK1","SMG1","GLI3","HIF1A","ROS1",
                  "BRDT","CDH11","CNTRL","EP400","FN1","GNAS","LAMA1","PIK3CA",
                  "POLE","PRDM16","ROCK2","TRRAP","BRCA2","DCLK1","EVC2","LIFR",
                  "MAST4","NAV3"),
                  Freq=c(48,39,35,28,26,17,17,17,16,15,14,14,14,14,14,14,14,14,13,
                  13,13,13,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,10,10,10,
                  10,10,10))
mydf
ggplot(mydf, aes(x=Gene)) +
      geom_histogram(aes(y=Freq),
      stat="identity",
      binwidth=.5, alpha=.5,
      position="identity")
</code>```

I have always used this simple code to produce this kind of histograms.

In fact, I have the plot for this particular example that I made some time ago...

However, now I run this exact same code, and I get the following error:

Error: Unknown parameters: binwidth, bins, pad

Why do I find this error now and not before, and what does it mean?

Thanks a lot!

答:
geom_histogram() is no longer the most appropriate way to plot counts of discrete values.

As you've pre-calculated your frequency values use geom_col() instead, then all the errors will disappear.

```<code>library(ggplot2)
mydf <- data.frame(
               Gene=c("APC","FAT4","XIRP2","TP53","CSMD3","BAI3","LRRK2","MACF1",
              "TRIO","SETD2","AKAP9","CENPF","ERBB4","FBXW7","NF1","PDE4DIP",
              "PTPRT","SPEN","ATM","FAT1","SDK1","SMG1","GLI3","HIF1A","ROS1",
              "BRDT","CDH11","CNTRL","EP400","FN1","GNAS","LAMA1","PIK3CA",
              "POLE","PRDM16","ROCK2","TRRAP","BRCA2","DCLK1","EVC2","LIFR",
              "MAST4","NAV3"),
              Freq=c(48,39,35,28,26,17,17,17,16,15,14,14,14,14,14,14,14,14,13,
              13,13,13,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,10,10,10,
              10,10,10), stringsAsFactors = FALSE)
mydf
ggplot(mydf, aes(x=Gene, y=Freq)) +
   geom_col() +
   scale_x_discrete(limits = mydf$Gene)
</code>```

NB: also need to define your Gene column as not a factor and scale_x_discrete() to avoid alphabetical ordering of the x-axis.

Body:
I want to do a very simple histogram with ggplot2. I have the following MWE:

library(ggplot2)
mydf <- data.frame(
                  Gene=c("APC","FAT4","XIRP2","TP53","CSMD3","BAI3","LRRK2","MACF1",
                  "TRIO","SETD2","AKAP9","CENPF","ERBB4","FBXW7","NF1","PDE4DIP",
                  "PTPRT","SPEN","ATM","FAT1","SDK1","SMG1","GLI3","HIF1A","ROS1",
                  "BRDT","CDH11","CNTRL","EP400","FN1","GNAS","LAMA1","PIK3CA",
                  "POLE","PRDM16","ROCK2","TRRAP","BRCA2","DCLK1","EVC2","LIFR",
                  "MAST4","NAV3"),
                  Freq=c(48,39,35,28,26,17,17,17,16,15,14,14,14,14,14,14,14,14,13,
                  13,13,13,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,10,10,10,
                  10,10,10))
mydf
ggplot(mydf, aes(x=Gene)) +
      geom_histogram(aes(y=Freq),
      stat="identity",
      binwidth=.5, alpha=.5,
      position="identity")

I have always used this simple code to produce this kind of histograms.

In fact, I have the plot for this particular example that I made some time ago...

However, now I run this exact same code, and I get the following error:

Error: Unknown parameters: binwidth, bins, pad

Why do I find this error now and not before, and what does it mean?

Thanks a lot!

Body:
geom_histogram() is no longer the most appropriate way to plot counts of discrete values.

As you've pre-calculated your frequency values use geom_col() instead, then all the errors will disappear.

library(ggplot2)
mydf <- data.frame(
               Gene=c("APC","FAT4","XIRP2","TP53","CSMD3","BAI3","LRRK2","MACF1",
              "TRIO","SETD2","AKAP9","CENPF","ERBB4","FBXW7","NF1","PDE4DIP",
              "PTPRT","SPEN","ATM","FAT1","SDK1","SMG1","GLI3","HIF1A","ROS1",
              "BRDT","CDH11","CNTRL","EP400","FN1","GNAS","LAMA1","PIK3CA",
              "POLE","PRDM16","ROCK2","TRRAP","BRCA2","DCLK1","EVC2","LIFR",
              "MAST4","NAV3"),
              Freq=c(48,39,35,28,26,17,17,17,16,15,14,14,14,14,14,14,14,14,13,
              13,13,13,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,10,10,10,
              10,10,10), stringsAsFactors = FALSE)
mydf
ggplot(mydf, aes(x=Gene, y=Freq)) +
   geom_col() +
   scale_x_discrete(limits = mydf$Gene)

NB: also need to define your Gene column as not a factor and scale_x_discrete() to avoid alphabetical ordering of the x-axis.


来源: stackexchange

问:
Java return array from class
So I have 2 classes that I use:

```<code>public class Vote {

      public String vote;

       public Vote(String vote) {
            this.vote = vote;
        }

        public String getvote() {
            return vote;
        }
}
</code>```

And then the other one that returns votes array:

```<code>public class Campaign {

    private String title;
    private Vote[] votes;

    public Campaign(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public Vote[] getvotes() {
        return votes;
    }
    }
</code>```

And in main im using this code:

```<code>public class maintest {

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    System.out.println(first.getTitle() + " " + " " + first.getvotes());
}
}
</code>```

In the end I get value null. However I want to get "vote1222" also if I add more campaigns i want to retrieve more votes as well.

答:
You should be better of not using arrays but collections, consider the fact that you dont know how many people will vote in advance...

to the issue:

vote is never initialized in the constructor, therefore null by printing the object, do instead...

```<code>private List<Vote> votes;

public Campaign(String title) {
    this.title = title;
    this.votes = new ArrayList<Vote>();
}
</code>```

and then

```<code>public void addVote(Vote v) {
    this.votes.add(v);
}

public List<Vote> getvotes() {
    return votes;
}
</code>```

and the implementation:

```<code>public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    first.addVote(pvote);
    System.out.println(first.getTitle() + " " + " " + first.getvotes());
}
</code>```

Edit:

dont forget to override the toString method in the Vote class :)

ContentLicense: CC BY-SA 3.0

Title: Java return array from class

Body:
So I have 2 classes that I use:

public class Vote {

      public String vote;

       public Vote(String vote) {
            this.vote = vote;
        }

        public String getvote() {
            return vote;
        }
}

And then the other one that returns votes array:

public class Campaign {

    private String title;
    private Vote[] votes;

    public Campaign(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public Vote[] getvotes() {
        return votes;
    }
    }

And in main im using this code:

public class maintest {

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    System.out.println(first.getTitle() + " " + " " + first.getvotes());
}
}

In the end I get value null. However I want to get "vote1222" also if I add more campaigns i want to retrieve more votes as well.

Body:
You should be better of not using arrays but collections, consider the fact that you dont know how many people will vote in advance...

to the issue:

vote is never initialized in the constructor, therefore null by printing the object, do instead...

private List<Vote> votes;

public Campaign(String title) {
    this.title = title;
    this.votes = new ArrayList<Vote>();
}

and then

public void addVote(Vote v) {
    this.votes.add(v);
}

public List<Vote> getvotes() {
    return votes;
}

and the implementation:

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    first.addVote(pvote);
    System.out.println(first.getTitle() + " " + " " + first.getvotes());
}

Edit:

dont forget to override the toString method in the Vote class :)


问:
In a Scatter Plot, I'd like to Autofill an Axis
I am loading data from a text file that is a single column. I want to make a scatter plot with this data, but I only have one axis (the loaded data). For my other axis, I would like to just count up (i.e. 0,1,2,3,4,5,...) until I have a matching value for every value loaded in.

Thanks for any help in advance!

答:
Consider the sample file txt

```<code>from io import StringIO
import pandas as pd

txt = """4
5
2
6
1
4
3
6
2
7"""

s = pd.read_csv(StringIO(txt), header=None, squeeze=True)
</code>```

The default index assigned to the series s will be 0 to length of series less 1.  You can reset the index to get it into the dataframe and plot accordingly.

```<code>s.reset_index(name='x').plot.scatter('x', 'index')
</code>```

Body:
Consider the sample file txt

from io import StringIO
import pandas as pd

txt = """4
5
2
6
1
4
3
6
2
7"""

s = pd.read_csv(StringIO(txt), header=None, squeeze=True)

The default index assigned to the series s will be 0 to length of series less 1.  You can reset the index to get it into the dataframe and plot accordingly.

s.reset_index(name='x').plot.scatter('x', 'index')


问:
Mysql Query to Merge Two Condition Into One Row
I just get confused. Already tried to search this whole site or google but didn't find the 'nearest' solution.

Ok let's say I have this table structure.

```<code>id date       finger_id finger_time is_enter
1  2017-03-30  2          09:00       1
2  2017-03-30  2          17:13       0
3  2017-03-31  4          09:10       1
4  2017-03-31  3          09:01       1
5. 2017-03-31  3          17:00       0
</code>```

I want to make the table to be like below.

```<code>date       finger_id  enter_time  exit_time
2017-03-30   2        09:00       17:13
2017-03-30   4        09:10
2017-03-31   3        09:10       17:00
</code>```

I have made sql statement but it turns like this.

```<code>date       finger_id  enter_time   exit_time
2017-03-30  2         09:00
2017-03-30  2                       17:13
2017-03-31  4         09:10
2017-03-31  3         09:01
2017-03-31  3                       17:00
</code>```

I just want to know how to merge the is_enter 1 with is_enter 0 on the same date by the finger_id column.

Here's my sql query for the reference.

```<code>SELECT *
FROM `tbl_fingerprint`
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
         `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30
</code>```

Thanks for your help guys.

答:
```<code>SELECT a1.*, a3.time as time_out FROM attendance as a1
INNER JOIN (SELECT MIN(id) as id FROM attendance where is_enter = '1' group by date, f_id ) as a2
ON a2.id = a1.id
LEFT JOIN attendance as a3 ON a3.date = a1.date AND a1.f_id = a3.f_id and a3.is_enter = '0'
</code>```

you may need to cast the date to not include the time portion or to char with the yyyy-mm-dd format

Body:
I just get confused. Already tried to search this whole site or google but didn't find the 'nearest' solution.

Ok let's say I have this table structure.

id date       finger_id finger_time is_enter
1  2017-03-30  2          09:00       1
2  2017-03-30  2          17:13       0
3  2017-03-31  4          09:10       1
4  2017-03-31  3          09:01       1
5. 2017-03-31  3          17:00       0

I want to make the table to be like below.

date       finger_id  enter_time  exit_time
2017-03-30   2        09:00       17:13
2017-03-30   4        09:10
2017-03-31   3        09:10       17:00

I have made sql statement but it turns like this.

date       finger_id  enter_time   exit_time
2017-03-30  2         09:00
2017-03-30  2                       17:13
2017-03-31  4         09:10
2017-03-31  3         09:01
2017-03-31  3                       17:00

I just want to know how to merge the is_enter 1 with is_enter 0 on the same date by the finger_id column.

Here's my sql query for the reference.

SELECT *
FROM `tbl_fingerprint`
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
         `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30

Thanks for your help guys.

Body:
SELECT a1.*, a3.time as time_out FROM attendance as a1
INNER JOIN (SELECT MIN(id) as id FROM attendance where is_enter = '1' group by date, f_id ) as a2
ON a2.id = a1.id
LEFT JOIN attendance as a3 ON a3.date = a1.date AND a1.f_id = a3.f_id and a3.is_enter = '0'

you may need to cast the date to not include the time portion or to char with the yyyy-mm-dd format


问:
MS SQL - How to update local variable and have variable in WHERE condition?
currently I'm trying to update a local Variable using an UPDATE statement while also trying to cancel the UPDATE statement when the variable reaches a certain value:

```<code>UPDATE table
SET @var = @var + 1,
    field = @var
WHERE @var < 10
</code>```

This unfortunately doesn't work since it runs for all records instead of just 10. Has anyone an idea how to elegantly solve this without using a loop?
Thanks!

EDIT:
What I'm trying to do ist to allocate some kind of votes to parties. Say a party got 36.47% of the total votes. So I calculate a ratio of .47% (cutting of the integer part) for this party. Now I order my results table by ratio DESC and add one vote to each party as long as there are votes remaining. The remaining votes are stored in the variable. That's overly simplified but I hope you get what I want to do.

答:
You can probably achieve what you're trying to do by using ROW_NUMBER(). Here's a basic example:

```<code>declare @t table (field int not null, Ord int not null)
insert into @t(field,Ord) values (0,1),(0,2),(0,3),(0,4),(0,5)

;With Numbered as (
    select
        *,
        ROW_NUMBER() OVER (ORDER BY Ord) as rn
    from
        @t
)
update Numbered
set field = rn
where rn < 4

select * from @t
</code>```

Results:

```<code>field       Ord
----------- -----------
1           1
2           2
3           3
0           4
0           5
</code>```

Here, the row numbers are being generated inside a CTE and using an appropriate column to make the ordering well-defined (as your edit suggests you have something similar available). We also take advantage that you can write an UPDATE against a CTE rather than the base table (provided the UPDATE clearly only attempts to update a single table)

Body:
currently I'm trying to update a local Variable using an UPDATE statement while also trying to cancel the UPDATE statement when the variable reaches a certain value:

UPDATE table
SET @var = @var + 1,
    field = @var
WHERE @var < 10

This unfortunately doesn't work since it runs for all records instead of just 10. Has anyone an idea how to elegantly solve this without using a loop?
Thanks!

EDIT:
What I'm trying to do ist to allocate some kind of votes to parties. Say a party got 36.47% of the total votes. So I calculate a ratio of .47% (cutting of the integer part) for this party. Now I order my results table by ratio DESC and add one vote to each party as long as there are votes remaining. The remaining votes are stored in the variable. That's overly simplified but I hope you get what I want to do.

Body:
You can probably achieve what you're trying to do by using ROW_NUMBER(). Here's a basic example:

declare @t table (field int not null, Ord int not null)
insert into @t(field,Ord) values (0,1),(0,2),(0,3),(0,4),(0,5)

;With Numbered as (
    select
        *,
        ROW_NUMBER() OVER (ORDER BY Ord) as rn
    from
        @t
)
update Numbered
set field = rn
where rn < 4

select * from @t

Results:

field       Ord
----------- -----------
1           1
2           2
3           3
0           4
0           5

Here, the row numbers are being generated inside a CTE and using an appropriate column to make the ordering well-defined (as your edit suggests you have something similar available). We also take advantage that you can write an UPDATE against a CTE rather than the base table (provided the UPDATE clearly only attempts to update a single table)


问:
How to sort immutable data by date
I am trying to sort immutable data by date but am having a hard time understanding why this doesn't work. Some of the examples out there use vanilla javascript sort functions and some use the get/set methods on the keys. I have tried both with no luck. Should I be using Map instead of List?

const data = [{"dateTimeMoved":1490884969509,"dateTimeUploaded":"2017-03-30 09:42:51.970","latNew":"29.839658296606263","latOld":"29.85996055603027","lngNew":"-95.20913287997246","lngOld":"-95.18970489501953","marketId":"13","subdivisionId":"249044","subdivisionName":"Tidwell Lakes Ranch","territoryId":"4899","territoryName":"Central NE","userId":"1a94157a-bb38-4157-95ea-2ff8b43113e2","userName":"Rudy Sanchez","status":"denied","apprDenyDate":1491067499657,"comment":"Deny-- now approved, now denied","apprDenyById":"1a94157a-bb38-4157-95ea-2ff8b43113e2","apprDenyByName":"Rudy Sanchez"},{"dateTimeMoved":1490884636849,"dateTimeUploaded":"2017-03-30 09:37:17.924","latNew":"29.801395477185157","latOld":"29.822208688618133","lngNew":"-95.20630147308111","lngOld":"-95.20605336874723","marketId":"13","subdivisionId":"246090","subdivisionName":"Hidden Meadow","territoryId":"4899","territoryName":"Central NE","userId":"1a94157a-bb38-4157-95ea-2ff8b43113e2","userName":"Rudy Sanchez","status":"approved","apprDenyDate":1490884662547,"comment":"Approved this move","apprDenyById":"1a94157a-bb38-4157-95ea-2ff8b43113e2","apprDenyByName":"Rudy Sanchez"}]

const immutableData = Immutable.List(data)

const sortMarkerMoveDate = (option, array) => {

  switch (option) {
    case 'dateTimeMoved':
      array.sort((a, b) => new Date(a.dateTimeMoved) - new Date(b.dateTimeMoved))
      break
    case '-dateTimeMoved':
      array.sort((a, b) => new Date(b.dateTimeMoved) - new Date(a.dateTimeMoved))
      break
  }
  return array
}

const dateTimeOption1 = '-dateTimeMoved'
const dateTimeOption2 = 'dateTimeMoved'
const result = sortMarkerMoveDate(dateTimeOption2, immutableData)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script></code>```

答:
The problem here is that .sort does not mutate the list it is sorting, but rather, return a new sorted list.

This will work for you (added better data for testing):

```<code>const data = [{"dateTimeMoved":2490884636849}, {"dateTimeMoved":10}, {"dateTimeMoved":1490884969509},{"dateTimeMoved":1490884636849}, {"dateTimeMoved":0}]

const immutableData = Immutable.List(data)

const sortMarkerMoveDate = (option, array) => {
  switch (option) {
    case 'dateTimeMoved':
      return array.sort((a, b) => new Date(a.dateTimeMoved) - new Date(b.dateTimeMoved))
    case '-dateTimeMoved':
      return array.sort((a, b) => new Date(b.dateTimeMoved) - new Date(a.dateTimeMoved))
    default:
      return array;
  }
}

const dateTimeOption1 = '-dateTimeMoved'
const dateTimeOption2 = 'dateTimeMoved'
const result = sortMarkerMoveDate(dateTimeOption2, immutableData)

console.log(result.toJS())
</code>```

So, just return the array.sort(…) right away.

Title: How to sort immutable data by date

Body:
The problem here is that .sort does not mutate the list it is sorting, but rather, return a new sorted list.

This will work for you (added better data for testing):

const data = [{"dateTimeMoved":2490884636849}, {"dateTimeMoved":10}, {"dateTimeMoved":1490884969509},{"dateTimeMoved":1490884636849}, {"dateTimeMoved":0}]

const immutableData = Immutable.List(data)

const sortMarkerMoveDate = (option, array) => {
  switch (option) {
    case 'dateTimeMoved':
      return array.sort((a, b) => new Date(a.dateTimeMoved) - new Date(b.dateTimeMoved))
    case '-dateTimeMoved':
      return array.sort((a, b) => new Date(b.dateTimeMoved) - new Date(a.dateTimeMoved))
    default:
      return array;
  }
}

const dateTimeOption1 = '-dateTimeMoved'
const dateTimeOption2 = 'dateTimeMoved'
const result = sortMarkerMoveDate(dateTimeOption2, immutableData)

console.log(result.toJS())

So, just return the array.sort(…) right away.


问:
What is Object Mocking and when do I need it?
Many people use Mock Objects when they are writing unit tests. What is a Mock Object? Why would I ever need one? Do I need a Mock Object Framework?

答:
A mock object lets you test against just what you are writing, and abstract details such as accessing a resource (disk, a network service, etc).  The mock then lets you pretend to be that external resource, or class or whatever.

You don't really need a mock object framework, just extend the class of the functionality you don't want to worry about in your test and make sure the class you are testing can use your mock instead of the real thing (pass it in via a constructor or setter or something.

Practice will show when mocks are helpful and when they aren't.

EDIT: Mocking resources is especially important so you don't have to rely on them to exist during the test, and you can mock the details of how they exist and what they respond (such as simulating a FileNotFoundException, or a webservice that is missing, or various possible return values of a webservice)... all without the slow access times involved (mocking will prove MUCH faster than accessing such resources in the test).

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mike Stone


问:
Selecting random records for use on a web page
HI Guys,

I own a website I have a section called "mobile Section" this section contain many catagories (Nameoftheobject + a picture + little description and a download link)
Now the section is considered as an internal section. I want to view random records from that section on the first page (I dont know Like RSS but not Rss) showing
the name of the object and to which subcategories it belong and its picture if possible.
I hope any one understand what I'm trying to say.

This is my website HERE and this the link of the internal page HERE check the block that say Mobile Section Its kinda a mess.
is there any script or a tech to view it in a proper way to view it show me examples if possible

I'm using php and MySQL

Thanx in advance

答:
Whatever you do, don't use ORDER BY RAND() in MySQL.  It won't scale.  Yes, it will seem to work fine for a small number of rows because the data set is small.  ORDER BY RAND() requires a full-table scan, which means that the larger your table is the longer the query will take.  This will manifest itself like "Gee, the website seems to be slower"...and slower...and slower...

If you've got an id column that happens to be an integer and acts as a primary key, you could generate the maximum value in PHP before querying it'll be much faster because you're actually using an index.

Example could be something like:

```<code>$random_row_id = rand(1, $max);
</code>```

and then...

```<code>SELECT * FROM foo WHERE id = $random_row_id
</code>```

You'll have to figure out how to get your $max, but most likely you can just grab the last row id.

One word of caution here is that if you've deleted records from the table you'll have "holes" where you may ask for a row that doesn't exist anymore.  In this case you could just keep probing until you find a match -- it'll still be way faster than a full table scan.

OwnerDisplayName: shicosvnki

LastEditorDisplayName: Tom Anderson

Body:
Whatever you do, don't use ORDER BY RAND() in MySQL.  It won't scale.  Yes, it will seem to work fine for a small number of rows because the data set is small.  ORDER BY RAND() requires a full-table scan, which means that the larger your table is the longer the query will take.  This will manifest itself like "Gee, the website seems to be slower"...and slower...and slower...

If you've got an id column that happens to be an integer and acts as a primary key, you could generate the maximum value in PHP before querying it'll be much faster because you're actually using an index.

Example could be something like:

$random_row_id = rand(1, $max);

and then...

SELECT * FROM foo WHERE id = $random_row_id

You'll have to figure out how to get your $max, but most likely you can just grab the last row id.

One word of caution here is that if you've deleted records from the table you'll have "holes" where you may ask for a row that doesn't exist anymore.  In this case you could just keep probing until you find a match -- it'll still be way faster than a full table scan.

OwnerDisplayName: revolutiontrigger


问:
Is there an alternate/better way to do this simple logic in java?
I have a method, say method1(), that takes a while to run. During it's execution, if there is another call to method1(), it should be ignored. I have, roughly, something like this

```<code>    boolean mFlag = false;

    void method1()
    {
        if(!mFlag)
        {
           mFlag=true;

           // do Stuff

          mFlag=false;
        }
    }
</code>```

This works. But I was wondering if there is a better way to do this preferably not involving any flags.

答:
Maybe you should use synchronized methods

http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

Body:
I have a method, say method1(), that takes a while to run. During it's execution, if there is another call to method1(), it should be ignored. I have, roughly, something like this

    boolean mFlag = false;

    void method1()
    {
        if(!mFlag)
        {
           mFlag=true;

           // do Stuff

          mFlag=false;
        }
    }

This works. But I was wondering if there is a better way to do this preferably not involving any flags.


问:
Object Variable not set error, Visual Basic
I keep on getting the following error in VBA

"Object Variable or With Block Variable not set"

I have no idea why

My code is

```<code>Private Sub Worksheet_Calculate()
    Dim RNG As Range
    RNG = Sheet1.Range("C15:D55,G11,G12,G15,G18,G19")
End Sub
</code>```

The Sheet CodeName is correct.

Anyone have any ideas?
Thanks

答:
A Range type is an Object type, and must be assigned to with the Set statement:

```<code>Private Sub Worksheet_Calculate()
    Dim RNG As Range
    Set RNG = Sheet1.Range("C15:D55,G11,G12,G15,G18,G19")
End Sub
</code>```

Body:
I keep on getting the following error in VBA

"Object Variable or With Block Variable not set"

I have no idea why

My code is

Private Sub Worksheet_Calculate()
    Dim RNG As Range
    RNG = Sheet1.Range("C15:D55,G11,G12,G15,G18,G19")
End Sub

The Sheet CodeName is correct.

Anyone have any ideas?
Thanks

Body:
A Range type is an Object type, and must be assigned to with the Set statement:

Private Sub Worksheet_Calculate()
    Dim RNG As Range
    Set RNG = Sheet1.Range("C15:D55,G11,G12,G15,G18,G19")
End Sub


问:
check if an item in weblist is indented or not
I have list of items in a weblist and which has both parent and child.  Child is indented to the right,  I need to retrieve values of child and parent in two different columns in a datatable.

My code goes like this:

```<code>list = qtp_getroproperty(page.weblist(), "items count", itemsCount
For n = 1 To itemsCount
  items = page.weblist(), getitem(n)
</code>```

答:
There are several ways to go about this:

Extract the first character with the Left function, as Ekkehard Horner suggested:

```<code>If Left(str, 1) = " " Then
  ...
End If
</code>```

Check the first character with the InStrRev function:

```<code>If InStrRev(str, " ", 1) > 0 Then
  ...
End If
</code>```

LTrim the string and compare it to the original string:

```<code>If LTrim(str) <> str Then
  ...
End If
</code>```

Use a regular expression:

```<code>Set re = New RegExp
re.Pattern = "^ "
If re.Test(str) Then
  ...
End If
</code>```

Note that this last approach is the most versatile, but also the most expensive. Usually it won't make sense to use this to check for something as simple as "does the string begin with a space". It becomes more useful if for instance you want to check "does the string begin with any kind of whitespace" ("^\s").

Body:
I have list of items in a weblist and which has both parent and child.  Child is indented to the right,  I need to retrieve values of child and parent in two different columns in a datatable.

My code goes like this:

list = qtp_getroproperty(page.weblist(), "items count", itemsCount
For n = 1 To itemsCount
  items = page.weblist(), getitem(n)

Body:
There are several ways to go about this:

Extract the first character with the Left function, as Ekkehard Horner suggested:

If Left(str, 1) = " " Then
  ...
End If

Check the first character with the InStrRev function:

If InStrRev(str, " ", 1) > 0 Then
  ...
End If

LTrim the string and compare it to the original string:

If LTrim(str) <> str Then
  ...
End If

Use a regular expression:

Set re = New RegExp
re.Pattern = "^ "
If re.Test(str) Then
  ...
End If

Note that this last approach is the most versatile, but also the most expensive. Usually it won't make sense to use this to check for something as simple as "does the string begin with a space". It becomes more useful if for instance you want to check "does the string begin with any kind of whitespace" ("^\s").


问:
Same sql query gives different results on sql server and on php output
Here is the sql query

```<code>    SELECT * FROM seedbed
LEFT OUTER JOIN fertilizers AS seedfert ON seedfert.fert_protocol =seedbed.seed_protocol
LEFT OUTER JOIN pesticides AS seedpest ON seedpest.pest_protocol = seedbed.seed_protocol
LEFT OUTER JOIN fertilizers_list AS seedfert_list ON  seedfert.fert_id =seedfert_list.id
LEFT OUTER JOIN pesticides_list AS seedpest_list ON  seedpest.pest_id = seedpest_list.id
LEFT OUTER JOIN field ON field.field_protocol = seedbed.seed_protocol + "%"
LEFT OUTER JOIN fertilizers AS fieldfert ON fieldfert.fert_protocol = field.field_protocol
LEFT OUTER JOIN pesticides AS fieldpest ON fieldpest.pest_protocol = field.field_protocol
LEFT OUTER JOIN stock ON stock.field_protocol = field.field_protocol
LEFT OUTER JOIN fertilizers_list AS fieldfert_list ON  fieldfert.fert_id =fieldfert_list.id
LEFT OUTER JOIN pesticides_list AS fieldpest_list ON  fieldpest.pest_id = fieldpest_list.id
WHERE seedbed.seed_protocol LIKE "1/2013/2%"
ORDER BY field_num;
</code>```

In php is exactly the same i use codeigniter but i dont use for this active record library so is pretty much the same.

```<code>$sql = "SELECT * FROM seedbed
LEFT OUTER JOIN fertilizers AS seedfert ON seedfert.fert_protocol = seedbed.seed_protocol
LEFT OUTER JOIN pesticides AS seedpest ON seedpest.pest_protocol = seedbed.seed_protocol
LEFT OUTER JOIN fertilizers_list AS seedfert_list ON  seedfert.fert_id = seedfert_list.id
LEFT OUTER JOIN pesticides_list AS seedpest_list ON  seedpest.pest_id = seedpest_list.id
LEFT OUTER JOIN field ON field.field_protocol = seedbed.seed_protocol + '%'
LEFT OUTER JOIN fertilizers AS fieldfert ON fieldfert.fert_protocol = field.field_protocol
LEFT OUTER JOIN pesticides AS fieldpest ON fieldpest.pest_protocol = field.field_protocol
LEFT OUTER JOIN stock ON stock.field_protocol = field.field_protocol
LEFT OUTER JOIN fertilizers_list AS fieldfert_list ON  fieldfert.fert_id =fieldfert_list.id
LEFT OUTER JOIN pesticides_list AS fieldpest_list ON  fieldpest.pest_id = fieldpest_list.id
WHERE seedbed.seed_protocol LIKE '".$this->db->escape_like_str($ins_protocol)."%'
ORDER BY field_num";
$query = $this->db->query($sql);
$data = $query->result();
print_r($data);
</code>```

The problem now is that in sql server i get all the results i should get although in php i dont get the results of my first two JOINS. And i have no idea why?

I hope someone knows whats going on.

答:
this works on me:</p>

```<code>SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_WARNINGS ON
SET ANSI_PADDING ON
</code>```

Body:
Here is the sql query

    SELECT * FROM seedbed
LEFT OUTER JOIN fertilizers AS seedfert ON seedfert.fert_protocol =seedbed.seed_protocol
LEFT OUTER JOIN pesticides AS seedpest ON seedpest.pest_protocol = seedbed.seed_protocol
LEFT OUTER JOIN fertilizers_list AS seedfert_list ON  seedfert.fert_id =seedfert_list.id
LEFT OUTER JOIN pesticides_list AS seedpest_list ON  seedpest.pest_id = seedpest_list.id
LEFT OUTER JOIN field ON field.field_protocol = seedbed.seed_protocol + "%"
LEFT OUTER JOIN fertilizers AS fieldfert ON fieldfert.fert_protocol = field.field_protocol
LEFT OUTER JOIN pesticides AS fieldpest ON fieldpest.pest_protocol = field.field_protocol
LEFT OUTER JOIN stock ON stock.field_protocol = field.field_protocol
LEFT OUTER JOIN fertilizers_list AS fieldfert_list ON  fieldfert.fert_id =fieldfert_list.id
LEFT OUTER JOIN pesticides_list AS fieldpest_list ON  fieldpest.pest_id = fieldpest_list.id
WHERE seedbed.seed_protocol LIKE "1/2013/2%"
ORDER BY field_num;

In php is exactly the same i use codeigniter but i dont use for this active record library so is pretty much the same.

$sql = "SELECT * FROM seedbed
LEFT OUTER JOIN fertilizers AS seedfert ON seedfert.fert_protocol = seedbed.seed_protocol
LEFT OUTER JOIN pesticides AS seedpest ON seedpest.pest_protocol = seedbed.seed_protocol
LEFT OUTER JOIN fertilizers_list AS seedfert_list ON  seedfert.fert_id = seedfert_list.id
LEFT OUTER JOIN pesticides_list AS seedpest_list ON  seedpest.pest_id = seedpest_list.id
LEFT OUTER JOIN field ON field.field_protocol = seedbed.seed_protocol + '%'
LEFT OUTER JOIN fertilizers AS fieldfert ON fieldfert.fert_protocol = field.field_protocol
LEFT OUTER JOIN pesticides AS fieldpest ON fieldpest.pest_protocol = field.field_protocol
LEFT OUTER JOIN stock ON stock.field_protocol = field.field_protocol
LEFT OUTER JOIN fertilizers_list AS fieldfert_list ON  fieldfert.fert_id =fieldfert_list.id
LEFT OUTER JOIN pesticides_list AS fieldpest_list ON  fieldpest.pest_id = fieldpest_list.id
WHERE seedbed.seed_protocol LIKE '".$this->db->escape_like_str($ins_protocol)."%'
ORDER BY field_num";
$query = $this->db->query($sql);
$data = $query->result();
print_r($data);

The problem now is that in sql server i get all the results i should get although in php i dont get the results of my first two JOINS. And i have no idea why?

I hope someone knows whats going on.

Body:
this works on me:

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_WARNINGS ON
SET ANSI_PADDING ON


问:
Implement HPKP in ASP.Net application
I have learned about the HPKP recently and I wanted to know how to correctly implement this in an MVC application.</p>

答:
If you are thinking about a code level implementation, you can do the following in the startup class using IAppBuilder

```<code>app.UseHpkp(options => options
    .Sha256Pins(
        "Base Certificate Hash value and Backup certificate hash value")
    .MaxAge(days: <Expiration Time>));
</code>```

You can generate the required hash values using the openssl tool using your certificate file.

If you do not about the exact implementation, it is best to use the OWASP ASP.NET MVC Boilerplate Project. All the security implementations are pre-build in to this template and you can carry-on build your application on top of it.

OwnerDisplayName: Stealth-prg

Title: Implement HPKP in ASP.Net application

Body:
If you are thinking about a code level implementation, you can do the following in the startup class using IAppBuilder

app.UseHpkp(options => options
    .Sha256Pins(
        "Base Certificate Hash value and Backup certificate hash value")
    .MaxAge(days: <Expiration Time>));

You can generate the required hash values using the openssl tool using your certificate file.

If you do not about the exact implementation, it is best to use the OWASP ASP.NET MVC Boilerplate Project. All the security implementations are pre-build in to this template and you can carry-on build your application on top of it.

OwnerDisplayName: CodeRed


问:
Sencha - hbox layout has invisible lines in fieldset
```<code>{
                    layout: {
                        type: 'hbox'
                    },
                    items: [
                        {
                            xtype: 'selectfield',
                            placeHolder: 'selectfield',
                            autoSelect: false,
                        },
                        {
                            xtype: 'textfield',
                            placeHolder: 'textfield'
                        }
                    ]

                },
</code>```

I want to use 'hbox' layoout with selectfield and textfield for horizontal components using Sencha Touch 2.0
but like this image, underlines for second component(textfield) in fieldset are not seen. What's wrong?

screenshot

答:
Hi its nothing with hbox layout and fieldset. Its is due to selectField.these lines are the border of selectField. If you want to remove it you need something like this

```<code>{
   xtype: 'selectfield',
   placeHolder: 'selectfield',
   autoSelect: false,
   border: 0,
},
</code>```

this will make it disappear these line
i hope you get it ;)

here is a simple fiddle

And In case if you want to have borders follow this code

{
  xtype: 'selectfield',
  border: 3,
  style: 'border-color: blue; border-style: solid;',
  flex: 1,
  placeHolder: 'selectfield',
  autoSelect: false,
},
{
  xtype: 'textfield',
  border: 3,
  style: 'border-color: blue; border-style: solid;',
  flex: 1,
  placeHolder: 'textfield'
}```

Body:
{
                    layout: {
                        type: 'hbox'
                    },
                    items: [
                        {
                            xtype: 'selectfield',
                            placeHolder: 'selectfield',
                            autoSelect: false,
                        },
                        {
                            xtype: 'textfield',
                            placeHolder: 'textfield'
                        }
                    ]

                },

I want to use 'hbox' layoout with selectfield and textfield for horizontal components using Sencha Touch 2.0
but like this image, underlines for second component(textfield) in fieldset are not seen. What's wrong?

screenshot

Body:
Hi its nothing with hbox layout and fieldset. Its is due to selectField.these lines are the border of selectField. If you want to remove it you need something like this

{
   xtype: 'selectfield',
   placeHolder: 'selectfield',
   autoSelect: false,
   border: 0,
},

this will make it disappear these line
i hope you get it ;)

here is a simple fiddle

And In case if you want to have borders follow this code

{
  xtype: 'selectfield',
  border: 3,
  style: 'border-color: blue; border-style: solid;',
  flex: 1,
  placeHolder: 'selectfield',
  autoSelect: false,
},
{
  xtype: 'textfield',
  border: 3,
  style: 'border-color: blue; border-style: solid;',
  flex: 1,
  placeHolder: 'textfield'
}


问:
How do I authorize a user to only see his own data with a Laravel oauth2 API?
I have created a Laravel (5.2) API with the oauth2 plugin from lucadegasperi. I use the PasswordGrant as grant type. Everything works fine, except that User A can also see the Data from User B.
How can I make sure that the users can only get their own data.

e.g. a user with the id 123 can only get data with this url: sumtotal/123

答:
I created a Middleware and checked the IDs.</p>

```<code>public function handle($request, Closure $next)
{
    $request_id=$request->route('cid');
    $user_id = Authorizer::getResourceOwnerId();

    if($request_id==$user_id){
        return $next($request);
    }
    abort(403, 'Access denied');
}
</code>```

Body:
I created a Middleware and checked the IDs.

public function handle($request, Closure $next)
{
    $request_id=$request->route('cid');
    $user_id = Authorizer::getResourceOwnerId();

    if($request_id==$user_id){
        return $next($request);
    }
    abort(403, 'Access denied');
}


问:
What are custom variables in google analytics how to use them in android app
I am already using custom dimension in google analytics but google analytics dashboard shows custom variables as well. There is no documentation how to create custom variables and how to use them and how they are different from custom dimensions

答:
Custom Variables exist for backwards compatibility. They have been a feature in previous versions of Google Analytics, and have become deprecated with the introduction of Universal Analytics in 2012. Although the features are not completely equivalent they have been supplanted by custom dimensions.

Since an account may hold data that was collected while custom variables where still a thing Google can't just remove them (lest people loose access to some of their historical data). But to the bet of my knowledge (and yours, apparently) there is no documented way to set custom vars these days.


问:
custom docker image is not running postgres
I am trying to create my own custom docker file for circleci v2. however, I am running into an issue where the postgres server is not running. I've run service postgresql start to no available.

the message I'm getting is:

```<code>psql: could not connect to server: Connection refused
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

Dockerfile:

```<code>FROM ubuntu:16.04

ENV NODEJS_VERSION 6
ENV POSTGRESQL_VERSION 9.6

RUN apt-get update && apt-get -y install curl
RUN curl -sL https://deb.nodesource.com/setup_$NODEJS_VERSION.x | bash -
RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list
RUN apt-get update

RUN apt-get install -y \
  nodejs \
  make \
  git \
  g++ \
  python-software-properties \
  software-properties-common \
  postgresql-$POSTGRESQL_VERSION \
  postgresql-client-$POSTGRESQL_VERSION \
  postgresql-contrib-$POSTGRESQL_VERSION

RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/$POSTGRESQL_VERSION/main/pg_hba.conf
RUN echo "listen_addresses='*'" >> /etc/postgresql/$POSTGRESQL_VERSION/main/postgresql.conf

USER postgres
RUN service postgresql start && \
  psql -c "create database pgdb;" && \
  psql -c "create role pgrole with login password 'pgrole'; grant all privileges on database pgdb to pgrole;"
</code>```

See also:

GitHub: https://github.com/jonathanong/docker-nodejs-postgres

CircleCI: https://circleci.com/gh/jonathanong/docker-nodejs-postgres/tree/master

thanks

答:
The problem

The issue is that you don't define which command your image should run, so it defaults to the command that was set in the Ubuntu base image: /bin/bash.

Take a look at the documentation for CMD:

Note: Don’t confuse RUN with CMD. RUN actually runs a command and commits the result; CMD does not execute anything at build time, but specifies the intended command for the image.

So your RUN service postgresql start is executed at build time, and the result of that command is committed to the image as a layer. When you start the image, e.g. on CircleCI, the CMD for the image is executed. And since you didn't set that, it uses the one that Ubuntu specified: /bin/bash. Which means at runtime, there is in fact to Postgres running.

Another thing to keep in mind is that the CMD must not be a daemon. Docker keeps a container running as long as a process is executed in the foreground, so if you do CMD service postgresql start, Docker will exit the container after the command has returned.

The solution

I recommend that you redo your whole CI setup. If you start Postgres in the CMD, you can't overwrite that command to run your tests (or Postgres wouldn't be running again).

Instead, use two images, one for your app and one for Postgres. You start Postgres, wait for it to accept connections and then in your app container run the tests.

You can reuse the existing postgresql image, which creates a database and user for you when you start it. You need to add a script to wait for the database to be ready, or your tests will run before the database is accepting connections. See this post: https://discuss.circleci.com/t/waiting-for-database/10946

With this approach, it is much easier to run multiple services at once and still have complete freedom over which commands you want to run on Circle CI.

The alternative

A little bit easier, but just for testing, is the option to create an entrypoint that starts Postgres and waits for it to be ready. Create a script, copy it in the Dockerfile and point the ENTRYPOINT to it. In the script, run services postgresql start, create your database and then wait for Postgres to accept connections. Once that is done, use exec $@ to execute whatever command you pass to the container.

You can find a script that we use to wait for Postgres here: https://gist.github.com/jdno/09377bde65095773e5daf1aaa8e62ef4

This script can easily be extended to serve as an ENTRYPOINT as well.

Start Postgres with services postgresql start.

Wait for Postgres to accept connections (i.e. what the script does now).

Run psql commands to create your database.

End the script with exec $@ to execute the Docker CMD.

This is a little bit easier to set up, but not suited for production.

Body:
I am trying to create my own custom docker file for circleci v2. however, I am running into an issue where the postgres server is not running. I've run service postgresql start to no available.

the message I'm getting is:

psql: could not connect to server: Connection refused
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Dockerfile:

FROM ubuntu:16.04

ENV NODEJS_VERSION 6
ENV POSTGRESQL_VERSION 9.6

RUN apt-get update && apt-get -y install curl
RUN curl -sL https://deb.nodesource.com/setup_$NODEJS_VERSION.x | bash -
RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list
RUN apt-get update

RUN apt-get install -y \
  nodejs \
  make \
  git \
  g++ \
  python-software-properties \
  software-properties-common \
  postgresql-$POSTGRESQL_VERSION \
  postgresql-client-$POSTGRESQL_VERSION \
  postgresql-contrib-$POSTGRESQL_VERSION

RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/$POSTGRESQL_VERSION/main/pg_hba.conf
RUN echo "listen_addresses='*'" >> /etc/postgresql/$POSTGRESQL_VERSION/main/postgresql.conf

USER postgres
RUN service postgresql start && \
  psql -c "create database pgdb;" && \
  psql -c "create role pgrole with login password 'pgrole'; grant all privileges on database pgdb to pgrole;"

See also:

GitHub: https://github.com/jonathanong/docker-nodejs-postgres

CircleCI: https://circleci.com/gh/jonathanong/docker-nodejs-postgres/tree/master

thanks


问:
When is it ever appropriate to place Javascript inside the body of a document?
The client has a bunch of Javascript that calls Microsoft Ajax etc. Aside from web page analytics which make sense to load at the same time static resources are loaded, wouldn't it make sense to load any AJAX scripts in the head instead of the body?

Ultimately the result is a bloated load time for the page since all the Javascript is being loaded at time of render.

What is your ideal placement of certain Javascript in a web page?

答:
Placing Javascript at the end of the body can help with the perception of good page load speed. Scripts in the head block other activity while they're run.

The claim of "bloated load time" is actually backwards.  Putting the scripts in the  means that the page won't be parsed and none of it will be rendered until all the scripts are loaded and executed. (Well, all the directly-loaded scripts.)

Body:
Placing Javascript at the end of the body can help with the perception of good page load speed. Scripts in the head block other activity while they're run.

The claim of "bloated load time" is actually backwards.  Putting the scripts in the <head> means that the page won't be parsed and none of it will be rendered until all the scripts are loaded and executed. (Well, all the directly-loaded scripts.)


答:
You have UTF-8 encoded data, not ASCII, with each byte encoded to a three-digit escape sequence using decimal numbers. The actual text consists mainly of arabic writing.

You need to replace each \ddd sequence with the corresponding byte value, then decode as UTF-8. In Python 3:

```<code>utf8_data = bytes([int(data[i + 1:i + 4]) for i in range(0, len(data), 4)])
print(utf8_data.decode('utf8'))
</code>```

Demo:

```<code>>>> data = r"\216\173\217\138\217\136\216\167\217\134\032\216\178\216\167\216\173\217\129\032\217\138\216\186\217\138\216\177\032\217\132\217\136\217\134\032\216\172\217\132\216\175\217\135"
>>> utf8_data = bytes([int(data[i + 1:i + 4]) for i in range(0, len(data), 4)])
>>> print(utf8_data.decode('utf8'))
حيوان زاحف يغير لون جلده
</code>```

Google Translate tells me this is A creepy animal changes the color of its skin in English.

We can otherwise convert the Lua syntax to JSON using a stack-based parser:

```<code>import re
import json

def lua_to_python(lua_data):
    return json.loads(''.join(_convert_lua_to_json_chunks(lua_data)))

def _lua_bytes_to_text(data):
    return bytes(
        [int(data[i + 1:i + 4]) for i in range(0, len(data), 4)]
    ).decode('utf8')

def _convert_lua_to_json_chunks(lua_data):
    tokens = re.split(br'(["{},])', lua_data)
    stack = []
    pos_tokens = enumerate(tokens)
    for pos, token in pos_tokens:
        if b'=' in token:
            if not stack:
                # top-level key-value, produce JSON object syntax
                stack.append('}')
                yield '{'
            yield '"{}":'.format(token.strip().rstrip(b' =').decode('utf8'))
        elif token == b'{':
            # array or object?
            next_nonws = next(t for t in tokens[pos + 1:] if t.strip())
            if b'=' in next_nonws:
                stack.append('}')
                yield '{'
            else:
                stack.append(']')
                yield '['
        elif token == b'}':
            yield stack.pop()
        elif token == b'"':
            yield '"'
            for pos, s in pos_tokens:
                if s == b'"':
                    yield '"'
                    break
                yield _lua_bytes_to_text(s)
        else:
            yield token.decode('utf8')
    yield from stack
</code>```

With two additional } characters at the end, your data then produces:

```<code>>>> lua_to_python(lua_data)
{'clues': [{'answer': ['ح', 'ر', 'ب', 'ا', 'ء'], 'text': 'حيوان زاحف يغير لون جلده', 'syllables': [['ح', 'ر'], ['ب', 'ا'], ['ء']]}]}
>>> pprint(lua_to_python(lua_data))
{'clues': [{'answer': ['ح', 'ر', 'ب', 'ا', 'ء'],
            'syllables': [['ح', 'ر'], ['ب', 'ا'], ['ء']],
            'text': 'حيوان زاحف يغير لون جلده'}]}
</code>```

This should give you plenty of options to further process the data.

OwnerDisplayName: Jawny Thompson

Title: Decode Ascii string values from reverse-engineered lua file

Body:
I decompiled a lua file with unluac and it turns out all the string variables are not readable and are instead ascii encoded

clues = {
  {
    answer = {
      "\216\173",
      "\216\177",
      "\216\168",
      "\216\167",
      "\216\161"
    },
    text = "\216\173\217\138\217\136\216\167\217\134\032\216\178\216\167\216\173\217\129\032\217\138\216\186\217\138\216\177\032\217\132\217\136\217\134\032\216\172\217\132\216\175\217\135",
    syllables = {
      {"\216\173", "\216\177"},
      {"\216\168", "\216\167"},
      {"\216\161"}
    }

How do i go about decoding the whole file ignoring any non ascii characters in python or java?

Body:
You have UTF-8 encoded data, not ASCII, with each byte encoded to a three-digit escape sequence using decimal numbers. The actual text consists mainly of arabic writing.

You need to replace each \ddd sequence with the corresponding byte value, then decode as UTF-8. In Python 3:

utf8_data = bytes([int(data[i + 1:i + 4]) for i in range(0, len(data), 4)])
print(utf8_data.decode('utf8'))

Demo:

>>> data = r"\216\173\217\138\217\136\216\167\217\134\032\216\178\216\167\216\173\217\129\032\217\138\216\186\217\138\216\177\032\217\132\217\136\217\134\032\216\172\217\132\216\175\217\135"
>>> utf8_data = bytes([int(data[i + 1:i + 4]) for i in range(0, len(data), 4)])
>>> print(utf8_data.decode('utf8'))
حيوان زاحف يغير لون جلده

Google Translate tells me this is A creepy animal changes the color of its skin in English.

We can otherwise convert the Lua syntax to JSON using a stack-based parser:

import re
import json

def lua_to_python(lua_data):
    return json.loads(''.join(_convert_lua_to_json_chunks(lua_data)))

def _lua_bytes_to_text(data):
    return bytes(
        [int(data[i + 1:i + 4]) for i in range(0, len(data), 4)]
    ).decode('utf8')

def _convert_lua_to_json_chunks(lua_data):
    tokens = re.split(br'(["{},])', lua_data)
    stack = []
    pos_tokens = enumerate(tokens)
    for pos, token in pos_tokens:
        if b'=' in token:
            if not stack:
                # top-level key-value, produce JSON object syntax
                stack.append('}')
                yield '{'
            yield '"{}":'.format(token.strip().rstrip(b' =').decode('utf8'))
        elif token == b'{':
            # array or object?
            next_nonws = next(t for t in tokens[pos + 1:] if t.strip())
            if b'=' in next_nonws:
                stack.append('}')
                yield '{'
            else:
                stack.append(']')
                yield '['
        elif token == b'}':
            yield stack.pop()
        elif token == b'"':
            yield '"'
            for pos, s in pos_tokens:
                if s == b'"':
                    yield '"'
                    break
                yield _lua_bytes_to_text(s)
        else:
            yield token.decode('utf8')
    yield from stack

With two additional } characters at the end, your data then produces:

>>> lua_to_python(lua_data)
{'clues': [{'answer': ['ح', 'ر', 'ب', 'ا', 'ء'], 'text': 'حيوان زاحف يغير لون جلده', 'syllables': [['ح', 'ر'], ['ب', 'ا'], ['ء']]}]}
>>> pprint(lua_to_python(lua_data))
{'clues': [{'answer': ['ح', 'ر', 'ب', 'ا', 'ء'],
            'syllables': [['ح', 'ر'], ['ب', 'ا'], ['ء']],
            'text': 'حيوان زاحف يغير لون جلده'}]}

This should give you plenty of options to further process the data.


问:
Conducting searches with REST that return large datasets?
I'm creating a RESTful WebAPI for our system in .Net, when conducting a search in my client I presume that it should hit the /person route passing parameters when required to filter the data. However, the person object that is return has quite a lot of nested objects which could slow down data retrieval. Should I have a separate controller which returns a more skeletonised view of a person, should I continue the way I am going, or should I be making subsequent requests to break down the person?</p>

答:
Actually, there is no silver-bullet way to solve your problem, but there are several approaches, which could be usefull for you. However, in my opinion, your idea about optimizing the size of resource representation in search results is correct.

You can include the list of requested fields in filtering query. (for example, see the similar signature/approach in ES search API). Many search engines are following this approach to reduce redundant response payload.

As you have metioned, you can break your heavy object in sub-resources, so that you would be able to include only links to nested objects inside the person, without including the whole represantations of inner-objects. The HATEOAS approach will fit perfectly for this purpose, but it will add extra complexity to your application (but the extra flexibility too).

However, you have to choose, which approach is better for your particular application, but I think, that a good starting point will be the approach with list of requested fields.


问:
Remove category and subcategory from the product url opencart
I want to remove category and sub-category name from the product URL in the opencart. I have made changes in seo_url.php file. Where I have replaced

```<code>$url .= '/' . $query->row['keyword'];
</code>```

with

```<code>$url = '/' . $query->row['keyword'];
</code>```

But still the url is not changed. Can any one suggest me what to do. I am using opencart version 2.0.3.1

答:
are you sure you've replaced all?

```<code>$url .= '/' . $query->row['keyword'];
</code>```

in seo_url.php file there is 3 matches.

Body:
I want to remove category and sub-category name from the product URL in the opencart. I have made changes in seo_url.php file. Where I have replaced

$url .= '/' . $query->row['keyword'];

with

$url = '/' . $query->row['keyword'];

But still the url is not changed. Can any one suggest me what to do. I am using opencart version 2.0.3.1

Body:
are you sure you've replaced all?

$url .= '/' . $query->row['keyword'];

in seo_url.php file there is 3 matches.


问:
FIELD from my TFS Bug.xml is not hidden as expected
I have a Field in my TFS Bug.xml as displayed below

```<code>  <FIELD name="Root Cause" refname="core.resolution" type="String">
    <ALLOWEDVALUES expanditems="true">
       <LISTITEM value="Code" />
       <LISTITEM value="Working as Designed" />
       <LISTITEM value="Documentation" />
       <LISTITEM value="SPaG" />
       <LISTITEM value="User Interface" />
       <LISTITEM value="Database" />
       <LISTITEM value="Test Data" />
       <LISTITEM value="Duplicate" />
       <LISTITEM value="Cannot Reproduce" />
       <LISTITEM value="UX" />
       <LISTITEM value="Environment" />
       <LISTITEM value="Integration" />
    </ALLOWEDVALUES>
    <WHENNOT field="System.State" value="Done">
      <READONLY />
    </WHENNOT>
  </FIELD>
</code>```

However, my intention is that when the State: field is done, only then should my Root cause field be visible,  how can I modify my XML to achieve this?

```<code>          <Column PercentWidth="33">
        <Group Label="Details">
          <Column PercentWidth="100">
            <Control FieldName="Microsoft.VSTS.Common.Severity" Type="FieldControl" Label="Priority" LabelPosition="Left" />
            <Control FieldName="System.CreatedDate" Type="FieldControl" Label="Created Date" LabelPosition="Left" />
            <Control FieldName="System.CreatedBy" Type="FieldControl" Label="Created By" LabelPosition="Left" />
            <Control FieldName="core.resolution" Type="FieldControl" Label="Root Cause" LabelPosition="Left" />
</code>```

答:
I found a better solution that to use EMPTY rule. You could change the xml like this below:

```<code><FIELD name="Root Cause" refname="core.resolution" type="String">
    <ALLOWEDVALUES expanditems="true">
       <LISTITEM value="Code" />
    ......
    </ALLOWEDVALUES>
    <WHENNOT field="System.State" value="Done">
      <EMPTY />
    </WHENNOT>
  </FIELD>
</code>```

Body:
I have a Field in my TFS Bug.xml as displayed below

  <FIELD name="Root Cause" refname="core.resolution" type="String">
    <ALLOWEDVALUES expanditems="true">
       <LISTITEM value="Code" />
       <LISTITEM value="Working as Designed" />
       <LISTITEM value="Documentation" />
       <LISTITEM value="SPaG" />
       <LISTITEM value="User Interface" />
       <LISTITEM value="Database" />
       <LISTITEM value="Test Data" />
       <LISTITEM value="Duplicate" />
       <LISTITEM value="Cannot Reproduce" />
       <LISTITEM value="UX" />
       <LISTITEM value="Environment" />
       <LISTITEM value="Integration" />
    </ALLOWEDVALUES>
    <WHENNOT field="System.State" value="Done">
      <READONLY />
    </WHENNOT>
  </FIELD>

However, my intention is that when the State: field is done, only then should my Root cause field be visible,  how can I modify my XML to achieve this?

          <Column PercentWidth="33">
        <Group Label="Details">
          <Column PercentWidth="100">
            <Control FieldName="Microsoft.VSTS.Common.Severity" Type="FieldControl" Label="Priority" LabelPosition="Left" />
            <Control FieldName="System.CreatedDate" Type="FieldControl" Label="Created Date" LabelPosition="Left" />
            <Control FieldName="System.CreatedBy" Type="FieldControl" Label="Created By" LabelPosition="Left" />
            <Control FieldName="core.resolution" Type="FieldControl" Label="Root Cause" LabelPosition="Left" />

Body:
I found a better solution that to use EMPTY rule. You could change the xml like this below:

<FIELD name="Root Cause" refname="core.resolution" type="String">
    <ALLOWEDVALUES expanditems="true">
       <LISTITEM value="Code" />
    ......
    </ALLOWEDVALUES>
    <WHENNOT field="System.State" value="Done">
      <EMPTY />
    </WHENNOT>
  </FIELD>


问:
angular filter - group by object (or multiple fields)
I extended the Angular filter group by example to the following by transforming the team to an object.

     var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){
  $scope.players = [
  {
    name: 'Gene',
    team: {
      'id' : '1',
      'name' : 'alpha'

    }
  },
  {
    name: 'George',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Steve',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  },
  {
    name: 'Paula',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Scruath',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  }
];
}]);

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <script data-require="angularjs@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script data-require="angular-filter@*" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller="MainController">
      <ul>
        <li ng-repeat="(team, players) in players | groupBy: 'team.name'">
          Group name: {{ team }}
          <ul>
            <li ng-repeat="player in players">
              player: {{ player.name }}
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </body>

</html></code>```

But, what if I need the team id in the group by? What can I do?

```<code><a href="#I need the team ID">Group name: {{ team }}</a>
</code>```

I tried to group by the team object and use team.name and team.id but it didn't work. Also, I didn't know how to create a group by with multiple fields (team.id, team.name)

Here's a working plnkr

答:
I have a simple solution:

I grouped by team.id

```<code><li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">
</code>```

Then I used: players[0].team.name within the group

```<code><li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">
    <a href="#Here I can use the group teamid">Group name: {{ players[0].team.name }}</a>
      <ul>
        <li ng-repeat="player in players">
          player: {{ player.name }}
        </li>
     </ul>
</li>
</code>```

Since players in each group are only the players belonging to this group where all of them have the same team, so players[0], players[1] and so on will have the same team name.

     var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){
  $scope.players = [
  {
    name: 'Gene',
    team: {
      'id' : '1',
      'name' : 'alpha'

    }
  },
  {
    name: 'George',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Steve',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  },
  {
    name: 'Paula',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Scruath',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  }
];
}]);

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <script data-require="angularjs@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script data-require="angular-filter@*" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller="MainController">
      <ul>
        <li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">
          Group name: {{ players[0].team.name }}
          <ul>
            <li ng-repeat="player in players">
              player: {{ player.name }}
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </body>

</html></code>```

Body:
I extended the Angular filter group by example to the following by transforming the team to an object.

     var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){
  $scope.players = [
  {
    name: 'Gene',
    team: {
      'id' : '1',
      'name' : 'alpha'

    }
  },
  {
    name: 'George',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Steve',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  },
  {
    name: 'Paula',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Scruath',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  }
];
}]);

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

          Group name: {{ team }}

              player: {{ player.name }}

But, what if I need the team id in the group by? What can I do?

Group name: {{ team }}

I tried to group by the team object and use team.name and team.id but it didn't work. Also, I didn't know how to create a group by with multiple fields (team.id, team.name)

Here's a working plnkr

Body:
I have a simple solution:

I grouped by team.id

<li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">

Then I used: players[0].team.name within the group

<li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">
    <a href="#Here I can use the group teamid">Group name: {{ players[0].team.name }}</a>
      <ul>
        <li ng-repeat="player in players">
          player: {{ player.name }}
        </li>
     </ul>
</li>

Since players in each group are only the players belonging to this group where all of them have the same team, so players[0], players[1] and so on will have the same team name.

     var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){
  $scope.players = [
  {
    name: 'Gene',
    team: {
      'id' : '1',
      'name' : 'alpha'

    }
  },
  {
    name: 'George',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Steve',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  },
  {
    name: 'Paula',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Scruath',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  }
];
}]);

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angularjs@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script data-require="angular-filter@*" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller="MainController">
      <ul>
        <li ng-repeat="(teamid, players) in players | groupBy: 'team.id'">
          <a href="#Here I can use the group teamid">Group name: {{ players[0].team.name }}</a>
          <ul>
            <li ng-repeat="player in players">
              player: {{ player.name }}
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </body>

</html>


问:
Does the --git argument in git-lfs-migrate tie the destination repo to that argument somehow?
The --git argument to git-lfs-migrate (and the --lfs argument) point to a remote server. Does that imply that the converted repository specified by --destination is somehow linked with this remote server?

As far as I can tell, no LFS objects are uploaded during the conversion, and the destination repository doesn't have the server from --git as a remote, so I'm not sure what the argument is even for. What's stopping me from running the conversion once with garbage as the --git argument, then adding a remote afterwards and pushing there?

I ask because I want to convert a repository to LFS then push to several git servers to test them out, and would like to avoid running the migrate step several times - if I can run it once and push to several remotes instead, that would save me some time.

答: To answer my own question; the argument appears to do nothing at all. Two repositories I have created with different URLs passed to --git are binary identical.


问:
SQlite implementation on Xamarin.Forms app
I have a Xamarin.Forms application and I need to be able to manage a DB. I'm developing in Microsoft Visual Studio 2017 and I'm following this tutorial dor the SQLite: https://msdn.microsoft.com/en-us/magazine/mt736454.aspx

The problem is that when I get to the point: Figure 6 Generating a Connection String in the Universal Windows Project, that is to say implementing the DatabaseConnection_UWP.cs class. There I get some errors:

```<code>using LocalDataAccess.UWP;
</code>```

Here it says: The type or namespace name "LocalDataAccess" could not be found (ar you missing a using directive or an assembly reference?)

And in the line:

```<code>[assembly: Dependency(typeof(DatabaseConnection_UWP))]
</code>```

It says: The type or namespace name "DatabaseConnection_UWP" could not be found (ar you missing a using directive or an assembly reference?)

The code is exactly the same, all I have done is to copy-paste from the tutorial.

答: Solved it following a different tutorial that worked perfectly: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/databases/</p>

Body:
I have a Xamarin.Forms application and I need to be able to manage a DB. I'm developing in Microsoft Visual Studio 2017 and I'm following this tutorial dor the SQLite: https://msdn.microsoft.com/en-us/magazine/mt736454.aspx

The problem is that when I get to the point: Figure 6 Generating a Connection String in the Universal Windows Project, that is to say implementing the DatabaseConnection_UWP.cs class. There I get some errors:

using LocalDataAccess.UWP;

Here it says: The type or namespace name "LocalDataAccess" could not be found (ar you missing a using directive or an assembly reference?)

And in the line:

[assembly: Dependency(typeof(DatabaseConnection_UWP))]

It says: The type or namespace name "DatabaseConnection_UWP" could not be found (ar you missing a using directive or an assembly reference?)

The code is exactly the same, all I have done is to copy-paste from the tutorial.


问:
Content of my page overlaps the drop-down menu in IE7
I've tried positioning the header 'relative' with a high z-index and the content with position relative as well but the drop down hides as soon as I mouse over above where the content starts in IE 7. It's on this page - http://www.legrandconfectionary.com/truffle-flavors/ I thought it has something to do with tool-tip on the truffles but it's happening on every page. Help is greatly appreciated.</p>

答:
I'm going to go out on a limb and say it's related to your tooltip plugin's divs which are left behind after you've no longer hovered over them. You can't see them, but they are there. Try adding this to your CSS file:

```<code>.tooltip { z-index: 50; }
</code>```

Theoretically this will prevent the tooltip from being rendered on top of the UL element making up the drop-down menu. I have a feeling that IE 7 is bubbling the mouseover event onto the hidden tooltip (which probably stops the bubbling at itself) thus cancelling the mouseover event on your UL. Which your nav relies on since IE7 doesn't support :hover on LI elements.

EDIT: After reviewing further I am no longer convinced that it is the div which is created by the tooltip plugin, but I am convinced that what I stated about the plugin cancelling the bubble on the mouseover event. I believe your tooltip plugin is the culprit. Try disabling it and then check if the behavior persists.

Body:
I'm going to go out on a limb and say it's related to your tooltip plugin's divs which are left behind after you've no longer hovered over them. You can't see them, but they are there. Try adding this to your CSS file:

.tooltip { z-index: 50; }

Theoretically this will prevent the tooltip from being rendered on top of the UL element making up the drop-down menu. I have a feeling that IE 7 is bubbling the mouseover event onto the hidden tooltip (which probably stops the bubbling at itself) thus cancelling the mouseover event on your UL. Which your nav relies on since IE7 doesn't support :hover on LI elements.

EDIT: After reviewing further I am no longer convinced that it is the div which is created by the tooltip plugin, but I am convinced that what I stated about the plugin cancelling the bubble on the mouseover event. I believe your tooltip plugin is the culprit. Try disabling it and then check if the behavior persists.


问:
Android studio 2.3 won't start
I upgraded from studio 2.2 to 2.3 yesterday and when it tried to restart it crashed.

I managed to see a setup wizard for a second but it crashes before I can click on anything.

I opened an issue here and decided to install from scratch.
Studio is still crashing - I tried the cleanup described here and nothing helps.

I updated the JVM to the latest version and nothing changed

This is the crash info I get from the mac

```<code>Process:               studio [772]
Path:                  /Applications/Android
Studio.app/Contents/MacOS/studio
Identifier:            com.google.android.studio
Version:               2.3 (AI-162.3764568)
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           studio [772]
User ID:               501

Date/Time:             2017-03-29 16:36:14.789 +0300
OS Version:            Mac OS X 10.10.4 (14E46)
Report Version:        11
Anonymous UUID:        E4F7576D-259B-A697-034A-7B7D528789D6

Time Awake Since Boot: 430 seconds

Crashed Thread:        0  AppKit Thread  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGABRT)
Exception Codes:       EXC_I386_GPFLT

Application Specific Information:
abort() called
</code>```

the full crash report

this is the java error log

Any ideas?

答:
looking at the mac crash - a coworker found this line
"JRSInputMethodController availableInputMethodLocales" which led to this known issue of JRE crashing due to additional inputs, I removed my additional keyboard layout and the crash went away.

As stated in the issue - it is fixed in OS X 10.11 or a lower java version - I'm on OS X 10.10 so I'll upgrade to 10.11

Title: Android studio 2.3 won't start

Body:
I upgraded from studio 2.2 to 2.3 yesterday and when it tried to restart it crashed.

I managed to see a setup wizard for a second but it crashes before I can click on anything.

I opened an issue here and decided to install from scratch.
Studio is still crashing - I tried the cleanup described here and nothing helps.

I updated the JVM to the latest version and nothing changed

This is the crash info I get from the mac

Process:               studio [772]
Path:                  /Applications/Android
Studio.app/Contents/MacOS/studio
Identifier:            com.google.android.studio
Version:               2.3 (AI-162.3764568)
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           studio [772]
User ID:               501

Date/Time:             2017-03-29 16:36:14.789 +0300
OS Version:            Mac OS X 10.10.4 (14E46)
Report Version:        11
Anonymous UUID:        E4F7576D-259B-A697-034A-7B7D528789D6

Time Awake Since Boot: 430 seconds

Crashed Thread:        0  AppKit Thread  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGABRT)
Exception Codes:       EXC_I386_GPFLT

Application Specific Information:
abort() called

the full crash report

this is the java error log

Any ideas?


问:
Only 14 bytes are uploaded into Google Cloud Storage
I'm trying to upload some files into Google Cloud Storage using PHP. It seems to be partially working, since I'm seeing the files in the web console, however I've noticed that all files are only 14 bytes in size, while the original is much bigger.

This is the code I'm using:

```<code>/**
 *
 */
public static function saveFile($originalFile, $newFilename) {

    $bucket = MyStorage::getBucket();

    if ($bucket == null) {

        // Save locally
        Storage::disk('local')->put(FileController::$FILE_DIR . $newFilename, file_get_contents($originalFile));

    } else {

        // Save to Google Cloud Platform
        $bucket->upload($originalFile->getRealPath(), ['name' => $newFilename]);

    }
}

/**
 *
 */
private static function getBucket() {

    $appEnv = getenv('APP_ENV');

    if ($appEnv == "production" || $appEnv == "test") {

        $GOOGLE_CLOUD_PROJECT_ID = getenv('GOOGLE_PROJECT_ID');
        $GOOGLE_CLOUD_BUCKET_NAME = getenv('GOOGLE_BUCKET_NAME');

        $storage = new StorageClient(['projectId' => $GOOGLE_CLOUD_PROJECT_ID]);
        $bucket = $storage->bucket($GOOGLE_CLOUD_BUCKET_NAME);

        return $bucket;

    } else {

        return null;
    }
}
</code>```

$originalFile->getRealPath() returns something like /tmp/asdfasdfadf and I've verified that that file exists and is a reasonable size. The $newFilename variable name is what I want it to be stored as and this part seems to work as I'm seeing that filename in the web console.

Any ideas what could be happening?

答:
It seems you're only uploading the path to the file as a string, as opposed to the actual file.

If you look at the client library, they seem to use fopen

$bucket->upload( fopen($originalFile->getRealPath(), 'rb'), ['name' => $newFilename]);

Body:
I'm trying to upload some files into Google Cloud Storage using PHP. It seems to be partially working, since I'm seeing the files in the web console, however I've noticed that all files are only 14 bytes in size, while the original is much bigger.

This is the code I'm using:

/**
 *
 */
public static function saveFile($originalFile, $newFilename) {

    $bucket = MyStorage::getBucket();

    if ($bucket == null) {

        // Save locally
        Storage::disk('local')->put(FileController::$FILE_DIR . $newFilename, file_get_contents($originalFile));

    } else {

        // Save to Google Cloud Platform
        $bucket->upload($originalFile->getRealPath(), ['name' => $newFilename]);

    }
}

/**
 *
 */
private static function getBucket() {

    $appEnv = getenv('APP_ENV');

    if ($appEnv == "production" || $appEnv == "test") {

        $GOOGLE_CLOUD_PROJECT_ID = getenv('GOOGLE_PROJECT_ID');
        $GOOGLE_CLOUD_BUCKET_NAME = getenv('GOOGLE_BUCKET_NAME');

        $storage = new StorageClient(['projectId' => $GOOGLE_CLOUD_PROJECT_ID]);
        $bucket = $storage->bucket($GOOGLE_CLOUD_BUCKET_NAME);

        return $bucket;

    } else {

        return null;
    }
}

$originalFile->getRealPath() returns something like /tmp/asdfasdfadf and I've verified that that file exists and is a reasonable size. The $newFilename variable name is what I want it to be stored as and this part seems to work as I'm seeing that filename in the web console.

Any ideas what could be happening?


问:
How to add a icon inside a spinner
I'm able to do this if I'm able to freely modify the html, but the problem is I'm restricted to using a this one specific layout to make this spinner.

The spinner that I want to make is something like this,

There is the pink spinner which goes around and around the grey path and an icon in the middle which stays still.

The problem is I have to get the above spinner to work with just this html layout

Only a div

```<code><div class="spinner"></div>
</code>```

Div with an icon inside.

```<code><div class="spinner">
 <i class="mickey"></i>
</div>
</code>```

An icon font or an image can be used for the icon in the middle.

EDIT: Link to JSFiddle

答:
Like this maybe

.test {
  display: inline-block;
  padding: 20px;
}
.spinner-circle {
  width: 50px;
  height: 50px;
  position: relative;
  margin: 20px;
}
.spinner {
  height: 100%;
  width: 100%;
  border-radius: 50%;
  border: 5px solid rgba(0,0,0,0.3);
  border-right: 5px solid red;
  animation: rotate--spinner 1.6s linear infinite;
  box-sizing: border-box;
}
.icon {
  position: absolute;
  left: 50%; top: 50%;
  transform: translate(-50%,-50%);
  font-size: 50px;
}

@keyframes rotate--spinner {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="test">
  <div class="spinner-circle">
    <div class="spinner"></div>
    <i class="icon fa fa-anchor"></i>
  </div>
</div></code>```

Title: How to add a icon inside a spinner

Body:
I'm able to do this if I'm able to freely modify the html, but the problem is I'm restricted to using a this one specific layout to make this spinner.

The spinner that I want to make is something like this,

There is the pink spinner which goes around and around the grey path and an icon in the middle which stays still.

The problem is I have to get the above spinner to work with just this html layout

Only a div

Div with an icon inside.

An icon font or an image can be used for the icon in the middle.

EDIT: Link to JSFiddle

Body:
Like this maybe

.test {
  display: inline-block;
  padding: 20px;
}
.spinner-circle {
  width: 50px;
  height: 50px;
  position: relative;
  margin: 20px;
}
.spinner {
  height: 100%;
  width: 100%;
  border-radius: 50%;
  border: 5px solid rgba(0,0,0,0.3);
  border-right: 5px solid red;
  animation: rotate--spinner 1.6s linear infinite;
  box-sizing: border-box;
}
.icon {
  position: absolute;
  left: 50%; top: 50%;
  transform: translate(-50%,-50%);
  font-size: 50px;
}

@keyframes rotate--spinner {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="test">
  <div class="spinner-circle">
    <div class="spinner"></div>
    <i class="icon fa fa-anchor"></i>
  </div>
</div>


问:
gridview asp.net
I have a gridview which was working fine with a small dataset in development. In production it has to bind to thousands of records, which is making it slower to load. Is there a way to improve performance, like retrieving the data during gridview pageindex changing?</p>

答: You should tell your datasource to take less records and then enable paging in your grid and datasource.</p>

Title: gridview asp.net


问:
React Js ALT - Call function on Success of another
In the Alt Actions code below, how can I call getCharacters() after success of addCharacter? Basically I am trying to refresh list of characters after saving a new record to database.

```<code>getCharacters() {
    requestPromise('http://localhost:3100/api/characters')
      .then((res) => {
        console.log("Getting Characters");
        var opdata = JSON.parse(res);
        this.actions.getCharactersSuccess(opdata.characters);
      }).catch((err) => {
        console.log('error:', err);
        this.actions.getCharactersFail(err)
      })
  }

  addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
          // How can I recall getCharacters() from here
      }).catch((err) => {
        console.log('error:', err);
      })
  }
</code>```

STORE

```<code>getCharactersSuccess(res) {
    this.setState({
      characters: res
    })
  }
</code>```

答:
You just need to call the getCharacters function.  You can do that by this.getCharacters()

```<code>addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
         return this.getCharacters();
      }).catch((err) => {
        console.log('error:', err);
      })
  }
</code>```

Body:
In the Alt Actions code below, how can I call getCharacters() after success of addCharacter? Basically I am trying to refresh list of characters after saving a new record to database.

getCharacters() {
    requestPromise('http://localhost:3100/api/characters')
      .then((res) => {
        console.log("Getting Characters");
        var opdata = JSON.parse(res);
        this.actions.getCharactersSuccess(opdata.characters);
      }).catch((err) => {
        console.log('error:', err);
        this.actions.getCharactersFail(err)
      })
  }

  addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
          // How can I recall getCharacters() from here
      }).catch((err) => {
        console.log('error:', err);
      })
  }

STORE

getCharactersSuccess(res) {
    this.setState({
      characters: res
    })
  }

Body:
You just need to call the getCharacters function.  You can do that by this.getCharacters()

addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
         return this.getCharacters();
      }).catch((err) => {
        console.log('error:', err);
      })
  }


答:
Ok, managed to fix it by just throwing expressions here and there, but it would still be great to read an answer that explains what is actually going on... here are my changes - only in mystuff.h:

mystuff.h:

```<code>#include <iostream>

class MyStuff
{
public:
  MyStuff();
  ~MyStuff();

  static const unsigned char temp_binary_data_7[];
  static constexpr const char* teapot_obj = (const char*) temp_binary_data_7;

  // from OpenGLDemo.cpp:
  struct Shape
  {
    Shape()
    {
      std::cout << "initializing " << static_cast<const void*>(teapot_obj) << std::endl ;
    }
  };
  Shape tmptest;
};
</code>```

So, basically:

```<code>const char* teapot_obj = (const char*) temp_binary_data_7;
</code>```

had to change into:

```<code>static constexpr const char* teapot_obj = (const char*) temp_binary_data_7;
</code>```

... which then means I have to make a static_cast<const void*> (instead of just static_cast<void*>) to print out the object address; and finally, have to add a Shape tmptest; so that the constructor of Shape runs at least once, so we can have something printed.

And now, the program runs without problems:

$ g++ -std=c++11 main.cpp mystuff.cpp -o main
$ ./main
initializing 0x400c60
hello world#
```

Title: Invalid use of non-static data member for accesing array in a struct

Body:
I am trying to work with JUCE Demo, and extract portions of BinaryData.cpp and OpenGLDemo.cpp into my own class. Unfortunately, I run into a problem I can't really parse, which I've managed to reduce in this minimal example of three files: main.cpp, mystuff.cpp and mystuff.h:

main.cpp:

// g++ -std=c++11 main.cpp mystuff.cpp -o main

#include "mystuff.h"

int main(int argc, char* argv[])
{
  MyStuff tmpstuff;
  std::cout << "hello world" << tmpstuff.temp_binary_data_7[0] << std::endl ;
}

mystuff.h

#include <iostream>

class MyStuff
{
public:
  MyStuff();
  ~MyStuff();

  // from BinaryData.cpp:
  //~ static const unsigned char temp_binary_data_7[] =
  //~ { 35,32,77,97,120,50,79,98,106,32,86,101,114,115,105,111,110,32,52,46,48,32,77,97,114,32,49,48,116,104,44,32,50,48,48,49,10,35,10,35,32,111,98,106,101,99,116,32,84,101,97,112,111,116,48,49,32,116,111,32,99,111,109,101,32,46,46,46,10,35,10,118,32,32,53,
  //~ 46,57,50,57,54,56,56,32,52,46,49,50,53,48,48,48,32,48,46,48,48,48,48,48,48,10,118,32,32,53,46,56,51,50,48,51,49,32,52,46,52,57,52,49,52,49,32,48,46,48,48,48,48,48,48,10,118,32,32,53,46,57,52,53,51,49,51,32,52,46,54,49,55,49,56,56,32,48,46,48,48,48,48,
  //~ 48,48,10,118,32,32,54,46,49,55,53,55,56,49,32,52,46,52,57,52,49,52,49,32,48,46,48,48,48,48,48,48,10,118,32,32,54,46,52,50,57,54,56,56,32,52,46,49,50,53,48,48,48,32,48,46,48,48,48,48,48,48,10,118,32,32,53,46,51,56,55,49,56,56,32,52,46,49,50,53,48,48,48
  //~ };
  // move definition to .cpp because of 'error: in-class initialization of static data member ‘const unsigned char MyStuff::temp_binary_data_7 []’ of incomplete type'
  static const unsigned char temp_binary_data_7[];

  const char* teapot_obj = (const char*) temp_binary_data_7;

  // from OpenGLDemo.cpp:
  struct Shape
  {
    Shape()
    {
      std::cout << "initializing " << static_cast<void*>(teapot_obj) << std::endl ;
    }
  };
};

mystuff.cpp:

#include "mystuff.h"

const unsigned char MyStuff::temp_binary_data_7[] =
{ 35,32,77,97,120,50,79,98,106,32,86,101,114,115,105,111,110,32,52,46,48,32,77,97,114,32,49,48,116,104,44,32,50,48,48,49,10,35,10,35,32,111,98,106,101,99,116,32,84,101,97,112,111,116,48,49,32,116,111,32,99,111,109,101,32,46,46,46,10,35,10,118,32,32,53,
46,57,50,57,54,56,56,32,52,46,49,50,53,48,48,48,32,48,46,48,48,48,48,48,48,10,118,32,32,53,46,56,51,50,48,51,49,32,52,46,52,57,52,49,52,49,32,48,46,48,48,48,48,48,48,10,118,32,32,53,46,57,52,53,51,49,51,32,52,46,54,49,55,49,56,56,32,48,46,48,48,48,48,
48,48,10,118,32,32,54,46,49,55,53,55,56,49,32,52,46,52,57,52,49,52,49,32,48,46,48,48,48,48,48,48,10,118,32,32,54,46,52,50,57,54,56,56,32,52,46,49,50,53,48,48,48,32,48,46,48,48,48,48,48,48,10,118,32,32,53,46,51,56,55,49,56,56,32,52,46,49,50,53,48,48,48
};

MyStuff::MyStuff() {

}
MyStuff::~MyStuff() {

}

When I compile with g++, I get this:

$ g++ -std=c++11 main.cpp mystuff.cpp -o main
In file included from main.cpp:3:0:
mystuff.h: In constructor ‘MyStuff::Shape::Shape()’:
mystuff.h:18:42: error: invalid use of non-static data member ‘MyStuff::teapot_obj’
   const char* teapot_obj = (const char*) temp_binary_data_7;
                                          ^
mystuff.h:25:58: error: from this location
       std::cout << "initializing " << static_cast<void*>(teapot_obj) << std::endl ;
                                                          ^
In file included from mystuff.cpp:1:0:
mystuff.h: In constructor ‘MyStuff::Shape::Shape()’:
mystuff.h:18:42: error: invalid use of non-static data member ‘MyStuff::teapot_obj’
   const char* teapot_obj = (const char*) temp_binary_data_7;
                                          ^
mystuff.h:25:58: error: from this location
       std::cout << "initializing " << static_cast<void*>(teapot_obj) << std::endl ;
                                                          ^

This happens only when the struct Shape code exists in mystuff.h - if you delete it, then the code compiles and runs fine.

So what are my options? How can I define the struct Shape (or the other variables) so that it can refer to teapot_obj without compilation errors?

Body:
Ok, managed to fix it by just throwing expressions here and there, but it would still be great to read an answer that explains what is actually going on... here are my changes - only in mystuff.h:

mystuff.h:

#include <iostream>

class MyStuff
{
public:
  MyStuff();
  ~MyStuff();

  static const unsigned char temp_binary_data_7[];
  static constexpr const char* teapot_obj = (const char*) temp_binary_data_7;

  // from OpenGLDemo.cpp:
  struct Shape
  {
    Shape()
    {
      std::cout << "initializing " << static_cast<const void*>(teapot_obj) << std::endl ;
    }
  };
  Shape tmptest;
};

So, basically:

const char* teapot_obj = (const char*) temp_binary_data_7;

had to change into:

static constexpr const char* teapot_obj = (const char*) temp_binary_data_7;

... which then means I have to make a static_cast<const void*> (instead of just static_cast<void*>) to print out the object address; and finally, have to add a Shape tmptest; so that the constructor of Shape runs at least once, so we can have something printed.

And now, the program runs without problems:

$ g++ -std=c++11 main.cpp mystuff.cpp -o main
$ ./main
initializing 0x400c60
hello world#


问:
Traverse through each row for a column text
I have a below grid

The html code is at pastebin.com/GBP3AZNQ

I want to verify whether "test123" is present. I want to traverse through each row of column master obligationname and look for the text test123.

Can anyone guide me how to do this?

答:
Your requirement can be fulfilled by using element.all().each() method of Protractor API. Please follow below code. Put the locator which gives all rows of a particular column in the below code.It will work perfectly.</p>

```<code>element.all(by.css('locatorwhichgiveallrows')).each(function(rowElement,
            index) {
          rowElement.getText().then(function (rowText) {
          if(rowText=="test123"){
              return true;}
     });
}).then(function(isPresent){
console.log("test123 is Present"+isPresent);
});
</code>```

Body:
Your requirement can be fulfilled by using element.all().each() method of Protractor API. Please follow below code. Put the locator which gives all rows of a particular column in the below code.It will work perfectly.

element.all(by.css('locatorwhichgiveallrows')).each(function(rowElement,
            index) {
          rowElement.getText().then(function (rowText) {
          if(rowText=="test123"){
              return true;}
     });
}).then(function(isPresent){
console.log("test123 is Present"+isPresent);
});