问:
How can I avoid global state?
So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests.  I believe it--my code is difficult to test right now.  So how do I avoid global state?

The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments.  For example, I have a static class named "Globals" with a static member called "DBConnectionString."  When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString.  I load file paths, server names, and other information in the Globals class.

Some of my functions rely on the global variables.  So, when I test my functions, I have to remember to set certain globals first or else the tests will fail.  I'd like to avoid this.

Is there a good way to manage state information?  (Or am I understanding global state incorrectly?)

答:
Great first question.

The short answer: make sure your application is a function from ALL its inputs (including implicit ones) to its outputs.

The problem you're describing doesn't seem like global state. At least not mutable state. Rather, what you're describing seems like what is often referred to as "The Configuration Problem", and it has a number of solutions. If you're using Java, you may want to look into light-weight injection frameworks like Guice. In Scala, this is usually solved with implicits. In some languages, you will be able to load another program to configure your program at runtime. This is how we used to configure servers written in Smalltalk, and I use a window manager written in Haskell called Xmonad whose configuration file is just another Haskell program.

OwnerDisplayName: Jim

Title: How can I avoid global state?

OwnerDisplayName: Apocalisp


来源: stackexchange

问:
Collections.max function for iterable<Integer> in java
The Java Collections.max takes only a collection of a sortable object. However since the collection is not necessarily sorted, I don't see any reason not to implement the same max function for iterable types.

Is there a max method for Iterable<T extends Comparable<? super T>> in java's standard library?

答:
Collections.max was introduced in 1.2. Iterable was introduced in 1.5.

It's rare to have an Iterable that is not a Collection. If you do then it's straightforward to implement (be careful to read the spec). If you think it is really important you can submit an RFE on bugs.sun.com (or vote if there is already one there).

OwnerDisplayName: Elazar Leibovich

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mmyers

OwnerDisplayName: Tom Hawtin - tackline


问:
how can i make a button on click move a div?
I created a div that I only want to be seen when a button is pressed to I positioned the div with a margin of -600 then when the button is pressed, it moves the div to margin: 0.

Here is the HTML for the div and button:

```<code><div id="mobile">
    <hr id="line">
    <ul id="listMobile">
        <li class="smallList"><span style="color:#ffe700">Home</span>
        </li>
        <li class="smallList">
            Gallery
        </li>
        <li class="smallList">
            Order Form
        </li>
        <li class="smallList">
            The Arena
        </li>
        <li class="smallList">
            Contact Us
        </li>
    </ul>

</div>

<button id="slideButton" onClick="toggleMenu();">
    <hr class="slider">
    <hr class="slider">
    <hr class="slider">
</button>
</code>```

Here is the JavaScript (I'm still a beginner with JavaScript so go easy on me):

```<code>function toggleMenu () {
    if (document.getElementById("mobile").style.left == "0px") {
        document.getElementById("mobile").style.left = "-630px";
    } else {
        document.getElementById("mobile").style.left = "0px";
    }
}
</code>```

Here is my CSS:

```<code>#mobile {
  margin:           0;
  margin-top:       0px;
  width:            250px;
  height:           1000px;
  background-color: #333333;
  margin-left:      -600px;
  position:         absolute;
  z-index:          -5;
}

.slider {
  border: none;
  background-color: white;
  height:           3px;
  width:            45px;
  margin-top:       10px;
  border-radius:    15px;
}

#slideButton {
  background-color: rgba(255, 255, 255, 0);
  border:           0;
  margin-top:       12px;
  margin-left:      15px;
  padding-right:    7px;
  padding-top:      7px;
  position:         fixed;
  border-radius:    5px;
  padding-left:     18px;
  visibility:       hidden;
}

#slideButton:focus {
  outline: none;
}

#slideButton:hover {
  background-color: rgba(100,100,100,0.1);
  transition:       ease 0.6s;
}

#listMobile {
  margin-top: 100px;
}

.smallList {
  display:        block;
  padding-top:    15px;
  padding-bottom: 15px;
  padding-left:   0px;
  font-size:      45px;
}
</code>```

Can anyone explain why this is not working? Thanks!

答:
Use marginLeft instead of left in your script:

function toggleMenu() {

  if (document.getElementById("mobile").style.marginLeft == "0px") {
    document.getElementById("mobile").style.marginLeft = "-630px"

  } else {
    document.getElementById("mobile").style.marginLeft = "0px"
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#mobile {
  margin: 0;
  margin-top: 0px;
  width: 250px;
  height: 1000px;
  background-color: #333333;
  margin-left: -600px;
  position: absolute;
  z-index: -5;
}

.slider {
  border: none;
  background-color: white;
  height: 3px;
  width: 45px;
  margin-top: 10px;
  border-radius: 15px;
}

#slideButton {
  margin-top: 12px;
  margin-left: 15px;
  padding-right: 7px;
  padding-top: 7px;
  position: fixed;
  border-radius: 5px;
  padding-left: 18px;
}

#slideButton:focus {
  outline: none;
}

#slideButton:hover {
  background-color: rgba(100, 100, 100, 0.1);
  transition: ease 0.6s;
}

#listMobile {
  margin-top: 100px;
}

.smallList {
  display: block;
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 0px;
  font-size: 45px;
}</code>```

           Home

      Gallery

      Order Form

      The Arena

      Contact Us

<button id="slideButton" onClick="toggleMenu()">

       </button>```

ContentLicense: CC BY-SA 3.0

Body:
I created a div that I only want to be seen when a button is pressed to I positioned the div with a margin of -600 then when the button is pressed, it moves the div to margin: 0.

Here is the HTML for the div and button:

Home

            Gallery

            Order Form

            The Arena

            Contact Us

<button id="slideButton" onClick="toggleMenu();">

</button>

Here is the JavaScript (I'm still a beginner with JavaScript so go easy on me):

function toggleMenu () {
    if (document.getElementById("mobile").style.left == "0px") {
        document.getElementById("mobile").style.left = "-630px";
    } else {
        document.getElementById("mobile").style.left = "0px";
    }
}

Here is my CSS:

#mobile {
  margin:           0;
  margin-top:       0px;
  width:            250px;
  height:           1000px;
  background-color: #333333;
  margin-left:      -600px;
  position:         absolute;
  z-index:          -5;
}

.slider {
  border: none;
  background-color: white;
  height:           3px;
  width:            45px;
  margin-top:       10px;
  border-radius:    15px;
}

#slideButton {
  background-color: rgba(255, 255, 255, 0);
  border:           0;
  margin-top:       12px;
  margin-left:      15px;
  padding-right:    7px;
  padding-top:      7px;
  position:         fixed;
  border-radius:    5px;
  padding-left:     18px;
  visibility:       hidden;
}

#slideButton:focus {
  outline: none;
}

#slideButton:hover {
  background-color: rgba(100,100,100,0.1);
  transition:       ease 0.6s;
}

#listMobile {
  margin-top: 100px;
}

.smallList {
  display:        block;
  padding-top:    15px;
  padding-bottom: 15px;
  padding-left:   0px;
  font-size:      45px;
}

Can anyone explain why this is not working? Thanks!

Body:
Use marginLeft instead of left in your script:

function toggleMenu() {

  if (document.getElementById("mobile").style.marginLeft == "0px") {
    document.getElementById("mobile").style.marginLeft = "-630px"

  } else {
    document.getElementById("mobile").style.marginLeft = "0px"
  }
}

#mobile {
  margin: 0;
  margin-top: 0px;
  width: 250px;
  height: 1000px;
  background-color: #333333;
  margin-left: -600px;
  position: absolute;
  z-index: -5;
}

.slider {
  border: none;
  background-color: white;
  height: 3px;
  width: 45px;
  margin-top: 10px;
  border-radius: 15px;
}

#slideButton {
  margin-top: 12px;
  margin-left: 15px;
  padding-right: 7px;
  padding-top: 7px;
  position: fixed;
  border-radius: 5px;
  padding-left: 18px;
}

#slideButton:focus {
  outline: none;
}

#slideButton:hover {
  background-color: rgba(100, 100, 100, 0.1);
  transition: ease 0.6s;
}

#listMobile {
  margin-top: 100px;
}

.smallList {
  display: block;
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 0px;
  font-size: 45px;
}

<div id="mobile">
  <hr id="line">
  <ul id="listMobile">
    <li class="smallList"><span style="color:#ffe700">
           Home</span>
    </li>
    <li class="smallList">
      Gallery
    </li>
    <li class="smallList">
      Order Form
    </li>
    <li class="smallList">
      The Arena
    </li>
    <li class="smallList">
      Contact Us
    </li>
  </ul>

</div>

<button id="slideButton" onClick="toggleMenu()">
          <hr class="slider">
          <hr class="slider">
          <hr class="slider">
       </button>


问:
Transpose groups of columns to rows
I have a large dataset with more than 600 columns. an extract looks like this:

```<code>  category q151_a34 q151_a35 q151_a36 q151_a37 q152_a34 q152_a35 q152_a36 q152_a37
1 men      2         12      37       24       0        7        19       23
2 women    3         10      23       19       2        4        29       16
</code>```

Now I want to convert/transpose it to the following structure:

```<code>  category  var     a34 a35 a36 a37
1 men       q151    2   12   37  24
2 men       q152    0   7    19  23
3 women     q151    3   10   23  19
4 women     q152    2   4    29  16
</code>```

I found a two step solution:
step 1: spliting variables

```<code>get.first<- function(x) sapply(strsplit(x, "\\_"), `[[`, 1)
data<- within(data, var<- get.first(as.character(variable)))
get.second <- function(x) sapply(strsplit(x, "\\_"), `[[`, 2)
data<- within(data, answer<- get.first(as.character(variable)))
</code>```

step 2: transposing

```<code>freqTest <- dcast(data, category + var~ idAnswer, value.var = "value")
</code>```

Is there a nicer/more performant way?

Many thanks

答:
You can use tidyr from the tidyverse group of packages for this:

```<code># install.packages('tidyverse')

library(tidyverse)

# Data

dff <- structure(list(category = structure(1:2, .Label = c("men", "women" ), class = "factor"), q151_a34 = 2:3, q151_a35 = c(12L, 10L),
    q151_a36 = c(37L, 23L), q151_a37 = c(24L, 19L), q152_a34 = c(0L,
    2L), q152_a35 = c(7L, 4L), q152_a36 = c(19L, 29L), q152_a37 = c(23L,
    16L)), .Names = c("category", "q151_a34", "q151_a35", "q151_a36",  "q151_a37", "q152_a34", "q152_a35", "q152_a36", "q152_a37"), class = "data.frame", row.names = c(NA,
-2L))

# Code

gather(dff, key=Qs, value = values, q151_a34:q152_a37) %>%
    separate(Qs, into = c('var','A')) %>%
    spread(A, values)

# Output

  category  var a34 a35 a36 a37
1      men q151   2  12  37  24
2      men q152   0   7  19  23
3    women q151   3  10  23  19
4    women q152   2   4  29  16
</code>```

Essentially, you first need to move the column names into rows with the help of the gather function, and then use the separate function to separate the values by the underscore. This will put both values starting with q in one column while putting those values starting with a in another column. From here, the next step is to put back the values starting with a as your column names, with the help of the spread function. Combined, these steps should get to your desired output.

Edit:

If you don't want to deal with getting the names of the columns you are looking to move into rows, then you can try using the following:

```<code>gather(dff, key=Qs, value = values, -category) %>%
    separate(Qs, into = c('var','A')) %>%
    spread(A, values)
</code>```

This is exactly the same as the previous solution, with the only difference being that you are only concerning yourself with the column you wish to have remain a column. Essentially, this brings down everything but the column name category.

I hope this helps.

Title: Transpose groups of columns to rows

Body:
I have a large dataset with more than 600 columns. an extract looks like this:

  category q151_a34 q151_a35 q151_a36 q151_a37 q152_a34 q152_a35 q152_a36 q152_a37
1 men      2         12      37       24       0        7        19       23
2 women    3         10      23       19       2        4        29       16

Now I want to convert/transpose it to the following structure:

  category  var     a34 a35 a36 a37
1 men       q151    2   12   37  24
2 men       q152    0   7    19  23
3 women     q151    3   10   23  19
4 women     q152    2   4    29  16

I found a two step solution:
step 1: spliting variables

get.first<- function(x) sapply(strsplit(x, "\\_"), `[[`, 1)
data<- within(data, var<- get.first(as.character(variable)))
get.second <- function(x) sapply(strsplit(x, "\\_"), `[[`, 2)
data<- within(data, answer<- get.first(as.character(variable)))

step 2: transposing

freqTest <- dcast(data, category + var~ idAnswer, value.var = "value")

Is there a nicer/more performant way?

Many thanks

Body:
You can use tidyr from the tidyverse group of packages for this:

# install.packages('tidyverse')

library(tidyverse)

# Data

dff <- structure(list(category = structure(1:2, .Label = c("men", "women" ), class = "factor"), q151_a34 = 2:3, q151_a35 = c(12L, 10L),
    q151_a36 = c(37L, 23L), q151_a37 = c(24L, 19L), q152_a34 = c(0L,
    2L), q152_a35 = c(7L, 4L), q152_a36 = c(19L, 29L), q152_a37 = c(23L,
    16L)), .Names = c("category", "q151_a34", "q151_a35", "q151_a36",  "q151_a37", "q152_a34", "q152_a35", "q152_a36", "q152_a37"), class = "data.frame", row.names = c(NA,
-2L))

# Code

gather(dff, key=Qs, value = values, q151_a34:q152_a37) %>%
    separate(Qs, into = c('var','A')) %>%
    spread(A, values)

# Output

  category  var a34 a35 a36 a37
1      men q151   2  12  37  24
2      men q152   0   7  19  23
3    women q151   3  10  23  19
4    women q152   2   4  29  16

Essentially, you first need to move the column names into rows with the help of the gather function, and then use the separate function to separate the values by the underscore. This will put both values starting with q in one column while putting those values starting with a in another column. From here, the next step is to put back the values starting with a as your column names, with the help of the spread function. Combined, these steps should get to your desired output.

Edit:

If you don't want to deal with getting the names of the columns you are looking to move into rows, then you can try using the following:

gather(dff, key=Qs, value = values, -category) %>%
    separate(Qs, into = c('var','A')) %>%
    spread(A, values)

This is exactly the same as the previous solution, with the only difference being that you are only concerning yourself with the column you wish to have remain a column. Essentially, this brings down everything but the column name category.

I hope this helps.


问:
How to encrypt my existing RDS Instance using Boto3?
I want to encrypt my existing rds instance.I am using the Boto Script to modify db instance.

```<code>modified_rds_attributes = rds_conn_boto3.modify_db_instance(
    DBInstanceIdentifier=id,
    StorageEncrypted=True
)
</code>```

Is it possible to encrypt existing RDS DB Instance?
If Yes,then how can I acheive the task?

答:
I agree that "A non encrypted instance cannot be converted to an encrypted one." However , I disagree that there is one way to do the mission.

Another way is to :

take a snapshot from the unencrypted instance.

copy the snapshot by specifying a Key Management System (KMS) encryption key

then restore a new encrypted instance from snapshot

__

Reference https://aws.amazon.com/blogs/aws/amazon-rds-update-share-encrypted-snapshots-encrypt-existing-instances/

ContentLicense: CC BY-SA 4.0

Body:
I want to encrypt my existing rds instance.I am using the Boto Script to modify db instance.

modified_rds_attributes = rds_conn_boto3.modify_db_instance(
    DBInstanceIdentifier=id,
    StorageEncrypted=True
)

Is it possible to encrypt existing RDS DB Instance?
If Yes,then how can I acheive the task?


问:
Plivo getting UUID of call recording
I'm using the following code to dial out and record the call.

```<code><Response>
<Record action="http://foo.com/get_recording/" startOnDialAnswer="true" redirect="false" />
<Dial>
    <Number>15551234567</Number>
</Dial>
</code>```

However, the action url http://foo.com/get_recording/ receives only the following parameters, which does not include the UUID of the call. So I do not know which uuid does the call recording file belong to.

```<code>callbackUrl Request Parameters
</code>```

The following parameters are sent to the callbackUrl

```<code>Parameter   Description
RecordUrl   Complete path to the recorded file URL.
RecordingDuration   Duration of recording in seconds.
RecordingDurationMs Duration of recording in milliseconds.
RecordingStartMs    When the recording started (epoch time UTC) in milliseconds.
RecordingEndMs  When the recording ended (epoch time UTC) in milliseconds.
RecordingID Recording ID of the file.
</code>```

Any help on associating uuid with record_id would be appreciated. Tried writing to support but still awaiting an answer.

答:
A simple trick!

Before you return the Dial XML, try capturing the callUUID in the request param you receive and append it with record action URL like a GET param dynamically. make your action method as GET

```<code><Response>
<Record action="http://foo.com/get_recording/?callUUID=<uuid>" startOnDialAnswer="true" redirect="false" />
<Dial>
    <Number>15551234567</Number>
</Dial>
</code>```

Title: Plivo getting UUID of call recording

Body:
I'm using the following code to dial out and record the call.

<Response>
<Record action="http://foo.com/get_recording/" startOnDialAnswer="true" redirect="false" />
<Dial>
    <Number>15551234567</Number>
</Dial>

However, the action url http://foo.com/get_recording/ receives only the following parameters, which does not include the UUID of the call. So I do not know which uuid does the call recording file belong to.

callbackUrl Request Parameters

The following parameters are sent to the callbackUrl

Parameter   Description
RecordUrl   Complete path to the recorded file URL.
RecordingDuration   Duration of recording in seconds.
RecordingDurationMs Duration of recording in milliseconds.
RecordingStartMs    When the recording started (epoch time UTC) in milliseconds.
RecordingEndMs  When the recording ended (epoch time UTC) in milliseconds.
RecordingID Recording ID of the file.

Any help on associating uuid with record_id would be appreciated. Tried writing to support but still awaiting an answer.

Body:
A simple trick!

Before you return the Dial XML, try capturing the callUUID in the request param you receive and append it with record action URL like a GET param dynamically. make your action method as GET

<Response>
<Record action="http://foo.com/get_recording/?callUUID=<uuid>" startOnDialAnswer="true" redirect="false" />
<Dial>
    <Number>15551234567</Number>
</Dial>


问:
php 'ISSET' function not working. OR the code skips my if statements
The not working and i get the same error output as defined in the last else statement.

I am new to Php, please help me out. What am I doing wrong?

HERE IS THE CODE

```<code><form action="imagespace.php?groupid=<?php echo $_GET['groupid'] ;?>" method = "POST">
<input type="button" name="Up-Vote" value ="Up-Vote" class="up-votes" />
<input type="button" name="Down-Vote" value="Down-Vote" class="down-votes" />
</form>
<?php

$emailid=$_SESSION['emailid'];
$groupid = $_GET['groupid'];
$emailid = mysqli_real_escape_string($con,$emailid);
$groupid = mysqli_real_escape_string($con,$emailid);

if(isset($_POST['Up-Vote']))
    { echo ' trial';
    $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '1') ";
    $query_run = mysqli_query($con,$query);
    if($query_run)
    {echo 'upvoted';}
    }

else if(isset($_POST['Down-Vote']))
    {
        $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '0') ";
        $query_run = mysqli_query($con,$query);
        if($query_run)
        {echo 'downvoted';}
    }
else{
echo 'error' ;
}
}
?>

</body>
</html>
</code>```

答: The extra submit button isn't needed, the <button>s act same in default type.

Body:
The not working and i get the same error output as defined in the last else statement.

I am new to Php, please help me out. What am I doing wrong?

HERE IS THE CODE

<form action="imagespace.php?groupid=<?php echo $_GET['groupid'] ;?>" method = "POST">
<input type="button" name="Up-Vote" value ="Up-Vote" class="up-votes" />
<input type="button" name="Down-Vote" value="Down-Vote" class="down-votes" />
</form>
<?php

$emailid=$_SESSION['emailid'];
$groupid = $_GET['groupid'];
$emailid = mysqli_real_escape_string($con,$emailid);
$groupid = mysqli_real_escape_string($con,$emailid);

if(isset($_POST['Up-Vote']))
    { echo ' trial';
    $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '1') ";
    $query_run = mysqli_query($con,$query);
    if($query_run)
    {echo 'upvoted';}
    }

else if(isset($_POST['Down-Vote']))
    {
        $query = "INSERT into VOTES (emailid, groupid, vote) values ('$emailid','$groupid', '0') ";
        $query_run = mysqli_query($con,$query);
        if($query_run)
        {echo 'downvoted';}
    }
else{
echo 'error' ;
}
}
?>


问:
Hibernate throws HibernateQueryException: could not resolve property
So I have a table that I've defined as an entity in hibernate like this:

```<code>@Entity
@Table(name = "sec_Preference")
public class Preference {
private long id;

@Column(name = "PreferenceId", nullable = false, insertable = true, updatable = true, length = 19, precision = 0)
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
public long getId() {
    return id;
}

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

private long systemuserid;

@Column(name = "SystemUserId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSystemUserId() {
    return systemuserid;
}

public void setSystemUserId(long systemuserid) {
    this.systemuserid = systemuserid;
}

private long dbgroupid;

@Column(name = "DBGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getDBGroupId() {
    return dbgroupid;
}

public void setDBGroupId(long dbgroupid) {
    this.dbgroupid = dbgroupid;
}

private long externalgroupid;

@Column(name = "ExternalGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getExternalGroupId() {
    return externalgroupid;
}

public void setExternalGroupId(long externalgroupid) {
    this.externalgroupid = externalgroupid;
}

private long securityroleid;

@Column(name = "SecurityRoleId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSecurityRoleId() {
    return securityroleid;
}

public void setSecurityRoleId(long securityroleid) {
    this.securityroleid = securityroleid;
}

public void setEnum(com.vitalimages.common.server.security.Preference pref) {
    this.preferencekey = pref.name();
}

private String preferencekey;

@Column(name = "PreferenceKey", nullable = false, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getKey() {
    return preferencekey;
}

public void setKey(String key) {
    this.preferencekey = key;
}

private String preferencevalue;

@Column(name = "PreferenceValue", nullable = true, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getValue() {
    return preferencevalue;
}

public void setValue(String value) {
    this.preferencevalue = value;
}

}
</code>```

When I tried to write a simple query against this table:

```<code>public Collection<Preference> getPreferencesForDBGroup(long dbgroupId) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(Preference.class)
            .add(Restrictions.eq("dbgroupid", dbgroupId))
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    return getHibernateTemplate().findByCriteria(criteria);
}
</code>```

I got the following error:

```<code>org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference; nested exception is org.hibernate.QueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference
</code>```

Why can't hibernate figure out what dbgroupid is on my class?

答:
It's probably because your getter (and setter) is not following the javabeans convention. It should be:

```<code>public long getDbgroupId() {
    return dbgroupid;
}
</code>```

What I'd suggest is - name your fields, and then use your IDE to generate setters and getters. It will follow the convention. (Another thing, that is a matter of preference, but in my opinion makes a class easier to read - annotate your fields, not getters)

Body:
So I have a table that I've defined as an entity in hibernate like this:

@Entity
@Table(name = "sec_Preference")
public class Preference {
private long id;

@Column(name = "PreferenceId", nullable = false, insertable = true, updatable = true, length = 19, precision = 0)
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
public long getId() {
    return id;
}

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

private long systemuserid;

@Column(name = "SystemUserId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSystemUserId() {
    return systemuserid;
}

public void setSystemUserId(long systemuserid) {
    this.systemuserid = systemuserid;
}

private long dbgroupid;

@Column(name = "DBGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getDBGroupId() {
    return dbgroupid;
}

public void setDBGroupId(long dbgroupid) {
    this.dbgroupid = dbgroupid;
}

private long externalgroupid;

@Column(name = "ExternalGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getExternalGroupId() {
    return externalgroupid;
}

public void setExternalGroupId(long externalgroupid) {
    this.externalgroupid = externalgroupid;
}

private long securityroleid;

@Column(name = "SecurityRoleId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSecurityRoleId() {
    return securityroleid;
}

public void setSecurityRoleId(long securityroleid) {
    this.securityroleid = securityroleid;
}

public void setEnum(com.vitalimages.common.server.security.Preference pref) {
    this.preferencekey = pref.name();
}

private String preferencekey;

@Column(name = "PreferenceKey", nullable = false, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getKey() {
    return preferencekey;
}

public void setKey(String key) {
    this.preferencekey = key;
}

private String preferencevalue;

@Column(name = "PreferenceValue", nullable = true, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getValue() {
    return preferencevalue;
}

public void setValue(String value) {
    this.preferencevalue = value;
}

}

When I tried to write a simple query against this table:

public Collection<Preference> getPreferencesForDBGroup(long dbgroupId) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(Preference.class)
            .add(Restrictions.eq("dbgroupid", dbgroupId))
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    return getHibernateTemplate().findByCriteria(criteria);
}

I got the following error:

org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference; nested exception is org.hibernate.QueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference

Why can't hibernate figure out what dbgroupid is on my class?

Body:
It's probably because your getter (and setter) is not following the javabeans convention. It should be:

public long getDbgroupId() {
    return dbgroupid;
}

What I'd suggest is - name your fields, and then use your IDE to generate setters and getters. It will follow the convention. (Another thing, that is a matter of preference, but in my opinion makes a class easier to read - annotate your fields, not getters)


问:
Accessing firebase.storage() with AngularFire2 (Angular2 rc.5)

I am trying to access firebase.storage() on my project, with:

"@angular": "2.0.0-rc.5"

"angularfire2": "^2.0.0-beta.3-pre2"

"firebase": "^3.3.0"

I found this solution, and created my .component.ts file with:

```<code>import { Component } from '@angular/core';
declare var firebase : any;

@Component({
  template: '<img [src]="image">'
})
export class RecipesComponent {
  image: string;
  constructor() {
    const storageRef = firebase.storage().ref().child('images/image.png');
    storageRef.getDownloadURL().then(url => this.image = url);
  }
}
</code>```

and I get the following error in the browser console:

```<code>EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in ./bstorageComponent class FBStorageComponent_Host - inline template:0:0
ORIGINAL EXCEPTION: Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().
ORIGINAL STACKTRACE:
Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().
</code>```

but, I initialised firebase in app.module.ts with this import

```<code>AngularFireModule.initializeApp(firebaseConfig)
</code>```

I'm not getting what I'm missing. How can I access storage using firebase? I have no problem with accessing database with angularfire2.

Thanks

答:
The above code no longer works, I keep getting 'firebase.storage is not a function', try adding the following code:</p>

```<code>import * as firebase from 'firebase/app';
import 'firebase/storage';
</code>```

Body:
I am trying to access firebase.storage() on my project, with:

"@angular": "2.0.0-rc.5"

"angularfire2": "^2.0.0-beta.3-pre2"

"firebase": "^3.3.0"

I found this solution, and created my .component.ts file with:

import { Component } from '@angular/core';
declare var firebase : any;

@Component({
  template: ''
})
export class RecipesComponent {
  image: string;
  constructor() {
    const storageRef = firebase.storage().ref().child('images/image.png');
    storageRef.getDownloadURL().then(url => this.image = url);
  }
}

and I get the following error in the browser console:

EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in ./bstorageComponent class FBStorageComponent_Host - inline template:0:0
ORIGINAL EXCEPTION: Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().
ORIGINAL STACKTRACE:
Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().

but, I initialised firebase in app.module.ts with this import

AngularFireModule.initializeApp(firebaseConfig)

I'm not getting what I'm missing. How can I access storage using firebase? I have no problem with accessing database with angularfire2.

Thanks

Body:
The above code no longer works, I keep getting 'firebase.storage is not a function', try adding the following code:

import * as firebase from 'firebase/app';
import 'firebase/storage';


问:
What is the initializing procedure underneath the __init__ method of python built-in list
My question is will the init method of list class calling other method such as append or insert to achieve its functionality.

like:

```<code>class test(list):

def __init__(self,values):
    super().__init__()

def append(self, value):
    self.append(value + 1)
</code>```

I want:

```<code>x = test([1,2,3])
x
[2,3,4]
</code>```

but I got:

```<code>[1,2,3]
</code>```

I know I can make it work by overload init itself.

```<code>def __init__(self,values):
    super().__init__([x+1 for x in values])
</code>```

Can I just overload some basic value insert method like setitem, so all the insert operation like append, insert will call it, and therefore have that addition effect.

thanks for any suggestion.

答:
I've seen another example overriding form collections.MutableSequencethat would let you get this functionality. I'm not sure if this is more convenient than your initial idea, but it will increment any numbers during __init__, append, insert, and extend

```<code>class IncList(collections.MutableSequence):
    def __init__(self, int_list):
        self._list = []
        for el in int_list:
            self.append(el)

    def __len__(self): return len(self._list)
    def __getitem__(self, item): return self._list[item]
    def __delitem__(self, item): del self._list[item]

    def __setitem__(self, index, value):
        self._list[index] = value + 1

    def insert(self, index, value):
        self._list.insert(index, value + 1)

    def __str__(self):
        return str(self._list)

    def __repr__(self):
        return "%s(%r)" % (self.__class__, self._list)

> l = IncList([1, 2, 3])
> print(l)
[2, 3, 4]
> l.append(4)
> print(l)
[2, 3, 4, 5]
> l[0] = 0
> print(l)
[1, 3, 4, 5]
> l.extend([5, 6])
> print(l)
[1, 3, 4, 5, 6, 7]
> l.insert(1, 1)
> print(l)
[1, 2, 3, 4, 5, 6, 7]
</code>```

See this answer for more information.

Body:
My question is will the init method of list class calling other method such as append or insert to achieve its functionality.

like:

class test(list):

def __init__(self,values):
    super().__init__()

def append(self, value):
    self.append(value + 1)

I want:

x = test([1,2,3])
x
[2,3,4]

but I got:

[1,2,3]

I know I can make it work by overload init itself.

def __init__(self,values):
    super().__init__([x+1 for x in values])

Can I just overload some basic value insert method like setitem, so all the insert operation like append, insert will call it, and therefore have that addition effect.

thanks for any suggestion.

Body:
I've seen another example overriding form collections.MutableSequencethat would let you get this functionality. I'm not sure if this is more convenient than your initial idea, but it will increment any numbers during __init__, append, insert, and extend

class IncList(collections.MutableSequence):
    def __init__(self, int_list):
        self._list = []
        for el in int_list:
            self.append(el)

    def __len__(self): return len(self._list)
    def __getitem__(self, item): return self._list[item]
    def __delitem__(self, item): del self._list[item]

    def __setitem__(self, index, value):
        self._list[index] = value + 1

    def insert(self, index, value):
        self._list.insert(index, value + 1)

    def __str__(self):
        return str(self._list)

    def __repr__(self):
        return "%s(%r)" % (self.__class__, self._list)

> l = IncList([1, 2, 3])
> print(l)
[2, 3, 4]
> l.append(4)
> print(l)
[2, 3, 4, 5]
> l[0] = 0
> print(l)
[1, 3, 4, 5]
> l.extend([5, 6])
> print(l)
[1, 3, 4, 5, 6, 7]
> l.insert(1, 1)
> print(l)
[1, 2, 3, 4, 5, 6, 7]

See this answer for more information.


问:
Create an array of arrays with Linq
I've the following XML :

```<code><datarow>
  <datacol><![CDATA[Value1]]></datacol>
  <datacol><![CDATA[Value2]]></datacol>
  <datacol><![CDATA[Value3]]></datacol>
</datarow>
<datarow>
  <datacol><![CDATA[Value5]]></datacol>
  <datacol><![CDATA[Value6]]></datacol>
  <datacol><![CDATA[Value7]]></datacol>
</datarow>
// ...
</code>```

How can I create an bi-dimensional array using linq?

I'll avoid doing :

```<code>foreach("datarow") {
    foreach ("datacol") { ... }
}
</code>```

Thanks !

[EDIT] Final array should be like this:

array[,] = {{ "Value1", "Value2", "Value3"} , { "Value4", "Value5", "Value6"}}

答:
Here is code to create Jagged Array:

```<code>        XDocument doc = XDocument.Load("...");

        string[][] data = (from row in doc.Elements("datarow")
                           select row.Elements("datacol").Select(col => col.Value).ToArray()).ToArray();
</code>```

I am not sure how you can create a Multi-Dimensional Array using Linq.

Title: Create an array of arrays with Linq

Body:
I've the following XML :

<datarow>
  <datacol><![CDATA[Value1]]></datacol>
  <datacol><![CDATA[Value2]]></datacol>
  <datacol><![CDATA[Value3]]></datacol>
</datarow>
<datarow>
  <datacol><![CDATA[Value5]]></datacol>
  <datacol><![CDATA[Value6]]></datacol>
  <datacol><![CDATA[Value7]]></datacol>
</datarow>
// ...

How can I create an bi-dimensional array using linq?

I'll avoid doing :

foreach("datarow") {
    foreach ("datacol") { ... }
}

Thanks !

[EDIT] Final array should be like this:

array[,] = {{ "Value1", "Value2", "Value3"} , { "Value4", "Value5", "Value6"}}

Body:
Here is code to create Jagged Array:

        XDocument doc = XDocument.Load("...");

        string[][] data = (from row in doc.Elements("datarow")
                           select row.Elements("datacol").Select(col => col.Value).ToArray()).ToArray();

I am not sure how you can create a Multi-Dimensional Array using Linq.


问:
Remove comments following # (number sign) in shell
I have a text file text0.txt like

```<code># text0.txt
# This is comment
Hello, I like banana.  # more comments
bra bra bra...
</code>```

The question is what is the command

```<code>$ some_command text0.txt
</code>```

which outputs

```<code>Hello, I like banana.
bra bra bra...
</code>```

to standard output.

I'm using bash.
Thanks.

答:
You want to delete lines that start with a # and to remove a # and any following characters anywhere else on a line.  That description practically defines what the sed script should look like:

```<code>sed -e '/^#/d' -e 's/[[:space:]]*#.*//' text0.txt
</code>```

This removes any spaces before the # at the end of a line too.  You could combine that into one argument if you insist:

```<code>sed '/^#/d; s/[[:space:]]*#.*//' text0.txt
</code>```

Personally, I think it's easier to read the separate operations when they're in separate arguments, but that's a choice you can make for yourself.

Note that there is no need to run two (or more) commands; one is sufficient.

Body:
I have a text file text0.txt like

# text0.txt
# This is comment
Hello, I like banana.  # more comments
bra bra bra...

The question is what is the command

$ some_command text0.txt

which outputs

Hello, I like banana.
bra bra bra...

to standard output.

I'm using bash.
Thanks.

Body:
You want to delete lines that start with a # and to remove a # and any following characters anywhere else on a line.  That description practically defines what the sed script should look like:

sed -e '/^#/d' -e 's/[[:space:]]*#.*//' text0.txt

This removes any spaces before the # at the end of a line too.  You could combine that into one argument if you insist:

sed '/^#/d; s/[[:space:]]*#.*//' text0.txt

Personally, I think it's easier to read the separate operations when they're in separate arguments, but that's a choice you can make for yourself.

Note that there is no need to run two (or more) commands; one is sufficient.


问:
Vuex: Access State From Another Module
I want to access state.session in instance.js from records_view.js. How is this accomplished?

store/modules/instance.js

```<code>const state = {
  // This is what I want to access in records_view.js
  session: {}
};

const getters = {
  sessionGetter: state => state.session
};
</code>```

store/modules/records_view.js

```<code>const actions = {
  getSettingsAction (context, props) {
    // This is how I'm trying to access session, which doesn't work
    let session = context.state.instance.session;

    Api(
      context,
      {
        noun: props.noun,
        verb: 'GetRecordsViewSettings',
        orgUnitKey: _.has(session, 'orgunit.key') ? session.orgunit.key : '',
        data: {}
      },
      props.callback
    );
  }
};
</code>```

This is for a little bit of added context.

store/index.js

```<code>import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import * as getters from './getters';
import * as types from './mutation-types';

import instance from './modules/instance';
import recordsView from './modules/records_view';

Vue.use(Vuex);

export default new Vuex.Store({
  state,
  actions,
  getters,
  mutations,
  modules: {
    instance,
    recordsView
  }
});
</code>```

答:
from an action : </p>

```<code>'contacts:update' ({ commit, rootState }) {
    console.log('rootState', rootState.users.form)
    ......

  },
</code>```

Title: Vuex: Access State From Another Module

Body:
I want to access state.session in instance.js from records_view.js. How is this accomplished?

store/modules/instance.js

const state = {
  // This is what I want to access in records_view.js
  session: {}
};

const getters = {
  sessionGetter: state => state.session
};

store/modules/records_view.js

const actions = {
  getSettingsAction (context, props) {
    // This is how I'm trying to access session, which doesn't work
    let session = context.state.instance.session;

    Api(
      context,
      {
        noun: props.noun,
        verb: 'GetRecordsViewSettings',
        orgUnitKey: _.has(session, 'orgunit.key') ? session.orgunit.key : '',
        data: {}
      },
      props.callback
    );
  }
};

This is for a little bit of added context.

store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import * as getters from './getters';
import * as types from './mutation-types';

import instance from './modules/instance';
import recordsView from './modules/records_view';

Vue.use(Vuex);

export default new Vuex.Store({
  state,
  actions,
  getters,
  mutations,
  modules: {
    instance,
    recordsView
  }
});

Body:
from an action :

'contacts:update' ({ commit, rootState }) {
    console.log('rootState', rootState.users.form)
    ......

  },


问:
How to determine in Windows whether file exists, does not exist or this can't be known (using c)
I have to clean up from a list of files the ones that do not exist any more. The ones whose status is indeterminable should be given a warning about but left on the list. Sounds simple enough. However, the c functions I tried to solve this with don't seem to give a reliable answer between whether the file really does not exist or it e.g. resides on a network share that is at the moment inaccessible (e.g. due to network problems).

stat function sets errno to ENOENT if the file can't be reached, so that is indistinguishable from the file not actually existing.

FindFirstFile in some cases sets last error (obtainable with GetLastError()) to ERROR_PATH_NOT_FOUND when the network share can't be reached.
Yes, I know FindFirstFile is for reading directories, but I thought I could deduce what I need to know by the error code it sets.

Also GetFileAttributes seems to in some cases set last error to ERROR_PATH_NOT_FOUND in case the network drive is unreachable.

答:
```<code>if((f = fopen(file, "r")) == NULL){
    //File does not exist or can not be read
}else{
    //File exists
    fclose(f);
}
</code>```

Drawbacks:

You don't know if a file is nonexistent or just can't be read (privileges etc),

On the other hand, it is 100% portable.

Body:
if((f = fopen(file, "r")) == NULL){
    //File does not exist or can not be read
}else{
    //File exists
    fclose(f);
}

Drawbacks:

You don't know if a file is nonexistent or just can't be read (privileges etc),

On the other hand, it is 100% portable.


问:
FOR... DO in batch with multiples outputs
I'm trying to create an output file; each line of the output file needs to contain the results from a program (few special characters) plus an explanatory plain string right after, but I'm not able to have a proper output. I'm sure it's something simple, but I just don’t have a lot of experience with cmd.

The first FOR creates the special output from my program (kind of a "#34FF123x" string, it's a barcode program). The second FOR is just an ECHO of the numbers that generated the special string. Of course, with two separate FORs I'm gonna have two separate groups on characters, I put them here just for explanation. Thanks for proposing any solution. The results may be also on two different lines, like alternating one from the Program and the next one being the string that generated the previous one. Cheers.

FOR /L %%G IN (1,1,5) DO Program %%G  >> output.file.txt

FOR /L %%i IN (1,1,5) DO ECHO %%i  >> output.file.txt

答:
The FOR command is not fully documented; I've not been able to find any formal reference (just lots of sample code) for the grouping of the commands, nor have I been able to find a way to suppress any EOLs in output, but you can combine commands - and in this case, get alternating lines from the program and the echo:

```<code>for /L %%i in (1,1,5) do (
    program %%i >> output.file.txt
    echo %%i >> output.file.txt
)
</code>```

If program n outputs this is n, then after running this, the contents of output.file.txt should be

```<code>this is 1
1
this is 2
2
this is 3
3
this is 4
4
this is 5
5
</code>```

which is not quite what you've indicated you'd prefer, but seems to match what you'd said is acceptable.

Body:
The FOR command is not fully documented; I've not been able to find any formal reference (just lots of sample code) for the grouping of the commands, nor have I been able to find a way to suppress any EOLs in output, but you can combine commands - and in this case, get alternating lines from the program and the echo:

for /L %%i in (1,1,5) do (
    program %%i >> output.file.txt
    echo %%i >> output.file.txt
)

If program n outputs this is n, then after running this, the contents of output.file.txt should be

this is 1
1
this is 2
2
this is 3
3
this is 4
4
this is 5
5

which is not quite what you've indicated you'd prefer, but seems to match what you'd said is acceptable.


问:
How to add Google Tag Manager firing rule for Backbone Marionette site?
I have already built a site with backbone marionette and now I am trying to use Google Tag manager to add the tracking. But I have no idea how to configure GTM, in order to listen page change and button click event.</p>

答:
There is a bit of fiddling required there.
Tag manager uses a data structure called dataLayer. It's an array, that you can add events to.
So to configure tag manager, you need to add a snippet to HTML page of the application as in any other case. On top of it, you have to initialise the dataLayer array but you need to make sure, that the code initialising this variable is invoked before the snippet.
So here is the full example in the head of the index.html page (in one page app):

```<code><html>
<head>
...
<script>
  dataLayer = [];
</script>
<script>
function loadProductDetails(productIdentifier) {
dataLayer.push({
  'event':'pageview',
  'virtualUrl':'/product/'+productIdentifier
});
// code to load product details and display to user
}
</script>
</head>
<body>
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-3VLTP"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-3VLTP');</script>
<!-- End Google Tag Manager -->
...
<a onclick="loadProductDetails('nexus7');">Nexus 7</a>
...
</body>
</html>
</code>```

The function called loadProductDetails is an example on how you push the events to Google servers - you just need to add an object to the dataLayer array.

Dan Russel wrote a full blog post about it, together with explanation how to setup the macro for extracting the events.

And there is a bit of documentation on this as well here

Body:
There is a bit of fiddling required there.
Tag manager uses a data structure called dataLayer. It's an array, that you can add events to.
So to configure tag manager, you need to add a snippet to HTML page of the application as in any other case. On top of it, you have to initialise the dataLayer array but you need to make sure, that the code initialising this variable is invoked before the snippet.
So here is the full example in the head of the index.html page (in one page app):

<html>
<head>
...
<script>
  dataLayer = [];
</script>
<script>
function loadProductDetails(productIdentifier) {
dataLayer.push({
  'event':'pageview',
  'virtualUrl':'/product/'+productIdentifier
});
// code to load product details and display to user
}
</script>
</head>
<body>
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-3VLTP"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-3VLTP');</script>
<!-- End Google Tag Manager -->
...
<a onclick="loadProductDetails('nexus7');">Nexus 7</a>
...
</body>
</html>

The function called loadProductDetails is an example on how you push the events to Google servers - you just need to add an object to the dataLayer array.

Dan Russel wrote a full blog post about it, together with explanation how to setup the macro for extracting the events.

And there is a bit of documentation on this as well here


问:
How to create a Circular Style ProgressBar
I need help on implementing a circular progress bar like this:

How should I implement the Circle to fill by increasing Value property?

答:
I know this is an old issue, but anyways here is my solution:

FOR WINFORMS:

```<code>using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

public class CircularProgressBar : Control
{
    #region Enums

    public enum _ProgressShape
    {
        Round,
        Flat
    }

    public enum _TextMode
    {
        None,
        Value,
        Percentage,
        Custom
    }

    #endregion

    #region Private Variables

    private long _Value;
    private long _Maximum = 100;
    private int _LineWitdh = 1;
    private float _BarWidth = 14f;

    private Color _ProgressColor1 = Color.Orange;
    private Color _ProgressColor2 = Color.Orange;
    private Color _LineColor = Color.Silver;
    private LinearGradientMode _GradientMode = LinearGradientMode.ForwardDiagonal;
    private _ProgressShape ProgressShapeVal;
    private _TextMode ProgressTextMode;

    #endregion

    #region Contructor

    public CircularProgressBar()
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        SetStyle(ControlStyles.Opaque, true);
        this.BackColor = SystemColors.Control;
        this.ForeColor = Color.DimGray;

        this.Size = new Size(130, 130);
        this.Font = new Font("Segoe UI", 15);
        this.MinimumSize = new Size(100, 100);
        this.DoubleBuffered = true;

        this.LineWidth = 1;
        this.LineColor = Color.DimGray;

        Value = 57;
        ProgressShape = _ProgressShape.Flat;
        TextMode = _TextMode.Percentage;
    }

    #endregion

    #region Public Custom Properties

    /// <summary>Determina el Valor del Progreso</summary>
    [Description("Valor Entero que determina la posision de la Barra de Progreso."), Category("Behavior")]
    public long Value
    {
        get { return _Value; }
        set
        {
            if (value > _Maximum)
                value = _Maximum;
            _Value = value;
            Invalidate();
        }
    }

    [Description("Obtiene o Establece el Valor Maximo de la barra de Progreso."), Category("Behavior")]
    public long Maximum
    {
        get { return _Maximum; }
        set
        {
            if (value < 1)
                value = 1;
            _Maximum = value;
            Invalidate();
        }
    }

    [Description("Color Inicial de la Barra de Progreso"), Category("Appearance")]
    public Color BarColor1
    {
        get { return _ProgressColor1; }
        set
        {
            _ProgressColor1 = value;
            Invalidate();
        }
    }

    [Description("Color Final de la Barra de Progreso"), Category("Appearance")]
    public Color BarColor2
    {
        get { return _ProgressColor2; }
        set
        {
            _ProgressColor2 = value;
            Invalidate();
        }
    }

    [Description("Ancho de la Barra de Progreso"), Category("Appearance")]
    public float BarWidth
    {
        get { return _BarWidth; }
        set
        {
            _BarWidth = value;
            Invalidate();
        }
    }

    [Description("Modo del Gradiente de Color"), Category("Appearance")]
    public LinearGradientMode GradientMode
    {
        get { return _GradientMode; }
        set
        {
            _GradientMode = value;
            Invalidate();
        }
    }

    [Description("Color de la Linea Intermedia"), Category("Appearance")]
    public Color LineColor
    {
        get { return _LineColor; }
        set
        {
            _LineColor = value;
            Invalidate();
        }
    }

    [Description("Ancho de la Linea Intermedia"), Category("Appearance")]
    public int LineWidth
    {
        get { return _LineWitdh; }
        set
        {
            _LineWitdh = value;
            Invalidate();
        }
    }

    [Description("Obtiene o Establece la Forma de los terminales de la barra de progreso."), Category("Appearance")]
    public _ProgressShape ProgressShape
    {
        get { return ProgressShapeVal; }
        set
        {
            ProgressShapeVal = value;
            Invalidate();
        }
    }

    [Description("Obtiene o Establece el Modo como se muestra el Texto dentro de la barra de Progreso."), Category("Behavior")]
    public _TextMode TextMode
    {
        get { return ProgressTextMode; }
        set
        {
            ProgressTextMode = value;
            Invalidate();
        }
    }

    [Description("Obtiene el Texto que se muestra dentro del Control"), Category("Behavior")]
    public override string Text { get; set; }

    #endregion

    #region EventArgs

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        SetStandardSize();
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        SetStandardSize();
    }

    protected override void OnPaintBackground(PaintEventArgs p)
    {
        base.OnPaintBackground(p);
    }

    #endregion

    #region Methods

    private void SetStandardSize()
    {
        int _Size = Math.Max(Width, Height);
        Size = new Size(_Size, _Size);
    }

    public void Increment(int Val)
    {
        this._Value += Val;
        Invalidate();
    }

    public void Decrement(int Val)
    {
        this._Value -= Val;
        Invalidate();
    }
    #endregion

    #region Events

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (Bitmap bitmap = new Bitmap(this.Width, this.Height))
        {
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                //graphics.Clear(Color.Transparent); //<-- this.BackColor, SystemColors.Control, Color.Transparent

                PaintTransparentBackground(this, e);

                //Dibuja el circulo blanco interior:
                using (Brush mBackColor = new SolidBrush(this.BackColor))
                {
                    graphics.FillEllipse(mBackColor,
                            18, 18,
                            (this.Width - 0x30) + 12,
                            (this.Height - 0x30) + 12);
                }
                // Dibuja la delgada Linea gris del medio:
                using (Pen pen2 = new Pen(LineColor, this.LineWidth))
                {
                    graphics.DrawEllipse(pen2,
                        18, 18,
                      (this.Width - 0x30) + 12,
                      (this.Height - 0x30) + 12);
                }

                //Dibuja la Barra de Progreso
                using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle,
                    this._ProgressColor1, this._ProgressColor2, this.GradientMode))
                {
                    using (Pen pen = new Pen(brush, this.BarWidth))
                    {
                        switch (this.ProgressShapeVal)
                        {
                            case _ProgressShape.Round:
                                pen.StartCap = LineCap.Round;
                                pen.EndCap = LineCap.Round;
                                break;

                            case _ProgressShape.Flat:
                                pen.StartCap = LineCap.Flat;
                                pen.EndCap = LineCap.Flat;
                                break;
                        }

                        //Aqui se dibuja realmente la Barra de Progreso
                        graphics.DrawArc(pen,
                            0x12, 0x12,
                            (this.Width - 0x23) - 2,
                            (this.Height - 0x23) - 2,
                            -90,
                            (int)Math.Round((double)((360.0 / ((double)this._Maximum)) * this._Value)));
                    }
                }

                #region Dibuja el Texto de Progreso

                switch (this.TextMode)
                {
                    case _TextMode.None:
                        this.Text = string.Empty;
                        break;

                    case _TextMode.Value:
                        this.Text = _Value.ToString();
                        break;

                    case _TextMode.Percentage:
                        this.Text = Convert.ToString(Convert.ToInt32((100 / _Maximum) * _Value));
                        break;

                    default:
                        break;
                }

                if (this.Text != string.Empty)
                {
                    using (Brush FontColor = new SolidBrush(this.ForeColor))
                    {
                        int ShadowOffset = 2;
                        SizeF MS = graphics.MeasureString(this.Text, this.Font);
                        SolidBrush shadowBrush = new SolidBrush(Color.FromArgb(100, this.ForeColor));

                        //Sombra del Texto:
                        graphics.DrawString(this.Text, this.Font, shadowBrush,
                            Convert.ToInt32(Width / 2 - MS.Width / 2) + ShadowOffset,
                            Convert.ToInt32(Height / 2 - MS.Height / 2) + ShadowOffset
                        );

                        //Texto del Control:
                        graphics.DrawString(this.Text, this.Font, FontColor,
                            Convert.ToInt32(Width / 2 - MS.Width / 2),
                            Convert.ToInt32(Height / 2 - MS.Height / 2));
                    }
                }

                #endregion

                //Aqui se Dibuja todo el Control:
                e.Graphics.DrawImage(bitmap, 0, 0);
                graphics.Dispose();
                bitmap.Dispose();
            }
        }
    }

    private static void PaintTransparentBackground(Control c, PaintEventArgs e)
    {
        if (c.Parent == null || !Application.RenderWithVisualStyles)
            return;

        ButtonRenderer.DrawParentBackground(e.Graphics, c.ClientRectangle, c);
    }

    /// <summary>Dibuja un Circulo Relleno de Color con los Bordes perfectos.</summary>
    /// <param name="g">'Canvas' del Objeto donde se va a dibujar</param>
    /// <param name="brush">Color y estilo del relleno</param>
    /// <param name="centerX">Centro del Circulo, en el eje X</param>
    /// <param name="centerY">Centro del Circulo, en el eje Y</param>
    /// <param name="radius">Radio del Circulo</param>
    private void FillCircle(Graphics g, Brush brush, float centerX, float centerY, float radius)
    {
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        using (System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath())
        {
            g.FillEllipse(brush, centerX - radius, centerY - radius,
                      radius + radius, radius + radius);
        }
    }

    #endregion
}
</code>```

IMPLEMENTATION:

Place the source code into a new class anywhere in your WinForms project, name the class 'CircularProgressBar.cs'.

Compile the Project.

After Compiling you should see a new Control or 'Component' at the ToolBar.

Drag and drop this new control into any form and customize its properties.

Control Looks like this:

Enjoy.

Body:
I know this is an old issue, but anyways here is my solution:

FOR WINFORMS:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

public class CircularProgressBar : Control
{
    #region Enums

    public enum _ProgressShape
    {
        Round,
        Flat
    }

    public enum _TextMode
    {
        None,
        Value,
        Percentage,
        Custom
    }

    #endregion

    #region Private Variables

    private long _Value;
    private long _Maximum = 100;
    private int _LineWitdh = 1;
    private float _BarWidth = 14f;

    private Color _ProgressColor1 = Color.Orange;
    private Color _ProgressColor2 = Color.Orange;
    private Color _LineColor = Color.Silver;
    private LinearGradientMode _GradientMode = LinearGradientMode.ForwardDiagonal;
    private _ProgressShape ProgressShapeVal;
    private _TextMode ProgressTextMode;

    #endregion

    #region Contructor

    public CircularProgressBar()
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        SetStyle(ControlStyles.Opaque, true);
        this.BackColor = SystemColors.Control;
        this.ForeColor = Color.DimGray;

        this.Size = new Size(130, 130);
        this.Font = new Font("Segoe UI", 15);
        this.MinimumSize = new Size(100, 100);
        this.DoubleBuffered = true;

        this.LineWidth = 1;
        this.LineColor = Color.DimGray;

        Value = 57;
        ProgressShape = _ProgressShape.Flat;
        TextMode = _TextMode.Percentage;
    }

    #endregion

    #region Public Custom Properties

    /// <summary>Determina el Valor del Progreso</summary>
    [Description("Valor Entero que determina la posision de la Barra de Progreso."), Category("Behavior")]
    public long Value
    {
        get { return _Value; }
        set
        {
            if (value > _Maximum)
                value = _Maximum;
            _Value = value;
            Invalidate();
        }
    }

    [Description("Obtiene o Establece el Valor Maximo de la barra de Progreso."), Category("Behavior")]
    public long Maximum
    {
        get { return _Maximum; }
        set
        {
            if (value < 1)
                value = 1;
            _Maximum = value;
            Invalidate();
        }
    }

    [Description("Color Inicial de la Barra de Progreso"), Category("Appearance")]
    public Color BarColor1
    {
        get { return _ProgressColor1; }
        set
        {
            _ProgressColor1 = value;
            Invalidate();
        }
    }

    [Description("Color Final de la Barra de Progreso"), Category("Appearance")]
    public Color BarColor2
    {
        get { return _ProgressColor2; }
        set
        {
            _ProgressColor2 = value;
            Invalidate();
        }
    }

    [Description("Ancho de la Barra de Progreso"), Category("Appearance")]
    public float BarWidth
    {
        get { return _BarWidth; }
        set
        {
            _BarWidth = value;
            Invalidate();
        }
    }

    [Description("Modo del Gradiente de Color"), Category("Appearance")]
    public LinearGradientMode GradientMode
    {
        get { return _GradientMode; }
        set
        {
            _GradientMode = value;
            Invalidate();
        }
    }

    [Description("Color de la Linea Intermedia"), Category("Appearance")]
    public Color LineColor
    {
        get { return _LineColor; }
        set
        {
            _LineColor = value;
            Invalidate();
        }
    }

    [Description("Ancho de la Linea Intermedia"), Category("Appearance")]
    public int LineWidth
    {
        get { return _LineWitdh; }
        set
        {
            _LineWitdh = value;
            Invalidate();
        }
    }

    [Description("Obtiene o Establece la Forma de los terminales de la barra de progreso."), Category("Appearance")]
    public _ProgressShape ProgressShape
    {
        get { return ProgressShapeVal; }
        set
        {
            ProgressShapeVal = value;
            Invalidate();
        }
    }

    [Description("Obtiene o Establece el Modo como se muestra el Texto dentro de la barra de Progreso."), Category("Behavior")]
    public _TextMode TextMode
    {
        get { return ProgressTextMode; }
        set
        {
            ProgressTextMode = value;
            Invalidate();
        }
    }

    [Description("Obtiene el Texto que se muestra dentro del Control"), Category("Behavior")]
    public override string Text { get; set; }

    #endregion

    #region EventArgs

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        SetStandardSize();
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        SetStandardSize();
    }

    protected override void OnPaintBackground(PaintEventArgs p)
    {
        base.OnPaintBackground(p);
    }

    #endregion

    #region Methods

    private void SetStandardSize()
    {
        int _Size = Math.Max(Width, Height);
        Size = new Size(_Size, _Size);
    }

    public void Increment(int Val)
    {
        this._Value += Val;
        Invalidate();
    }

    public void Decrement(int Val)
    {
        this._Value -= Val;
        Invalidate();
    }
    #endregion

    #region Events

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (Bitmap bitmap = new Bitmap(this.Width, this.Height))
        {
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                //graphics.Clear(Color.Transparent); //<-- this.BackColor, SystemColors.Control, Color.Transparent

                PaintTransparentBackground(this, e);

                //Dibuja el circulo blanco interior:
                using (Brush mBackColor = new SolidBrush(this.BackColor))
                {
                    graphics.FillEllipse(mBackColor,
                            18, 18,
                            (this.Width - 0x30) + 12,
                            (this.Height - 0x30) + 12);
                }
                // Dibuja la delgada Linea gris del medio:
                using (Pen pen2 = new Pen(LineColor, this.LineWidth))
                {
                    graphics.DrawEllipse(pen2,
                        18, 18,
                      (this.Width - 0x30) + 12,
                      (this.Height - 0x30) + 12);
                }

                //Dibuja la Barra de Progreso
                using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle,
                    this._ProgressColor1, this._ProgressColor2, this.GradientMode))
                {
                    using (Pen pen = new Pen(brush, this.BarWidth))
                    {
                        switch (this.ProgressShapeVal)
                        {
                            case _ProgressShape.Round:
                                pen.StartCap = LineCap.Round;
                                pen.EndCap = LineCap.Round;
                                break;

                            case _ProgressShape.Flat:
                                pen.StartCap = LineCap.Flat;
                                pen.EndCap = LineCap.Flat;
                                break;
                        }

                        //Aqui se dibuja realmente la Barra de Progreso
                        graphics.DrawArc(pen,
                            0x12, 0x12,
                            (this.Width - 0x23) - 2,
                            (this.Height - 0x23) - 2,
                            -90,
                            (int)Math.Round((double)((360.0 / ((double)this._Maximum)) * this._Value)));
                    }
                }

                #region Dibuja el Texto de Progreso

                switch (this.TextMode)
                {
                    case _TextMode.None:
                        this.Text = string.Empty;
                        break;

                    case _TextMode.Value:
                        this.Text = _Value.ToString();
                        break;

                    case _TextMode.Percentage:
                        this.Text = Convert.ToString(Convert.ToInt32((100 / _Maximum) * _Value));
                        break;

                    default:
                        break;
                }

                if (this.Text != string.Empty)
                {
                    using (Brush FontColor = new SolidBrush(this.ForeColor))
                    {
                        int ShadowOffset = 2;
                        SizeF MS = graphics.MeasureString(this.Text, this.Font);
                        SolidBrush shadowBrush = new SolidBrush(Color.FromArgb(100, this.ForeColor));

                        //Sombra del Texto:
                        graphics.DrawString(this.Text, this.Font, shadowBrush,
                            Convert.ToInt32(Width / 2 - MS.Width / 2) + ShadowOffset,
                            Convert.ToInt32(Height / 2 - MS.Height / 2) + ShadowOffset
                        );

                        //Texto del Control:
                        graphics.DrawString(this.Text, this.Font, FontColor,
                            Convert.ToInt32(Width / 2 - MS.Width / 2),
                            Convert.ToInt32(Height / 2 - MS.Height / 2));
                    }
                }

                #endregion

                //Aqui se Dibuja todo el Control:
                e.Graphics.DrawImage(bitmap, 0, 0);
                graphics.Dispose();
                bitmap.Dispose();
            }
        }
    }

    private static void PaintTransparentBackground(Control c, PaintEventArgs e)
    {
        if (c.Parent == null || !Application.RenderWithVisualStyles)
            return;

        ButtonRenderer.DrawParentBackground(e.Graphics, c.ClientRectangle, c);
    }

    /// <summary>Dibuja un Circulo Relleno de Color con los Bordes perfectos.</summary>
    /// <param name="g">'Canvas' del Objeto donde se va a dibujar</param>
    /// <param name="brush">Color y estilo del relleno</param>
    /// <param name="centerX">Centro del Circulo, en el eje X</param>
    /// <param name="centerY">Centro del Circulo, en el eje Y</param>
    /// <param name="radius">Radio del Circulo</param>
    private void FillCircle(Graphics g, Brush brush, float centerX, float centerY, float radius)
    {
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        using (System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath())
        {
            g.FillEllipse(brush, centerX - radius, centerY - radius,
                      radius + radius, radius + radius);
        }
    }

    #endregion
}

IMPLEMENTATION:

Place the source code into a new class anywhere in your WinForms project, name the class 'CircularProgressBar.cs'.

Compile the Project.

After Compiling you should see a new Control or 'Component' at the ToolBar.

Drag and drop this new control into any form and customize its properties.

Control Looks like this:

Enjoy.


问:
How to set the image to image view that is downloaded to your application in android local
I have a image downloaded locally in application

```<code>/data/data/com.starboard.stella/files/Stella/FragranceFinder/QuestionImages/option1_woman.png
</code>```

How do I access the image to set for image view?

答:
I think you should try this:</p>

```<code>try {
        File file = new File(getExternalFilesDir(null) + "/Stella/FragranceFinder/QuestionImages/", "option1_woman.png");
        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
        ImageView image =(ImageView)findViewById(R.id.image);
        image.setImageBitmap(bitmap);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
</code>```

Body:
I have a image downloaded locally in application

/data/data/com.starboard.stella/files/Stella/FragranceFinder/QuestionImages/option1_woman.png

How do I access the image to set for image view?

Body:
I think you should try this:

try {
        File file = new File(getExternalFilesDir(null) + "/Stella/FragranceFinder/QuestionImages/", "option1_woman.png");
        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
        ImageView image =(ImageView)findViewById(R.id.image);
        image.setImageBitmap(bitmap);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


问:
Get the functionality of a Webpage into an iOS App - Swift
Is it possible to have an HTML website, coded with JavaScript and get the functionality of this website into my App with WebKit or something else?

With WebKit or WebViews it is possible to load a whole Webpage into my app, so the functionality is automatically there, too.

But isn't there a way to change the UI in the app?

For example, there is an HTML-Webpage which represents a table, with some information.
Above the table are 3 text fields, depending on what you type into the text fields the information in the table changes.

Is it possible to load this web page into my app and change the table in some way? Like creating a whole new app based on this web page?

答:
Yes.  WKWebView is Apple's latest API for displaying websites (built on top of WebKit).  If you do not want to display the webpage in your app and instead run your own custom UI, you can look into Apple's Javascript Core .  This framework allows you to run native Javascript functions within your iOS App without having to load any web pages.  WKWebView also has function called:

func evaluateJavaScript(_ javaScriptString: String,
      completionHandler: ((Any?, Error?) -> Void)? = nil)

That allows you to alter the contents of the webpage based on the javascript that is passed in.


问:
Using Linq to order lists within a list
I have a list of items (actually an IEnumerable). Each item has a list of values. For example:

```<code>Item1.Value[0] = "Health & Safety"
Item1.Value[1] = "Economic"
Item1.Value[2] = "Environment"

Item2.Value[0] = "Reputation"
Item2.Value[1] = "Environment"
Item2.Value[2] = "Regulatory"

...
</code>```

How can I order the list of values using linq? I know I can order the list of items using something like:

Items.Orderby(x => x.something)

...but how do I get to the list of values in each item?

答:
You can try this</p>

```<code>Items.ForEach(i=> x.something = x.something.OrderBy(o=> o.field));
</code>```

Title: Using Linq to order lists within a list

Body:
I have a list of items (actually an IEnumerable). Each item has a list of values. For example:

Item1.Value[0] = "Health & Safety"
Item1.Value[1] = "Economic"
Item1.Value[2] = "Environment"

Item2.Value[0] = "Reputation"
Item2.Value[1] = "Environment"
Item2.Value[2] = "Regulatory"

...

How can I order the list of values using linq? I know I can order the list of items using something like:

Items.Orderby(x => x.something)

...but how do I get to the list of values in each item?

Body:
You can try this

Items.ForEach(i=> x.something = x.something.OrderBy(o=> o.field));


问:
join strings in JS
I have an array A and array B:

```<code>A = ["1234","5678","4444"]
B = 7868,9090
</code>```

I want array C to be:

```<code>C = ["1234","5678","4444","7868","9090"]
</code>```

The length of array A and B can vary and array B should join the end of array A.

What is the best way to do this?

I tried using push() but I'm still having problems.

Thank you.

答:
I did the following to get the result I need:</p>

```<code>B = JSON.stringify(B);
A = A.concat(B);
A = A.replace('][', ',');
</code>```

Title: join strings in JS

Body:
I have an array A and array B:

A = ["1234","5678","4444"]
B = 7868,9090

I want array C to be:

C = ["1234","5678","4444","7868","9090"]

The length of array A and B can vary and array B should join the end of array A.

What is the best way to do this?

I tried using push() but I'm still having problems.

Thank you.

Body:
I did the following to get the result I need:

B = JSON.stringify(B);
A = A.concat(B);
A = A.replace('][', ',');


问:
How to get hostname call my API
Eg: website abc.com access my REST API  by link xyz.com/rest/api/order/new
. In my function, how can I get hostname abc.com?

I want to check the token is matched with the hostname that is saved in the database.

答:
For codeigniter, you can use:

```<code>$this->input->server('HTTP_HOST');
</code>```

In argument, you can use all options of $_SERVER veriable.

Title: How to get hostname call my API

Body:
For codeigniter, you can use:

$this->input->server('HTTP_HOST');

In argument, you can use all options of $_SERVER veriable.


答:
We can use startsWith from base R

```<code>df[startsWith(names(df), "best..F")]
</code>```

Title: how to search and retrieve specific columns from a huge data

Body:
I have a data looks like this

df<- structure(list(X..taminn = c(86L, 102L, 34L, 35L, 53L, 54L, 43L,
31L, 62L, 54L), X..turtia = c(413L, 322L, 525L, 535L, 247L, 207L,
241L, 440L, 189L, 221L), X..bestt = c(82L, 102L, 6L, 2L, 46L,
1L, 39L, 7L, 62L, 54L), Best..F1..129..test = c(3079.3, 1512.9,
497, 2804.5, 1353.7, 1597.6, 2005.1, 186.4, 1847.5, 1558.2),
    best..F1..130..test = c(8972.7, 1944, 2022.7, 13001.7, 2085,
    3228.6, 4948.5, 943.6, 1329, 2655.9), best..F1..131..test = c(2634.4,
    1181.3, 505.2, 2802.4, 1573.2, 1707.6, 1585.9, 192.1, 809.2,
    1219), how1 = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
    2L, 1L), .Label = c("", "High", "Not Found"), class = "factor"),
    how2 = structure(c(2L, 2L, 2L, 3L, 2L, 2L, 2L, 3L, 2L, 1L
    ), .Label = c("", "High", "Not Found"), class = "factor"),
    how3 = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L
    ), .Label = c("", "High"), class = "factor"), Best.test...F1..129..test = c(3079.3,
    1512.9, 497, 2804.5, 1353.7, 1597.6, 2005.1, 186.4, 1847.5,
    1558.2), best.test...F1..130..test = c(8972.7, 1944, 2022.7,
    13001.7, 2085, 3228.6, 4948.5, 943.6, 1329, 2655.9), best.test...F1..131..test = c(2634.4,
    1181.3, 505.2, 2802.4, 1573.2, 1707.6, 1585.9, 192.1, 809.2,
    1219), Best..test..129..test = c(3079.3, 1512.9, 497, 2804.5,
    1353.7, 1597.6, 2005.1, 186.4, 1847.5, 1558.2), best..test..130..test = c(8972.7,
    1944, 2022.7, 13001.7, 2085, 3228.6, 4948.5, 943.6, 1329,
    2655.9), best..test..131..test = c(2634.4, 1181.3, 505.2,
    2802.4, 1573.2, 1707.6, 1585.9, 192.1, 809.2, 1219)), .Names = c("X..taminn",
"X..turtia", "X..bestt", "Best..F1..129..test", "best..F1..130..test",
"best..F1..131..test", "how1", "how2", "how3", "Best.test...F1..129..test",
"best.test...F1..130..test", "best.test...F1..131..test", "Best..test..129..test",
"best..test..130..test", "best..test..131..test"), class = "data.frame", row.names = c(NA,
-10L))

Basically, I want to extract all those columns that their name starts with

best..F1
best..F2
.
.

is there a way to do it without going to the data one by one and find its place ?

Body:
We can use startsWith from base R

df[startsWith(names(df), "best..F")]


问:
How to Imploade Two Arrays in Mysql Query IN Clause
I have Two Arrays Like $idarray and $idarray1

I want Combine Two Arrays Like This

```<code>$sql = "SELECT * FROM meeting WHERE meet_id IN('" . implode("','", $idarray) . "')";
</code>```

In this Query I want to add $idarray1

How can i do that

答:
You can merge two array with array_merge function:

```<code>$idarray_merged = array_merge($idarray, $idarray1);
$sql = "SELECT * FROM meeting WHERE meet_id IN('" . implode("','", $idarray_merged) . "')";
</code>```

Body:
I have Two Arrays Like $idarray and $idarray1

I want Combine Two Arrays Like This

$sql = "SELECT * FROM meeting WHERE meet_id IN('" . implode("','", $idarray) . "')";

In this Query I want to add $idarray1

How can i do that

Body:
You can merge two array with array_merge function:

$idarray_merged = array_merge($idarray, $idarray1);
$sql = "SELECT * FROM meeting WHERE meet_id IN('" . implode("','", $idarray_merged) . "')";


问:
How to add method comments with Live template in IntelliJ idea
I would like to generate comments automatically,but the /**+enter only generates Javadoc containing the @param and @return tags.

I want to also generate the date and author,but when I made the Live Template, I used methodparameters() to autogenerate parameters, but this does not work outside of the method. I had to generate documentation in the method and then move the it to the top of the method.

How do I generate comments outside of a method with the @param,@author,and @date tags?

Update:

@javau's answer worked out,tanks! Thanks for fixing grammar,Luciano van der Veekens

I modified the xml like that:

<template name="auth" value="@author $USER$
    * @since  $DATE;" description="Inset Javadoc @author and @since tags" toReformat="true" toShortenFQNames="true">
  <variable name="USER" expression="user()" defaultValue="" alwaysStopAt="false" />
  <variable name="DATE" expression="date()" defaultValue="" alwaysStopAt="false" />
  <context>
    <option name="JAVA_COMMENT" value="true" />
  </context>
</template>
```

答:
You won't be able to do exactly what you want. The /**Enter shortcut isn't a live template per se. And it can't be edited. And a live template does not have access to the method parameters of a method it is not inside of.

Long term, I recommend you open a feature request that a setting be put in to include the @author and @since tags when the /** shortcut is used.

For now, you can do it in two steps. Create a live template to insert the @author and @since tags. (I have an example below you can copy and paste.) Then you would need to type: /**EnterauthTab where auth is the shortcut for your live template. You would end up with something like:

```<code>/**
 * @author Dilbert
 * @since 2017-06-07
 * @param foo
 * @param bar
 */
void m1(String foo, String bar)
</code>```

Here's an example template:

```<code><template name="auth" value="@author $USER$
    * @since  $DATE$
    *" description="Inset Javadoc @author and @since tags" toReformat="true" toShortenFQNames="true">
  <variable name="USER" expression="user()" defaultValue="" alwaysStopAt="false" />
  <variable name="DATE" expression="date()" defaultValue="" alwaysStopAt="false" />
  <context>
    <option name="JAVA_COMMENT" value="true" />
  </context>
</template>
</code>```

UPDATE

To answer your question from the comment "I was wondering  where you found the option name JAVA_COMMENT?" That is at the bottom of the Live Template dialog. You can set the context/scope for which the template (i.e. is shortcut) is applicable/available. Here's a screenshot.

In case you are not aware, you can create the template by copying the XML I show and then pasting it into a template group. The paste option is available only if you have a valid template XML in your clipboard. Be sure there are no leading spaces or lines before the <template element. (I got the XML via the copy option.)

Body:
You won't be able to do exactly what you want. The /**Enter shortcut isn't a live template per se. And it can't be edited. And a live template does not have access to the method parameters of a method it is not inside of.

Long term, I recommend you open a feature request that a setting be put in to include the @author and @since tags when the /** shortcut is used.

For now, you can do it in two steps. Create a live template to insert the @author and @since tags. (I have an example below you can copy and paste.) Then you would need to type: /**EnterauthTab where auth is the shortcut for your live template. You would end up with something like:

/**
 * @author Dilbert
 * @since 2017-06-07
 * @param foo
 * @param bar
 */
void m1(String foo, String bar)

Here's an example template:

<template name="auth" value="@author $USER$ &#10;    * @since  $DATE$&#10;    *" description="Inset Javadoc @author and @since tags" toReformat="true" toShortenFQNames="true">
  <variable name="USER" expression="user()" defaultValue="" alwaysStopAt="false" />
  <variable name="DATE" expression="date()" defaultValue="" alwaysStopAt="false" />
  <context>
    <option name="JAVA_COMMENT" value="true" />
  </context>
</template>

UPDATE

To answer your question from the comment "I was wondering  where you found the option name JAVA_COMMENT?" That is at the bottom of the Live Template dialog. You can set the context/scope for which the template (i.e. is shortcut) is applicable/available. Here's a screenshot.

In case you are not aware, you can create the template by copying the XML I show and then pasting it into a template group. The paste option is available only if you have a valid template XML in your clipboard. Be sure there are no leading spaces or lines before the <template element. (I got the XML via the copy option.)


问:
filter es6 accept a function as condition
I'm stuck on a tutorial.

Q: Create a function called 'reject'.  Reject should work in the opposite way of 'filter' - if a function returns 'true', the item should not be included in the new array.  you have to use filter.

For example:

```<code>var numbers = [10, 20, 30];
var lessThanFifteen = reject(numbers, function(number){
  return number > 15;
});
console.log(lessThanFifteen) // [ 10 ];
</code>```

My failed attempts

```<code>function reject(array, iteratorFunction) {
  array.filter(number => !iteratorFunction(number));
}
</code>```

答:
Your reject function should return the new array</p>

```<code>function reject(array, iteratorFunction) {
  return array.filter(number => !iteratorFunction(number));
}
</code>```

Body:
I'm stuck on a tutorial.

Q: Create a function called 'reject'.  Reject should work in the opposite way of 'filter' - if a function returns 'true', the item should not be included in the new array.  you have to use filter.

For example:

var numbers = [10, 20, 30];
var lessThanFifteen = reject(numbers, function(number){
  return number > 15;
});
console.log(lessThanFifteen) // [ 10 ];

My failed attempts

function reject(array, iteratorFunction) {
  array.filter(number => !iteratorFunction(number));
}

Body:
Your reject function should return the new array

function reject(array, iteratorFunction) {
  return array.filter(number => !iteratorFunction(number));
}


答:
you can use find_in_set to achieve this.

http://www.w3resource.com/mysql/string-functions/mysql-find_in_set-function.php

Title: How to Imploade Two Arrays in Mysql Query IN Clause