问:
AndroidMainfest merger error
Can someone help me to solve this problem.

Error:Execution failed for task ':app:processDebugManifest'

Manifest merger failed : Attribute application@icon value=(@mipmap/ic_launcher) from AndroidManifest.xml:8:9-43
      is also present at [Sample:HomeLockerLib:unspecified] AndroidManifest.xml:15:9-45 value=(@drawable/ic_launcher).
      Suggestion: add 'tools:replace="android:icon"' to  element at AndroidManifest.xml:6:5-22:19 to override.

答:
Add below line inside application tag of your apps Manifest.xml

```<code>tools:replace="android:icon"
</code>```

for eg :

```<code><application
    android:name=".ApplicationSubClass"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Holo.Light"
    tools:replace="android:icon" > //HERE
</code>```

For more information about this bug refer to this url.

Title: AndroidMainfest merger error

Body:
Add below line inside application tag of your apps Manifest.xml

tools:replace="android:icon"

for eg :

<application
    android:name=".ApplicationSubClass"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Holo.Light"
    tools:replace="android:icon" > //HERE

For more information about this bug refer to this url.


来源: stackexchange

问:
Making changes to an existing table?
I just had a quick question. Once you've ran a change migration like say you needed to add a column to an existing table, so you create a change migration. If I've already ran that change migration, and wanted to add a different new column in that table, can i just edit the code in the change migration to add the second new column or do i have to create a whole new change migration?</p>

答:
As you said you ran migration already that means your change has been reflected to your database. so at this point if you want another change then its quite straight you need to make new migration, but there is a way that to make change in same migration for that

1 first you need to revert that migration that means you need to rollback that migration on which you want to change

```<code>rake db:migrate:down VERSION=20100905201547
</code>```

2- now make changes(in your case add another column also) in this migration file and run

```<code>rake db:migrate
</code>```

but its always recommended to create new migration if you haven't push your code to git yet.

ContentLicense: CC BY-SA 3.0

Title: Making changes to an existing table?

Body:
As you said you ran migration already that means your change has been reflected to your database. so at this point if you want another change then its quite straight you need to make new migration, but there is a way that to make change in same migration for that

1 first you need to revert that migration that means you need to rollback that migration on which you want to change

rake db:migrate:down VERSION=20100905201547

2- now make changes(in your case add another column also) in this migration file and run

rake db:migrate

but its always recommended to create new migration if you haven't push your code to git yet.


问:
Set PySpark Serializer in PySpark Builder
I am using PySpark 2.1.1 and am trying to set the serializer when using Spark Submit. In my application, I initialize the SparkSession.builder as follows

```<code>print("creating spark session")
spark = SparkSession.builder.master("yarn").appName("AppName").\
config("driver-library-path","libPath")).\
config("driver-java-options",driverJavaOptions).\
enableHiveSupport().\
config("deploy-mode","client").\
config("spark.serializer","PickleSerializer").\
config("spark.executor.instances",100).\
config("spark.executor.memory","4g").\
getOrCreate()
</code>```

I am getting the following error

```<code>java.lang.ClassNotFoundException: PickleSerializer
</code>```

What is the right way to initialize the serializer? I realize Pickle is default but I want to know for if I use one of the other supported serializers as well.

答:
spark.serializer is used to set Java serializer. For Python serializer use serializer argument of SparkContext

```<code>from pyspark.serializers import PickleSerializer

conf = SparkConf().set(...)
sc  = SparkContext(conf=conf, serializer=PickleSerializer())
</code>```

Once SparkContext is ready you can  use it to initialize SparkSession explicitly:

```<code>spark = SparkSession(sc)
spark.sparkContext is sc

## True
</code>```

or implicitly (it will use SparkContext.getOrCreate):

```<code>spark = SparkSession.builder.enableHiveSupport().getOrCreate()
spark.sparkContext is sc

## True
</code>```

Body:
I am using PySpark 2.1.1 and am trying to set the serializer when using Spark Submit. In my application, I initialize the SparkSession.builder as follows

print("creating spark session")
spark = SparkSession.builder.master("yarn").appName("AppName").\
config("driver-library-path","libPath")).\
config("driver-java-options",driverJavaOptions).\
enableHiveSupport().\
config("deploy-mode","client").\
config("spark.serializer","PickleSerializer").\
config("spark.executor.instances",100).\
config("spark.executor.memory","4g").\
getOrCreate()

I am getting the following error

java.lang.ClassNotFoundException: PickleSerializer

What is the right way to initialize the serializer? I realize Pickle is default but I want to know for if I use one of the other supported serializers as well.

Body:
spark.serializer is used to set Java serializer. For Python serializer use serializer argument of SparkContext

from pyspark.serializers import PickleSerializer

conf = SparkConf().set(...)
sc  = SparkContext(conf=conf, serializer=PickleSerializer())

Once SparkContext is ready you can  use it to initialize SparkSession explicitly:

spark = SparkSession(sc)
spark.sparkContext is sc

## True

or implicitly (it will use SparkContext.getOrCreate):

spark = SparkSession.builder.enableHiveSupport().getOrCreate()
spark.sparkContext is sc

## True


问:
Highlight cells based on cell content with Excel VBA
This is for an Microsoft Excel VBA macro. What it is supposed to do, for every row, when "Late" is entered into column C, to highlight the cell 2 spaces to the left and Range of cells 3 spaces to the right through 43. So example is C4 contains "Late", highlight A4 and F4:AW4. Same goes for the word "Hold" just a different color.</p>

```<code>Private Sub Highlight_Condition(ByVal Target As Range)

Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
  lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
  Application.EnableEvents = False
  For i = lastRow To 1 Step -1
     If .Range("C" & i).Value = "LATE" Then
        Debug.Print "Checking Row: " & i
        .Range("A" & i).Interior.ColorIndex = 39
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
     ElseIf .Range("C" & i).Value = "HOLD" Then
        .Range("A" & i).Interior.ColorIndex = 43
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
     Else
        .Range("A" & i & ":AW" & i).ClearContents
        .Range("F" & i & ":AW" & i).ClearContents

     End If
  Next i
  Application.EnableEvents = True
End With
End Sub
</code>```

答:
... C4 contains "Late" ... (emphasis mine)

This seems to indicate that Late may be part of a longer string. I will code to that effect.

Conditional formatting rules are a quick method of achieving your cell highlighting and respond as soon as values in column C change without rerunning the sub procedure (unless more values are added below the lastRow).

```<code>Option Explicit

Sub Macro1()
    Const TEST_COLUMN As String = "D"
    Dim lastRow As Long, sSheetName As String

    sSheetName = ActiveSheet.Name

    With Worksheets(sSheetName)
        lastRow = .Cells(.Rows.Count, TEST_COLUMN).End(xlUp).Row
        With .Range("A4:A" & lastRow & ", F4:AW" & lastRow)
            .FormatConditions.Delete
            .FormatConditions.Add Type:=xlExpression, Formula1:="=isnumber(search(""late"", $c4))"
            .FormatConditions(.FormatConditions.Count).Interior.ColorIndex = 39
            .FormatConditions.Add Type:=xlExpression, Formula1:="=isnumber(search(""hold"", $c4))"
            .FormatConditions(.FormatConditions.Count).Interior.ColorIndex = 43
        End With
    End With

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is for an Microsoft Excel VBA macro. What it is supposed to do, for every row, when "Late" is entered into column C, to highlight the cell 2 spaces to the left and Range of cells 3 spaces to the right through 43. So example is C4 contains "Late", highlight A4 and F4:AW4. Same goes for the word "Hold" just a different color.

Private Sub Highlight_Condition(ByVal Target As Range)

Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
  lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
  Application.EnableEvents = False
  For i = lastRow To 1 Step -1
     If .Range("C" & i).Value = "LATE" Then
        Debug.Print "Checking Row: " & i
        .Range("A" & i).Interior.ColorIndex = 39
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
     ElseIf .Range("C" & i).Value = "HOLD" Then
        .Range("A" & i).Interior.ColorIndex = 43
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
     Else
        .Range("A" & i & ":AW" & i).ClearContents
        .Range("F" & i & ":AW" & i).ClearContents

     End If
  Next i
  Application.EnableEvents = True
End With
End Sub

Body:
... C4 contains "Late" ... (emphasis mine)

This seems to indicate that Late may be part of a longer string. I will code to that effect.

Conditional formatting rules are a quick method of achieving your cell highlighting and respond as soon as values in column C change without rerunning the sub procedure (unless more values are added below the lastRow).

Option Explicit

Sub Macro1()
    Const TEST_COLUMN As String = "D"
    Dim lastRow As Long, sSheetName As String

    sSheetName = ActiveSheet.Name

    With Worksheets(sSheetName)
        lastRow = .Cells(.Rows.Count, TEST_COLUMN).End(xlUp).Row
        With .Range("A4:A" & lastRow & ", F4:AW" & lastRow)
            .FormatConditions.Delete
            .FormatConditions.Add Type:=xlExpression, Formula1:="=isnumber(search(""late"", $c4))"
            .FormatConditions(.FormatConditions.Count).Interior.ColorIndex = 39
            .FormatConditions.Add Type:=xlExpression, Formula1:="=isnumber(search(""hold"", $c4))"
            .FormatConditions(.FormatConditions.Count).Interior.ColorIndex = 43
        End With
    End With

End Sub


问:
Cannot convert from java Double to java Date
I am having an issue with converting a double to a Java date object in the format: yyyy-MM-dd HH:mm:ss

I have tried to convert this double value to a long value then instanciate a Date object with the result, but I got errors saying that I cannot convert from double to long.

my timestamp double values are in this format:

1.511554592277516E9

Can anybody help me with this issue please, thanks in advance.

答:
Assuming that this floating point value is seconds past the Unix Epoch of 1 Jan 1970 0:00 GMT, this will provide a conversion to a LocalDateTime with that offset:

```<code>LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(
                Double.valueOf(1.511554592277516E9).longValue(), 0, ZoneOffset.UTC);
System.out.println(localDateTime);
</code>```

I leave converting this to a Date as an exercise for the reader.

Body:
Assuming that this floating point value is seconds past the Unix Epoch of 1 Jan 1970 0:00 GMT, this will provide a conversion to a LocalDateTime with that offset:

LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(
                Double.valueOf(1.511554592277516E9).longValue(), 0, ZoneOffset.UTC);
System.out.println(localDateTime);

I leave converting this to a Date as an exercise for the reader.


问:
Minimizing the distance between curves stacked on each other in R plot
I have an R function that plots some curves stacked on top of each other (see picture below the code).

I was wondering, however, how I could adjust the distance between the curves (see blue arrows) so that the curves don't look so flat?

Also, is it possible to use polygon instead of lines to plot these curves?

```<code>stacked = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

h = list()

for(i in 1:length(d)){
         p = function(x) get(d[i])(x, a, b)
     prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
likelihood = function(x) dbinom(Bi, n, x)
 posterior = function(x) prior(x)*likelihood(x)
      h[i] = list(curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n", n = 1e3))
}
plot(matrix(c(rep(c(.4, .8), each = length(d))), length(d), 2), rep(1:length(d), 2), ty = "n", xlim = 0:1, ann = FALSE, xaxt = "n", ylim = c(1, length(d)+.4))

for(i in 1:length(d)){
lines(h[[i]]$x, h[[i]]$y+i, ty = "l", xpd = NA, col = i)
  }
}
# Example of use:
stacked(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dbeta", "dlogis", "dweibull"))
</code>```

答:
You can just scale the y-values before drawing the lines.  I have added a scale parameter to your function.  Try scale =2 or 3

```<code>stacked = function(a, b, lo, hi, d, Bi = 55, n = 1e2, scale=1){

    h = list()
    for(i in 1:length(d)) {
             p = function(x) get(d[i])(x, a, b)
         prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
    likelihood = function(x) dbinom(Bi, n, x)
     posterior = function(x) prior(x)*likelihood(x)
          h[i] = list(curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n", n = 1e3))
    }
    plot(matrix(c(rep(c(.4, .8), each = length(d))), length(d), 2), rep(1:length(d), 2), ty = "n", xlim = 0:1, ann = FALSE, xaxt = "n", ylim = c(1, length(d)+.4))

    for(i in 1:length(d)){
        lines(h[[i]]$x, scale*h[[i]]$y+i, ty = "l", xpd = NA, col = i)
      }
}

stacked(lo = 0, hi = 1, a = 2, b = 3, scale=2,
    d = c("dgamma", "dnorm", "dcauchy", "dbeta", "dlogis", "dweibull"))
</code>```

If you wish to fill in the area under the curves,  you can use polygon. Change the lines:

```<code>for(i in 1:length(d)){
        lines(h[[i]]$x, scale*h[[i]]$y+i, ty = "l", xpd = NA, col = i)
      }
</code>```

TO

```<code>for(i in 1:length(d)){
    polygon(x=h[[i]]$x, y=scale*h[[i]]$y+i, col = i)
  }
</code>```

Body:
I have an R function that plots some curves stacked on top of each other (see picture below the code).

I was wondering, however, how I could adjust the distance between the curves (see blue arrows) so that the curves don't look so flat?

Also, is it possible to use polygon instead of lines to plot these curves?

stacked = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

h = list()

for(i in 1:length(d)){
         p = function(x) get(d[i])(x, a, b)
     prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
likelihood = function(x) dbinom(Bi, n, x)
 posterior = function(x) prior(x)*likelihood(x)
      h[i] = list(curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n", n = 1e3))
}
plot(matrix(c(rep(c(.4, .8), each = length(d))), length(d), 2), rep(1:length(d), 2), ty = "n", xlim = 0:1, ann = FALSE, xaxt = "n", ylim = c(1, length(d)+.4))

for(i in 1:length(d)){
lines(h[[i]]$x, h[[i]]$y+i, ty = "l", xpd = NA, col = i)
  }
}
# Example of use:
stacked(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dbeta", "dlogis", "dweibull"))

Body:
You can just scale the y-values before drawing the lines.  I have added a scale parameter to your function.  Try scale =2 or 3

stacked = function(a, b, lo, hi, d, Bi = 55, n = 1e2, scale=1){

    h = list()
    for(i in 1:length(d)) {
             p = function(x) get(d[i])(x, a, b)
         prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
    likelihood = function(x) dbinom(Bi, n, x)
     posterior = function(x) prior(x)*likelihood(x)
          h[i] = list(curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n", n = 1e3))
    }
    plot(matrix(c(rep(c(.4, .8), each = length(d))), length(d), 2), rep(1:length(d), 2), ty = "n", xlim = 0:1, ann = FALSE, xaxt = "n", ylim = c(1, length(d)+.4))

    for(i in 1:length(d)){
        lines(h[[i]]$x, scale*h[[i]]$y+i, ty = "l", xpd = NA, col = i)
      }
}

stacked(lo = 0, hi = 1, a = 2, b = 3, scale=2,
    d = c("dgamma", "dnorm", "dcauchy", "dbeta", "dlogis", "dweibull"))

If you wish to fill in the area under the curves,  you can use polygon. Change the lines:

for(i in 1:length(d)){
        lines(h[[i]]$x, scale*h[[i]]$y+i, ty = "l", xpd = NA, col = i)
      }

TO

for(i in 1:length(d)){
    polygon(x=h[[i]]$x, y=scale*h[[i]]$y+i, col = i)
  }


问:
Temporarily disable an input field if second input field is filled
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.

The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.

JS

```<code>var inp1 = document.getElementById("input1");
inp1.onchange = function () {
   if (this.value != "" || this.value.length > 0) {
      document.getElementById("input2").disabled = true;
   }
}
</code>```

HTML

```<code><input type="text" id="input1">
<input type="text" id="input2">
</code>```

答:
Don't make it harder than it is, this is simple.

var one = document.getElementById('one');
var two = document.getElementById('two');

//checks instantly
var checker = setInterval(function() {
    if(two.value !== '') {
      one.disabled = true;
    } else {
      //when its clear, it enabled again
      one.disabled = false;
    }
    if(one.value !== '') {
      two.disabled = true
    } else {
      two.disabled = false;
    }
}, 30);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="one">
<input id="two"></code>```

Body:
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.

The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.

JS

var inp1 = document.getElementById("input1");
inp1.onchange = function () {
   if (this.value != "" || this.value.length > 0) {
      document.getElementById("input2").disabled = true;
   }
}

HTML

<input type="text" id="input1">
<input type="text" id="input2">

Body:
Don't make it harder than it is, this is simple.

var one = document.getElementById('one');
var two = document.getElementById('two');

//checks instantly
var checker = setInterval(function() {
    if(two.value !== '') {
      one.disabled = true;
    } else {
      //when its clear, it enabled again
      one.disabled = false;
    }
    if(one.value !== '') {
      two.disabled = true
    } else {
      two.disabled = false;
    }
}, 30);

<input id="one">
<input id="two">


问:
Can't make drop-down hover work
I am trying to make a drop-down menu that drops from image but I can't seem to make it work. How should I target the hover? Because everything I am trying is not working. How I am trying to initiate hover effect is shown at the end of CSS.

.area-left {
  float: left;
}

.menu-icon {
  width: 28px;
  display: inline-block;
  vertical-align: middle;
  margin-top: 5px;
}

.menu-icon hr {
  border: 2px solid #A5CF4C;
  border-radius: 100px;
  margin-top: 3px;
  margin-bottom: 4px;
  margin-right: 5px;
  margin-left: 3px;
}

.area-left .menu li:hover {
  background-color: rgba(165, 207, 76, 0.4);
}

.logo img {
  vertical-align: middle;
  margin-top: 2px;
}

.sub-menu ul {
  background-color: rgba(255, 255, 255, 0.8);
}

.sub-menu li {
  border: 1px solid green;
  padding: 0px 5px;
}

.sub-menu .menu li:first-child {
  margin-top: 3px;
}

.sub-menu ul li {
  display: none;
}

.logo img:hover .sub-menu ul li {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="area-left">
  <ul id="htc-menu" class="parent-menu">
    <li class="logo ico-container">
      <div class="menu-icon">
        <hr/>
        <hr/>
        <hr/>
      </div><img src="images/logo.png" alt="HTC Logo"></li>
    <li class="sub-menu">
      <ul class="menu">
        <li>smartphones</li>
        <li>accessories</li>
        <li>virtual reality</li>
        <li>fitness</li>
      </ul>
    </li>
  </ul>
</div></code>```

答:
Try this :)

I purposely did not go with the adjacent CSS selector because once your mouse moves off the menu icon, the menu would disappear again, making it unhelpful. So you'll want to target the hover state of the parent element so that the menu remains visible while the mouse moves from the logo to the menu that just appears.

.area-left {
  float: left;
}

.menu-icon {
  width: 28px;
  display: inline-block;
  vertical-align: middle;
  margin-top: 5px;
}

.menu-icon hr {
  border: 2px solid #A5CF4C;
  border-radius: 100px;
  margin-top: 3px;
  margin-bottom: 4px;
  margin-right: 5px;
  margin-left: 3px;
}

.area-left .menu li:hover {
  background-color: rgba(165, 207, 76, 0.4);
}

.logo img {
  vertical-align: middle;
  margin-top: 2px;
}

.sub-menu ul {
  background-color: rgba(255, 255, 255, 0.8);
}

.sub-menu li {
  border: 1px solid green;
  padding: 0px 5px;
}

.sub-menu .menu li:first-child {
  margin-top: 3px;
}

.sub-menu ul li {
  display: none;
}

.logo img:hover .sub-menu ul li {
  display: block;
}

/* Tessa's Changes */

#htc-menu {
  list-style: none;
}

#htc-menu:hover li.sub-menu ul.menu li {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="area-left">
  <ul id="htc-menu" class="parent-menu">
    <li class="logo ico-container">
      <div class="menu-icon">
        <hr/>
        <hr/>
        <hr/>
      </div><img src="images/logo.png" alt="HTC Logo">
    </li>
    <li class="sub-menu">
      <ul class="menu">
        <li>smartphones</li>
        <li>accessories</li>
        <li>virtual reality</li>
        <li>fitness</li>
      </ul>
    </li>
  </ul>
</div></code>```

Title: Can't make drop-down hover work

Body:
I am trying to make a drop-down menu that drops from image but I can't seem to make it work. How should I target the hover? Because everything I am trying is not working. How I am trying to initiate hover effect is shown at the end of CSS.

.area-left {
  float: left;
}

.menu-icon {
  width: 28px;
  display: inline-block;
  vertical-align: middle;
  margin-top: 5px;
}

.menu-icon hr {
  border: 2px solid #A5CF4C;
  border-radius: 100px;
  margin-top: 3px;
  margin-bottom: 4px;
  margin-right: 5px;
  margin-left: 3px;
}

.area-left .menu li:hover {
  background-color: rgba(165, 207, 76, 0.4);
}

.logo img {
  vertical-align: middle;
  margin-top: 2px;
}

.sub-menu ul {
  background-color: rgba(255, 255, 255, 0.8);
}

.sub-menu li {
  border: 1px solid green;
  padding: 0px 5px;
}

.sub-menu .menu li:first-child {
  margin-top: 3px;
}

.sub-menu ul li {
  display: none;
}

.logo img:hover .sub-menu ul li {
  display: block;
}

smartphones

accessories

virtual reality

fitness

Body:
Try this :)

I purposely did not go with the adjacent CSS selector because once your mouse moves off the menu icon, the menu would disappear again, making it unhelpful. So you'll want to target the hover state of the parent element so that the menu remains visible while the mouse moves from the logo to the menu that just appears.

.area-left {
  float: left;
}

.menu-icon {
  width: 28px;
  display: inline-block;
  vertical-align: middle;
  margin-top: 5px;
}

.menu-icon hr {
  border: 2px solid #A5CF4C;
  border-radius: 100px;
  margin-top: 3px;
  margin-bottom: 4px;
  margin-right: 5px;
  margin-left: 3px;
}

.area-left .menu li:hover {
  background-color: rgba(165, 207, 76, 0.4);
}

.logo img {
  vertical-align: middle;
  margin-top: 2px;
}

.sub-menu ul {
  background-color: rgba(255, 255, 255, 0.8);
}

.sub-menu li {
  border: 1px solid green;
  padding: 0px 5px;
}

.sub-menu .menu li:first-child {
  margin-top: 3px;
}

.sub-menu ul li {
  display: none;
}

.logo img:hover .sub-menu ul li {
  display: block;
}

/* Tessa's Changes */

#htc-menu {
  list-style: none;
}

#htc-menu:hover li.sub-menu ul.menu li {
  display: block;
}

<div class="area-left">
  <ul id="htc-menu" class="parent-menu">
    <li class="logo ico-container">
      <div class="menu-icon">
        <hr/>
        <hr/>
        <hr/>
      </div><img src="images/logo.png" alt="HTC Logo">
    </li>
    <li class="sub-menu">
      <ul class="menu">
        <li><a href="http://www.htc.com/us/smartphones-learn/">smartphones</a></li>
        <li><a href="http://www.htc.com/us/accessories/">accessories</a></li>
        <li><a href="https://www.vive.com/us/">virtual reality</a></li>
        <li><a href="http://www.htc.com/us/fitness/ua-healthbox/">fitness</a></li>
      </ul>
    </li>
  </ul>
</div>


问:
derived function is invoked instead of base c++
Why does below code invoke base class' method in the second call?

Base class:

```<code>class Number{

      public:
         Number(){}

        virtual print(){cout<<"Number"<<endl;}
        virtual bool isEqual (Number* number){ cout<<"Base class"<<endl;}
};
</code>```

Derived class :

```<code>class Int: public Number{
   int member;
     public:
        Int(int number){ member =number; }

       int get Number(){ return member; }
       print(){ cout<<"member"<<endl;}
       bool isEqual(Int* number){ return member == number->getNumber(); }
};
</code>```

Main function:

```<code>int main(){
Int i1(3);
Int i2(4);

Number* nPtr = &i1;

nPter->print();  ///  prints 3
nPter->isEqual(&i2); /// "Base class"

...
</code>```

by the way:

```<code>i1.isEqual(&i2); /// prints 0 -- works fine
</code>```

答:
bool(Int*) is not the same type as bool(Number*), hence your function Int::isEqual does not override Number::isEqual -- rather, it's a completely separate function.

Just think about it for a minute; the attempted override makes no sense: Your derived class expects a constrained argument, but the base function's parameter is less constrained! If what you wanted were allowed,  nPtr->isEqual could be called with any Number pointer, which the derived class does not support!

The correct question would be for covariant return types but contravariant parameters. However, C++ does not allow contravariant parameter overriders.

Body:
Why does below code invoke base class' method in the second call?

Base class:

class Number{

      public:
         Number(){}

        virtual print(){cout<<"Number"<<endl;}
        virtual bool isEqual (Number* number){ cout<<"Base class"<<endl;}
};

Derived class :

class Int: public Number{
   int member;
     public:
        Int(int number){ member =number; }

       int get Number(){ return member; }
       print(){ cout<<"member"<<endl;}
       bool isEqual(Int* number){ return member == number->getNumber(); }
};

Main function:

int main(){
Int i1(3);
Int i2(4);

Number* nPtr = &i1;

nPter->print();  ///  prints 3
nPter->isEqual(&i2); /// "Base class"

...

by the way:

i1.isEqual(&i2); /// prints 0 -- works fine


问:
Java Graphics drawArc with high precision
I'm trying to draw a high precision arc in Java using AWT/Swing. The Graphics class offers the "drawArc" method to do this and in most cases this is fine. However, when the arc has a large radius (I.e. The "width" and "height" parameters are large) then the arc will not be drawn precisely. This is because the "startAngle" and "arcAngle" parameters are given as integer degrees. I'm forced to convert an angle (given in radians) to degrees and then rounding it. The loss of precision leads to the arc falling short of its actual end point (if you round down) or go further than it should (if you round up).

I'm looking for an alternative method of drawing arcs. Preferable this should work in the same way but accept floating point angles as parameters.

If such a function does not exist (I've not been able to find one) I would like to write it myself, but I have no idea how to go about this as the Graphics class already offers the lowest level drawing methods I can find. The only idea I had is to approximate the arc with a sequence of straight lines but to get a smooth arc you would need a lot of lines and this seems dreadfully inefficient.

答:
Using Graphics2D, you can use the rotate(theta,x,y) function to precisely draw one end of your arc:

```<code>g2.rotate(-1*thetaStartRadians,xc,yc);
g2.drawArc(x1,y1,width,height,0, thetaLengthDegrees-1);
g2.rotate(thetaStartRadians,xc,yc);
</code>```

Then you just need to precisely draw the last little bit on the other side:

```<code>g2.rotate(-1*thetaLengthRadians,xc,yc);
g2.drawArc(x1,y1,width,height,0,-2));
g2.rotate(thetaLengthRadians,xc,yc);
</code>```

And you'll have one arc drawn to precise theta values. It's probably not the most efficient way to do it, machine-wise, because of the bit of redraw overlap; but it's the simplest way to do it that I can think of.

Body:
Using Graphics2D, you can use the rotate(theta,x,y) function to precisely draw one end of your arc:

g2.rotate(-1*thetaStartRadians,xc,yc);
g2.drawArc(x1,y1,width,height,0, thetaLengthDegrees-1);
g2.rotate(thetaStartRadians,xc,yc);

Then you just need to precisely draw the last little bit on the other side:

g2.rotate(-1*thetaLengthRadians,xc,yc);
g2.drawArc(x1,y1,width,height,0,-2));
g2.rotate(thetaLengthRadians,xc,yc);

And you'll have one arc drawn to precise theta values. It's probably not the most efficient way to do it, machine-wise, because of the bit of redraw overlap; but it's the simplest way to do it that I can think of.


问:
What's at risk when we circumvent SQL Server's limitation for side effect operations in UDF?
Today I used the approach in this answer to great success, to replace names, insurance numbers and addresses with randomized garbage in multiple instances of the same database schema, depending on a "test" / "production" flag in the data.

Background: Trying to do

```<code>CREATE FUNCTION dbo.FailsToCreate()
RETURNS uniqueidentifier
AS
BEGIN
  RETURN NEWID()
END
</code>```

inevitably fails with

Msg 443, Level 16, State 1, Procedure FailsToCreate, Line 6 [Batch Start Line 27]
  Invalid use of a side-effecting operator 'newid' within a function.

Now we can be badass enough to do

```<code>CREATE VIEW dbo.vwGuessWhat AS SELECT NEWID() Fooled
</code>```

which surprisingly allows us to make it work with

```<code>CREATE FUNCTION dbo.SuddenlyWorks()
RETURNS uniqueidentifier
AS
BEGIN
  RETURN (SELECT Fooled FROM vwGuessWhat)
END
</code>```

Documentation is silent about consequences. It merely lists the functions that cannot be used, and does not mention a possibility to bypass the limitation.

Can I safely continue to use this approach in production code, or is there a danger in bypassing SQL Server's validation that will cause it to malfunction?

答:
There is no risk per se. You present an interesting way to circumvent a limitation with SQL functions.

On a seperate note, one of the many problems with scalar udfs is that they kill parallelism. In other words, queries that use dbo.SuddenlyWorks() will always run serially, even if you use Adam Machanic's make_parallel() or traceflag 8649.

If you wanted a parallel plan you would need to make dbo.SuddenlyWorks() an inline table valued function.

Body:
Today I used the approach in this answer to great success, to replace names, insurance numbers and addresses with randomized garbage in multiple instances of the same database schema, depending on a "test" / "production" flag in the data.

Background: Trying to do

CREATE FUNCTION dbo.FailsToCreate()
RETURNS uniqueidentifier
AS
BEGIN
  RETURN NEWID()
END

inevitably fails with

Msg 443, Level 16, State 1, Procedure FailsToCreate, Line 6 [Batch Start Line 27]
  Invalid use of a side-effecting operator 'newid' within a function.

Now we can be badass enough to do

CREATE VIEW dbo.vwGuessWhat AS SELECT NEWID() Fooled

which surprisingly allows us to make it work with

CREATE FUNCTION dbo.SuddenlyWorks()
RETURNS uniqueidentifier
AS
BEGIN
  RETURN (SELECT Fooled FROM vwGuessWhat)
END

Documentation is silent about consequences. It merely lists the functions that cannot be used, and does not mention a possibility to bypass the limitation.

Can I safely continue to use this approach in production code, or is there a danger in bypassing SQL Server's validation that will cause it to malfunction?


问:
Getting CheckBoxList Item values
I have a CheckBoxList which I'm populating with data. When I attempt to retrieve the checked items from the list I can only grab the item ordinal, I cannot get the value.

I've read that you can use Items[i].Value however when I try to do this I get an error stating that there is no extension method 'value'.

Here's the code I'm using to try and grab the information (note the GetItemText(i) actually only gives me the item position, not the text for the item)

```<code>   private void btnGO_Click(object sender, EventArgs e)
{
    for (int i = 0; i < chBoxListTables.Items.Count; i++)
    {
        if (chBoxListTables.GetItemChecked(i))
        {
            string str = chBoxListTables.GetItemText(i);
            MessageBox.Show(str);

            //next line invalid extension method
            chBoxListTables.Items[i].value;
        }
    }
}
</code>```

This is using .Net 4.0

Any thoughts would be appreciated...thanks

答:
You can try this:-</p>

```<code>string values = "";
foreach(ListItem item in myCBL.Items){
if(item.Selected)
{
values += item.Value.ToString() + ",";
}
}
values = values.TrimEnd(',');  //To eliminate comma in last.
</code>```

Title: Getting CheckBoxList Item values

Body:
I have a CheckBoxList which I'm populating with data. When I attempt to retrieve the checked items from the list I can only grab the item ordinal, I cannot get the value.

I've read that you can use Items[i].Value however when I try to do this I get an error stating that there is no extension method 'value'.

Here's the code I'm using to try and grab the information (note the GetItemText(i) actually only gives me the item position, not the text for the item)

   private void btnGO_Click(object sender, EventArgs e)
{
    for (int i = 0; i < chBoxListTables.Items.Count; i++)
    {
        if (chBoxListTables.GetItemChecked(i))
        {
            string str = chBoxListTables.GetItemText(i);
            MessageBox.Show(str);

            //next line invalid extension method
            chBoxListTables.Items[i].value;
        }
    }
}

This is using .Net 4.0

Any thoughts would be appreciated...thanks

Body:
You can try this:-

string values = "";
foreach(ListItem item in myCBL.Items){
if(item.Selected)
{
values += item.Value.ToString() + ",";
}
}
values = values.TrimEnd(',');  //To eliminate comma in last.


问:
Can't install profiler symfony flex
I'm unable to use the symfony profiler after running composer req profiler
I'm using symfony/skeleton in version 4.0 beta, but i remember having the same problem when i tested it a few months ago in 3.3.

The toolbar isn't working, message here :

An error occurred while loading the web debug toolbar. Open the web profiler.

And when click on "open the web profiler", i have a 404 error.

If someone resolved it, thank you for your help. If not, I'll report a bug while this is still in bêta.

About installation :
created a project with composer, with the symfony/skeleton package in version 4.0-beta linked here : https://github.com/symfony/skeleton

My php version is 7.1 ; i try to install profiler from the command above.

答:
OP fixed his issue already, but I thought I'd comment on my experience.  In my case, I used Flex to install the profiler just fine; checking out my app, routes were set correctly.  I followed Symfony's guide to webserver configuration for Apache and PHP-FPM, which worked great for getting PHP files running.  However, the section on rewrite rules for non-PHP files is in the mod_php section and not repeated in the FPM section.  I missed this while reading through quickly.  Specifically, you need to ensure you have the mod_rewrite block in your  configuration as follows (use either the Apache 2.2 or 2.4 setting, not both):</p>

```<code>DocumentRoot /var/www/project/public
<Directory /var/www/project/public>
    AllowOverride None

    # Apache 2.2
    Order Allow,Deny
    Allow from All
    # /Apache 2.2

    # Apache 2.4
    Require all granted
    # /Apache 2.4

    <IfModule mod_rewrite.c>
        Options -MultiViews
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php [QSA,L]
    </IfModule>
</Directory>
</code>```

Title: Can't install profiler symfony flex

Body:
OP fixed his issue already, but I thought I'd comment on my experience.  In my case, I used Flex to install the profiler just fine; checking out my app, routes were set correctly.  I followed Symfony's guide to webserver configuration for Apache and PHP-FPM, which worked great for getting PHP files running.  However, the section on rewrite rules for non-PHP files is in the mod_php section and not repeated in the FPM section.  I missed this while reading through quickly.  Specifically, you need to ensure you have the mod_rewrite block in your  configuration as follows (use either the Apache 2.2 or 2.4 setting, not both):

DocumentRoot /var/www/project/public
<Directory /var/www/project/public>
    AllowOverride None

    # Apache 2.2
    Order Allow,Deny
    Allow from All
    # /Apache 2.2

    # Apache 2.4
    Require all granted
    # /Apache 2.4

    <IfModule mod_rewrite.c>
        Options -MultiViews
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php [QSA,L]
    </IfModule>
</Directory>


问:
What's the equivalent 'nth_element' function in Java?
I don't want get a sorted array, just nth element's value.   For example, given the array

```<code> a = [20, 5, 1, -3]
</code>```

I'd like to be able to query

```<code>nth_element(a,2) = 1
</code>```

In C++, there is a function std::nth_element that can do this.  Is there an equivalent Java function?

Thanks!

答:
Here is a Java implementation of nth_element:</p>

```<code>class Nth_element
{
    static void nth_element_helper2(double[] arr, int beg, int end)
    {
        for(int i = beg + 1; i < end; i++)
        {
            for(int j = i; j > beg; j--)
            {
                if(arr[j - 1] < arr[j])
                    break;
                double t = arr[j];
                arr[j] = arr[j - 1];
                arr[j - 1] = t;
            }
        }
    }

    static void nth_element_helper(double[] arr, int beg, int end, int index)
    {
        if(beg + 4 >= end)
        {
            nth_element_helper2(arr, beg, end);
            return;
        }
        int initial_beg = beg;
        int initial_end = end;

        // Pick a pivot (using the median of 3 technique)
        double pivA = arr[beg];
        double pivB = arr[(beg + end) / 2];
        double pivC = arr[end - 1];
        double pivot;
        if(pivA < pivB)
        {
            if(pivB < pivC)
                pivot = pivB;
            else if(pivA < pivC)
                pivot = pivC;
            else
                pivot = pivA;
        }
        else
        {
            if(pivA < pivC)
                pivot = pivA;
            else if(pivB < pivC)
                pivot = pivC;
            else
                pivot = pivB;
        }

        // Divide the values about the pivot
        while(true)
        {
            while(beg + 1 < end && arr[beg] < pivot)
                beg++;
            while(end > beg + 1 && arr[end - 1] > pivot)
                end--;
            if(beg + 1 >= end)
                break;

            // Swap values
            double t = arr[beg];
            arr[beg] = arr[end - 1];
            arr[end - 1] = t;

            beg++;
            end--;
        }
        if(arr[beg] < pivot)
            beg++;

        // Recurse
        if(beg == initial_beg || end == initial_end)
            throw new RuntimeException("No progress. Bad pivot");
        if(index < beg) // This is where we diverge from QuickSort. We only recurse on one of the two sides. This is what makes nth_element fast.
            nth_element_helper(arr, initial_beg, beg, index);
        else
            nth_element_helper(arr, beg, initial_end, index);
    }

    static double nth_element(double[] arr, int index)
    {
        nth_element_helper(arr, 0, arr.length, index);
        return arr[index];
    }

    public static void main(String[] args)
    {
        double[] arr = { 9, 7, 1, 5, 6, 4, 3, 2, 8, 0, 10 };
        if(nth_element(arr, 5) == 5)
            System.out.println("seems to work");
        else
            System.out.println("broken");
    }
}
</code>```

Body:
I don't want get a sorted array, just nth element's value.   For example, given the array

 a = [20, 5, 1, -3]

I'd like to be able to query

nth_element(a,2) = 1

In C++, there is a function std::nth_element that can do this.  Is there an equivalent Java function?

Thanks!

Body:
Here is a Java implementation of nth_element:

class Nth_element
{
    static void nth_element_helper2(double[] arr, int beg, int end)
    {
        for(int i = beg + 1; i < end; i++)
        {
            for(int j = i; j > beg; j--)
            {
                if(arr[j - 1] < arr[j])
                    break;
                double t = arr[j];
                arr[j] = arr[j - 1];
                arr[j - 1] = t;
            }
        }
    }

    static void nth_element_helper(double[] arr, int beg, int end, int index)
    {
        if(beg + 4 >= end)
        {
            nth_element_helper2(arr, beg, end);
            return;
        }
        int initial_beg = beg;
        int initial_end = end;

        // Pick a pivot (using the median of 3 technique)
        double pivA = arr[beg];
        double pivB = arr[(beg + end) / 2];
        double pivC = arr[end - 1];
        double pivot;
        if(pivA < pivB)
        {
            if(pivB < pivC)
                pivot = pivB;
            else if(pivA < pivC)
                pivot = pivC;
            else
                pivot = pivA;
        }
        else
        {
            if(pivA < pivC)
                pivot = pivA;
            else if(pivB < pivC)
                pivot = pivC;
            else
                pivot = pivB;
        }

        // Divide the values about the pivot
        while(true)
        {
            while(beg + 1 < end && arr[beg] < pivot)
                beg++;
            while(end > beg + 1 && arr[end - 1] > pivot)
                end--;
            if(beg + 1 >= end)
                break;

            // Swap values
            double t = arr[beg];
            arr[beg] = arr[end - 1];
            arr[end - 1] = t;

            beg++;
            end--;
        }
        if(arr[beg] < pivot)
            beg++;

        // Recurse
        if(beg == initial_beg || end == initial_end)
            throw new RuntimeException("No progress. Bad pivot");
        if(index < beg) // This is where we diverge from QuickSort. We only recurse on one of the two sides. This is what makes nth_element fast.
            nth_element_helper(arr, initial_beg, beg, index);
        else
            nth_element_helper(arr, beg, initial_end, index);
    }

    static double nth_element(double[] arr, int index)
    {
        nth_element_helper(arr, 0, arr.length, index);
        return arr[index];
    }

    public static void main(String[] args)
    {
        double[] arr = { 9, 7, 1, 5, 6, 4, 3, 2, 8, 0, 10 };
        if(nth_element(arr, 5) == 5)
            System.out.println("seems to work");
        else
            System.out.println("broken");
    }
}


问:
How to retrieve the system timezone in TZ format .net c#
I'm trying to work out how to retrieve the current system timezone in a (TZ) format on windows, ie. America/New_York, I need to supply this to an API this application communicates with.

I'm currently using

```<code>TimeZone.CurrentTimeZone
</code>```

Which gives me this output

```<code>GMT Standard Time
</code>```

What I hope to get is something like

```<code>Europe/London
</code>```

Am I missing something simple or is this not available and thus does that mean I need to do the conversion myself?

答:
Noda Time is an excellent option.  It is a much better and more comprehensive API for working with dates, times, and time zones than what comes built-in to .NET.

However, if getting the system time zone in IANA TZDB format is the only thing you are doing in this space, you may find it simpler to use my TimeZoneConverter library.

```<code>string tz = TZConvert.WindowsToIana(TimeZoneInfo.Local.Id);
</code>```

Body:
I'm trying to work out how to retrieve the current system timezone in a (TZ) format on windows, ie. America/New_York, I need to supply this to an API this application communicates with.

I'm currently using

TimeZone.CurrentTimeZone

Which gives me this output

GMT Standard Time

What I hope to get is something like

Europe/London

Am I missing something simple or is this not available and thus does that mean I need to do the conversion myself?

Body:
Noda Time is an excellent option.  It is a much better and more comprehensive API for working with dates, times, and time zones than what comes built-in to .NET.

However, if getting the system time zone in IANA TZDB format is the only thing you are doing in this space, you may find it simpler to use my TimeZoneConverter library.

string tz = TZConvert.WindowsToIana(TimeZoneInfo.Local.Id);


问:
Passing a list<string> into Linq
The first query returns a list of string, and I am passing them into another table to find corresponding items, but nothing happens. no error message or nothing</p>

```<code>var classIds = _contextSpecRepo.Get(x => x.cId.Equals(cId)).Select(x => x.classNames).Distinct().ToList();
// issue happens in the following query
var classes= Repository.Get(x => x.Id.Equals(classIds)).ToList();
</code>```

答:
The call to Equals, which takes object, hides the problem: you are comparing a single Id to a list of Ids, rather than checking if the Id is present in a collection. This compiles, but yields no result.

Here is how you can fix it:

```<code>var classes= Repository.Get(x => classIds.Any(y => y == x.Id)).ToList();
</code>```

or

```<code>var classes= Repository.Get(x => classIds.Contains(x.Id)).ToList();
</code>```

Title: Passing a list<string> into Linq

Body:
The first query returns a list of string, and I am passing them into another table to find corresponding items, but nothing happens. no error message or nothing

var classIds = _contextSpecRepo.Get(x => x.cId.Equals(cId)).Select(x => x.classNames).Distinct().ToList();
// issue happens in the following query
var classes= Repository.Get(x => x.Id.Equals(classIds)).ToList();

Body:
The call to Equals, which takes object, hides the problem: you are comparing a single Id to a list of Ids, rather than checking if the Id is present in a collection. This compiles, but yields no result.

Here is how you can fix it:

var classes= Repository.Get(x => classIds.Any(y => y == x.Id)).ToList();

or

var classes= Repository.Get(x => classIds.Contains(x.Id)).ToList();


答:
If you must do it in 2 queries then you have to use contains

```<code>var classes= Repository.Get(x => classIds.Contains(x.Id)).ToList();
</code>```

A better solution would be to use a join on the tables.

Title: Passing a list<string> into Linq

Body:
If you must do it in 2 queries then you have to use contains

var classes= Repository.Get(x => classIds.Contains(x.Id)).ToList();

A better solution would be to use a join on the tables.


问:
User Profile Synchronization Service stuck at starting stage and stops automatically
We have two WFE servers and Application server for the SharePoint. User profile service is configured and we want use it. But User Profile Synchronization Service stays on starting state and after a while stops, then it makes the forefront identity manager services disabled too.

I just checked the farm user account access and also configure the service again and again to fix this issue.

答:
The stuck on starting issue can be a real pain to deal with.  Spencer Harbar wrote an article a few years ago that I, unfortunately, have to refer to from time to time.  It's very comprehensive and there are several things that could cause the problem but it usually comes down to incorrect permissions on either a windows service, a SharePoint service, a DB, or issues in forefront.  Bookmark this one... it will be your friend :)

http://www.harbar.net/articles/sp2010ups2.aspx


问:
download windows API reference (MSDN) for offline use
I would like to have a windows API reference document available offline. MSDN is fine, but I also need this kind of information when I don't have access to internet.

pdf, chm, help (for emacs) would be fine.

Surely I am not the first person to want that, but I can't find anything. Could someone please point to a place to find that?

I saw the reference was maybe available in the SDK, but installing it takes ~200 MB, and I only want the documentation.

答:
Just the Win32 API, but it's a thing of beauty: https://sourceforge.net/projects/win32-help-chm/files/

Edit: Dead link replaced with alternate download.

Although it is now 17 years old, the Win32.hlp file from Microsoft is
still a useful reference for those, like me, still programming using
the "flat" Windows API. It still covers 99% of what I need and is much
more convenient and faster to use than the current MSDN and Windows
SDK documentation because it is much smaller. It is a file that is
possible to add to the help menu of your IDE or favorite editor and
call up instantly, even offline.

ContentLicense: CC BY-SA 2.5


答:
If you are having uneven spaces, read the values as a single line first then squeeze the data with a regular expression then use STRSPLIT to split the single space separated data.

```<code>text_data = load 'file.txt' as line;

squeezed_data = foreach text_data generate REPLACE(line, '\\s+', ' ');
</code>```

Title: Remove uneven blank spaces from a txt file in pig

Body:
I have a text file with uneven blank spaces and I want to store it as a csv file using pig.My file is of the format

2013 210      0  2878 -7543 4  29  20 116
2013 210     10  2875 -7538 4  32  20 116
2013 210     20  2872 -7533 4  29  20 116
2013 210     30  2870 -7527 4  29  20 115
2013 210     40  2867 -7522 4  30  20 115
2013 210     50  2864 -7516 4  29  20 115
2013 210     60  2861 -7511 4  29  20 115

Body:
If you are having uneven spaces, read the values as a single line first then squeeze the data with a regular expression then use STRSPLIT to split the single space separated data.

text_data = load 'file.txt' as line;

squeezed_data = foreach text_data generate REPLACE(line, '\\s+', ' ');


问:
How to efficiently calculate multiple quantiles of column z when grouping by columns (x, y)
For example,

```<code>set.seed(2017)
dt <- data.table(
  x = sample(LETTERS, size = 10^7, replace = T),
  y = sample(LETTERS, size = 10^7, replace = T),
  z = sample(10^7, size = 10^7, replace = T)
)

          x y       z
       1: Y U 6830565
       2: N V 5063188
       3: M L 7551719
      ---
 9999998: C J 8951173
 9999999: C T 2265750
10000000: L B 1303897
</code>```

I would like to group by (x, y) and calculate multiple things regarding z.  This works,

```<code>system.time(
  result1 <- dt[, list(
    firstval = first(z),
    q1 = quantile(z, 0.5),
    q2 = quantile(z, 0.75),
    q3 = quantile(z, 0.9)
    ), keyby=list(x, y)]
)

     x y firstval      q1      q2      q3
  1: A A  4600349 4982000 7469398 8981072
  2: A B  9731616 4984859 7493566 9028473
  3: A C  3672771 5071190 7496436 8972589
 ---
674: Z X  1908196 5048164 7521350 9014482
675: Z Y  2933076 4985024 7500346 8977680
676: Z Z  6215175 5018085 7524220 9031993
</code>```

but is unnecessarily slow because each call to quantile is presumably re-ordering the same data.  I can vectorize this as follows

```<code>system.time(
  result2 <- dt[, list(
    firstval = first(z),
    quant = c(0.5, 0.75, 0.9),
    val = quantile(z, c(0.5, 0.75, 0.9))
  ), keyby=list(x, y)]
)

      x y firstval quant     val
   1: A A  4600349  0.50 4982000
   2: A A  4600349  0.75 7469398
   3: A A  4600349  0.90 8981072
  ---
2026: Z Z  6215175  0.50 5018085
2027: Z Z  6215175  0.75 7524220
2028: Z Z  6215175  0.90 9031993
</code>```

^^ this is faster but now my data is the wrong shape (and could be significantly, unnecessarily larger in size).  I can dcast the result to get what I want, but this is still memory inefficient.

How can I calculate the quantiles efficiently without transforming the shape of my data?  Ideally, I'm looking for something like

```<code>result3 <- dt[, c(
  list(firstval = first(z)),
  c("q1", "q2", "q3") = t(quantile(z, c(0.5, 0.75, 0.9)))
), keyby=list(x, y)]
</code>```

答:
We could use as.list instead of calling quantile multiple times

```<code>system.time(
 result2 <- dt[, c(list(
  firstval = first(z)), as.list(
  quantile(z, c(0.5, 0.75, 0.9)))
 ), keyby=list(x, y)]
)
</code>```

Body:
For example,

set.seed(2017)
dt <- data.table(
  x = sample(LETTERS, size = 10^7, replace = T),
  y = sample(LETTERS, size = 10^7, replace = T),
  z = sample(10^7, size = 10^7, replace = T)
)

          x y       z
       1: Y U 6830565
       2: N V 5063188
       3: M L 7551719
      ---
 9999998: C J 8951173
 9999999: C T 2265750
10000000: L B 1303897

I would like to group by (x, y) and calculate multiple things regarding z.  This works,

system.time(
  result1 <- dt[, list(
    firstval = first(z),
    q1 = quantile(z, 0.5),
    q2 = quantile(z, 0.75),
    q3 = quantile(z, 0.9)
    ), keyby=list(x, y)]
)

     x y firstval      q1      q2      q3
  1: A A  4600349 4982000 7469398 8981072
  2: A B  9731616 4984859 7493566 9028473
  3: A C  3672771 5071190 7496436 8972589
 ---
674: Z X  1908196 5048164 7521350 9014482
675: Z Y  2933076 4985024 7500346 8977680
676: Z Z  6215175 5018085 7524220 9031993

but is unnecessarily slow because each call to quantile is presumably re-ordering the same data.  I can vectorize this as follows

system.time(
  result2 <- dt[, list(
    firstval = first(z),
    quant = c(0.5, 0.75, 0.9),
    val = quantile(z, c(0.5, 0.75, 0.9))
  ), keyby=list(x, y)]
)

      x y firstval quant     val
   1: A A  4600349  0.50 4982000
   2: A A  4600349  0.75 7469398
   3: A A  4600349  0.90 8981072
  ---
2026: Z Z  6215175  0.50 5018085
2027: Z Z  6215175  0.75 7524220
2028: Z Z  6215175  0.90 9031993

^^ this is faster but now my data is the wrong shape (and could be significantly, unnecessarily larger in size).  I can dcast the result to get what I want, but this is still memory inefficient.

How can I calculate the quantiles efficiently without transforming the shape of my data?  Ideally, I'm looking for something like

result3 <- dt[, c(
  list(firstval = first(z)),
  c("q1", "q2", "q3") = t(quantile(z, c(0.5, 0.75, 0.9)))
), keyby=list(x, y)]

Body:
We could use as.list instead of calling quantile multiple times

system.time(
 result2 <- dt[, c(list(
  firstval = first(z)), as.list(
  quantile(z, c(0.5, 0.75, 0.9)))
 ), keyby=list(x, y)]
)


问:
How to go back to parent screen in react-navigation?

Problem

```<code>RootTabNavigator
    | Auth Screen
    | Welcome Screen
    | MainTabNavigator
              | FeedStacknavigator
                       | Screen A

              | MenuStackNavigator
                       | Screen B <-I'm here and want to reset to 'Auth Screen'
</code>```

The tree structure shows my app's Navigation structure. I'm on 'Screen B' and would like to go back to Auth Screen. (NOT Navigate) When I navigate to Auth Screen, it create new Auth Screen and I want to avoid it.

```<code>if ( ... ) {
      // I'm getting undefined error here
      nextProps.navigation.reset('Autho');
</code>```

Why is it not working?

Possible Solution1: reset

```<code>  const resetAction = NavigationActions.reset({
      index: 0,
      actions: [
          // getting error because auth screen is not in MenuStacknavigator.
          NavigationActions.navigate({ routeName: 'Auth'})
      ]
  })
  this.props.navigation.dispatch(resetAction);
</code>```

Possible Solution #2 :

```<code>  const backAction = NavigationActions.back({
    key: 'Autho'
  })
  # Back Action doesn't do anything
  this.props.navigation.dispatch(backAction); # not working
</code>```

Possible Solution #3 :

dispatch custom action. <- there were some solutions for StackNavigator but in my case it's TabNavigator.

答:
To reset to the start, I usually use:

```<code>NavigationActions.reset({
    index: 0,
    actions: []
)
</code>```

As an aside, a better navigation structure would be to have multiple tab navigators that you switch out depending on the auth state. In your case that would be something like an AuthTabNavigator and a MainTabNavigator, that you can switch between.

Hope this helps!

Body:
Problem

RootTabNavigator
    | Auth Screen
    | Welcome Screen
    | MainTabNavigator
              | FeedStacknavigator
                       | Screen A

              | MenuStackNavigator
                       | Screen B <-I'm here and want to reset to 'Auth Screen'

The tree structure shows my app's Navigation structure. I'm on 'Screen B' and would like to go back to Auth Screen. (NOT Navigate) When I navigate to Auth Screen, it create new Auth Screen and I want to avoid it.

if ( ... ) {
      // I'm getting undefined error here
      nextProps.navigation.reset('Autho');

Why is it not working?

Possible Solution1: reset

  const resetAction = NavigationActions.reset({
      index: 0,
      actions: [
          // getting error because auth screen is not in MenuStacknavigator.
          NavigationActions.navigate({ routeName: 'Auth'})
      ]
  })
  this.props.navigation.dispatch(resetAction);

Possible Solution #2 :

  const backAction = NavigationActions.back({
    key: 'Autho'
  })
  # Back Action doesn't do anything
  this.props.navigation.dispatch(backAction); # not working

Possible Solution #3 :

dispatch custom action. <- there were some solutions for StackNavigator but in my case it's TabNavigator.

Body:
To reset to the start, I usually use:

NavigationActions.reset({
    index: 0,
    actions: []
)

As an aside, a better navigation structure would be to have multiple tab navigators that you switch out depending on the auth state. In your case that would be something like an AuthTabNavigator and a MainTabNavigator, that you can switch between.

Hope this helps!


问:
Python RandomForest - Unknown label Error
I have trouble using RandomForest fit function

This is my training set

```<code>         P1      Tp1           IrrPOA     Gz          Drz2
0        0.0     7.7           0.0       -1.4        -0.3
1        0.0     7.7           0.0       -1.4        -0.3
2        ...     ...           ...        ...         ...
3        49.4    7.5           0.0       -1.4        -0.3
4        47.4    7.5           0.0       -1.4        -0.3
... (10k rows)
</code>```

I want to predict P1 thanks to all the other variables using sklearn.ensemble RandomForest

```<code>colsRes = ['P1']
X_train = train.drop(colsRes, axis = 1)
Y_train = pd.DataFrame(train[colsRes])
rf = RandomForestClassifier(n_estimators=100)
rf.fit(X_train, Y_train)
</code>```

Here is the error I get:

```<code>ValueError: Unknown label type: array([[  0. ],
       [  0. ],
       [  0. ],
       ...,
       [ 49.4],
       [ 47.4],
</code>```

I did not find anything about this label error, I use Python 3.5.
Any advice would be a great help !

答:
may be a tad late to the party but I just got this error and solved it by making sure my y variable was type(int) using </p>

```<code> y = df['y_variable'].astype(int)
</code>```

<p>before doing a train test split, also like others have said you problem seems better fit with a RFReg rather then RF </p>

Body:
I have trouble using RandomForest fit function

This is my training set

         P1      Tp1           IrrPOA     Gz          Drz2
0        0.0     7.7           0.0       -1.4        -0.3
1        0.0     7.7           0.0       -1.4        -0.3
2        ...     ...           ...        ...         ...
3        49.4    7.5           0.0       -1.4        -0.3
4        47.4    7.5           0.0       -1.4        -0.3
... (10k rows)

I want to predict P1 thanks to all the other variables using sklearn.ensemble RandomForest

colsRes = ['P1']
X_train = train.drop(colsRes, axis = 1)
Y_train = pd.DataFrame(train[colsRes])
rf = RandomForestClassifier(n_estimators=100)
rf.fit(X_train, Y_train)

Here is the error I get:

ValueError: Unknown label type: array([[  0. ],
       [  0. ],
       [  0. ],
       ...,
       [ 49.4],
       [ 47.4],

I did not find anything about this label error, I use Python 3.5.
Any advice would be a great help !

Body:
may be a tad late to the party but I just got this error and solved it by making sure my y variable was type(int) using

 y = df['y_variable'].astype(int)

before doing a train test split, also like others have said you problem seems better fit with a RFReg rather then RF


问:
you are using a browser that is not supported by the google maps javascript api

I have .net windows web browser control, which loads the Google map

Recently it started to show "you are using a browser that is not supported by the google maps javascript api". I pin pointed that by default it is loaded on IE 7. Then I controlled it by adding

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge" />
</code>```

Then made sure that it loads on IE 11 with the help of custom javascript function. But still it shows the message.
Note: This message is not appeared when map is loaded on stand alone browser with above tag.

Some one an idea why or what I should change? Control it by registry is not an option.

答:
Remove directly with CSS.</p>

```<code>  .infomsg {
      display:none;
    }
</code>```

Body:
I have .net windows web browser control, which loads the Google map

Recently it started to show "you are using a browser that is not supported by the google maps javascript api". I pin pointed that by default it is loaded on IE 7. Then I controlled it by adding

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Then made sure that it loads on IE 11 with the help of custom javascript function. But still it shows the message.
Note: This message is not appeared when map is loaded on stand alone browser with above tag.

Some one an idea why or what I should change? Control it by registry is not an option.

Body:
Remove directly with CSS.

  .infomsg {
      display:none;
    }


问:
Unix cksum on Windows Machine through Matlab
My company develops products, primarily using Matlab scripts, that gets used by our customer in a RedHat environment we do not have access to.

I am trying to figure out a way to to a unix cksum command in Matlab so that when our costumer receives it they can verify that nothing has changed.

Edit for clarification: Since the tools used for development are in matlab, the PM would like the Unix cksum function integrated into the creation so that the output of our tool always matches what we deliver to the customer on a Unix system. We've found that a DOS cksum command and a Unix cksum don't give the exact same results

答:
So, if your goal is to calculate a *NIX style checksum within the Matlab application itself and you really can't avoid this (for example, calling cksum with unix), the best option you have is to use Java interop within Matlab to achieve this task. Implementing a CRC32 Checksum calculation based exclusively on Matlab built-in functions risks to become a painful task... fortunately, Matlab allows full usage of Java technology within its environment.

The following code should perfectly replicate the *NIX cksum command output:

```<code>function crc32 = CalculateCRC32(file_path)

    persistent array;

    if isempty(array)
        array = javaArray('java.lang.String',0);
    end

    import('java.lang.Long');
    import('java.nio.file.Files');
    import('java.nio.file.Paths');
    import('java.util.zip.CRC32');

    path = Paths.get(file_path,array);
    data = Files.readAllBytes(path);

    provider = java.util.zip.CRC32();
    provider.update(data);

    crc32 = char(Long.toHexString(provider.getValue()));

end
</code>```

Use it within your application as follows:

```<code>crc32 = CalculateCRC32('C:\Path\To\MyFile.something');
</code>```

Body:
So, if your goal is to calculate a *NIX style checksum within the Matlab application itself and you really can't avoid this (for example, calling cksum with unix), the best option you have is to use Java interop within Matlab to achieve this task. Implementing a CRC32 Checksum calculation based exclusively on Matlab built-in functions risks to become a painful task... fortunately, Matlab allows full usage of Java technology within its environment.

The following code should perfectly replicate the *NIX cksum command output:

function crc32 = CalculateCRC32(file_path)

    persistent array;

    if isempty(array)
        array = javaArray('java.lang.String',0);
    end

    import('java.lang.Long');
    import('java.nio.file.Files');
    import('java.nio.file.Paths');
    import('java.util.zip.CRC32');

    path = Paths.get(file_path,array);
    data = Files.readAllBytes(path);

    provider = java.util.zip.CRC32();
    provider.update(data);

    crc32 = char(Long.toHexString(provider.getValue()));

end

Use it within your application as follows:

crc32 = CalculateCRC32('C:\Path\To\MyFile.something');


问:
C++11: accessing member functions from vector of vectors
How to access functions of this class from a vector of vectors?

someNamespace::SomeClass *test;
test->doSomething();

If I want to have multiple instances of the same class, I am giving it like this:

std::vector< std::vector<someNamespace::SomeClass> > test;
test.resize(SomeValueofSize_t);

The number of instances of "test" is known at runtime.

This is how I am accessing doSomething() now.

test[0][0].doSomething();

The code compiles, but I am not sure if that is the correct way to do

答:
It's not clear to me why you have a two-dimensional vector of class objects, but to do what you ask, you should iterate over both dimensions like @nwp suggested.

Assuming that you have a vector of vector of objects someClass called test as opposed to pointers to someClass instances i.e. std::vector <std::vector <someNamespace::SomeClass> > test; you would just iterate over them like this and make your call to doSomething().  If doSomething() has to modify the test object, just remove the const.

```<code>for (const auto& element : test)
{
    for (const auto& obj : element)
    {
        obj.doSomething();
    }
}
</code>```

Body:
It's not clear to me why you have a two-dimensional vector of class objects, but to do what you ask, you should iterate over both dimensions like @nwp suggested.

Assuming that you have a vector of vector of objects someClass called test as opposed to pointers to someClass instances i.e. std::vector <std::vector <someNamespace::SomeClass> > test; you would just iterate over them like this and make your call to doSomething().  If doSomething() has to modify the test object, just remove the const.

for (const auto& element : test)
{
    for (const auto& obj : element)
    {
        obj.doSomething();
    }
}


问:
How to get Android simple Firebase Authentication to work? Getting null object reference error

Issue Fixed Update: Fixed by downgrading Firebase to 9.6.0 (just a random version I chose). I'm assuming the original issue has something to do with the emulator's good play or something.

Old Issue: So I need help, trying to set up Firebase Auth for logging in a user. I've enable this in  my Firebase console and I've done this before and had it working as a class assignment weeks ago. But this time I'm getting a Null Object Reference when trying to login.

I'm starting to think this is related to my gradle files.
mAuth isn't null, String email and password aren't null. I'm simply following this Firebase guide: https://firebase.google.com/docs/auth/android/password-auth

Exact Logcat error here

Module app Gradle file here

Project Gradle file here

Full class below. Line 43 where the error begins (as from the screenshot) is
 'mAuth.signInWithEmailAndPassword(email, password)'

```<code>package com.example.bri.inclass09;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class LoginActivity extends AppCompatActivity {

private FirebaseAuth mAuth;
private EditText emailET, passwordET;
private Button login, signup;
private static final String TAG = "test";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mAuth = FirebaseAuth.getInstance();
    Log.d(TAG, "mAuth is: " + mAuth.toString());
    login = findViewById(R.id.loginButton);
    signup = findViewById(R.id.signupButton);
    emailET =  findViewById(R.id.loginEmailET);
    passwordET = findViewById(R.id.loginPassET);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String email = emailET.getText().toString();
            String password = passwordET.getText().toString();
            Log.d(TAG, email + " " + password);

            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
                                Log.d(TAG, "createUserWithEmail:success");
                                FirebaseUser user = mAuth.getCurrentUser();
                            } else {
                                // If sign in fails, display a message to the user.
                                Log.w(TAG, "createUserWithEmail:failure", task.getException());
                                Toast.makeText(LoginActivity.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            }

                            // ...
                        }
                    });
        }
    });
}

@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    //FirebaseUser currentUser = mAuth.getCurrentUser();
}
</code>```

}

答:
In your app module build.gradle file:

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

is misplaced.  It should be the very last line, outside the dependencies block.

In addition, the device or emulator must have a version of Google Play services installed that is compatible with the version of Firebase you build with.  If you are seeing this problem on a device, you can go to the Play Store to download the latest version.  If you are using an emulator, you need to use the SDK Manager to download the latest Google APIs System Image for the emulator you are using.

Body:
Issue Fixed Update: Fixed by downgrading Firebase to 9.6.0 (just a random version I chose). I'm assuming the original issue has something to do with the emulator's good play or something.

Old Issue: So I need help, trying to set up Firebase Auth for logging in a user. I've enable this in  my Firebase console and I've done this before and had it working as a class assignment weeks ago. But this time I'm getting a Null Object Reference when trying to login.

I'm starting to think this is related to my gradle files.
mAuth isn't null, String email and password aren't null. I'm simply following this Firebase guide: https://firebase.google.com/docs/auth/android/password-auth

Exact Logcat error here

Module app Gradle file here

Project Gradle file here

Full class below. Line 43 where the error begins (as from the screenshot) is
 'mAuth.signInWithEmailAndPassword(email, password)'

package com.example.bri.inclass09;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class LoginActivity extends AppCompatActivity {

private FirebaseAuth mAuth;
private EditText emailET, passwordET;
private Button login, signup;
private static final String TAG = "test";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mAuth = FirebaseAuth.getInstance();
    Log.d(TAG, "mAuth is: " + mAuth.toString());
    login = findViewById(R.id.loginButton);
    signup = findViewById(R.id.signupButton);
    emailET =  findViewById(R.id.loginEmailET);
    passwordET = findViewById(R.id.loginPassET);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String email = emailET.getText().toString();
            String password = passwordET.getText().toString();
            Log.d(TAG, email + " " + password);

            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
                                Log.d(TAG, "createUserWithEmail:success");
                                FirebaseUser user = mAuth.getCurrentUser();
                            } else {
                                // If sign in fails, display a message to the user.
                                Log.w(TAG, "createUserWithEmail:failure", task.getException());
                                Toast.makeText(LoginActivity.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            }

                            // ...
                        }
                    });
        }
    });
}

@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    //FirebaseUser currentUser = mAuth.getCurrentUser();
}

}

Body:
In your app module build.gradle file:

apply plugin: 'com.google.gms.google-services'

is misplaced.  It should be the very last line, outside the dependencies block.

In addition, the device or emulator must have a version of Google Play services installed that is compatible with the version of Firebase you build with.  If you are seeing this problem on a device, you can go to the Play Store to download the latest version.  If you are using an emulator, you need to use the SDK Manager to download the latest Google APIs System Image for the emulator you are using.


问:
Calling flet or labels functions in clisp
I new to common lisp (clisp-2.49)

Can I call an flet or labels function from a different outside function?
If so, how? (In a source file)

This code works except for the last print statement where it loses scope to f(n) on the last line.

```<code>(labels ((f (n)
         (+ n 10)))
  (print(f 5)))

(print (f 2))
</code>```

答:
Related to the answer by Earl D, you can do things like this

```<code>(defmacro define-function (name v)
  `(progn
     (setf (fdefinition ',name) ,v)
     ',name))
</code>```

Then

```<code>(define-function global-x (let ((s 0))
                            (labels ((local-x (a)
                                       (incf s a)))
                              #'local-x)))
</code>```

Will do what you think it should.

This is slightly more different than the (let ... (defun ...)) case than it seems: in that case, the defining macro (defun here) is not at top-level, even if the let is, and that can result in various hair when compiling things.

Body:
I new to common lisp (clisp-2.49)

Can I call an flet or labels function from a different outside function?
If so, how? (In a source file)

This code works except for the last print statement where it loses scope to f(n) on the last line.

(labels ((f (n)
         (+ n 10)))
  (print(f 5)))

(print (f 2))

Body:
Related to the answer by Earl D, you can do things like this

(defmacro define-function (name v)
  `(progn
     (setf (fdefinition ',name) ,v)
     ',name))

Then

(define-function global-x (let ((s 0))
                            (labels ((local-x (a)
                                       (incf s a)))
                              #'local-x)))

Will do what you think it should.

This is slightly more different than the (let ... (defun ...)) case than it seems: in that case, the defining macro (defun here) is not at top-level, even if the let is, and that can result in various hair when compiling things.


问:
emacs configuration: python-mode-hook
I am struggling with my emacs configuration. The relevant lines in .emacs are:

```<code>(require 'python-mode)
(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))

(add-hook
 'python-mode-hook
 '(lambda ()
    (message "python-mode-hook called")
    (require 'jedi)
    (when (require 'elpy nil t)
      (elpy-enable)
      (setq elpy-rpc-backend "jedi")
      (add-hook
       'jedi-mode-hook
       '(lambda ()
          (setq-local ac-max-width 0.5))))))
</code>```

Whan I load a python file, the hook is called and I get the "python-mode-hook called" message. However, the elpy functionality is not there. If I then M-x python-mode, everything is as it should.

I don't understand why I need to call "python-mode" twice. I somehow think it may be related to the hooks being called/defined in the wrong order, but I don't understand what is wrong here.

I'd appreciate some hints.

答:
To enable elpy functionality, all you need in your .emacs is

```<code>(package-initialize)
(elpy-enable)
</code>```

However, you also have to properly install elpy package itself.

Try to perform all steps from "Quick installation" section: https://github.com/jorgenschaefer/elpy#quick-installation

Title: emacs configuration: python-mode-hook

Body:
I am struggling with my emacs configuration. The relevant lines in .emacs are:

(require 'python-mode)
(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))

(add-hook
 'python-mode-hook
 '(lambda ()
    (message "python-mode-hook called")
    (require 'jedi)
    (when (require 'elpy nil t)
      (elpy-enable)
      (setq elpy-rpc-backend "jedi")
      (add-hook
       'jedi-mode-hook
       '(lambda ()
          (setq-local ac-max-width 0.5))))))

Whan I load a python file, the hook is called and I get the "python-mode-hook called" message. However, the elpy functionality is not there. If I then M-x python-mode, everything is as it should.

I don't understand why I need to call "python-mode" twice. I somehow think it may be related to the hooks being called/defined in the wrong order, but I don't understand what is wrong here.

I'd appreciate some hints.

Body:
To enable elpy functionality, all you need in your .emacs is

(package-initialize)
(elpy-enable)

However, you also have to properly install elpy package itself.

Try to perform all steps from "Quick installation" section: https://github.com/jorgenschaefer/elpy#quick-installation


问:
Getting changed data from PyQt5 QDialog
I've got a configuration dialog that I'm pre-populating with the existing options, which are stored in cfg. When the user clicks "Save" (or equivalent), I need to get the new values from the QLineEdit objects. Except I can't figure that bit out. I've been Googling and testing since yesterday evening, before I came here on bended knee yet again. Here's my dialog code (the form is from Qt Designer, which is why there's no GUI code):

```<code>class Config(QDialog):
    def __init__(self):
        super(Config, self).__init__()

        popup = QDialog()
        config_ui = configform()
        config_ui.setupUi(popup)

        config_ui.programver.setText(cfg['config']['programver'])

        if cfg['config']['dummycopy']:
            config_ui.democheck.setChecked(True)

        config_ui.tmdbAPIkey.setText(cfg['config']['TMDB_KEY'])
        config_ui.tvdbAPIkey.setText(cfg['config']['TVDB_KEY'])
        config_ui.tvdbUserkey.setText(cfg['config']['TVDB_USERKEY'])

        theme = cfg['config']['theme']

        if theme == "blue":
            config_ui.bluebutton.setChecked(True)
        elif theme == "yellow":
            config_ui.yellowbutton.setChecked(True)
        elif theme == "light":
            config_ui.lightmetalbutton.setChecked(True)
        elif theme == "dark":
            config_ui.darkmetalbutton.setChecked(True)

        programversion = config_ui.programver.text()

        config_ui.savebutton.clicked.connect(lambda: Config.save(self, programversion))

        popup.exec_()

    def save(self, programversion):
        QDialog.close(self)
        print(programversion)
</code>```

I need some voodoo to get at the changed fields. All I can get now are the original values from when the dialog was brought to life. Is there a trick to this? I can't be the first person to try pre-populating a dialog box. I swear I've tried every combination of button and buttonBox variations available.

I'm thinking maybe there's some way of hiding the dialog, grabbing the data, and then destroying the dialog? That's one working theory, anyway.

Thanks in advance.

答:
To work in a simple way we use the design of Qt Designer to fill the Dialog, and we connect the cancel button to self.reject () and the save button to the save () slot, in this we save the data and issue self.accept () :</p>

```<code>from PyQt5.QtWidgets import *
from Ui_config_dialog import Ui_configdialog
import configparser

class Config(QDialog, Ui_configdialog):
    def __init__(self, *args, **kwargs):
        QDialog.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.cancelbutton.clicked.connect(self.reject)
        self.filename = "joe.conf"
        self.cfg = configparser.ConfigParser()
        self.cfg.read(self.filename)
        self.load()

    def load(self):
        self.programver.setText(self.cfg['config']['programver'])
        self.democheck.setChecked(self.cfg.getboolean("config", "dummycopy"))
        self.tmdbAPIkey.setText(self.cfg['config']['TMDB_KEY'])
        self.tvdbAPIkey.setText(self.cfg['config']['TVDB_KEY'])
        self.tvdbUserkey.setText(self.cfg['config']['TVDB_USERKEY'])
        theme = self.cfg['config']['theme']

        self.buttons = {"blue": self.bluebutton,
                        "yellow": self.yellowbutton,
                        "light": self.lightmetalbutton,
                        "dark": self.darkmetalbutton}

        self.buttons[theme].setChecked(True)
        self.group = QButtonGroup(self)
        self.group.addButton(self.bluebutton)
        self.group.addButton(self.yellowbutton)
        self.group.addButton(self.lightmetalbutton)
        self.group.addButton(self.darkmetalbutton)
        self.savebutton.clicked.connect(self.save)

    def save(self):
        self.cfg['config']['programver'] = self.programver.text()
        self.cfg['config']['dummycopy'] = "True" if self.democheck.isChecked() else "False"
        self.cfg['config']['TMDB_KEY'] = self.tmdbAPIkey.text()
        self.cfg['config']['TVDB_KEY'] = self.tvdbUserkey.text()
        for key, btn in self.buttons.items():
            if btn == self.group.checkedButton():
                 self.cfg['config']['theme'] = key
                 break

        with open(self.filename, 'w') as configfile:
            self.cfg.write(configfile)
        self.accept()

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = Config()
    w.show()
    sys.exit(app.exec_())
</code>```

Title: Getting changed data from PyQt5 QDialog

Body:
I've got a configuration dialog that I'm pre-populating with the existing options, which are stored in cfg. When the user clicks "Save" (or equivalent), I need to get the new values from the QLineEdit objects. Except I can't figure that bit out. I've been Googling and testing since yesterday evening, before I came here on bended knee yet again. Here's my dialog code (the form is from Qt Designer, which is why there's no GUI code):

class Config(QDialog):
    def __init__(self):
        super(Config, self).__init__()

        popup = QDialog()
        config_ui = configform()
        config_ui.setupUi(popup)

        config_ui.programver.setText(cfg['config']['programver'])

        if cfg['config']['dummycopy']:
            config_ui.democheck.setChecked(True)

        config_ui.tmdbAPIkey.setText(cfg['config']['TMDB_KEY'])
        config_ui.tvdbAPIkey.setText(cfg['config']['TVDB_KEY'])
        config_ui.tvdbUserkey.setText(cfg['config']['TVDB_USERKEY'])

        theme = cfg['config']['theme']

        if theme == "blue":
            config_ui.bluebutton.setChecked(True)
        elif theme == "yellow":
            config_ui.yellowbutton.setChecked(True)
        elif theme == "light":
            config_ui.lightmetalbutton.setChecked(True)
        elif theme == "dark":
            config_ui.darkmetalbutton.setChecked(True)

        programversion = config_ui.programver.text()

        config_ui.savebutton.clicked.connect(lambda: Config.save(self, programversion))

        popup.exec_()

    def save(self, programversion):
        QDialog.close(self)
        print(programversion)

I need some voodoo to get at the changed fields. All I can get now are the original values from when the dialog was brought to life. Is there a trick to this? I can't be the first person to try pre-populating a dialog box. I swear I've tried every combination of button and buttonBox variations available.

I'm thinking maybe there's some way of hiding the dialog, grabbing the data, and then destroying the dialog? That's one working theory, anyway.

Thanks in advance.

Body:
To work in a simple way we use the design of Qt Designer to fill the Dialog, and we connect the cancel button to self.reject () and the save button to the save () slot, in this we save the data and issue self.accept () :

from PyQt5.QtWidgets import *
from Ui_config_dialog import Ui_configdialog
import configparser

class Config(QDialog, Ui_configdialog):
    def __init__(self, *args, **kwargs):
        QDialog.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.cancelbutton.clicked.connect(self.reject)
        self.filename = "joe.conf"
        self.cfg = configparser.ConfigParser()
        self.cfg.read(self.filename)
        self.load()

    def load(self):
        self.programver.setText(self.cfg['config']['programver'])
        self.democheck.setChecked(self.cfg.getboolean("config", "dummycopy"))
        self.tmdbAPIkey.setText(self.cfg['config']['TMDB_KEY'])
        self.tvdbAPIkey.setText(self.cfg['config']['TVDB_KEY'])
        self.tvdbUserkey.setText(self.cfg['config']['TVDB_USERKEY'])
        theme = self.cfg['config']['theme']

        self.buttons = {"blue": self.bluebutton,
                        "yellow": self.yellowbutton,
                        "light": self.lightmetalbutton,
                        "dark": self.darkmetalbutton}

        self.buttons[theme].setChecked(True)
        self.group = QButtonGroup(self)
        self.group.addButton(self.bluebutton)
        self.group.addButton(self.yellowbutton)
        self.group.addButton(self.lightmetalbutton)
        self.group.addButton(self.darkmetalbutton)
        self.savebutton.clicked.connect(self.save)

    def save(self):
        self.cfg['config']['programver'] = self.programver.text()
        self.cfg['config']['dummycopy'] = "True" if self.democheck.isChecked() else "False"
        self.cfg['config']['TMDB_KEY'] = self.tmdbAPIkey.text()
        self.cfg['config']['TVDB_KEY'] = self.tvdbUserkey.text()
        for key, btn in self.buttons.items():
            if btn == self.group.checkedButton():
                 self.cfg['config']['theme'] = key
                 break

        with open(self.filename, 'w') as configfile:
            self.cfg.write(configfile)
        self.accept()

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = Config()
    w.show()
    sys.exit(app.exec_())


问:
Entity Framework Code Only error: the model backing the context has changed since the database was created
I created a "Code Only" POCO for use against an existing database using Entity Framework 4 and the CTP4.  When I run a query I get the error

The model backing the 'xyzContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

I'm unclear on why this is happening or what I can change.  I merely created the POCO, defined a simple DbContext, made a few tweaks, and then tried to run a simple query.  Since I'm using "Code Only", I'm unaware of any configuration settings that need to be made. And I certainly don't want to recreate or delete the database since it's an existing database.

Thanks for any ideas.

答:
This is a bug in CTP4 for using EF with pre-existing databases.

You can fix it by calling:

```<code>Database.SetInitializer<YourContext>(null);
</code>```

in the Application_Start method of Global.asax

Body:
This is a bug in CTP4 for using EF with pre-existing databases.

You can fix it by calling:

Database.SetInitializer<YourContext>(null);

in the Application_Start method of Global.asax


问:
Using google cloud plateform to analyse logs
What is the best way to store logs in GCP from a external system (ex: embedding system) , and analyse it .

Thanks.

答:
Stackdriver Logging is the thing you're looking for.  Here's an example of how it's used:
https://cloud.google.com/solutions/stackdriver-logging-for-dgs</p>


问:
Can't resize iFrame
The iFrame or wrapper div will not change size, whatever i try:

The Output:

The HTML:

```<code><html>
<head>
    <link rel="stylesheet" href="CV.css">
<title>
George's CV
</title>
</head>
<body>
    <div className="phone" style="height: 737px; width: 654px">
        <div className="container" style="height: 536px; width: 350px">
            <iframe src="http://foodsharing-production.herokuapp.com"></iframe>
        </div>
    </div>
</body>
</html>
</code>```

The CSS:

```<code>.phone{
    margin:auto;
    height: 737px;
    width: 654px;
    background-image: url("/imgs/phone.png");
    position: fixed;
    top: 50%;
    left: 50%;
    display: block;
}
.container {
    position: fixed;
    left:0; right:0;
    top:0; bottom:0;
    margin: auto;
    height: 536px;
    width: 350px;
    border:1px solid #000000;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    display: block;
 }
</code>```

feel like i might be missing something obvious, any help would be appreciated...

答:
No need to have inline and external styles at the same time, just use one or the other, ideally external. You need to target the iframe element to affect it with your styles. I've also made it's width responsive with the max-width: 100% because I think it might come in handy:

.phone {
  margin:auto;
  height: 737px;
  width: 654px;
  background-image: url("/imgs/phone.png");
  position: fixed;
  top: 50%;
  left: 50%;
  display: block;
}

.container {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  height: 536px;
  width: 350px;
  border: 1px solid;
  border-radius: 5px;
  display: block;
}

iframe {
  width: 500px; /* adjust to your needs */
  max-width: 100%; /* to make it responsive */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div className="phone">
  <div className="container">
    <iframe src="http://foodsharing-production.herokuapp.com"></iframe>
  </div>
</div></code>```

Title: Can't resize iFrame

Body:
The iFrame or wrapper div will not change size, whatever i try:

The Output:

The HTML:

    <link rel="stylesheet" href="CV.css">
<title>
George's CV
</title>

The CSS:

.phone{
    margin:auto;
    height: 737px;
    width: 654px;
    background-image: url("/imgs/phone.png");
    position: fixed;
    top: 50%;
    left: 50%;
    display: block;
}
.container {
    position: fixed;
    left:0; right:0;
    top:0; bottom:0;
    margin: auto;
    height: 536px;
    width: 350px;
    border:1px solid #000000;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    display: block;
 }

feel like i might be missing something obvious, any help would be appreciated...

Body:
No need to have inline and external styles at the same time, just use one or the other, ideally external. You need to target the iframe element to affect it with your styles. I've also made it's width responsive with the max-width: 100% because I think it might come in handy:

.phone {
  margin:auto;
  height: 737px;
  width: 654px;
  background-image: url("/imgs/phone.png");
  position: fixed;
  top: 50%;
  left: 50%;
  display: block;
}

.container {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  height: 536px;
  width: 350px;
  border: 1px solid;
  border-radius: 5px;
  display: block;
}

iframe {
  width: 500px; /* adjust to your needs */
  max-width: 100%; /* to make it responsive */
}

<div className="phone">
  <div className="container">
    <iframe src="http://foodsharing-production.herokuapp.com"></iframe>
  </div>
</div>