问:
How do I change line color in ggplot2 without legend disappearing?
I have the following problem:

I have this code:

```<code>oly12 <- VGAMdata::oly12
ggplot(oly12, aes(y = Weight, x = Height)
) +
geom_hex(
) +
facet_wrap("Sex", scales = "free"
) +
geom_line(aes(y = 29.99*Height^2, color = "black")
) +
geom_line(aes(y = 24.99*Height^2, color = "blue")
) +
geom_line(aes(y = 18.50*Height^2, color = "red")
) +
geom_line(aes(y = 17.00*Height^2, color = "pink")
) +
scale_color_discrete(name = "BMI limits", labels = c("Pre−obese (upper
bound)", "Normal range (upper bound)", "Normal range (lower bound)", "Mild
thinness (lower bound)")
) +
theme(legend.position="bottom", legend.direction="vertical"
)
</code>```

and I want to have all lines in black color, but when I change it in code, all lines are pink and legend disappears.

I don't know how to add a picture, it is not working, so I am sorry, but data are available in R.

What am I doing wrong?

Thank you

答:
MrFlick's comment has already given you the solution, so here's an attempt at explaining where things went wrong.

TL;DR explanation

The color = "some color" part is inside aes(), but scale_color_discrete() isn't prepared to handle it properly.

Long explanation

Let's use a base data set for illustration, since not everyone has the VGAMdata package:

```<code>df <- subset(airquality, Month == 5)[, c("Day", "Wind", "Temp")]

> head(df)
  Day Wind Temp
1   1  7.4   67
2   2  8.0   72
3   3 12.6   74
4   4 11.5   62
5   5 14.3   56
6   6 14.9   66

> summary(df)
      Day            Wind            Temp
 Min.   : 1.0   Min.   : 5.70   Min.   :56.00
 1st Qu.: 8.5   1st Qu.: 8.90   1st Qu.:60.00
 Median :16.0   Median :11.50   Median :66.00
 Mean   :16.0   Mean   :11.62   Mean   :65.55
 3rd Qu.:23.5   3rd Qu.:14.05   3rd Qu.:69.00
 Max.   :31.0   Max.   :20.10   Max.   :81.00
</code>```

Plot:

```<code>ggplot(df,
       aes(x = Day)) +
  geom_line(aes(y = Wind, color = "red")) +
  geom_line(aes(y = Temp, color = "blue")) +
  scale_color_discrete(name = "Variables",
                       labels = c("wind", "temperature")) +
  theme(legend.position = "bottom",
        legend.direction = "vertical")
</code>```

Several problems come to mind:

We know from the data that Temp's values (56-81) are magnitudes larger than Wind's values (5.7-20.1). So why is the upper line (Temp's values) labelled "wind"?

Why are pink / cyan shown in the plot when we specified red / blue?

When a color is specified inside aes(), it's interpreted as a variable value by default, rather than a color (scale_XX_identity overrides this). If I replaced the above with color = "xyz" / color = "abc", the chart would look exactly the same except for the legend labels.

Essentially, ggplot understands the code to say "Line color takes on the variable value "red" in the first geom_line and "blue" in the second; map "red" & "blue" to the default color palette in alphabetical order. If a vector of labels is provided, it is mapped to the alphabetically sorted vector of c("blue", "red")"

So we have:

```<code>|Variable |Assigned.color.value |Mapped.color.value |Mapped.label |
|:--------|:--------------------|:------------------|:------------|
|Temp     |blue                 |pink               |wind         |
|Wind     |red                  |cyan               |temperature  |
</code>```

(Side note: the default palette translates to pinkish-cyan if there are two values, red-green-blue if there are three, red-green-blue-purple if there are four, etc. See this question for more details on how this comes about.)

And if that's not confusing enough, this is what happens if you change both colors to the same value (again, it doesn't matter what that value is... could be "black", "white", "purple", or any other character string):

```<code>|Variable |Assigned.color.value |Mapped.color.value |Mapped.label |
|:--------|:--------------------|:------------------|:------------|
|Temp     |black                |pink               |wind         |
|Wind     |black                |pink               |wind         |
</code>```

Since there's only one value given, the lines take on the first color in the default palette, and only the first value in the label vector is mapped to it. Hence your plot's lines all turned pink, and all but the first line of legend disappeared.

Alternative solution

Generally, if I need to use several geom_line() lines & assign a different colour to each (rather than convert the original data into long format), I prefer to define each line's color using its intended label inside aes(), and specify the corresponding color manually using scale_XX_manual():

```<code>ggplot(df,
       aes(x = Day)) +
  geom_line(aes(y = Wind, color = "1: wind")) +
  geom_line(aes(y = Temp, color = "2: temp")) +
  scale_color_manual(name = "Variables",
                     values = c("1: wind" = "red", "2: temp" = "blue")) +
  theme(legend.position = "bottom",
        legend.direction = "vertical")
</code>```

This has the advantage of keeping all the movable parts in one place (inside scale_XX_manual()), so that if I need to update colours later on, I only need to look at that one line. The use of a named vector for values also ensures that the colors & labels are always mapped correctly to one another.

In this case, if I want to change all the line colours to black, I'd just use values = c("1: wind" = "black", "2: temp" = "black") instead.

For reference, this is what I got when I ran your original code:

The colours shown in the plot follow ggplot's default template for 4 values, rather than any combination of black / blue / red / pink.

In addition, the initial color values were (in stated order) c("black", "blue", "red", "pink"), but the alphabetical order would have been c("black", "blue", "pink", "red"). The labels are mapped to this alphabetical order, which is why the purple line ("Mild thinness" according to the legend) is actually the line for "Normal range (lower bound)".

Body:
I have the following problem:

I have this code:

oly12 <- VGAMdata::oly12
ggplot(oly12, aes(y = Weight, x = Height)
) +
geom_hex(
) +
facet_wrap("Sex", scales = "free"
) +
geom_line(aes(y = 29.99*Height^2, color = "black")
) +
geom_line(aes(y = 24.99*Height^2, color = "blue")
) +
geom_line(aes(y = 18.50*Height^2, color = "red")
) +
geom_line(aes(y = 17.00*Height^2, color = "pink")
) +
scale_color_discrete(name = "BMI limits", labels = c("Pre−obese (upper
bound)", "Normal range (upper bound)", "Normal range (lower bound)", "Mild
thinness (lower bound)")
) +
theme(legend.position="bottom", legend.direction="vertical"
)

and I want to have all lines in black color, but when I change it in code, all lines are pink and legend disappears.

I don't know how to add a picture, it is not working, so I am sorry, but data are available in R.

What am I doing wrong?

Thank you

Body:
MrFlick's comment has already given you the solution, so here's an attempt at explaining where things went wrong.

TL;DR explanation

The color = "some color" part is inside aes(), but scale_color_discrete() isn't prepared to handle it properly.

Long explanation

Let's use a base data set for illustration, since not everyone has the VGAMdata package:

df <- subset(airquality, Month == 5)[, c("Day", "Wind", "Temp")]

> head(df)
  Day Wind Temp
1   1  7.4   67
2   2  8.0   72
3   3 12.6   74
4   4 11.5   62
5   5 14.3   56
6   6 14.9   66

> summary(df)
      Day            Wind            Temp
 Min.   : 1.0   Min.   : 5.70   Min.   :56.00
 1st Qu.: 8.5   1st Qu.: 8.90   1st Qu.:60.00
 Median :16.0   Median :11.50   Median :66.00
 Mean   :16.0   Mean   :11.62   Mean   :65.55
 3rd Qu.:23.5   3rd Qu.:14.05   3rd Qu.:69.00
 Max.   :31.0   Max.   :20.10   Max.   :81.00

Plot:

ggplot(df,
       aes(x = Day)) +
  geom_line(aes(y = Wind, color = "red")) +
  geom_line(aes(y = Temp, color = "blue")) +
  scale_color_discrete(name = "Variables",
                       labels = c("wind", "temperature")) +
  theme(legend.position = "bottom",
        legend.direction = "vertical")

Several problems come to mind:

We know from the data that Temp's values (56-81) are magnitudes larger than Wind's values (5.7-20.1). So why is the upper line (Temp's values) labelled "wind"?

Why are pink / cyan shown in the plot when we specified red / blue?

When a color is specified inside aes(), it's interpreted as a variable value by default, rather than a color (scale_XX_identity overrides this). If I replaced the above with color = "xyz" / color = "abc", the chart would look exactly the same except for the legend labels.

Essentially, ggplot understands the code to say "Line color takes on the variable value "red" in the first geom_line and "blue" in the second; map "red" & "blue" to the default color palette in alphabetical order. If a vector of labels is provided, it is mapped to the alphabetically sorted vector of c("blue", "red")"

So we have:

|Variable |Assigned.color.value |Mapped.color.value |Mapped.label |
|:--------|:--------------------|:------------------|:------------|
|Temp     |blue                 |pink               |wind         |
|Wind     |red                  |cyan               |temperature  |

(Side note: the default palette translates to pinkish-cyan if there are two values, red-green-blue if there are three, red-green-blue-purple if there are four, etc. See this question for more details on how this comes about.)

And if that's not confusing enough, this is what happens if you change both colors to the same value (again, it doesn't matter what that value is... could be "black", "white", "purple", or any other character string):

|Variable |Assigned.color.value |Mapped.color.value |Mapped.label |
|:--------|:--------------------|:------------------|:------------|
|Temp     |black                |pink               |wind         |
|Wind     |black                |pink               |wind         |

Since there's only one value given, the lines take on the first color in the default palette, and only the first value in the label vector is mapped to it. Hence your plot's lines all turned pink, and all but the first line of legend disappeared.

Alternative solution

Generally, if I need to use several geom_line() lines & assign a different colour to each (rather than convert the original data into long format), I prefer to define each line's color using its intended label inside aes(), and specify the corresponding color manually using scale_XX_manual():

ggplot(df,
       aes(x = Day)) +
  geom_line(aes(y = Wind, color = "1: wind")) +
  geom_line(aes(y = Temp, color = "2: temp")) +
  scale_color_manual(name = "Variables",
                     values = c("1: wind" = "red", "2: temp" = "blue")) +
  theme(legend.position = "bottom",
        legend.direction = "vertical")

This has the advantage of keeping all the movable parts in one place (inside scale_XX_manual()), so that if I need to update colours later on, I only need to look at that one line. The use of a named vector for values also ensures that the colors & labels are always mapped correctly to one another.

In this case, if I want to change all the line colours to black, I'd just use values = c("1: wind" = "black", "2: temp" = "black") instead.

For reference, this is what I got when I ran your original code:

The colours shown in the plot follow ggplot's default template for 4 values, rather than any combination of black / blue / red / pink.

In addition, the initial color values were (in stated order) c("black", "blue", "red", "pink"), but the alphabetical order would have been c("black", "blue", "pink", "red"). The labels are mapped to this alphabetical order, which is why the purple line ("Mild thinness" according to the legend) is actually the line for "Normal range (lower bound)".


来源: stackexchange

问:
Hibernate inheritance with different primary key
I'm trying to create a inheritance with TABLE_PER_CLASS strategy, but i want to have different primary key for each table is it possible?

I've one class Register which has millions of instances, some of these instances are "special" and have different rules for theirs columns and extra columns.

```<code>@MappedSuperclass

public abstract class Register {

    @Id
    @Column(nullable = false, unique = true, updatable = false)
    private Long userId;

    private Date checked;

    @Column(nullable = false)
    private RegisterState tipo;
}

@Entity
@AttributeOverrides({ @AttributeOverride(name = "userId", column = @Column(nullable = false, unique = false, updatable = false)) })
public class PotencialRegister extends Register implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(length = 64, nullable = false, unique = false)
    private String referer;
}
</code>```

For the basic register I dont need an Id attribute because I've one unique column, but for the specialized entity that column is not unique so I added an extra attribute.

the problem is that hibernate is using the parent id to created a composite primary key (the generated schema is):

```<code>create table PotencialRegister (
        id integer not null,
        userId bigint not null,
        checked datetime(6),
        tipo integer not null,
        referer varchar(64) not null,
        primary key (id, userId)
    )

    create table Register (
        userId bigint not null,
        checked datetime(6),
        tipo integer not null,
        primary key (userId)
    )
</code>```

The columns are right and the schama is what i want, but I would like to remove the "id" member from PotencialRegister primary key.

答:
You can create another class that do not have @Id column in it and use this class as base class for each type of Register.

so your Register class would look like:

```<code>@MappedSuperclass

public abstract class Register {

    @Column(nullable = false, unique = true, updatable = false)
    private Long userId;

    private Date checked;

   @Column(nullable = false)
    private RegisterState tipo;
}
</code>```

Now for your Normal Register you can do following:

```<code> @Entity
 public class NormalRegister extends Register implements Serializable{

    @Id
    public Long getUserId(){
      return super.userId;
    }

     public void setUserId(Long uId){
        super.userId=uId;
      }

   }
</code>```

next you define your PotencialRegister  class as:

```<code>@Entity
@AttributeOverrides({ @AttributeOverride(name = "userId", column = @Column(nullable = false, unique = false, updatable = false)) })
public class PotencialRegister extends Register implements Serializable {

    private Integer id;

    @Column(length = 64, nullable = false, unique = false)
    private String referer;

    @Id
    public Long getUserId(){
      return super.userId;
    }

     public void setUserId(Long uId){
        super.userId=uId;
      }

}
</code>```

With this you do not have Id in base class and all the sub classes can define their own Id attribute

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a inheritance with TABLE_PER_CLASS strategy, but i want to have different primary key for each table is it possible?

I've one class Register which has millions of instances, some of these instances are "special" and have different rules for theirs columns and extra columns.

@MappedSuperclass

public abstract class Register {

    @Id
    @Column(nullable = false, unique = true, updatable = false)
    private Long userId;

    private Date checked;

    @Column(nullable = false)
    private RegisterState tipo;
}

@Entity
@AttributeOverrides({ @AttributeOverride(name = "userId", column = @Column(nullable = false, unique = false, updatable = false)) })
public class PotencialRegister extends Register implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(length = 64, nullable = false, unique = false)
    private String referer;
}

For the basic register I dont need an Id attribute because I've one unique column, but for the specialized entity that column is not unique so I added an extra attribute.

the problem is that hibernate is using the parent id to created a composite primary key (the generated schema is):

create table PotencialRegister (
        id integer not null,
        userId bigint not null,
        checked datetime(6),
        tipo integer not null,
        referer varchar(64) not null,
        primary key (id, userId)
    )

    create table Register (
        userId bigint not null,
        checked datetime(6),
        tipo integer not null,
        primary key (userId)
    )

The columns are right and the schama is what i want, but I would like to remove the "id" member from PotencialRegister primary key.

Body:
You can create another class that do not have @Id column in it and use this class as base class for each type of Register.

so your Register class would look like:

@MappedSuperclass

public abstract class Register {

    @Column(nullable = false, unique = true, updatable = false)
    private Long userId;

    private Date checked;

   @Column(nullable = false)
    private RegisterState tipo;
}

Now for your Normal Register you can do following:

 @Entity
 public class NormalRegister extends Register implements Serializable{

    @Id
    public Long getUserId(){
      return super.userId;
    }

     public void setUserId(Long uId){
        super.userId=uId;
      }

   }

next you define your PotencialRegister  class as:

@Entity
@AttributeOverrides({ @AttributeOverride(name = "userId", column = @Column(nullable = false, unique = false, updatable = false)) })
public class PotencialRegister extends Register implements Serializable {

    private Integer id;

    @Column(length = 64, nullable = false, unique = false)
    private String referer;

    @Id
    public Long getUserId(){
      return super.userId;
    }

     public void setUserId(Long uId){
        super.userId=uId;
      }

}

With this you do not have Id in base class and all the sub classes can define their own Id attribute


问:
Count the average of number of surveys per year, Spring Data Jpa
I have a Model, called Survey that has a

```<code>@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date submittedDate;
</code>```

field, which is a timestamp that shows the time that a row is insterted in this table.
What I want to be able to query and show is this :
The total number of rows for every month, 12 months.
And then find the average. Which would be :

(countJan+CountFeb+...)/12; ( cycle through countInEveryMonth, and divide by 12 )

How do I query this using Spring Data Jpa ?

Do I write a method like :

```<code>int countBySubmittedDate(Date submittedDate) ? -
</code>```

but this will count the number of Surveys at a given timestamp?
Thank you.

答:
Whole year average can be:

public interface SurveyRepository extends CrudRepository<Survey, Integer> {
    @Query("SELECT COUNT(s) FROM Survey s WHERE (date_field BETWEEN :yearStart AND :yearEnd)")
    Long yearAverage(@Param("yearStart") Date yearEnd, @Param("yearEnd") Date yearEnd);
    //you may divide it by 12
}
```

Same can be done for other scenario.

Body:
I have a Model, called Survey that has a

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date submittedDate;

field, which is a timestamp that shows the time that a row is insterted in this table.
What I want to be able to query and show is this :
The total number of rows for every month, 12 months.
And then find the average. Which would be :

(countJan+CountFeb+...)/12; ( cycle through countInEveryMonth, and divide by 12 )

How do I query this using Spring Data Jpa ?

Do I write a method like :

int countBySubmittedDate(Date submittedDate) ? -

but this will count the number of Surveys at a given timestamp?
Thank you.

Body:
Whole year average can be:

public interface SurveyRepository extends CrudRepository<Survey, Integer> {
    @Query("SELECT COUNT(s) FROM Survey s WHERE (date_field BETWEEN :yearStart AND :yearEnd)")
    Long yearAverage(@Param("yearStart") Date yearEnd, @Param("yearEnd") Date yearEnd);
    //you may divide it by 12
}

Same can be done for other scenario.


问:
Amazon MWS with PHP integration
I am new to amazon mws. I want to do the mws api integration with php. I have all the credentials whatever needed like secret key, seller id, and etc.

Basically i want to display all my orders in my php website. I tried with use of developer guide which is provided by the mws documentation. but i could not get a proper idea of how to integrate api in my php site.

答:
Verify Credentials & Play Around With API:

Please verify if your credentials are correct & you do have orders in your seller account to download from. You can use amazon's scratchpad here: Amazon MWS scratchpad

 On scratchpad you want to use following methods.

 API Selection: Orders

 Operation: ListOrders

 You can also refer to this API Guide to better understand scratchpad.

Integration:

Download PHP library from Amazon MWS

You want to add your  MWS credentials in this file MarketplaceWebServiceOrders/Samples/.config.inc.php

Here you put in values that you used to play around at scratchpad

MarketplaceWebServiceOrders/Samples/ListOrders.php

eg: CreatedAfter, LastUpdatedAfter, OrderStatus

Run this file in browser & you will receive data in XML format MarketplaceWebServiceOrders/Samples/ListOrders.php

Title: Amazon MWS with PHP integration


问:
PHP script using ssh2_scp_send Fails to create remote file
I'm trying to transfer files to a shared hosting account (godaddy) and it's failing:

Warning: ssh2_scp_send(): Failure creating remote file: failed to send file in 'local/file/path'

I have SSH2 installed and the connection is working. I even ran a ssh2_exec command to see if I can affect the remote server and I was able to create a directory. I also successfully used scp directly on the command line going both ways... As a further troubleshooting attempt, I reversed the file paths and created a remote server file for it to attempt downloading, I get this error:

failed to open stream: No such file or directory

I called the host to make sure I'm using the correct absolute file path, I've tried many variations, and I still get this error. I think my issue lies somewhere with the remote file path.

The problem code is below:

```<code>$localpath=$_SERVER['DOCUMENT_ROOT'].'/local_file_path/' ;

$remotepath = 'website.com/public_html/folder/' ;

$connection = ssh2_connect('website.com', 22);

ssh2_auth_password($connection,'username','password' );

ssh2_scp_send($connection,"$localpath"."SUCCESS.txt", "$remotepath"."SUCCESS.txt", 0644);
</code>```

I am also having issues trying to use sftp via PHP. I read elsewhere on the web that you have to use double quotes on the file paths, whenever they fail, the printed path appears correct, but perhaps I'm missing something?

UPDATE

I logged into the shared hosting account via sftp with filezilla and discovered that, when copied, the full url path is different then what I was being given when logged in threw regular ftp. I can now upload a file, but, I can't seem to download just yet, ironically... I still get the error about not being able to locate the file path on the remote server.

答:
ssh2_scp_send need absolute path, I solved my issue by using pwd where I need to send my files. ~/ dont works either, it's not an absolute path.

The bottom comment on this page http://www.php.net/manual/en/function.ssh2-scp-send.php refers to a problem you might be having.

I suggest that, use phpseclib or ssh2_sftp

Interesting topics:

Uploading files with SFTP & phpseclib interesting debate with good informations.

How to SFTP with PHP?

Body:
I'm trying to transfer files to a shared hosting account (godaddy) and it's failing:

Warning: ssh2_scp_send(): Failure creating remote file: failed to send file in 'local/file/path'

I have SSH2 installed and the connection is working. I even ran a ssh2_exec command to see if I can affect the remote server and I was able to create a directory. I also successfully used scp directly on the command line going both ways... As a further troubleshooting attempt, I reversed the file paths and created a remote server file for it to attempt downloading, I get this error:

failed to open stream: No such file or directory

I called the host to make sure I'm using the correct absolute file path, I've tried many variations, and I still get this error. I think my issue lies somewhere with the remote file path.

The problem code is below:

$localpath=$_SERVER['DOCUMENT_ROOT'].'/local_file_path/' ;

$remotepath = 'website.com/public_html/folder/' ;

$connection = ssh2_connect('website.com', 22);

ssh2_auth_password($connection,'username','password' );

ssh2_scp_send($connection,"$localpath"."SUCCESS.txt", "$remotepath"."SUCCESS.txt", 0644);

I am also having issues trying to use sftp via PHP. I read elsewhere on the web that you have to use double quotes on the file paths, whenever they fail, the printed path appears correct, but perhaps I'm missing something?

UPDATE

I logged into the shared hosting account via sftp with filezilla and discovered that, when copied, the full url path is different then what I was being given when logged in threw regular ftp. I can now upload a file, but, I can't seem to download just yet, ironically... I still get the error about not being able to locate the file path on the remote server.


问:
Parsing XML to an array for GMaps API using jQuery
I'm teaching myself javascript by creating my wedding website using the google maps API.  I've figured out a lot through the docs and copypasta experimentation, but don't know how to make this happen: what I want to do is read an external XML file containing icon information (names and offsets for a sprite image containing the icons), and store it in an array that I can access when creating map markers.  For example, I want to be able to create a marker for the reception and assign it the icon "party".  Here's the code I have so far for reading the icon file:

```<code>        jQuery.get("markericons.xml", {}, function(data) {
        jQuery(data).find("markericon").each(function() {
            var icon = jQuery(this);
            var name = icon.attr("name");
            var url = 'images/icons/mapsprites.png';
            var size = new google.maps.Size(32, 37);
            var origin = new google.maps.Point(parseInt(icon.attr("x")),parseInt(icon.attr("y")));
            var anchor = new google.maps.Point((origin.x+16),origin.y);
            var icon = new google.maps.MarkerImage(url, size, origin, anchor);
        });
    });  // how to store this in an array so that I can access elements by name later?
</code>```

And then, when creating the actual placemarks on the google map, something like the following:

```<code>                var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: icon.name=="party",  // pseudo-code... how to do this?
                title: title
            });
</code>```

I'm still a programming noob, so I'd appreciate any help.  Thanks!

答:
You should use GIcon: http://code.google.com/apis/maps/documentation/javascript/v2/reference.html#GIcon

example how to use it:
http://code.google.com/apis/maps/documentation/javascript/v2/examples/icon-simple.html

ContentLicense: CC BY-SA 2.5

Body:
I'm teaching myself javascript by creating my wedding website using the google maps API.  I've figured out a lot through the docs and copypasta experimentation, but don't know how to make this happen: what I want to do is read an external XML file containing icon information (names and offsets for a sprite image containing the icons), and store it in an array that I can access when creating map markers.  For example, I want to be able to create a marker for the reception and assign it the icon "party".  Here's the code I have so far for reading the icon file:

        jQuery.get("markericons.xml", {}, function(data) {
        jQuery(data).find("markericon").each(function() {
            var icon = jQuery(this);
            var name = icon.attr("name");
            var url = 'images/icons/mapsprites.png';
            var size = new google.maps.Size(32, 37);
            var origin = new google.maps.Point(parseInt(icon.attr("x")),parseInt(icon.attr("y")));
            var anchor = new google.maps.Point((origin.x+16),origin.y);
            var icon = new google.maps.MarkerImage(url, size, origin, anchor);
        });
    });  // how to store this in an array so that I can access elements by name later?

And then, when creating the actual placemarks on the google map, something like the following:

                var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: icon.name=="party",  // pseudo-code... how to do this?
                title: title
            });

I'm still a programming noob, so I'd appreciate any help.  Thanks!


问:
Edge: browserAction.setIcon not working when using a default icon with multiple sizes
I can't get browser.browserAction.setIcon to work in Microsoft Edge when manifest.json is specifying a default icon in multiple sizes:

manifest.json

```<code>{
  "manifest_version": 2,
  "name": "test",
  "version": "0.0.1",
  "author": "John Doe",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": {
      "19": "icon.png",
      "38": "icon2.png"
    }
  }
}
</code>```

background.js

```<code>setInterval(function() {
  browser.browserAction.setIcon({
      path: "testimage.png"
  });
}, 2000);
</code>```

No error logged, the code is executed but the icon doesn't change. The same code works fine in Chrome.

Changing the manifest.json to

```<code>"browser_action": {
  "default_icon": "icon.png"
}
</code>```

Fixes the issue, but what if I need to use multiple default icons?

EDIT:

Unfortunately not even "default_icon": "icon.png" is usable, even though Edge happily loads the extension, when submitting it to the store, the validation fails with

Validation failed: Invalid type: string (expected object)
Schema location: /properties/browser_action/allOf/0/properties/default_icon/type
Manifest location: /browser_action/default_icon
Validation failed for extension manifest: Extension\manifest.json

Which is indeed what MDN says: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/browser_action#Browser_compatibility

'default_icon' must be an object, with explicit sizes.

答:
In the end I came to the conclusion that Edge doesn't like string values for the browser action icon path, neither in manifest.json nor in browserAction.setIcon, it fails silently without producing any error.

A way to make it work is to always set explicit sizes in both manifest.json and in every browserAction.setIcon call, even if the different sizes all point to the same image.

manifest.json

```<code>{
  "manifest_version": 2,
  "name": "test",
  "version": "0.0.1",
  "author": "John Doe",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": {
      "19": "icon.png",
      "38": "icon2.png"
    }
  }
}
</code>```

background.js

```<code>browser.browserAction.setIcon({
    path: {
      "19": "testimage.png",
      "38": "testimage.png"
});
</code>```

Body:
I can't get browser.browserAction.setIcon to work in Microsoft Edge when manifest.json is specifying a default icon in multiple sizes:

manifest.json

{
  "manifest_version": 2,
  "name": "test",
  "version": "0.0.1",
  "author": "John Doe",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": {
      "19": "icon.png",
      "38": "icon2.png"
    }
  }
}

background.js

setInterval(function() {
  browser.browserAction.setIcon({
      path: "testimage.png"
  });
}, 2000);

No error logged, the code is executed but the icon doesn't change. The same code works fine in Chrome.

Changing the manifest.json to

"browser_action": {
  "default_icon": "icon.png"
}

Fixes the issue, but what if I need to use multiple default icons?

EDIT:

Unfortunately not even "default_icon": "icon.png" is usable, even though Edge happily loads the extension, when submitting it to the store, the validation fails with

Validation failed: Invalid type: string (expected object)
Schema location: /properties/browser_action/allOf/0/properties/default_icon/type
Manifest location: /browser_action/default_icon
Validation failed for extension manifest: Extension\manifest.json

Which is indeed what MDN says: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/browser_action#Browser_compatibility

'default_icon' must be an object, with explicit sizes.

Body:
In the end I came to the conclusion that Edge doesn't like string values for the browser action icon path, neither in manifest.json nor in browserAction.setIcon, it fails silently without producing any error.

A way to make it work is to always set explicit sizes in both manifest.json and in every browserAction.setIcon call, even if the different sizes all point to the same image.

manifest.json

{
  "manifest_version": 2,
  "name": "test",
  "version": "0.0.1",
  "author": "John Doe",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": {
      "19": "icon.png",
      "38": "icon2.png"
    }
  }
}

background.js

browser.browserAction.setIcon({
    path: {
      "19": "testimage.png",
      "38": "testimage.png"
});


问:
Exporting and importing same package from an osgi bundle
I have a class org.foo.Customer in an osgi bundle Bundle1 and another class
org.foo.Subscriber in another osgi bundle Bundle2 in the same osgi environment. Bundle1 exports-package org.foo .

Is it possible to import org.foo package of Bundle2 by Bundle1. Will there be any conflict during runtime as the same package is specified in export and import in the manifest file of Bundle1 .

答:
Split packages are strongly discouraged in OSGi. If you own these bundles, you should either rename one or both packages, or join the split package into one bundle.

Bundle2 could import the split package, but then the classloader of Bundle2 would only see the classes in Bundle1, not those internally in Bundle2.

You could make one of the bundles a fragment of the other, which has the effect that they will use the same classloader. This requires changing only the manifest of the fragment bundle, and could be an option if you for some reason cannot join the bundles or change the package names.

ContentLicense: CC BY-SA 4.0


问:
Polymer - dom-repeat when end binding event?
I have a simple question, because I didn't found this after long search.

Scenario:

When a component is loading, I make AJAX call to get data from an API. After call ends i put data in a property that is used for dom-repeat. After dom-repeat ends rendering I want to do some operation on elements in it. Read() is called even before AJAX call ends. Are there others ways to handle that?

答:
You can couple a dom-change event and a debounce to get what you want.

```<code><template is='dom-repeat' items='[[items]]' on-dom-change='_handleDomChangeEvent'>
...
</template>

...

_handleDomChangeEvent: function() {
  this.debounce('domEndEvent', function() {
    // dom-repeat has finished rendering
  }, 100)
}
</code>```

This can be considered brittle - if dom-change events fire between spans of more than 100ms the debouncer will fire twice. For practical purposes however it's unlikely that a DOM change would take that long to complete.

Body:
You can couple a dom-change event and a debounce to get what you want.

<template is='dom-repeat' items='[[items]]' on-dom-change='_handleDomChangeEvent'>
...
</template>

...

_handleDomChangeEvent: function() {
  this.debounce('domEndEvent', function() {
    // dom-repeat has finished rendering
  }, 100)
}

This can be considered brittle - if dom-change events fire between spans of more than 100ms the debouncer will fire twice. For practical purposes however it's unlikely that a DOM change would take that long to complete.


问:
Prestashop 1.7.2.0 display currency symbol before price on home page
I want to change 100 $ to $ 100 for the products list on the home page in Prestashop 1.7.2.0.

I edited the file from the path Translations/cldr/main-es-ES-numbers as follows:

```<code>"accounting":"#,##0\u00a4\u00a0","standard":"#,##0\u00a4\u00a0"
</code>```

to

```<code>"accounting":"\u00a4#,##0.00;(\u00a4#,##0.00)","standard":"\u00a4#,##0.00",
</code>```

But it works well except for the home page

答:
Clearing the prestashop cache by clicking "Clear Cache" at the top right of Advanced Parameters / Performance should do the trick.

Prices and other product related information on the index page of prestashops are ususally cached by the homefeaturedor other modules. Since modules ignore the performance setting of "clear cache everytime something has been modified", the cache needs to be cleared manually.

Body:
I want to change 100 $ to $ 100 for the products list on the home page in Prestashop 1.7.2.0.

I edited the file from the path Translations/cldr/main-es-ES-numbers as follows:

"accounting":"#,##0\u00a4\u00a0","standard":"#,##0\u00a4\u00a0"

to

"accounting":"\u00a4#,##0.00;(\u00a4#,##0.00)","standard":"\u00a4#,##0.00",

But it works well except for the home page


问:
"XamlCTask" task failed unexpectedly" error when building with the new Xamarin Forms
After I've updated to the latest Xamarin.Forms (2.3.4.224) I keep getting build errors. anyone knows what this could be?

I suspect it might have to do with the new behavior changes they have introduced with the new version regarding Attached Properties (but I don't know that that means)

more info here https://forums.xamarin.com/discussion/92455/xamarin-forms-2-3-4-224

and here is my build log

```<code>Error       The "XamlCTask" task failed unexpectedly.
System.ArgumentException: An item with the same key has already been added.

Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() Shared
</code>```

答: Clean your solution and close your Visual Studio 2017. The error will gone when you open it again.</p>

Body:
After I've updated to the latest Xamarin.Forms (2.3.4.224) I keep getting build errors. anyone knows what this could be?

I suspect it might have to do with the new behavior changes they have introduced with the new version regarding Attached Properties (but I don't know that that means)

more info here https://forums.xamarin.com/discussion/92455/xamarin-forms-2-3-4-224

and here is my build log

Error       The "XamlCTask" task failed unexpectedly.
System.ArgumentException: An item with the same key has already been added.

Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() Shared


问:
Manage long-running connection to Twitter streaming API from java EE application
I need to create a long-running connection from within a Java EE6 application to the Twitter streaming API and also be able to monitor and re-establish the connection on failure.

I've run up a test with Jersey JAX-RS and OAuth as follows and this handles the streaming data as I would like.

```<code>WebResource resource = client.resource(STATUS_URI);
resource.addFilter(oauthFilter);
ClientResponse clientResponse = resource.get(ClientResponse.class);
InputStream is = clientResponse.getEntityInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF8"));
boolean more = true;
while (more) {
    String jsonTweet = r.readLine();
    //send tweet to JMS queue
    .....
}
</code>```

I've tried running the above code in a singleton '@PostConstruct' method but it blocks and the application does not load properly.

My question is what would be the recommended way to initialise the connection from within a Java EE environment on application startup and then monitor + re-connect on errors without directly creating new threads?

答:
recommended way to initialise the
  connection from within a Java EE
  environment on application startup

You can use @Service to create Singleton MBean(JBoss Specific implementation), but still I prefer @Startup & @Singleton to get things done at application deployment for portability with server.

monitor + re-connect on errors without
  directly creating new threads?

ThreadPoolExecutor : An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.

In exception, tasks can be resubmitted to executor service, task may comprise of monitoring, reconnecting the connection etc.

Body:
I need to create a long-running connection from within a Java EE6 application to the Twitter streaming API and also be able to monitor and re-establish the connection on failure.

I've run up a test with Jersey JAX-RS and OAuth as follows and this handles the streaming data as I would like.

WebResource resource = client.resource(STATUS_URI);
resource.addFilter(oauthFilter);
ClientResponse clientResponse = resource.get(ClientResponse.class);
InputStream is = clientResponse.getEntityInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF8"));
boolean more = true;
while (more) {
    String jsonTweet = r.readLine();
    //send tweet to JMS queue
    .....
}

I've tried running the above code in a singleton '@PostConstruct' method but it blocks and the application does not load properly.

My question is what would be the recommended way to initialise the connection from within a Java EE environment on application startup and then monitor + re-connect on errors without directly creating new threads?


问:
Generate a simple table with javascript
I dont understand why but I'm getting the wrong body structure. You can see on the image that I get a

 and I dont have that on javascript.

I just want a table with 3 columns and up to 10 rows.

What's happening?

My generated html

JavaScript

```<code>  $('#selectMRPC').change(function () {
    //fetch data
    var mrpc = $(this).find('option:selected').data('mrpc');

    $('#paramBody').empty();
    for (var i = 1; i <= 10; i++) {
        var field = mrpc["field" + i];
        if (field !== undefined) {
            var parsedField = field.split('_');
            var value = parsedField[0];
            var type = parsedField[1];

            switch (type) {
                case  "S":
                    type = "text";
                    if (value === '""')
                        value = null;
                    break;
                case "B":
                    type = "checkbox";
                    break;
                case "N":
                    type = "number";
                    value = parseInt(value);
                    break;
                case "D":
                    type = "number";
                    value = parseInt(value);
                    if (value === '""')
                        value = null;
                    break;
            }
            $('#paramBody').append('<tr>');
            $('#paramBody').append('<td>' + i + '</td>');
            $('#paramBody').append('<td>' + type + '</td>');
            $('#paramBody').append('<td><input name="Fields" type="' + type + '">').val(value);
            $('#paramBody').append('</tr>');

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

答:
append will create an element from the parameter if the given input is not already a valid html string

Make it

```<code>$('#paramBody').append('<tr><td>' + i + '</td><td>' + type + '</td><td><input name="Fields" type="' + type + '" value="' +value + '"></tr>');
</code>```

Or append them one by one (example below)

```<code>$( "<tr></tr>" ).append('<td>' + i + '</td>').appendTo( '#paramBody' );
</code>```

Or create a string first

```<code>  var html = '<tr>';
  html += '<td>' + i + '</td>';
  html += '<td>' + type + '</td>';
  html += '<td><input name="Fields" type="' + type + '" value="' + value + '">';
  html += '</tr>';

 $('#paramBody').append(html );
</code>```

Title: Generate a simple table with javascript

Body:
I dont understand why but I'm getting the wrong body structure. You can see on the image that I get a

 and I dont have that on javascript.

I just want a table with 3 columns and up to 10 rows.

What's happening?

My generated html

JavaScript

  $('#selectMRPC').change(function () {
    //fetch data
    var mrpc = $(this).find('option:selected').data('mrpc');

    $('#paramBody').empty();
    for (var i = 1; i <= 10; i++) {
        var field = mrpc["field" + i];
        if (field !== undefined) {
            var parsedField = field.split('_');
            var value = parsedField[0];
            var type = parsedField[1];

            switch (type) {
                case  "S":
                    type = "text";
                    if (value === '""')
                        value = null;
                    break;
                case "B":
                    type = "checkbox";
                    break;
                case "N":
                    type = "number";
                    value = parseInt(value);
                    break;
                case "D":
                    type = "number";
                    value = parseInt(value);
                    if (value === '""')
                        value = null;
                    break;
            }
            $('#paramBody').append('
');
            $('#paramBody').append('' + i + '	');
            $('#paramBody').append('' + type + '	');
            $('#paramBody').append('<input name="Fields" type="' + type + '">').val(value);
            $('#paramBody').append('
');

        }
    }
});

Body:
append will create an element from the parameter if the given input is not already a valid html string

Make it

$('#paramBody').append('<tr><td>' + i + '</td><td>' + type + '</td><td><input name="Fields" type="' + type + '" value="' +value + '"></tr>');

Or append them one by one (example below)

$( "<tr></tr>" ).append('<td>' + i + '</td>').appendTo( '#paramBody' );

Or create a string first

  var html = '<tr>';
  html += '<td>' + i + '</td>';
  html += '<td>' + type + '</td>';
  html += '<td><input name="Fields" type="' + type + '" value="' + value + '">';
  html += '</tr>';

 $('#paramBody').append(html );


问:
Django queryset - column IN() GROUP BY HAVING COUNT DISTINCT
With the following models:

```<code>class Post(models.Model):

    class Meta:
        db_table = "posts"

class Tag(models.Model):
    tag = models.CharField(max_length=50)

   class Meta:
       db_table = "tags"

class PostTag(models.Model):
    postid = models.PositiveIntegerField()
    tagid = models.PositiveIntegerField()

    class Meta:
        unique_together = ("postid", "tagid")
        db_table = "posttags"
</code>```

To get postids of posts which contain all the tagids given in TAGLIST where TAGLEN is the number of tagids in TAGLIST:

```<code>SELECT postid
FROM posttags
WHERE tagid IN (TAGLIST)
GROUP BY postid
HAVING COUNT(DISTINCT tagid) = TAGLEN
</code>```

But how do I do this with Django ORM?

答:
I found a solution.

```<code>    TAGLEN = TAGLIST.count()
    withtags = PostTag.objects.filter(tagid__in=TAGLIST)
    withall = withtags.values("postid").annotate(tagtotal=Count("tagid", distinct=True)).order_by()
    withall.filter(tagtotal=TAGLEN).values_list("postid", flat=True)
</code>```

And running .query.__str__() on all this returns basically the following SQL below.

```<code>SELECT "postid"
FROM "posttags"
WHERE "tagid" IN (TAGLIST)
GROUP BY "postid"
HAVING COUNT(DISTINCT "tagid") = TAGLEN'
</code>```

Body:
With the following models:

class Post(models.Model):

    class Meta:
        db_table = "posts"

class Tag(models.Model):
    tag = models.CharField(max_length=50)

   class Meta:
       db_table = "tags"

class PostTag(models.Model):
    postid = models.PositiveIntegerField()
    tagid = models.PositiveIntegerField()

    class Meta:
        unique_together = ("postid", "tagid")
        db_table = "posttags"

To get postids of posts which contain all the tagids given in TAGLIST where TAGLEN is the number of tagids in TAGLIST:

SELECT postid
FROM posttags
WHERE tagid IN (TAGLIST)
GROUP BY postid
HAVING COUNT(DISTINCT tagid) = TAGLEN

But how do I do this with Django ORM?

Body:
I found a solution.

    TAGLEN = TAGLIST.count()
    withtags = PostTag.objects.filter(tagid__in=TAGLIST)
    withall = withtags.values("postid").annotate(tagtotal=Count("tagid", distinct=True)).order_by()
    withall.filter(tagtotal=TAGLEN).values_list("postid", flat=True)

And running .query.__str__() on all this returns basically the following SQL below.

SELECT "postid"
FROM "posttags"
WHERE "tagid" IN (TAGLIST)
GROUP BY "postid"
HAVING COUNT(DISTINCT "tagid") = TAGLEN'


问:
What happened to my file after this 'mv' command?
I was moving my private key file (for ssl) but I used a wrong syntax.

I wanted to move it in a folder named 'ssl'

The wrong command syntax I typed is:

```<code>sudo mv private.key /ssl
</code>```

(There was no ssl directory in the path)

My question is:

Where is my file? What happened to it? :sarcasm

答: If there is no /ssl directory, your private.key will be moved to root directory (/) and named with ssl.

Body:
I was moving my private key file (for ssl) but I used a wrong syntax.

I wanted to move it in a folder named 'ssl'

The wrong command syntax I typed is:

sudo mv private.key /ssl

(There was no ssl directory in the path)

My question is:

Where is my file? What happened to it? :sarcasm


问:
Type with bad antialiasing using webkit transformation, what's the cause?
I'm using a script that uses Webkit transformations, and in Safari I can see the type jagged, not clear — like in an old pc browser.

The type is good in Chrome and Safari Mobile. What could it be? Do I have to set anything on CSS?

thanks

答:
I am not sure what the problem is... but, you can always force antialisasing with this:

```<code>html
{
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
}
</code>```

the 'text-rendering' function is optional, it only affects Windows and Linux.
Learn more »

Body:
I am not sure what the problem is... but, you can always force antialisasing with this:

html
{
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
}

the 'text-rendering' function is optional, it only affects Windows and Linux.
Learn more »


答:
You are appending everything to #paramBody, which is incorrect. Consecutively, you need to append/insert data into
. So I would recommend, you concatenate everything together instead of appending.

You need to change

```<code>$('#paramBody').append('<tr>');
            $('#paramBody').append('<td>' + i + '</td>');
            $('#paramBody').append('<td>' + type + '</td>');
            $('#paramBody').append('<td><input name="Fields" type="' + type + '">').val(value);
            $('#paramBody').append('</tr>');
</code>```

to

```<code>var rowHtml = '<tr>' + '<td>' + i + '</td>' + '<td>' + type + '</td>' + '<td><input name="Fields" type="' + type + '">' + value + '</tr>';
$('#paramBody').append(rowHtml);
</code>```

Title: Generate a simple table with javascript

Body:
You are appending everything to #paramBody, which is incorrect. Consecutively, you need to append/insert data into <tr>. So I would recommend, you concatenate everything together instead of appending.

You need to change

$('#paramBody').append('<tr>');
            $('#paramBody').append('<td>' + i + '</td>');
            $('#paramBody').append('<td>' + type + '</td>');
            $('#paramBody').append('<td><input name="Fields" type="' + type + '">').val(value);
            $('#paramBody').append('</tr>');

to

var rowHtml = '<tr>' + '<td>' + i + '</td>' + '<td>' + type + '</td>' + '<td><input name="Fields" type="' + type + '">' + value + '</tr>';
$('#paramBody').append(rowHtml);


问:
Scala groupBy for a list
I'd like to create a map on which the key is the string and the value is the number of how many times the string appears on the list. I tried the groupBy method, but have been unsuccessful with that.

答:
Required Answer</p>

```<code>scala> val l = List("abc","abc","cbe","cab")
l: List[String] = List(abc, abc, cbe, cab)

scala> l.groupBy(identity).mapValues(_.size)
res91: scala.collection.immutable.Map[String,Int] = Map(cab -> 1, abc -> 2, cbe -> 1)
</code>```

Title: Scala groupBy for a list

Body:
Required Answer

scala> val l = List("abc","abc","cbe","cab")
l: List[String] = List(abc, abc, cbe, cab)

scala> l.groupBy(identity).mapValues(_.size)
res91: scala.collection.immutable.Map[String,Int] = Map(cab -> 1, abc -> 2, cbe -> 1)


问:
Is it possible to integrate Spring-Security-SAML-Extension to Wicket1.5 application without spring security?
I have two wicket web applications. I want to integrate these two application in SAML based authentication.

Is it possible to integrate Spring SAML extension to Wicket1.5 application without spring security?

答:
Saml extension dependency

Spring saml extension relies on spring security.

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.security.extensions</groupId>
        <artifactId>spring-security-saml2-core</artifactId>
        <version>1.0.2.RELEASE</version>
    </dependency>
</dependencies>
</code>```

Here is the pom.xml of spring-security-saml2-core

```<code><dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
   <version>3.1.2.RELEASE</version>
   <scope>compile</scope>
</dependency>
<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-core</artifactId>
   <version>3.1.2.RELEASE</version>
   <scope>compile</scope>
</dependency>
<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-web</artifactId>
   <version>3.1.2.RELEASE</version>
   <scope>compile</scope>
</dependency>
</code>```

Body:
Saml extension dependency

Spring saml extension relies on spring security.

<dependencies>
    <dependency>
        <groupId>org.springframework.security.extensions</groupId>
        <artifactId>spring-security-saml2-core</artifactId>
        <version>1.0.2.RELEASE</version>
    </dependency>
</dependencies>

Here is the pom.xml of spring-security-saml2-core

<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
   <version>3.1.2.RELEASE</version>
   <scope>compile</scope>
</dependency>
<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-core</artifactId>
   <version>3.1.2.RELEASE</version>
   <scope>compile</scope>
</dependency>
<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-web</artifactId>
   <version>3.1.2.RELEASE</version>
   <scope>compile</scope>
</dependency>


问:
How do I enter data into a form input in an iframe using cypress?
I have been trying to test a stripe checkout form using cypress.io

If anyone has managed to get this to work please let me know. I found a thread on the matter here https://github.com/cypress-io/cypress/issues/136 and based on this I came up with:

```<code>   cy.get('iframe.stripe_checkout_app')
      .wait(10000)
      .then($iframe => {
        const iframe = $iframe.contents()
        const myInput0 = iframe.find('input:eq(0)')
        const myInput1 = iframe.find('input:eq(1)')
        const myInput2 = iframe.find('input:eq(2)')
        const myButton = iframe.find('button')

        cy
          .wrap(myInput0)
          .invoke('val', 4000056655665556)
          .trigger('change')
        cy
          .wrap(myInput1)
          .invoke('val', 112019)
          .trigger('change')

        cy
          .wrap(myInput2)
          .invoke('val', 424)
          .trigger('change')

        cy.wrap(myButton).click({ force: true })
      })
</code>```

But the problem is that the stripe form still does not register the input values. Here is a little gif of what happens http://www.giphy.com/gifs/xT0xeEZ8CmCTVMwOU8. Basically, the form does not register the change input trigger.

Does anyone know how to enter data into a form in an iframe using cypress?

答:
The iframe workflow is still pretty clunky (until this feature is implemented). For now, you can try forcing pretty much every DOM interaction:</p>

```<code>cy.visit("https://jsfiddle.net/1w9jpnxo/1/");
cy.get("iframe").then( $iframe => {

    const $doc = $iframe.contents();
    cy.wrap( $doc.find("#input") ).type( "test", { force: true });
    cy.wrap( $doc.find("#submit") ).click({ force: true });
});
</code>```

Body:
I have been trying to test a stripe checkout form using cypress.io

If anyone has managed to get this to work please let me know. I found a thread on the matter here https://github.com/cypress-io/cypress/issues/136 and based on this I came up with:

   cy.get('iframe.stripe_checkout_app')
      .wait(10000)
      .then($iframe => {
        const iframe = $iframe.contents()
        const myInput0 = iframe.find('input:eq(0)')
        const myInput1 = iframe.find('input:eq(1)')
        const myInput2 = iframe.find('input:eq(2)')
        const myButton = iframe.find('button')

        cy
          .wrap(myInput0)
          .invoke('val', 4000056655665556)
          .trigger('change')
        cy
          .wrap(myInput1)
          .invoke('val', 112019)
          .trigger('change')

        cy
          .wrap(myInput2)
          .invoke('val', 424)
          .trigger('change')

        cy.wrap(myButton).click({ force: true })
      })

But the problem is that the stripe form still does not register the input values. Here is a little gif of what happens http://www.giphy.com/gifs/xT0xeEZ8CmCTVMwOU8. Basically, the form does not register the change input trigger.

Does anyone know how to enter data into a form in an iframe using cypress?

Body:
The iframe workflow is still pretty clunky (until this feature is implemented). For now, you can try forcing pretty much every DOM interaction:

cy.visit("https://jsfiddle.net/1w9jpnxo/1/");
cy.get("iframe").then( $iframe => {

    const $doc = $iframe.contents();
    cy.wrap( $doc.find("#input") ).type( "test", { force: true });
    cy.wrap( $doc.find("#submit") ).click({ force: true });
});


问:
How can i merge the two Array JSON nested responses using NODE JS?
1. First response is categories with two fields, category and name.

```<code>categories = [{ category: '1', name: 'category1' },
              { category: '2', name: 'category2' }]
</code>```

2. Second response is commits with three fields, commit, branch and Commit ID.

```<code> commits = [{ commit: '1', branch: '1', Commit ID: 'commitid1' },
            { commit: '1', branch: '2', Commit ID: 'commitid2' }]
</code>```

3. I want to create one merged JSON, based on the category that would have the following structure:

```<code>all = [
       { category: '1', name: 'category1',
             body: [{ commit: '1', branch: '1', Commit ID: 'commitid1' }],
        { category: '2', name: 'category2',
              body: [{ commit: '1', branch: '1', Commit ID: 'commitid2' }]
</code>```

I searched and found several methods of joining or extending two json objects but nothing similar to that.

Any help would be appreciated.

My Actual Code

```<code>exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
  status: Boolean,
  message: String,
  data: String
};
var request = require('request');
var username =
  const.username;
var password =
  const.password;
var options = {
  url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
  auth: {
    username: username,
    password: password
  }
};

request(options, function(error, obj) {
      if (error) {
        response.message = appmsg.DATA_NT_FOUND;
        response.status = false;
        response.data = obj;
        res.send(response);
      } else {
        response.message = appmsg.DATA_FOUND;
        response.status = true;
        response.data = JSON.parse(obj.body);
        //res.send(response);
        var issueKey = response.data.issues;

        // var keyData = issueKey[0].key;
        // console.log(response.data.issues);
        // console.log(keyData);
        var output = [];
        for (var i = 0; i < issueKey.length; i++) {
          var issue = issueKey[i].key;
          //var key = [];
          //key.push(issue);
          console.log(issue);

          var respon = {
            status: Boolean,
            message: String,
            data: String
          };
          var request = require('request'),
            username =
            const.username,
            password =
            const.username,
            url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
            auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

          //console.log(url);
          request({
            url: url,
            headers: {
              "Authorization": auth
            }
          }, function(err, object) {
            if (object) {

              var info = object;
              output.push(info); // this is not working as ouput is undefined at this    point
              //var pout = JSON.parse(output);
              //console.log(info);
              console.log("==============================================================================");
              //console.log(output);
              console.log("******************************************************************************");
              if (issueKey.length === output.length) {
                respon.message = appmsg.DATA_FOUND;
                respon.status = true;
                respon.data = output;
                //console.log(output);
                //res.send(respon);

                var id = issueKey[0].id;
                console.log(id);

                var commitout = [];
                for (var i = 0; i < issueKey.length; i++) {
                  var commits = issueKey[i].id;
                  console.log(commits);

                  var request = require('request'),
                    username =
                    const.username,
                    password =
                    const.password,
                    url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                  //console.log(url);
                  var test = [];
                  request({
                      url: url,
                      headers: {
                        "Authorization": auth
                      }
                    }, function(err, obj1) {
                      if (obj1) {

                        var info1 = obj1.body;
                        commitout.push(info1);
                        if (issueKey.length === commitout.length) {
                          respon.message = appmsg.DATA_FOUND;
                          respon.status = true;
                          respon.data = commitout;
                          // console.log(commitout);
                          //var test = merge(output, commitout);

                          var resultdone = [];
                          request({
                            url: url,
                            headers: {
                              "Authorization": auth
                            }
                          }, function(err, obj1) {
                            if (obj1) {

                              var info1 = obj1.body;
                              commitout.push(info1);
                              if (issueKey.length === commitout.length) {

                                // console.log(commitout);
                                //var test = merge(output, commitout);
                                //var text = output.body[0];
                                //var resultdone = [];
                                resultdone.push(commitout.concat(output));
                                console.log(resultdone);
                                respon.message = appmsg.DATA_FOUND;
                                respon.status = true;
                                respon.data = resultdone;
                                res.send(respon);
                              }
                            }
                          });
                        }

                      }
                    }

                  });

              }
            }

          });
</code>```

答:
I tested this and it worked:

```<code>var all= categories.map(function(cat,index){
             cat.body=commits[index];
             return cat;
})
</code>```

If you want to have "body" attribute as an array:

```<code>var all= categories.map(function(cat,index){
  var body = [];
  body.push(commits[index]);
             cat["body"] = body;
             return cat;
})

console.log("all :",JSON.stringify(all));
</code>```

Body:
1. First response is categories with two fields, category and name.

categories = [{ category: '1', name: 'category1' },
              { category: '2', name: 'category2' }]

2. Second response is commits with three fields, commit, branch and Commit ID.

 commits = [{ commit: '1', branch: '1', Commit ID: 'commitid1' },
            { commit: '1', branch: '2', Commit ID: 'commitid2' }]

3. I want to create one merged JSON, based on the category that would have the following structure:

all = [
       { category: '1', name: 'category1',
             body: [{ commit: '1', branch: '1', Commit ID: 'commitid1' }],
        { category: '2', name: 'category2',
              body: [{ commit: '1', branch: '1', Commit ID: 'commitid2' }]

I searched and found several methods of joining or extending two json objects but nothing similar to that.

Any help would be appreciated.

My Actual Code

exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
  status: Boolean,
  message: String,
  data: String
};
var request = require('request');
var username =
  const.username;
var password =
  const.password;
var options = {
  url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
  auth: {
    username: username,
    password: password
  }
};

request(options, function(error, obj) {
      if (error) {
        response.message = appmsg.DATA_NT_FOUND;
        response.status = false;
        response.data = obj;
        res.send(response);
      } else {
        response.message = appmsg.DATA_FOUND;
        response.status = true;
        response.data = JSON.parse(obj.body);
        //res.send(response);
        var issueKey = response.data.issues;

        // var keyData = issueKey[0].key;
        // console.log(response.data.issues);
        // console.log(keyData);
        var output = [];
        for (var i = 0; i < issueKey.length; i++) {
          var issue = issueKey[i].key;
          //var key = [];
          //key.push(issue);
          console.log(issue);

          var respon = {
            status: Boolean,
            message: String,
            data: String
          };
          var request = require('request'),
            username =
            const.username,
            password =
            const.username,
            url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
            auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

          //console.log(url);
          request({
            url: url,
            headers: {
              "Authorization": auth
            }
          }, function(err, object) {
            if (object) {

              var info = object;
              output.push(info); // this is not working as ouput is undefined at this    point
              //var pout = JSON.parse(output);
              //console.log(info);
              console.log("==============================================================================");
              //console.log(output);
              console.log("******************************************************************************");
              if (issueKey.length === output.length) {
                respon.message = appmsg.DATA_FOUND;
                respon.status = true;
                respon.data = output;
                //console.log(output);
                //res.send(respon);

                var id = issueKey[0].id;
                console.log(id);

                var commitout = [];
                for (var i = 0; i < issueKey.length; i++) {
                  var commits = issueKey[i].id;
                  console.log(commits);

                  var request = require('request'),
                    username =
                    const.username,
                    password =
                    const.password,
                    url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                  //console.log(url);
                  var test = [];
                  request({
                      url: url,
                      headers: {
                        "Authorization": auth
                      }
                    }, function(err, obj1) {
                      if (obj1) {

                        var info1 = obj1.body;
                        commitout.push(info1);
                        if (issueKey.length === commitout.length) {
                          respon.message = appmsg.DATA_FOUND;
                          respon.status = true;
                          respon.data = commitout;
                          // console.log(commitout);
                          //var test = merge(output, commitout);

                          var resultdone = [];
                          request({
                            url: url,
                            headers: {
                              "Authorization": auth
                            }
                          }, function(err, obj1) {
                            if (obj1) {

                              var info1 = obj1.body;
                              commitout.push(info1);
                              if (issueKey.length === commitout.length) {

                                // console.log(commitout);
                                //var test = merge(output, commitout);
                                //var text = output.body[0];
                                //var resultdone = [];
                                resultdone.push(commitout.concat(output));
                                console.log(resultdone);
                                respon.message = appmsg.DATA_FOUND;
                                respon.status = true;
                                respon.data = resultdone;
                                res.send(respon);
                              }
                            }
                          });
                        }

                      }
                    }

                  });

              }
            }

          });

Body:
I tested this and it worked:

var all= categories.map(function(cat,index){
             cat.body=commits[index];
             return cat;
})

If you want to have "body" attribute as an array:

var all= categories.map(function(cat,index){
  var body = [];
  body.push(commits[index]);
             cat["body"] = body;
             return cat;
})

console.log("all :",JSON.stringify(all));


问:
Interpolating data points in Curve Fitting Tool in Matlab 2017
I have a set of 13 experimental points with X ranging from 0 to 100 in unequal intervals and corresponding values of Y. Using curve fitting tool (Interpolant, PCHIP) I can get a graph and also get values of intermittent points using data cursor. However I need 1000 values spaced at an equal interval of 0.1 from 0 to 100. How can I get these 1000 values from the tool? There used to be an 'evaluate' option in older matlab, but I do not see that in this one. </p>

答:
Found out the option to save the fitted results to workspace. After that it was pretty easy.
x1 = (0:0.1:100).';
y1 = fittedcurve (x1);

Now I feel very stupid.


问:
How to trace and profile all low level calls (c libraries) being used by a mod_perl or a mod_php application?
I've seen once on a site, a call graph digging into the most low level libraries of a web request initiated by a PHP appplication with call timings and summary. Seems to me that this is a great way to spot the reason of bottlenecks that aren't obvious while profiling PHP-only code.

Something like strace does but with far more detail.

答: Rasmus mentioned valgrind a couple times in his presentations.  If I remember correctly it measures IO, memory, etc.  Might want to take a look.</p>

OwnerDisplayName: UnbiasedEntropy

OwnerDisplayName: Allain Lalonde


问:
preg_match to find specific string followed by arbitrary numbers
I have the HTML markup of a web page as $subject. I'm using preg_match to search for a particular string artist_x? and trying to return just the x portion. x can be any number ranging from 1 to 12 digits. So, the pattern would have to match any/all of the following:

```<code>artist_1?
artist_12345?
artist_123456789012?
</code>```

...and bring back:

```<code>1
12345
123456789012
</code>```

...respectively.

This is the closest I can come up with:

```<code>$pattern = '|[artist_][0-9]{1,12}|';
preg_match($pattern, $subject, $matches);
</code>```

But it's not working right... It's finding the string I'm looking for and even returning the expected number, but the returned number still has the underscore prepended. I've tried quite a few solutions to get this far, but am out of ideas.

Thanks!

答:
I don't really understand what your pattern is supposed to do.
Anyway, this should work: you just capture the number that interest you. $matches will be an array containing first the whole match and then the group. So the first group will be what you want.

```<code>$subject = "artist_3333";
$pattern = '/artist_(\d{1,12})/';
preg_match($pattern, $subject, $matches);
echo($matches[1]); // 3333
</code>```

\d in here means the same thing as [0-9], it matches digits

Body:
I have the HTML markup of a web page as $subject. I'm using preg_match to search for a particular string artist_x? and trying to return just the x portion. x can be any number ranging from 1 to 12 digits. So, the pattern would have to match any/all of the following:

artist_1?
artist_12345?
artist_123456789012?

...and bring back:

1
12345
123456789012

...respectively.

This is the closest I can come up with:

$pattern = '|[artist_][0-9]{1,12}|';
preg_match($pattern, $subject, $matches);

But it's not working right... It's finding the string I'm looking for and even returning the expected number, but the returned number still has the underscore prepended. I've tried quite a few solutions to get this far, but am out of ideas.

Thanks!

Body:
I don't really understand what your pattern is supposed to do.
Anyway, this should work: you just capture the number that interest you. $matches will be an array containing first the whole match and then the group. So the first group will be what you want.

$subject = "artist_3333";
$pattern = '/artist_(\d{1,12})/';
preg_match($pattern, $subject, $matches);
echo($matches[1]); // 3333

\d in here means the same thing as [0-9], it matches digits


问:
7-digit Julian Date to Normal Calendar Date
How do I convert a 7-digit Julian Date (2016092) to a regular Calendar date (MM-DD-YYYY)?

I was thinking of taking the last three digits and converting it to a regular date then appending the first four digits as the year but I'd have to consider leap years.

Expected output: 04-01-2016

My current (SQL) code which solves the problem is

```<code>DECLARE @dt char(7)
SET @dt = 2016092

SELECT DATEADD(dd, CAST(RIGHT(@dt, 3) AS int) - 1, CAST(LEFT(@dt, 4) AS datetime))
</code>```

How can I implement it on C#?

答:
You don't have any kind of Julian Day (Date) format which is

https://en.wikipedia.org/wiki/Julian_day

But a kind of custom format which can be reconstructed from the sql provided:

```<code>  year * 1000 + days from 1st Jan + 1
</code>```

So 2016092 means year 2016 and 092 - 1 = 91st day from the 1st of Jan (1st of Apr)

Implementation:

```<code>int source = 2016092;
DateTime result = new DateTime(source / 1000, 1, 1).AddDays(source % 1000 - 1);

Console.WriteLine($"{result:MM-dd-yyyy}");
</code>```

Outcome:

```<code>04-01-2016
</code>```

Body:
How do I convert a 7-digit Julian Date (2016092) to a regular Calendar date (MM-DD-YYYY)?

I was thinking of taking the last three digits and converting it to a regular date then appending the first four digits as the year but I'd have to consider leap years.

Expected output: 04-01-2016

My current (SQL) code which solves the problem is

DECLARE @dt char(7)
SET @dt = 2016092

SELECT DATEADD(dd, CAST(RIGHT(@dt, 3) AS int) - 1, CAST(LEFT(@dt, 4) AS datetime))

How can I implement it on C#?

Body:
You don't have any kind of Julian Day (Date) format which is

https://en.wikipedia.org/wiki/Julian_day

But a kind of custom format which can be reconstructed from the sql provided:

  year * 1000 + days from 1st Jan + 1

So 2016092 means year 2016 and 092 - 1 = 91st day from the 1st of Jan (1st of Apr)

Implementation:

int source = 2016092;
DateTime result = new DateTime(source / 1000, 1, 1).AddDays(source % 1000 - 1);

Console.WriteLine($"{result:MM-dd-yyyy}");

Outcome:

04-01-2016


问:
Eclipse won't start after Java update
I updated Java and now Eclipse won't start, it says Java was started but returned exit code = 13. Eclipse was working just fine until this update. Does anyone know what to do? </p>

答: re-install java jdk to solve the problem</p>

Title: Eclipse won't start after Java update


问:
Facebook chat can't work in Smack API with Android
I am developing chat client for my app. Now I am testing it on Gtalk, Facebook, Yahoo. I am using Smack api for that. I am now successfully tested it on Gtalk. But in case of Facebook I got error:

```<code> 01-13 10:53:05.938: INFO/XMPPClient(389): [SettingsDialog] Connected to chat.facebook.com
01-13 10:53:07.178: ERROR/XMPPClient(389): [SettingsDialog] Failed to log in as chikka0305@chat.facebook.com
01-13 10:53:07.178: ERROR/XMPPClient(389): SASL authentication failed using mechanism DIGEST-MD5:
</code>```

As you can see I can connect but can't login. I already saw same question here: http://stackoverflow.com/questions/3750547/facing-problem-using-smack-on-android but answer of that doesn't work for me.

答:
i got my problem.it si perfectly work with asmack-issue 15.jar.and you have to set:  connConfig.setSASLAuthenticationEnabled(true);

and you have to set write username only without @chat.facebook.com

Body:
I am developing chat client for my app. Now I am testing it on Gtalk, Facebook, Yahoo. I am using Smack api for that. I am now successfully tested it on Gtalk. But in case of Facebook I got error:

 01-13 10:53:05.938: INFO/XMPPClient(389): [SettingsDialog] Connected to chat.facebook.com
01-13 10:53:07.178: ERROR/XMPPClient(389): [SettingsDialog] Failed to log in as chikka0305@chat.facebook.com
01-13 10:53:07.178: ERROR/XMPPClient(389): SASL authentication failed using mechanism DIGEST-MD5:

As you can see I can connect but can't login. I already saw same question here: http://stackoverflow.com/questions/3750547/facing-problem-using-smack-on-android but answer of that doesn't work for me.


问:
How to force position fixed when parent container has a transformation?
I need to apply position fixed to the viewport of a child div inside a parent which has a transformation applied.
Unfortunately I cannot remove the transformation on the parent.

Any ideas how to overrides this behavior?

Can I use transform on the child element to make it looks similar to position fixed?

.rotate {
  transform: rotate(30deg);
  background: blue;
   width: 300px;
  height: 300px;
  margin: 0 auto;

}
.fixed {
  position: fixed;
  background: red;
padding: 10px;
color: white;
 top: 50px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <html>
  <body>
<div class="rotate">
<div class="fixed"> I am fixed inside a rotated div.</div>
</div>
  <div class="fixed"> I am fixed outside a rotated div.</div>
</body>
</html></code>```

答:
The Answer is simple this is not possible with CSS. Visit the following question for details

Positions fixed doesn't work when using -webkit-transform

'transform3d' not working with position: fixed children

But you can achieve your target with js here is a basic example.

$(window).scroll(function() {
    $(".transform-fixed").css({
        "top": $(window).scrollTop()
    });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.rotate {
  transform: rotate(30deg);
  background: blue;
   width: 300px;
  height: 300px;
  margin: 0 auto;

}
.fixed {
  position: fixed;
  background: red;
  padding: 10px;
  color: white;
  top: 50px;
}</code>```

 I am fixed inside a rotated div.

 I am fixed outside a rotated div.

```

Body:
I need to apply position fixed to the viewport of a child div inside a parent which has a transformation applied.
Unfortunately I cannot remove the transformation on the parent.

Any ideas how to overrides this behavior?

Can I use transform on the child element to make it looks similar to position fixed?

.rotate {
  transform: rotate(30deg);
  background: blue;
   width: 300px;
  height: 300px;
  margin: 0 auto;

}
.fixed {
  position: fixed;
  background: red;
padding: 10px;
color: white;
 top: 50px;
  }

 I am fixed inside a rotated div.

 I am fixed outside a rotated div.

Body:
The Answer is simple this is not possible with CSS. Visit the following question for details

Positions fixed doesn't work when using -webkit-transform

'transform3d' not working with position: fixed children

But you can achieve your target with js here is a basic example.

$(window).scroll(function() {
    $(".transform-fixed").css({
        "top": $(window).scrollTop()
    });
})

.rotate {
  transform: rotate(30deg);
  background: blue;
   width: 300px;
  height: 300px;
  margin: 0 auto;

}
.fixed {
  position: fixed;
  background: red;
  padding: 10px;
  color: white;
  top: 50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <div class="rotate">
    <div class="fixed transform-fixed"> I am fixed inside a rotated div.</div>
  </div>
  <div class="fixed"> I am fixed outside a rotated div.</div>
</body>

</html>


问:
Radio button styles not getting changed
I'm trying to implement custom styles for radio buttons.

I've almost achieved it but issue is when i try to click on other radio button it is not getting highlighted.

I'm struck here please help.

.radio-radio-wrapper {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-radio-wrapper input[type='radio'] {
  display: none;
}

.radio-radio-wrapper label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
  cursor: pointer;
}

.radio-radio-wrapper input[type=radio]:checked+span>label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 4px;
  left: 4px;
  content: " ";
  display: block;
  background: #004c97;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div _ngcontent-c9="" class="col-lg-12 radioBlock">
  <span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Capacity" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio1">Capacity & Partial Service</label></span>
  </span><span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Prod" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio1">Full Network Service (No Capacity)</label></span>
  </span>
</div></code>```

答:
You forgot the unique id's. Both id's are radio1. You should set it to radio1 and radio2 and so on.

And don't forget the labels for property to link to the correct input field. See below.

.radio-radio-wrapper {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-radio-wrapper input[type='radio'] {
  display: none;
}

.radio-radio-wrapper label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
  cursor: pointer;
}

.radio-radio-wrapper input[type=radio]:checked+span>label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 4px;
  left: 4px;
  content: " ";
  display: block;
  background: #004c97;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div _ngcontent-c9="" class="col-lg-12 radioBlock">
  <span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Capacity" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio1">Capacity & Partial Service</label></span>
  </span><span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio2" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Prod" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio2">Full Network Service (No Capacity)</label></span>
  </span>
</div></code>```

Title: Radio button styles not getting changed

Body:
I'm trying to implement custom styles for radio buttons.

I've almost achieved it but issue is when i try to click on other radio button it is not getting highlighted.

I'm struck here please help.

.radio-radio-wrapper {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-radio-wrapper input[type='radio'] {
  display: none;
}

.radio-radio-wrapper label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
  cursor: pointer;
}

.radio-radio-wrapper input[type=radio]:checked+span>label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 4px;
  left: 4px;
  content: " ";
  display: block;
  background: #004c97;
}

            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Capacity" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            Capacity & Partial Service

            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Prod" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            Full Network Service (No Capacity)

Body:
You forgot the unique id's. Both id's are radio1. You should set it to radio1 and radio2 and so on.

And don't forget the labels for property to link to the correct input field. See below.

.radio-radio-wrapper {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-radio-wrapper input[type='radio'] {
  display: none;
}

.radio-radio-wrapper label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
  cursor: pointer;
}

.radio-radio-wrapper input[type=radio]:checked+span>label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 4px;
  left: 4px;
  content: " ";
  display: block;
  background: #004c97;
}

<div _ngcontent-c9="" class="col-lg-12 radioBlock">
  <span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Capacity" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio1">Capacity &amp; Partial Service</label></span>
  </span><span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio2" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Prod" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio2">Full Network Service (No Capacity)</label></span>
  </span>
</div>


问:
Why are only final variables accessible in anonymous class?

a can only be final here.  Why?  How can I reassign a in onClick() method without keeping it as private member?

```<code>private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5;

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

How can I return the 5 * a when it clicked? I mean,

```<code>private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void
        }
    });
}
</code>```

答:
An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.

I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.

(Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)

Body:
a can only be final here.  Why?  How can I reassign a in onClick() method without keeping it as private member?

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5;

        }
    });
}

How can I return the 5 * a when it clicked? I mean,

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void
        }
    });
}


问:
Add filename as column on import to BigQuery?
This is a question about importing data files from Google Cloud Storage to BigQuery.

I have a number of JSON files that follow a strict naming convention to include some key data not included in the JSON data itself.

For example:

```<code>xxx_US_20170101.json.gz
xxx_GB_20170101.json.gz
xxx_DE_20170101.json.gz
</code>```

Which is client_country_date.json.gz At the moment, I have some convoluted processes in a Ruby app that reads the files, appends the additional data and then writes it back to a file that is then imported into a single daily table for the client in BigQuery.

I am wondering if it is possible to grab and parse the filename as part of the import to BigQuery? I could then drop the convoluted Ruby processes which occasionally fail on larger files.

答:
You could define an external table pointing to your files:

Note that the table type is "external table", and that it points to multiple files with the * glob.

Now you can query for all data in these files, and query for the meta-column _FILE_NAME:

```<code>#standardSQL
SELECT *, _FILE_NAME filename
FROM `project.dataset.table`
</code>```

You can now save these results to a new native table.

Body:
This is a question about importing data files from Google Cloud Storage to BigQuery.

I have a number of JSON files that follow a strict naming convention to include some key data not included in the JSON data itself.

For example:

xxx_US_20170101.json.gz
xxx_GB_20170101.json.gz
xxx_DE_20170101.json.gz

Which is client_country_date.json.gz At the moment, I have some convoluted processes in a Ruby app that reads the files, appends the additional data and then writes it back to a file that is then imported into a single daily table for the client in BigQuery.

I am wondering if it is possible to grab and parse the filename as part of the import to BigQuery? I could then drop the convoluted Ruby processes which occasionally fail on larger files.

Body:
You could define an external table pointing to your files:

Note that the table type is "external table", and that it points to multiple files with the * glob.

Now you can query for all data in these files, and query for the meta-column _FILE_NAME:

#standardSQL
SELECT *, _FILE_NAME filename
FROM `project.dataset.table`

You can now save these results to a new native table.


问:
VideoTexture is not playing in VR
At first the texture works fine and the video plays as expected, but when VR is entered via VRDisplay.requestPresent it stops. Why is this and how to fix it?

答:
The VR display has its own render loop. Usually needsUpdate is automatically set to true on every animation frame by three.js, but this is only true for the default display.

To fix this, get the VR display from the vrdisplayconnect event and create your own update loop. E.g.

```<code>let display = e.display;
</code>```

```<code>let displayUpdateLoop = () =>
{
    // May get a warning if getFrameData is not called.
    let frameData = new VRFrameData();
    display.getFrameData(frameData);

    videoTexture.needsUpdate = true;

    // Stop loop if no longer presenting.
    if (display.isPresenting)
        display.requestAnimationFrame(displayUpdateLoop);
}
display.requestAnimationFrame(displayUpdateLoop);
</code>```

Title: VideoTexture is not playing in VR

Body:
The VR display has its own render loop. Usually needsUpdate is automatically set to true on every animation frame by three.js, but this is only true for the default display.

To fix this, get the VR display from the vrdisplayconnect event and create your own update loop. E.g.

let display = e.display;

let displayUpdateLoop = () =>
{
    // May get a warning if getFrameData is not called.
    let frameData = new VRFrameData();
    display.getFrameData(frameData);

    videoTexture.needsUpdate = true;

    // Stop loop if no longer presenting.
    if (display.isPresenting)
        display.requestAnimationFrame(displayUpdateLoop);
}
display.requestAnimationFrame(displayUpdateLoop);