问:
strange things with btrace and java.lang.NoSuchMethodError
the main class:

```<code>package com.xxx.yyy;

public class Hello{
    public static void main(String[] args){
        A a = new A();
        while(true){
            try {
                a.execute(1000);
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
</code>```

class A:

```<code>package com.xxx.yyy;

public class A{
    public void execute(int sleepTime) throws Exception {
        System.out.println("sleep time is "+sleepTime);
    }
}
</code>```

btrace script:

```<code>import static com.sun.btrace.BTraceUtils.println;
import static com.sun.btrace.BTraceUtils.str;
import static com.sun.btrace.BTraceUtils.strcat;
import static com.sun.btrace.BTraceUtils.timeMillis;

import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.Kind;
import com.sun.btrace.annotations.Location;
import com.sun.btrace.annotations.OnMethod;
import com.sun.btrace.annotations.ProbeClassName;
import com.sun.btrace.annotations.ProbeMethodName;
import com.sun.btrace.annotations.TLS;
@BTrace
public class BtraceTest{

    @OnMethod(clazz="com.xxx.yyy.A",method="execute",location=@Location(Kind.RETURN))
    public static void traceExecute(@ProbeClassName String name,@ProbeMethodName String method,int sleepTime){
        println(strcat("the class name=>", name));
        println(strcat("the class method=>", method));
        println(strcat("the class method params=>", str(sleepTime)));
    }
}
</code>```

everything is right.
BUT: when I move the line Thread.sleep(1000) to class A's execute function, like this:

```<code>package com.xxx.yyy;

public class A{
    public void execute(int sleepTime) throws Exception {
        System.out.println("sleep time is "+sleepTime);
        Thread.sleep(1000);
    }
}
</code>```

the NoSuchMethodError is thrown by Hello.

```<code>Exception in thread "main" java.lang.NoSuchMethodError: com.xxx.yyy.A.$btrace$BtraceTest$traceExecute(Ljava/lang/String;Ljava/lang/String;I)V
    at com.xxx.yyy.A.execute(Unknown Source)
    at com.xxx.yyy.Hello.main(Hello.java:8)
</code>```

my environment is

java version "1.8.0_121"

  BTrace v.1.3.9 (20170111)

anyone can explain why?thanks!

答: I think your class should implements Runnable or extends Thread.  Then only you can use start, sleepand such similar methods in your program. Have a look at here to know how to implement thread methods.

Body:
the main class:

package com.xxx.yyy;

public class Hello{
    public static void main(String[] args){
        A a = new A();
        while(true){
            try {
                a.execute(1000);
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

class A:

package com.xxx.yyy;

public class A{
    public void execute(int sleepTime) throws Exception {
        System.out.println("sleep time is "+sleepTime);
    }
}

btrace script:

import static com.sun.btrace.BTraceUtils.println;
import static com.sun.btrace.BTraceUtils.str;
import static com.sun.btrace.BTraceUtils.strcat;
import static com.sun.btrace.BTraceUtils.timeMillis;

import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.Kind;
import com.sun.btrace.annotations.Location;
import com.sun.btrace.annotations.OnMethod;
import com.sun.btrace.annotations.ProbeClassName;
import com.sun.btrace.annotations.ProbeMethodName;
import com.sun.btrace.annotations.TLS;
@BTrace
public class BtraceTest{

    @OnMethod(clazz="com.xxx.yyy.A",method="execute",location=@Location(Kind.RETURN))
    public static void traceExecute(@ProbeClassName String name,@ProbeMethodName String method,int sleepTime){
        println(strcat("the class name=>", name));
        println(strcat("the class method=>", method));
        println(strcat("the class method params=>", str(sleepTime)));
    }
}

everything is right.
BUT: when I move the line Thread.sleep(1000) to class A's execute function, like this:

package com.xxx.yyy;

public class A{
    public void execute(int sleepTime) throws Exception {
        System.out.println("sleep time is "+sleepTime);
        Thread.sleep(1000);
    }
}

the NoSuchMethodError is thrown by Hello.

Exception in thread "main" java.lang.NoSuchMethodError: com.xxx.yyy.A.$btrace$BtraceTest$traceExecute(Ljava/lang/String;Ljava/lang/String;I)V
    at com.xxx.yyy.A.execute(Unknown Source)
    at com.xxx.yyy.Hello.main(Hello.java:8)

my environment is

java version "1.8.0_121"

  BTrace v.1.3.9 (20170111)

anyone can explain why?thanks!


来源: stackexchange

问:
How to filter a list using an async predicate
Suppose you have a list of strings (or of any other type, just using string as an example), e.g.

```<code>IEnumerable<string> fullList = ...;
</code>```

and an async predicate, e.g.

```<code>static Task<bool> IncludeString(string s) { ... }
</code>```

What is the simplest way of filtering the list by that predicate, with the following constraints:

Predicates should not be run sequentially (assume the list is long and the async predicate is slow)

Resulting filtered list should preserve ordering

I did find a solution, but it involves creating a temporary list that has the result of the predicate for each entry, and then using that to do the filtering. It just doesn't feel elegant enough. Here it is:

```<code>var includedIndices = await Task.WhenAll(fullList.Select(IncludeString));
var filteredList = fullList.Where((_, i) => includedIndices[i]);
</code>```

It feels like something that should be possible with a simple framework call, but I wasn't able to find one.

答:
It's not particularly elegant, but you can create anonymous types in a Task.ContinueWith call from the predicate in select, awaiting the WhenAll call on that array, and using the values included in those task results.

public async Task<T[]> FilterAsync<T>(IEnumerable<T> sourceEnumerable, Func<T, Task<bool>> predicateAsync)
{
    return (await Task.WhenAll(
        sourceEnumerable.Select(
            v => predicateAsync(v)
            .ContinueWith(task => new { Predicate = task.Result, Value = v })))
        ).Where(a => a.Predicate).Select(a => a.Value).ToArray();
}
```

<p>Example usage (made-up function for demonstration):</p>

```// Returns { "ab", "abcd" } after 1000ms
string[] evenLengthStrings = await FilterAsync<string>(new string[] { "a", "ab", "abc", "abcd" }, (async s => { await Task.Delay(1000); return s.Length % 2 == 0; }));
```

Note that even without the ToArray call, the returned enumerable will not re-enumerate the source enumerable when enumerated - it will not be lazy because  Task.WhenAll doesn't return a LINQy lazy enumerable.

ContentLicense: CC BY-SA 3.0

Body:
Suppose you have a list of strings (or of any other type, just using string as an example), e.g.

IEnumerable<string> fullList = ...;

and an async predicate, e.g.

static Task<bool> IncludeString(string s) { ... }

What is the simplest way of filtering the list by that predicate, with the following constraints:

Predicates should not be run sequentially (assume the list is long and the async predicate is slow)

Resulting filtered list should preserve ordering

I did find a solution, but it involves creating a temporary list that has the result of the predicate for each entry, and then using that to do the filtering. It just doesn't feel elegant enough. Here it is:

var includedIndices = await Task.WhenAll(fullList.Select(IncludeString));
var filteredList = fullList.Where((_, i) => includedIndices[i]);

It feels like something that should be possible with a simple framework call, but I wasn't able to find one.

Body:
It's not particularly elegant, but you can create anonymous types in a Task.ContinueWith call from the predicate in select, awaiting the WhenAll call on that array, and using the values included in those task results.

public async Task<T[]> FilterAsync<T>(IEnumerable<T> sourceEnumerable, Func<T, Task<bool>> predicateAsync)
{
    return (await Task.WhenAll(
        sourceEnumerable.Select(
            v => predicateAsync(v)
            .ContinueWith(task => new { Predicate = task.Result, Value = v })))
        ).Where(a => a.Predicate).Select(a => a.Value).ToArray();
}

Example usage (made-up function for demonstration):

// Returns { "ab", "abcd" } after 1000ms
string[] evenLengthStrings = await FilterAsync<string>(new string[] { "a", "ab", "abc", "abcd" }, (async s => { await Task.Delay(1000); return s.Length % 2 == 0; }));

Note that even without the ToArray call, the returned enumerable will not re-enumerate the source enumerable when enumerated - it will not be lazy because  Task.WhenAll doesn't return a LINQy lazy enumerable.


问:
Break Array Values Into New Line in Angular
How can i break this array of errors into new line? I tried using "\n" and it doesn't break into lines in Angular?

JSON

```<code>{
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "http://sample.com",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://sample.com: 404 Not Found",
  "error": {
    "error": [
      "Error1",
      "Error2",
      "Error3"
    ]
  }
}
</code>```

error.ts

```<code>error => {
             alert("ERROR" + "\n" +  error.error.error + "\n");
             console.log(error.error.error);
          });
</code>```

答:
The problem is that error.error.error in an array and you are printing it as it is.

Try this

var error = {
"headers": {
 "normalizedNames": {},
 "lazyUpdate": null
},
"status": 404,
"statusText": "Not Found",
"url": "http://sample.com",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for http://sample.com: 404 Not Found",
"error": {
 "error": [
 "Error1",
 "Error2",
 "Error3"
 ]
}
}
var alertString = 'error ';
for (var i = 0; i < error.error.error.length; i++) {
alertString = alertString + '\n ' + error.error.error[i];
}
alert(alertString);
 console.log(alertString);```

Body:
How can i break this array of errors into new line? I tried using "\n" and it doesn't break into lines in Angular?

JSON

{
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "http://sample.com",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://sample.com: 404 Not Found",
  "error": {
    "error": [
      "Error1",
      "Error2",
      "Error3"
    ]
  }
}

error.ts

error => {
             alert("ERROR" + "\n" +  error.error.error + "\n");
             console.log(error.error.error);
          });


问:
Spring SAML Application using two IDPs and different URLs
I can’t seem to figure out how to use two different IDPS and 2 different applications URLs. I had this working on weblogic but not with a spring boot application using the spring saml security.

One important part is that we have two different URLs.

Proxy URL for external users. They must use this URL as they are not in the network.
a. These users hit IDP-A

Internal URL for internal users.
b. These users hit IDP-B

The metadata we sent to the each of the IDPs use the same entity ID but different endpoint URLs.

One thing we did was turn on discovery and where able to hit each IDP but it always redirects us to the internal URL. I noticed that AssertionConsumerServiceUrl is always set to the internal URL, which explains why it is returned to is the same. In our weblogic implementation we do not send AssertionConsumerServiceUrl.

Can we exclude AssertionConsumerServiceUrl?

Do you know if the configuration I am attempting to do is even possible?

答:
you can autowire the MetadataManager bean in your service and then call the addMetadataProvider to inititate a metadata.

You can get the entityId from the Metadata Obtained from IDP and can append to the url :
'http:///saml/login?idp=' by hitting this url it will redirect you to appropriate IDP login.


问:
Javascript String.replace(/\$/,str) works weirdly in jsp file
For simplicity, i have the following file named test.jsp:

```<code><script language="javascript">
    alert("a$b".replace(/\$/g,"k"));
</script>
</code>```

I put this file in my local server, then display it using firefox:  http://localhost:8080/myproj/test.jsp. It works okay, the result alert string is:

```<code> akb
</code>```

But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me.

Then i change the test.jsp content to:

```<code><script language="javascript">
    alert("a$b".replace(/\\$/g,"k"));
</script>
</code>```

Note here i add two slashes instead of one. In this case it works in the remote server but not in local one.

Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.:

```<code><script language="javascript">
    alert("a$b".replace(/\$/g,"k"));
</script>
</code>```

By using the same firefox, it works okay in both servers.

But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario?

My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is  3.0.4.

答:
JSP 2.0 Spec says: "When EL evaluation is disabled, \$ will not be recognized as a quote, whereas when EL evaluation is enabled, \$ will be recognized as a quote for $." (JSP.3.3.2)

Whether EL Evaluation is enabled or disabled depends on many things:

if application server supports JSP 2.0 (Tomcat 5.0 and higher does)

web.xml descriptor file... if declares (e.g. by not using web-app_2_4.xsd schema) that it uses Servet 2.3 spec or earlier, EL is disabled by default.

JSP Configuration <el-ignored>

Page directive isELIgnored (<%@ page isELIgnored=”true|false” %>)

(See JSP Spec 2.0, part JSP.3.3.2 for more details)

Simple way to check if EL is enabled/disabled is to use ${request} on your page. If you see '${request}' in output, EL is disabled. If you see something different, it is enabled.

You may want to change \$ (one backslash) to \\$ (two backslashes) to get \$ in output if you also use EL on your page.

If you see differences between local/remote server, their settings related to EL probably differ. Best what you can do is to 1) use JSP 2.0, Servlet 2.4 or later (enables EL), 2) run same web server on machines. (Btw, I suggest you upgrade Tomcat 5.0 to 5.5 at least).

OwnerDisplayName: jscoot

ContentLicense: CC BY-SA 2.5

Body:
For simplicity, i have the following file named test.jsp:

I put this file in my local server, then display it using firefox:  http://localhost:8080/myproj/test.jsp. It works okay, the result alert string is:

 akb

But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me.

Then i change the test.jsp content to:

Note here i add two slashes instead of one. In this case it works in the remote server but not in local one.

Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.:

By using the same firefox, it works okay in both servers.

But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario?

My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is  3.0.4.

LastEditorDisplayName: jscoot

OwnerDisplayName: Peter Štibraný

LastEditorDisplayName: Peter Štibraný


问:
Sort all List properties (and subproperties) of an object
I'm trying to sort all of the List properties of an object (using OrderBy). It's a complex object that has Lists that may contain Lists. I figured that reflection and recursion would get me there, but I seem to be stumbling on actually sorting the lists.

Here is the code I have:

```<code>Private Sub SortData(ByRef obj As Object)
    Dim type As Type = obj.GetType()
    Dim properties As PropertyInfo() = type.GetProperties()

    For Each item As PropertyInfo In properties
        If Not item.PropertyType.FullName.Contains("System.Collection") AndAlso item.PropertyType.FullName.Contains("MyType") Then
            Dim value = obj.GetType().GetProperty(item.Name).GetValue(obj)
            If value IsNot Nothing Then
                SortData(value)
            End If
        End If

        If item.PropertyType.FullName.Contains("System.Collection") Then
            Dim value = obj.GetType().GetProperty(item.Name).GetValue(obj)
            If value IsNot Nothing Then
                Dim subType As Type = value(0).GetType()
                Dim subProperties As PropertyInfo() = subType.GetProperties()
                If subProperties.Any(Function(x) x.Name = "SortKey") Then
                    ' --- Struggling here! ---
                    Dim castList = TryCast(value, List(Of MoreDetail))
                    value = castList.OrderBy(Function(x) x.SortKey)
                    value = TryCast(value, List(Of MoreDetail))
                    ' --- End struggle ---
                End If

                For Each subProperty In subProperties
                    SortData(value.GetType().GetProperty(subProperty.Name).GetValue(value))
                Next
            End If
        End If
    Next

End Sub
</code>```

The main problem is in the "struggling here" section of the code - I seem to have to cast the object into its original type, but that defeats the purpose of the reflection as different objects will have a different list type, so ideally I'd be able to cast the object based on its reflected type.

Thanks for the help!

EDIT: To alleviate the "XY problem" in my question, here's what I'm trying to do... I want to be able to sort all List properties of an object - the problem is that the object can have nested lists, so ideally I'd do this via reflection, recursively checking to see if a list contains a list in any of the child properties. The lists are mostly complex types, so I want to sort a list only if the collection contains objects that have the "SortKey" property defined.

EDIT 2: An example of what I'm after is something like (pseudocode):

```<code>Public Class SuperList
    Public Property A As String = ""
    Public Property BList As New List(Of B)
End Class

Public Class B
   Public Property SortKey As String = ""
   Public Property Name As String = ""
   Public Property CList As New List(Of C)
End Class

Public Class C
   Public Property SortKey As String = ""
   Public Property Name As String = ""
End Class

Dim cExampleSecond As New C With {.SortKey = "345", .Name = "C Second"}
Dim cExampleFirst As New C With {.SortKey = "123", .Name = "C First"}
Dim BExampleFirst As New B With {.Sortkey = "ABC", .Name = "B First"}
BExampleFirst.CList.Add(cExampleSecond)
BExampleFirst.CList.Add(cExampleFirst)
Dim superExample As New SuperList With {.A = "Whatever"}
superExample.BList.Add(BExampleFirst)

...
SortData(superExample)
...
</code>```

After running SortData() it should look like:

```<code>superExample =
   .A = "Whatever"
   .BList =
      .SortKey = "ABC"
      .BExampleFirst =
         cExampleFirst =
            .SortKey = "123"
            .Name = "C First"
         cExampleSecond =
            .SortKey = "345"
            .Name = "C Second"
</code>```

Note that if superExample.BList had more elements, they would also be sorted...

答:
Looking at your example, I would consider that you want to sort a kind of tree.

1- Tree means recursivity: the SortData() will sort the current level/current list, and call SortData() for every sub-element. You can use  inheritance or composition to implement this functionality in every element of your tree.

2- You can use the sort functionality of the List and Dictionary. You only have to implement the IComparable for the element of you list.

Here is some sample code that illustrates the global method.

```<code>Public Class SortedElem

    Implements IComparable(Of SortedElem)
    Public Property Children As New List(Of SortedElem)
    Public Property SortKey As String

    Public Sub SortData()
        Children.Sort()
        For Each child In Children
            child.Children.Sort()
        Next
    End Sub

    Public Function CompareTo(other As SortedElem) As Integer Implements IComparable(Of SortedElem).CompareTo
        Return String.Compare(Me.SortKey, other.SortKey)
    End Function

End Class

Public Class SuperList
    Inherits SortedElem
    Public Property A As String = ""
End Class

Public Class B
    Inherits SortedElem
    Public Property Name As String = ""

End Class

Public Class C
    Inherits SortedElem
    Public Property Name As String = ""
End Class

Public Sub AnySub()

    Dim cExampleFirst As New C With {.SortKey = "1", .Name = "C First"}
    Dim cExampleSecond As New C With {.SortKey = "3", .Name = "C Second"}
    Dim cExampleThird As New C With {.SortKey = "2", .Name = "C Third"}

    Dim BExampleFirst As New B With {.SortKey = "ABC", .Name = "B First"}
    Dim BExampleSecond As New B With {.SortKey = "XYZ", .Name = "B Second"}
    Dim BExampleThird As New B With {.SortKey = "DEF", .Name = "B Third"}

    BExampleFirst.Children.Add(cExampleFirst)
    BExampleFirst.Children.Add(cExampleSecond)
    BExampleFirst.Children.Add(cExampleThird)

    Dim superExample As New SuperList With {.A = "Whatever"}
    superExample.Children.Add(BExampleFirst)
    superExample.Children.Add(BExampleSecond)
    superExample.Children.Add(BExampleThird)

    superExample.SortData()

End Sub
</code>```

Body:
I'm trying to sort all of the List properties of an object (using OrderBy). It's a complex object that has Lists that may contain Lists. I figured that reflection and recursion would get me there, but I seem to be stumbling on actually sorting the lists.

Here is the code I have:

Private Sub SortData(ByRef obj As Object)
    Dim type As Type = obj.GetType()
    Dim properties As PropertyInfo() = type.GetProperties()

    For Each item As PropertyInfo In properties
        If Not item.PropertyType.FullName.Contains("System.Collection") AndAlso item.PropertyType.FullName.Contains("MyType") Then
            Dim value = obj.GetType().GetProperty(item.Name).GetValue(obj)
            If value IsNot Nothing Then
                SortData(value)
            End If
        End If

        If item.PropertyType.FullName.Contains("System.Collection") Then
            Dim value = obj.GetType().GetProperty(item.Name).GetValue(obj)
            If value IsNot Nothing Then
                Dim subType As Type = value(0).GetType()
                Dim subProperties As PropertyInfo() = subType.GetProperties()
                If subProperties.Any(Function(x) x.Name = "SortKey") Then
                    ' --- Struggling here! ---
                    Dim castList = TryCast(value, List(Of MoreDetail))
                    value = castList.OrderBy(Function(x) x.SortKey)
                    value = TryCast(value, List(Of MoreDetail))
                    ' --- End struggle ---
                End If

                For Each subProperty In subProperties
                    SortData(value.GetType().GetProperty(subProperty.Name).GetValue(value))
                Next
            End If
        End If
    Next

End Sub

The main problem is in the "struggling here" section of the code - I seem to have to cast the object into its original type, but that defeats the purpose of the reflection as different objects will have a different list type, so ideally I'd be able to cast the object based on its reflected type.

Thanks for the help!

EDIT: To alleviate the "XY problem" in my question, here's what I'm trying to do... I want to be able to sort all List properties of an object - the problem is that the object can have nested lists, so ideally I'd do this via reflection, recursively checking to see if a list contains a list in any of the child properties. The lists are mostly complex types, so I want to sort a list only if the collection contains objects that have the "SortKey" property defined.

EDIT 2: An example of what I'm after is something like (pseudocode):

Public Class SuperList
    Public Property A As String = ""
    Public Property BList As New List(Of B)
End Class

Public Class B
   Public Property SortKey As String = ""
   Public Property Name As String = ""
   Public Property CList As New List(Of C)
End Class

Public Class C
   Public Property SortKey As String = ""
   Public Property Name As String = ""
End Class

Dim cExampleSecond As New C With {.SortKey = "345", .Name = "C Second"}
Dim cExampleFirst As New C With {.SortKey = "123", .Name = "C First"}
Dim BExampleFirst As New B With {.Sortkey = "ABC", .Name = "B First"}
BExampleFirst.CList.Add(cExampleSecond)
BExampleFirst.CList.Add(cExampleFirst)
Dim superExample As New SuperList With {.A = "Whatever"}
superExample.BList.Add(BExampleFirst)

...
SortData(superExample)
...

After running SortData() it should look like:

superExample =
   .A = "Whatever"
   .BList =
      .SortKey = "ABC"
      .BExampleFirst =
         cExampleFirst =
            .SortKey = "123"
            .Name = "C First"
         cExampleSecond =
            .SortKey = "345"
            .Name = "C Second"

Note that if superExample.BList had more elements, they would also be sorted...

Body:
Looking at your example, I would consider that you want to sort a kind of tree.

1- Tree means recursivity: the SortData() will sort the current level/current list, and call SortData() for every sub-element. You can use  inheritance or composition to implement this functionality in every element of your tree.

2- You can use the sort functionality of the List and Dictionary. You only have to implement the IComparable for the element of you list.

Here is some sample code that illustrates the global method.

Public Class SortedElem

    Implements IComparable(Of SortedElem)
    Public Property Children As New List(Of SortedElem)
    Public Property SortKey As String

    Public Sub SortData()
        Children.Sort()
        For Each child In Children
            child.Children.Sort()
        Next
    End Sub

    Public Function CompareTo(other As SortedElem) As Integer Implements IComparable(Of SortedElem).CompareTo
        Return String.Compare(Me.SortKey, other.SortKey)
    End Function

End Class

Public Class SuperList
    Inherits SortedElem
    Public Property A As String = ""
End Class

Public Class B
    Inherits SortedElem
    Public Property Name As String = ""

End Class

Public Class C
    Inherits SortedElem
    Public Property Name As String = ""
End Class

Public Sub AnySub()

    Dim cExampleFirst As New C With {.SortKey = "1", .Name = "C First"}
    Dim cExampleSecond As New C With {.SortKey = "3", .Name = "C Second"}
    Dim cExampleThird As New C With {.SortKey = "2", .Name = "C Third"}

    Dim BExampleFirst As New B With {.SortKey = "ABC", .Name = "B First"}
    Dim BExampleSecond As New B With {.SortKey = "XYZ", .Name = "B Second"}
    Dim BExampleThird As New B With {.SortKey = "DEF", .Name = "B Third"}

    BExampleFirst.Children.Add(cExampleFirst)
    BExampleFirst.Children.Add(cExampleSecond)
    BExampleFirst.Children.Add(cExampleThird)

    Dim superExample As New SuperList With {.A = "Whatever"}
    superExample.Children.Add(BExampleFirst)
    superExample.Children.Add(BExampleSecond)
    superExample.Children.Add(BExampleThird)

    superExample.SortData()

End Sub


问:
Script timeout passed, if you want to finish import, please resubmit the same file and import will resume
I have a database
Un-zipped size 50mb zipped size 7mb
So when I try to import the database zipped(7mb) after few minutes it is throwing this error:

Script timeout passed, if you want to finish import, please resubmit
  the same file and import will resume.

I have resubmitted it but still not importing total data.

I am working in local and these are my php.ini configurations:

```<code>max_execution_time = 3000000
max_input_time = 60000000000000
memory_limit = 1280000000000000000000M
post_max_size = 4096456M
upload_max_filesize = 40964564M
max_file_uploads = 200
</code>```

how can I let the system to take its own time for import.?

答:
Instead of XAMPP you may use LAMP(Linux Apache MySQL PHP) mostly. Using LAMP you may also face this problem.

In my case(using Ubuntu 15.10), I had configured/set post_max_size, upload_max_filesize, max_execution_time, max_input_time, memory_limit following my needs using php.ini file which is located at /etc/php5/apache2/php.ini

But still I was faced this problem. Then solved the problem using  config.default.php file, where you can find out like this line below:

$cfg['ExecTimeLimit'] = 300;
Make it to

$cfg['ExecTimeLimit'] = 0;

Note: You can locate config.default.php file via your terminal(Ctrl+Alt+T) by this commandlocate config.default.php possible path is /usr/share/phpmyadmin/libraries/config.default.php

ContentLicense: CC BY-SA 4.0

Body:
I have a database
Un-zipped size 50mb zipped size 7mb
So when I try to import the database zipped(7mb) after few minutes it is throwing this error:

Script timeout passed, if you want to finish import, please resubmit
  the same file and import will resume.

I have resubmitted it but still not importing total data.

I am working in local and these are my php.ini configurations:

max_execution_time = 3000000
max_input_time = 60000000000000
memory_limit = 1280000000000000000000M
post_max_size = 4096456M
upload_max_filesize = 40964564M
max_file_uploads = 200

how can I let the system to take its own time for import.?


问:
RSSService item with the same key multiple times
I have a RSSService with an item like the one show below

```<code><item>
        <title>Accessori per la cura della persona</title>
        <link>http://www.myurl.it/accessori-per-la-cura-della-persona/</link>
        <comments>http://www.myurl.it/accessori-per-la-cura-della-persona/#comments</comments>
        <pubDate>Tue, 24 Oct 2017 09:29:44 +0000</pubDate>
        <dc:creator><![CDATA[Farmacia Rizzo Davide]]></dc:creator>
                <category><![CDATA[News]]></category>
        <category><![CDATA[Offerte]]></category>
        <category><![CDATA[Callifugo]]></category>
        <category><![CDATA[Raspa piedi]]></category>
        <category><![CDATA[Spazzola ceramica]]></category>
        <category><![CDATA[Spazzola piatta]]></category>
        <category><![CDATA[Spazzola tonda]]></category>
        <category><![CDATA[Spazzole capelli]]></category>

        <guid isPermaLink="false">http://www.myurl.it/?p=3982</guid>
        <description>.....
</code>```

To read all the content I use this:

```<code>List<Map> records;
...
records = rss.getResults();
...
for (Map m : records) {
                Button b = new Button((String)m.get("title"));
                if(((String)m.get("category")).equals(CATEGORY_OFFERTE)){
                    b.setIcon(iconStar);
                } else {
                    b.setIcon(iconNews);
                }
                b.addActionListener((l)->{
                    Boolean can = Display.getInstance().canExecute((String)m.get("link"));
                    if(can != null && can) {
                      Display.getInstance().execute((String)m.get("link"));
                    } else {
                      ToastBar.Status status = ToastBar.getInstance().createStatus();
                      status.setMessage("Non riesco a connettermi");
                      status.setExpires(3000);
                      status.show();
                    }
                });
                recordsContainer.addComponent(b);
            }
</code>```

When I read the key "category" I always get the last entry (in this item "Spazzole capelli").
There is a way to read a key like an array? Something like that:

```<code>String[] mc = (String[]) m.get("category");
</code>```

Thank's in advance for any help.
Davide.

答:
This looks like a missing feature in RSSService that expects to find only one category entry and so it parses it into a hash map which effectively allows only one such entry.

I would suggest implementing your own RSS reading and go to the XML directly to get the full power of the protocol. You can use the existing class as a reference on how to do the RSS/ATOM parsing.

Body:
I have a RSSService with an item like the one show below

<item>
        <title>Accessori per la cura della persona</title>
        <link>http://www.myurl.it/accessori-per-la-cura-della-persona/</link>
        <comments>http://www.myurl.it/accessori-per-la-cura-della-persona/#comments</comments>
        <pubDate>Tue, 24 Oct 2017 09:29:44 +0000</pubDate>
        <dc:creator><![CDATA[Farmacia Rizzo Davide]]></dc:creator>
                <category><![CDATA[News]]></category>
        <category><![CDATA[Offerte]]></category>
        <category><![CDATA[Callifugo]]></category>
        <category><![CDATA[Raspa piedi]]></category>
        <category><![CDATA[Spazzola ceramica]]></category>
        <category><![CDATA[Spazzola piatta]]></category>
        <category><![CDATA[Spazzola tonda]]></category>
        <category><![CDATA[Spazzole capelli]]></category>

        <guid isPermaLink="false">http://www.myurl.it/?p=3982</guid>
        <description>.....

To read all the content I use this:

List<Map> records;
...
records = rss.getResults();
...
for (Map m : records) {
                Button b = new Button((String)m.get("title"));
                if(((String)m.get("category")).equals(CATEGORY_OFFERTE)){
                    b.setIcon(iconStar);
                } else {
                    b.setIcon(iconNews);
                }
                b.addActionListener((l)->{
                    Boolean can = Display.getInstance().canExecute((String)m.get("link"));
                    if(can != null && can) {
                      Display.getInstance().execute((String)m.get("link"));
                    } else {
                      ToastBar.Status status = ToastBar.getInstance().createStatus();
                      status.setMessage("Non riesco a connettermi");
                      status.setExpires(3000);
                      status.show();
                    }
                });
                recordsContainer.addComponent(b);
            }

When I read the key "category" I always get the last entry (in this item "Spazzole capelli").
There is a way to read a key like an array? Something like that:

String[] mc = (String[]) m.get("category");

Thank's in advance for any help.
Davide.


问:
Using streams to find Max
Is the following the recommended way to attempt finding Max with streams?

```<code>List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b));
System.out.println("Max " + maxSal);
</code>```

It results in a compilation error - what does this mean?

```<code>error: incompatible types: OptionalInt cannot be
nverted to Integer
                  Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).
uce((a,b)->Math.max(a, b));
</code>```

答:
You can use the method Integer.min in reduce which returns OptionalInt, can be used to get Int (make sure the boundary checks)

using IntStream

```<code>int max1 = emps.stream().mapToInt(Employee::getSalary).max().getAsInt();
</code>```

using IntSummaryStatistics [if you are interested in statistics, like min, max, avg]

```<code>IntSummaryStatistics stats = emps.stream().mapToInt(Employee::getSalary).summaryStatistics();
int max2 = stats.getMax();
</code>```

reduce function

```<code>int max3 = emps.stream().mapToInt(Employee::getSalary).reduce(Integer::min).getAsInt();
</code>```

Title: Using streams to find Max

Body:
Is the following the recommended way to attempt finding Max with streams?

List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b));
System.out.println("Max " + maxSal);

It results in a compilation error - what does this mean?

error: incompatible types: OptionalInt cannot be
nverted to Integer
                  Integer maxSal= emps.stream().mapToInt(e -> e.getSalary()).
uce((a,b)->Math.max(a, b));

Body:
You can use the method Integer.min in reduce which returns OptionalInt, can be used to get Int (make sure the boundary checks)

using IntStream

int max1 = emps.stream().mapToInt(Employee::getSalary).max().getAsInt();

using IntSummaryStatistics [if you are interested in statistics, like min, max, avg]

IntSummaryStatistics stats = emps.stream().mapToInt(Employee::getSalary).summaryStatistics();
int max2 = stats.getMax();

reduce function

int max3 = emps.stream().mapToInt(Employee::getSalary).reduce(Integer::min).getAsInt();


答:
First, you might shorten your emps initialization withArrays.asList(T...) like

```<code>List<Employee> emps = Arrays.asList(new Employee("Roy1", 32),
        new Employee("Roy2", 12), new Employee("Roy3", 22),
        new Employee("Roy4", 42), new Employee("Roy5", 52));
</code>```

Next, you can use OptionalInt.orElseThrow(Supplier<X>) which will get the max value from the List or throw a RuntimeException

```<code>int maxSal = emps.stream().mapToInt(Employee::getSalary).max()
        .orElseThrow(() -> new RuntimeException("No Such Element"));
System.out.println("Max " + maxSal);
</code>```

Finally, you could also reason that no one would accept a negative salary, and use orElse(int) like

```<code>int maxSal = emps.stream().mapToInt(Employee::getSalary).max().orElse(-1);
System.out.println("Max " + maxSal);
</code>```

Title: Using streams to find Max

Body:
First, you might shorten your emps initialization withArrays.asList(T...) like

List<Employee> emps = Arrays.asList(new Employee("Roy1", 32),
        new Employee("Roy2", 12), new Employee("Roy3", 22),
        new Employee("Roy4", 42), new Employee("Roy5", 52));

Next, you can use OptionalInt.orElseThrow(Supplier<X>) which will get the max value from the List or throw a RuntimeException

int maxSal = emps.stream().mapToInt(Employee::getSalary).max()
        .orElseThrow(() -> new RuntimeException("No Such Element"));
System.out.println("Max " + maxSal);

Finally, you could also reason that no one would accept a negative salary, and use orElse(int) like

int maxSal = emps.stream().mapToInt(Employee::getSalary).max().orElse(-1);
System.out.println("Max " + maxSal);


问:
How to access variables set using app.set() in express js
How do i access the variables set using express's app.set() for e.g

```<code>
app.set('view engine','jade');
app.set('jsDirectory',/js/');
</code>
```

From the guide, i understand that i can access the same using app.get(<key>), but this is the output of console.log(app.get('view engine')).

```
{ router:
   { app:
      { stack: [Object],
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 0,
        connections: [Getter/Setter],
        allowHalfOpen: true,
        _handle: null,
        httpAllowHalfOpen: false,
        cache: {},
        settings: [Object],
        redirects: {},
        isCallbacks: {},
        _locals: [Object],
        dynamicViewHelpers: {},
        errorHandlers: [],
        route: '/',
        routes: [Circular],
        router: [Getter],
        root: 'C:\\Users\\Shahal\\Works\\App',
        models: {},
        extensions: {},
        disconnectSchemas: [Function: disconnectSchemas],
        passport: [Object] },
     routes: {},
     params: {},
     _params: [],
     middleware: [Function] } }
```

答:
```<code>app.set('view engine','hbs')
**All are correct:**
app.get('view engine')
app.locals.settings['view engine']
app.settings['view engine']
</code>```

Body:
How do i access the variables set using express's app.set() for e.g

app.set('view engine','jade');
app.set('jsDirectory',/js/');

From the guide, i understand that i can access the same using app.get(<key>), but this is the output of console.log(app.get('view engine')).

{ router:
   { app:
      { stack: [Object],
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 0,
        connections: [Getter/Setter],
        allowHalfOpen: true,
        _handle: null,
        httpAllowHalfOpen: false,
        cache: {},
        settings: [Object],
        redirects: {},
        isCallbacks: {},
        _locals: [Object],
        dynamicViewHelpers: {},
        errorHandlers: [],
        route: '/',
        routes: [Circular],
        router: [Getter],
        root: 'C:\\Users\\Shahal\\Works\\App',
        models: {},
        extensions: {},
        disconnectSchemas: [Function: disconnectSchemas],
        passport: [Object] },
     routes: {},
     params: {},
     _params: [],
     middleware: [Function] } }


问:
How to write a safe `length` function to a `Vec` in Agda?
Since we have Data.Vec, we know what Vec is.

I want to prove that Nat and Vec ⊤ are isomorphic.

I've successfully created a function that proves Nat can be converted to Vec:

```<code>ℕ→vec : (n : ℕ) → Vec ⊤ n
ℕ→vec  zero   = []
ℕ→vec (suc a) = tt ∷ ℕ→vec a
</code>```

While when I'm trying to write a corresponding vec→ℕ, I failed.

I want to write something like this (it doesn't compile but it's readable):

```<code>vec→ℕ : ∀ {n} → Vec ⊤ n → (n : ℕ)
vec→ℕ  []      = zero
vec→ℕ (tt ∷ a) = suc (vec→ℕ a)
</code>```

In the first code, it's ensured that the argument is exactly the length of the return value.
However, how can I ensure that the length of the first argument is exactly the return value?

答:
You could make vec→ℕ definitionally equal to the length:

```<code>vec→ℕ : ∀ {n} → Vec ⊤ n → ℕ
vec→ℕ {n} _ = n
</code>```

and then I think this is sufficiently transparent to Agda that anywhere you'd need the property that the ℕ you get is the right one, it will be available to you automatically (i.e. by reduction).

Edited to add: you might think this is underspecified, since vec→ℕ's type doesn't prescribe which exact ℕatural it returns. However, Agda sees through this definition, so e.g. you can prove the following external correctness proof if you need it (but I'd argue it doesn't add any value):

```<code>open import Relation.Binary.PropositionalEquality

vec→ℕ-correct : ∀ {n} {xs : Vec ⊤ n} → vec→ℕ xs ≡ n
vec→ℕ-correct = refl
</code>```

Note that because vec→ℕ xs is definitionally equal to n, we don't need to look at either n or xs in the proof.

Body:
Since we have Data.Vec, we know what Vec is.

I want to prove that Nat and Vec ⊤ are isomorphic.

I've successfully created a function that proves Nat can be converted to Vec:

ℕ→vec : (n : ℕ) → Vec ⊤ n
ℕ→vec  zero   = []
ℕ→vec (suc a) = tt ∷ ℕ→vec a

While when I'm trying to write a corresponding vec→ℕ, I failed.

I want to write something like this (it doesn't compile but it's readable):

vec→ℕ : ∀ {n} → Vec ⊤ n → (n : ℕ)
vec→ℕ  []      = zero
vec→ℕ (tt ∷ a) = suc (vec→ℕ a)

In the first code, it's ensured that the argument is exactly the length of the return value.
However, how can I ensure that the length of the first argument is exactly the return value?

Body:
You could make vec→ℕ definitionally equal to the length:

vec→ℕ : ∀ {n} → Vec ⊤ n → ℕ
vec→ℕ {n} _ = n

and then I think this is sufficiently transparent to Agda that anywhere you'd need the property that the ℕ you get is the right one, it will be available to you automatically (i.e. by reduction).

Edited to add: you might think this is underspecified, since vec→ℕ's type doesn't prescribe which exact ℕatural it returns. However, Agda sees through this definition, so e.g. you can prove the following external correctness proof if you need it (but I'd argue it doesn't add any value):

open import Relation.Binary.PropositionalEquality

vec→ℕ-correct : ∀ {n} {xs : Vec ⊤ n} → vec→ℕ xs ≡ n
vec→ℕ-correct = refl

Note that because vec→ℕ xs is definitionally equal to n, we don't need to look at either n or xs in the proof.


问:
Failed to install android SDK tools 26.1.1 and Emulator
Can't download and install android SDK tools 26.1.1 and emulator.

This is the log output :

```<code>To install:
- Android Emulator (emulator)
- Android SDK Tools (tools)
Preparing "Install Android Emulator (revision: 26.1.4)".
Downloading https://dl.google.com/android/repository/emulator-windows-4266726.zip
An error occurred while preparing SDK package Android Emulator: Cannot download 'https://dl.google.com/android/repository/emulator-windows-4266726.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation07\emulator-windows-4266726.zip (The system cannot find the path specified)
, response: 200 OK.
"Install Android Emulator (revision: 26.1.4)" failed.
Preparing "Install Android SDK Tools (revision: 26.1.1)".
Downloading https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
An error occurred while preparing SDK package Android SDK Tools: Cannot download 'https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation02\android\repository\sdk-tools-windows-4333796.zip (The system cannot find the path specified)
, response: 200 OK
"Install Android SDK Tools (revision: 26.1.1)" failed.
Preparing "Install Android SDK Tools (revision: 26.1.1)".
Downloading https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
An error occurred while preparing SDK package Android SDK Tools: Cannot download 'https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation02\sdk-tools-windows-4333796.zip (The system cannot find the path specified)
, response: 200 OK.
"Install Android SDK Tools (revision: 26.1.1)" failed.
Failed packages:
- Android Emulator (emulator)
- Android SDK Tools (tools)
</code>```

答:
After Running Android Studio as Administrator solved my issue.

I am successfully able to download sdk now.

Body:
Can't download and install android SDK tools 26.1.1 and emulator.

This is the log output :

To install:
- Android Emulator (emulator)
- Android SDK Tools (tools)
Preparing "Install Android Emulator (revision: 26.1.4)".
Downloading https://dl.google.com/android/repository/emulator-windows-4266726.zip
An error occurred while preparing SDK package Android Emulator: Cannot download 'https://dl.google.com/android/repository/emulator-windows-4266726.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation07\emulator-windows-4266726.zip (The system cannot find the path specified)
, response: 200 OK.
"Install Android Emulator (revision: 26.1.4)" failed.
Preparing "Install Android SDK Tools (revision: 26.1.1)".
Downloading https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
An error occurred while preparing SDK package Android SDK Tools: Cannot download 'https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation02\android\repository\sdk-tools-windows-4333796.zip (The system cannot find the path specified)
, response: 200 OK
"Install Android SDK Tools (revision: 26.1.1)" failed.
Preparing "Install Android SDK Tools (revision: 26.1.1)".
Downloading https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
An error occurred while preparing SDK package Android SDK Tools: Cannot download 'https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation02\sdk-tools-windows-4333796.zip (The system cannot find the path specified)
, response: 200 OK.
"Install Android SDK Tools (revision: 26.1.1)" failed.
Failed packages:
- Android Emulator (emulator)
- Android SDK Tools (tools)


问:
JS click function open url in new windown
I create a link with text using html and i want to create when user click it goes to specific url. I new in javascript!!

here my code

```<code><a class="dt-button add_new_table_entry DTTT_button DTTT_button_new" tabindex="0" aria-controls="table_1" href="#">
<span>Add new</span>
</a>
</code>```

my script

```<code>$("dt-button add_new_table_entry DTTT_button DTTT_button_new").click(function () {
window.location="http://project.co/add-new/";
});
</code>```

UPDATE
I have create my script

```<code> let classic = document.getElementsByClassName('add_new DTTT_button DTTT_button_new');
for (var i=0; i < classic.length; i++) {
classic[i].addEventListener("click", clickfunc, false);
}
function.clickfunc(){
document.location.href="http://google.com";
}
</code>```

but give error unexpected token ;

答:
Try it , it will work, here on click of class = add_new_table_entry, javascript click event gets called and in same window redirection happens
we use window.location for redirection<br>

Add new
</p>

```<code>$(".add_new_table_entry").click(function () {
        window.location ="http://project.co/add-new/";
    });
</code>```

Body:
I create a link with text using html and i want to create when user click it goes to specific url. I new in javascript!!

here my code

Add new

my script

$("dt-button add_new_table_entry DTTT_button DTTT_button_new").click(function () {
window.location="http://project.co/add-new/";
});

UPDATE
I have create my script

 let classic = document.getElementsByClassName('add_new DTTT_button DTTT_button_new');
for (var i=0; i < classic.length; i++) {
classic[i].addEventListener("click", clickfunc, false);
}
function.clickfunc(){
document.location.href="http://google.com";
}

but give error unexpected token ;

Body:
Try it , it will work, here on click of class = add_new_table_entry, javascript click event gets called and in same window redirection happens
we use window.location for redirection

Add new

$(".add_new_table_entry").click(function () {
        window.location ="http://project.co/add-new/";
    });


问:
Force quotes in yaml
I have a ruby hash that is something like this:

```<code>myhash = { title: 'http://google.com'}
</code>```

I'm trying to add this to a yaml file like this:

```<code>params['myhash'] = myhash
File.open('config.yaml', 'w') do |k|
  k.write params.to_yaml
end
</code>```

The problem is that YAML is removing the  quotes  around the links even though they are needed (they contain ':').

According to several questions on Stackoverflow, YAML should only remove the quotes when they are not needed.

I found a Solution, but it's really ugly and I prefer not to use it if there was another solution.

I suppose that yaml should be including the quotes in this case. Is there any reason why it's not doing this?

Note: the links are dynamically created

答:
After couple hours i found it's easier in python.

usage: python quotes.py *.yml

This script use literal format if string has '\n'.

Use ruamel to replace yaml lib, yaml lib seems not handle some UTF-8 entry

```<code>from ruamel import yaml
import io
import sys

class quote_or_literal(unicode):
    pass

def str_presenter(dumper, data):
    if data.count("\n"):  # check for multiline string
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
    else:
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')

yaml.add_representer(quote_or_literal, str_presenter)

def quote_dict(d):
    new = {}
    for k, v in d.items():
        if isinstance(v, dict):
            v = quote_dict(v)
        else:
            v = quote_or_literal(v)
        new[k] = v
    return new

def ensure_quotes(path):
    with io.open(path, 'r', encoding='utf-8') as stream:
        a = yaml.load(stream, Loader=yaml.Loader)
        a = quote_dict(a)

    with io.open(path, 'w', encoding='utf-8') as stream:
        yaml.dump(a, stream, allow_unicode=True,
                  width=1000, explicit_start=True)

if __name__ == "__main__":
    for path in sys.argv[1:]:
        ensure_quotes(path)
</code>```

Title: Force quotes in yaml

Body:
I have a ruby hash that is something like this:

myhash = { title: 'http://google.com'}

I'm trying to add this to a yaml file like this:

params['myhash'] = myhash
File.open('config.yaml', 'w') do |k|
  k.write params.to_yaml
end

The problem is that YAML is removing the  quotes  around the links even though they are needed (they contain ':').

According to several questions on Stackoverflow, YAML should only remove the quotes when they are not needed.

I found a Solution, but it's really ugly and I prefer not to use it if there was another solution.

I suppose that yaml should be including the quotes in this case. Is there any reason why it's not doing this?

Note: the links are dynamically created

Body:
After couple hours i found it's easier in python.

usage: python quotes.py *.yml

This script use literal format if string has '\n'.

Use ruamel to replace yaml lib, yaml lib seems not handle some UTF-8 entry

from ruamel import yaml
import io
import sys

class quote_or_literal(unicode):
    pass

def str_presenter(dumper, data):
    if data.count("\n"):  # check for multiline string
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
    else:
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')

yaml.add_representer(quote_or_literal, str_presenter)

def quote_dict(d):
    new = {}
    for k, v in d.items():
        if isinstance(v, dict):
            v = quote_dict(v)
        else:
            v = quote_or_literal(v)
        new[k] = v
    return new

def ensure_quotes(path):
    with io.open(path, 'r', encoding='utf-8') as stream:
        a = yaml.load(stream, Loader=yaml.Loader)
        a = quote_dict(a)

    with io.open(path, 'w', encoding='utf-8') as stream:
        yaml.dump(a, stream, allow_unicode=True,
                  width=1000, explicit_start=True)

if __name__ == "__main__":
    for path in sys.argv[1:]:
        ensure_quotes(path)


问:
Dynamically change header string in angular 2
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a

```<code><h1>{{title}}</h1>
</code>```

and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page

below is an image of what im trying to change

Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..

Not sure how I can go about this and everything ive researched has been to change the title in the  tags

答:
You can create a service dedicated for updating the title in your header component. Simply inject the service in your header component and subscribe to a dedicated BehaviorSubject. Then you can inject this service in any component you have and use the setTitle method from that component which will update the title in the header component. Check out the following code

```<code>//headerTitle.service.ts
@Injectable()
export class headerTitleService {
  title = new BehaviorSubject('Initial Title');

  setTitle(title: string) {
    this.title.next(title);
  }
}

//header.component.ts
title = '';

constructor(private headerTitleService: HeaderTitleService) {}

ngOnInit() {
  this.headerTitleService.title.subscribe(updatedTitle => {
    this.title = updatedTitle;
  });
}

//header.component.html
<h1>{{title}}</h1>

//about.component.ts
constructor(private headerTitleService: HeaderTitleService) {}

ngOnInit() {
  this.headerTitleService.setTitle('About');
}
</code>```

Working demo

Body:
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a

{{title}}

and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page

below is an image of what im trying to change

Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..

Not sure how I can go about this and everything ive researched has been to change the title in the  tags

Body:
You can create a service dedicated for updating the title in your header component. Simply inject the service in your header component and subscribe to a dedicated BehaviorSubject. Then you can inject this service in any component you have and use the setTitle method from that component which will update the title in the header component. Check out the following code

//headerTitle.service.ts
@Injectable()
export class headerTitleService {
  title = new BehaviorSubject('Initial Title');

  setTitle(title: string) {
    this.title.next(title);
  }
}

//header.component.ts
title = '';

constructor(private headerTitleService: HeaderTitleService) {}

ngOnInit() {
  this.headerTitleService.title.subscribe(updatedTitle => {
    this.title = updatedTitle;
  });
}

//header.component.html
<h1>{{title}}</h1>

//about.component.ts
constructor(private headerTitleService: HeaderTitleService) {}

ngOnInit() {
  this.headerTitleService.setTitle('About');
}

Working demo


问:
Win32 console problem
is it possible to create a program that works as console application if started from the console and works as windows program (with GUI) when started otherwise?

If it is possible - how can I do that?

regards
Tobias

答:
You can sort of guess whether you are started from the console or not by doing this:

```<code>CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
fConsole = csbi.dwCursorPosition.X | csbi.dwCursorPosition.Y;
</code>```

It's a guess -- if your cursor position is not 0,0 than you are in a console and can work as a console app.  Otherwise go and create your windows.

Another way to guess is to look at the process tree and see what process launched your app.  If it is cmd.exe go in console mode, otherwise go into GUI mode.

Title: Win32 console problem

Body:
You can sort of guess whether you are started from the console or not by doing this:

CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
fConsole = csbi.dwCursorPosition.X | csbi.dwCursorPosition.Y;

It's a guess -- if your cursor position is not 0,0 than you are in a console and can work as a console app.  Otherwise go and create your windows.

Another way to guess is to look at the process tree and see what process launched your app.  If it is cmd.exe go in console mode, otherwise go into GUI mode.


问:
Refresh ListView on another Content Page via button click event
I am having a hard time refreshing a listView. I've tried using ObservableCollection instead of List for contacts but it didn't help. Can someone points me to the right direction please? Any help would be very much appreciated.

ContactListPage.cs file (This is the default page. Add Contact button loads up NewContactPage.)

```<code>public class ContactListPage : ContentPage
{
    public ListView listView = new ListView();
    public List<Contact> contacts { get; set; }

    public ContactListPage()
    {
        Button button = new Button
        {
            Text = "Add Contact",
            Margin = new Thickness(0, 0, 10, 0)
        };
        button.Clicked += OnButtonClicked;

        StackLayout buttonLayout = new StackLayout { Orientation = StackOrientation.Horizontal, VerticalOptions = LayoutOptions.Center,
            Children =
            {
                new Label {Text = "Contact List", FontSize = 30, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, Margin = new Thickness(10,0,0,0)},
                new Label {Text = "", FontSize = 30, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, HorizontalOptions = LayoutOptions.CenterAndExpand},
                button
            }
        };
        contacts = new List<Contact>
        {
            // Add some contacts
            new Contact("Jason", "Bourne", "Family"),
            new Contact("Sunny", "An", "Family Dog"),
            new Contact("Jenny", "Bahn", "Family"),
            new Contact("Joshua", "Brown", "Work")
        };

        // Set up listview
        listView.ItemsSource = contacts;
        listView.ItemTemplate = new DataTemplate(typeof(TextCell));
        listView.ItemTemplate.SetBinding(TextCell.TextProperty, "FullName");
        listView.ItemTemplate.SetBinding(TextCell.DetailProperty, "ContactType");
        listView.HeightRequest = (40 * contacts.Count);

        // Add things to the stacklayout
        StackLayout layout = new StackLayout();
        layout.Children.Add(buttonLayout);
        layout.Children.Add(listView);

        Content = layout;

        void OnButtonClicked(object sender, EventArgs args)
        {
            Navigation.PushAsync(new NewContactPage());
        };
    }
}
</code>```

Contact.cs file

```<code>public class Contact
{
    // constructor
    public Contact(string firstName, string lastName, string contactType)
    {
        FirstName = firstName;
        LastName = lastName;
        ContactType = contactType;
    }

    // properties
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string ContactType { get; set; }
    public string FullName
    {
        get
        {
            return FirstName + " " + LastName;
        }
        set
        {
            FullName = value;
        }
    }
}
</code>```

NewContactPage.cs file (Save button seems to be working. I've used Debug.WriteLine to see the list of contacts prior and after adding a new contact. Return button suppose to refresh the contactPage.listView.ItemSource with the latest contents of contacts but it doesn't.)

```<code>public NewContactPage()
    {
        ContactListPage contactPage = new ContactListPage();

        // Setup tableview
        EntryCell firstName = new EntryCell {Label = "First Name:", Keyboard = Keyboard.Default};
        EntryCell lastName = new EntryCell {Label = "Last Name:", Keyboard = Keyboard.Default};
        EntryCell contactType = new EntryCell {Label = "Contact Type:", Keyboard = Keyboard.Default};
        Label firstLabel = new Label { Text = "", FontSize = 10, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, HorizontalOptions = LayoutOptions.CenterAndExpand};
        Label secondLabel = new Label {Text = "", FontSize = 10, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, HorizontalOptions = LayoutOptions.CenterAndExpand};
        TableView tableView = new TableView {VerticalOptions = LayoutOptions.Start, Intent = TableIntent.Form,
            Root = new TableRoot("Table Title") {
                new TableSection ("Add a New Contact") {
                    firstName,
                    lastName,
                    contactType
                }
            }
        };

        // Setup buttons
        Button saveContactButton = new Button {Text = "Save Contact", WidthRequest = 150, Margin = new Thickness(50, 0, 0, 0)};
        saveContactButton.Clicked += saveContactButtonClicked;
        Button returnButton = new Button {Text = "Return", WidthRequest = 150, Margin = new Thickness(10, 0, 50, 0)};
        returnButton.Clicked += returnButtonClicked;

        StackLayout buttonLayout = new StackLayout {Orientation = StackOrientation.Horizontal, VerticalOptions = LayoutOptions.Start,
            Children =
            {
                saveContactButton,
                new Label {Text = "", FontSize = 30, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, HorizontalOptions = LayoutOptions.CenterAndExpand},
                returnButton
            }
        };

        Content = new StackLayout {Children = { tableView, buttonLayout, firstLabel, secondLabel }};

        void saveContactButtonClicked(object sender, EventArgs e)
        {
            try
            {
                foreach (var yeah in contactPage.contacts)
                {
                    Debug.WriteLine(yeah.FirstName.ToString());
                }
                // Add new contact to list
                contactPage.contacts.Add(new Contact(firstName.Text.ToString(), lastName.Text.ToString(), contactType.Text.ToString()));
                foreach (var yeah in contactPage.contacts)
                {
                    Debug.WriteLine(yeah.FullName.ToString());
                }

                firstName.Text = String.Empty;
                lastName.Text = String.Empty;
                contactType.Text = String.Empty;
                DisplayAlert("Success", "New contact has been added.", "OK");

            }
            catch(Exception ex)
            {
                Debug.WriteLine("Exception: {0}", ex);
            }
        };

        void returnButtonClicked(object sender, EventArgs e)
        {
            contactPage.listView.ItemsSource = null;
            contactPage.listView.ItemsSource = contactPage.contacts;
            Navigation.PopAsync();
        };
    }
}
</code>```

答:
As Jason said, in the constructor of NewContactPage you are creating a new instance of ContactListPage which is completely different than the page you came from (and will return to upon PopAsync()).

To make it so you are adding the new contact to the correct page, I suggest passing in the your ContactListPage in the constructor of the NewContactPage:

```<code>public NewContactPage(ContactListPage contactPage)
{
    //As a side note it's probably better practice to make
    //contactPage a private variable for the NewContactPage class
    //...
}
</code>```

Then in your ContactListPage change the button click method to pass in the page:

```<code>void OnButtonClicked(object sender, EventArgs args)
{
    Navigation.PushAsync(new NewContactPage(this));
};
</code>```

Hope this helps!

Body:
I am having a hard time refreshing a listView. I've tried using ObservableCollection instead of List for contacts but it didn't help. Can someone points me to the right direction please? Any help would be very much appreciated.

ContactListPage.cs file (This is the default page. Add Contact button loads up NewContactPage.)

public class ContactListPage : ContentPage
{
    public ListView listView = new ListView();
    public List<Contact> contacts { get; set; }

    public ContactListPage()
    {
        Button button = new Button
        {
            Text = "Add Contact",
            Margin = new Thickness(0, 0, 10, 0)
        };
        button.Clicked += OnButtonClicked;

        StackLayout buttonLayout = new StackLayout { Orientation = StackOrientation.Horizontal, VerticalOptions = LayoutOptions.Center,
            Children =
            {
                new Label {Text = "Contact List", FontSize = 30, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, Margin = new Thickness(10,0,0,0)},
                new Label {Text = "", FontSize = 30, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, HorizontalOptions = LayoutOptions.CenterAndExpand},
                button
            }
        };
        contacts = new List<Contact>
        {
            // Add some contacts
            new Contact("Jason", "Bourne", "Family"),
            new Contact("Sunny", "An", "Family Dog"),
            new Contact("Jenny", "Bahn", "Family"),
            new Contact("Joshua", "Brown", "Work")
        };

        // Set up listview
        listView.ItemsSource = contacts;
        listView.ItemTemplate = new DataTemplate(typeof(TextCell));
        listView.ItemTemplate.SetBinding(TextCell.TextProperty, "FullName");
        listView.ItemTemplate.SetBinding(TextCell.DetailProperty, "ContactType");
        listView.HeightRequest = (40 * contacts.Count);

        // Add things to the stacklayout
        StackLayout layout = new StackLayout();
        layout.Children.Add(buttonLayout);
        layout.Children.Add(listView);

        Content = layout;

        void OnButtonClicked(object sender, EventArgs args)
        {
            Navigation.PushAsync(new NewContactPage());
        };
    }
}

Contact.cs file

public class Contact
{
    // constructor
    public Contact(string firstName, string lastName, string contactType)
    {
        FirstName = firstName;
        LastName = lastName;
        ContactType = contactType;
    }

    // properties
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string ContactType { get; set; }
    public string FullName
    {
        get
        {
            return FirstName + " " + LastName;
        }
        set
        {
            FullName = value;
        }
    }
}

NewContactPage.cs file (Save button seems to be working. I've used Debug.WriteLine to see the list of contacts prior and after adding a new contact. Return button suppose to refresh the contactPage.listView.ItemSource with the latest contents of contacts but it doesn't.)

public NewContactPage()
    {
        ContactListPage contactPage = new ContactListPage();

        // Setup tableview
        EntryCell firstName = new EntryCell {Label = "First Name:", Keyboard = Keyboard.Default};
        EntryCell lastName = new EntryCell {Label = "Last Name:", Keyboard = Keyboard.Default};
        EntryCell contactType = new EntryCell {Label = "Contact Type:", Keyboard = Keyboard.Default};
        Label firstLabel = new Label { Text = "", FontSize = 10, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, HorizontalOptions = LayoutOptions.CenterAndExpand};
        Label secondLabel = new Label {Text = "", FontSize = 10, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, HorizontalOptions = LayoutOptions.CenterAndExpand};
        TableView tableView = new TableView {VerticalOptions = LayoutOptions.Start, Intent = TableIntent.Form,
            Root = new TableRoot("Table Title") {
                new TableSection ("Add a New Contact") {
                    firstName,
                    lastName,
                    contactType
                }
            }
        };

        // Setup buttons
        Button saveContactButton = new Button {Text = "Save Contact", WidthRequest = 150, Margin = new Thickness(50, 0, 0, 0)};
        saveContactButton.Clicked += saveContactButtonClicked;
        Button returnButton = new Button {Text = "Return", WidthRequest = 150, Margin = new Thickness(10, 0, 50, 0)};
        returnButton.Clicked += returnButtonClicked;

        StackLayout buttonLayout = new StackLayout {Orientation = StackOrientation.Horizontal, VerticalOptions = LayoutOptions.Start,
            Children =
            {
                saveContactButton,
                new Label {Text = "", FontSize = 30, FontAttributes = FontAttributes.Bold | FontAttributes.Italic, HorizontalOptions = LayoutOptions.CenterAndExpand},
                returnButton
            }
        };

        Content = new StackLayout {Children = { tableView, buttonLayout, firstLabel, secondLabel }};

        void saveContactButtonClicked(object sender, EventArgs e)
        {
            try
            {
                foreach (var yeah in contactPage.contacts)
                {
                    Debug.WriteLine(yeah.FirstName.ToString());
                }
                // Add new contact to list
                contactPage.contacts.Add(new Contact(firstName.Text.ToString(), lastName.Text.ToString(), contactType.Text.ToString()));
                foreach (var yeah in contactPage.contacts)
                {
                    Debug.WriteLine(yeah.FullName.ToString());
                }

                firstName.Text = String.Empty;
                lastName.Text = String.Empty;
                contactType.Text = String.Empty;
                DisplayAlert("Success", "New contact has been added.", "OK");

            }
            catch(Exception ex)
            {
                Debug.WriteLine("Exception: {0}", ex);
            }
        };

        void returnButtonClicked(object sender, EventArgs e)
        {
            contactPage.listView.ItemsSource = null;
            contactPage.listView.ItemsSource = contactPage.contacts;
            Navigation.PopAsync();
        };
    }
}

Body:
As Jason said, in the constructor of NewContactPage you are creating a new instance of ContactListPage which is completely different than the page you came from (and will return to upon PopAsync()).

To make it so you are adding the new contact to the correct page, I suggest passing in the your ContactListPage in the constructor of the NewContactPage:

public NewContactPage(ContactListPage contactPage)
{
    //As a side note it's probably better practice to make
    //contactPage a private variable for the NewContactPage class
    //...
}

Then in your ContactListPage change the button click method to pass in the page:

void OnButtonClicked(object sender, EventArgs args)
{
    Navigation.PushAsync(new NewContactPage(this));
};

Hope this helps!


问:
CSS selector id not working
here is my code: http://jsbin.com/sinacel/edit?html,css,output

#octagon selector doesn't work at all, and doesn't get any styling.

it should produce at least a red background, but this is what I get instead

I'm using Google Chrome latest version.
Any idea why this could happen or is it happening just on my pc?

答:
if you are using css to style your website just remember it
while you use id so in css you tell it with # but e.g

```<code><button id="try">
 </button>
</code>```

so in css you can call that style with

```<code>#try{
background-color:red;
}
</code>```

Title: CSS selector id not working

Body:
if you are using css to style your website just remember it
while you use id so in css you tell it with # but e.g

<button id="try">
 </button>

so in css you can call that style with

#try{
background-color:red;
}


问:
JavaFX not redrawing properly
I am trying to make a cryptex program using JavaFX, but sometimes the rendering gets corrupted.

What it should be showing:

However, sometimes the rotation snags it show this:

Why is this happening? What can I do to fix this? I've found lots of other posts saying that JavaFX should handle all of the rendering for you, but forcing a redraw seems like the only solution, and I couldn't figure out how to do that either.

Here is my code:

```<code>import java.awt.Image;
import java.util.Timer;
import java.util.TimerTask;

import javafx.application.Application;
import javafx.scene.effect.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.StrokeType;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.*;
import javafx.stage.Stage;

public class Cryptex extends Application{
    private Spool[] spools;
    private double radius = 100, perspectiveScale = 0.1;
    Stage stage;
    Scene scene;

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage primaryStage){
        stage = primaryStage;
        stage.setTitle("Criptex");

        Group root = new Group();
        scene = new Scene(root, 550, 400);
        stage.setScene(scene);
        stage.show();

        spools = new Spool[5];
        spools[0] = new Spool("jdkwndityc", -150);
        spools[1] = new Spool("lqhmnxfgso", -75);
        spools[2] = new Spool("usjnzuvbid", 0);
        spools[3] = new Spool("ihgkewobde", 75);
        spools[4] = new Spool("cdelsprkar", 150);
        for (Spool sp : spools){
            sp.angle = Math.random()*Math.PI*2;
            root.getChildren().add(sp);
        }

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                for (Spool s : spools){
                    if (s.angle != 0){
                        if (Math.abs(s.distToAngle(0)) < Math.toRadians(1)){
                            System.out.println("snap");
                            s.snapToAngle(0);
                            for (Spool.Cell c : s.cells){
                                c.draw(s.angle);
                            }
                        }
                        else {
                            s.rotate(s.directionToAngle(0));
                            System.out.println((s.x+150)/75+1 + ": "+Math.round((s.angle/Math.PI)*180));
                            for (Spool.Cell c : s.cells){
                                c.draw(s.angle);
                            }
                        }
                    }
                }
                //System.out.println("--");
            }
        }, 0, 10);
    }

    public class Spool extends Group{
        double angle;
        char[] chars;
        Image[] letters;
        int x;
        Cell[] cells;
        public Spool(String charList, int x){
            chars = charList.toCharArray();
            letters = new Image[chars.length];
            this.x = x;
            angle = 0;
            cells = new Cell[chars.length];
            for (int i = 0; i < chars.length; i++){
                cells[i] = new Cell(i);
                this.getChildren().add(cells[i]);
            }
        }

        public void rotate(double distance){
            angle += Math.toRadians(distance);
            if (angle >= Math.PI*2){
                angle -= Math.PI*2;
            }
            if (angle < 0){
                angle += Math.PI*2;
            }
        }
        //TODO: check if this is way off
        public double distToAngle(double angle){
            rotate(0);
            if ((this.angle > angle && this.angle - angle > Math.PI) ||
                    (this.angle < angle && angle - this.angle > Math.PI)){
                return Math.abs(this.angle - angle);
            }
            else {
                return -Math.abs(this.angle - angle);
            }
        }
        public double closestAngle(){
            int closest = 0;
            for (int i = 0; i < chars.length; i++){
                if (Math.abs(distToAngle(i*((Math.PI*2)/chars.length)))
                        < Math.abs(distToAngle(closest*((Math.PI*2)/chars.length)))){
                    closest = i;
                }
            }
            return closest;
        }
        public boolean snapToAngle(double angle){
            if (Math.abs(this.distToAngle(angle)) > Math.toRadians(1)){
                if (this.distToAngle(angle) > 0){
                    this.rotate(-1);
                }
                else {
                    this.rotate(1);
                }
                return false;
            }
            else if (this.angle != angle){
                this.angle = angle;
            }
            return true;
        }
        public double indexToAngle(int index){
            return ((Math.PI*2)/chars.length)*index;
        }
        public double perspectiveWidth(double d){
            return Math.sqrt(Math.pow(radius, 2) - Math.pow(d, 2)) * perspectiveScale;
        }
        public double toAngle(int index){
            return ((Math.PI*2)/chars.length)*(index) + angle + ((Math.PI*2)/(chars.length*2));
        }
        public int directionToAngle(double angle){
            return (int) Math.signum(this.distToAngle(angle));
        }

        public class Cell extends Group {
            private int index;
            PerspectiveTransform pt = new PerspectiveTransform();
            public Cell(int index){//, double angle, Stage stage){
                this.index = index;

                Text text = new Text();
                //System.out.println("char: " + String.valueOf(chars[c]));
                text.setText(String.valueOf(chars[index]).toUpperCase());
                text.setFont(Font.font("Monospaced", FontWeight.BOLD, 36));
                text.setFill(Color.BLACK);
                text.setX(9);
                text.setY(32);

                Rectangle rect = new Rectangle(40, 40);
                rect.setFill(Color.BEIGE);
                rect.setStrokeType(StrokeType.OUTSIDE);
                rect.setStrokeWidth(3);
                rect.setStroke(Color.BLACK);

                this.draw(angle);
                this.setCache(true);
                this.getChildren().addAll(rect, text);
            }

            public void draw(double angle){
                double cx = stage.getWidth()/2 + x;
                double cy = (stage.getHeight()-100)/2;
                if (cy + radius*Math.sin(toAngle(index)+angle) <= cy + radius*Math.sin(toAngle(index+1)+angle)){
                    this.setVisible(true);
                    pt.setUlx(cx - 20 - perspectiveWidth(radius*Math.sin(toAngle(index)+angle)));
                    pt.setUrx(cx + 20 + perspectiveWidth(radius*Math.sin(toAngle(index)+angle)));
                    pt.setLrx(cx + 20 + perspectiveWidth(radius*Math.sin(toAngle(index+1)+angle)));
                    pt.setLlx(cx - 20 - perspectiveWidth(radius*Math.sin(toAngle(index+1)+angle)));

                    pt.setUly(cy + radius*Math.sin(toAngle(index)+angle));
                    pt.setUry(cy + radius*Math.sin(toAngle(index)+angle));
                    pt.setLry(cy + radius*Math.sin(toAngle(index+1)+angle));
                    pt.setLly(cy + radius*Math.sin(toAngle(index+1)+angle));
                    this.setEffect(pt);
                }
                else {
                    this.setVisible(false);
                }
            }
        }
    }
}
</code>```

答:
Your issue is the same as the one seen here, using a java.util.Timer directly inside JavaFX is not thread safe.

This is because timer uses it's own background thread, but if you want to do any updates to the GUI, you need to be using the JavaFX GUI thread (a special thread JavaFX creates and handles). Trying to touch the GUI from another thread creates problems like the ones you are seeing.

You can pass changes to JavaFX components to the special JavaFX thread by wrapping the changes in a Platform.runLater block.

The code looks like this:

```<code>Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        Platform.runLater(() -> { //Lambda for Runnable
            for (Spool s : spools){
                if (s.angle != 0){
                    if (Math.abs(s.distToAngle(0)) < Math.toRadians(1)){
                        System.out.println("snap");
                        s.snapToAngle(0);
                        for (Spool.Cell c : s.cells){
                            c.draw(s.angle);
                        }
                    }
                    else {
                        s.rotate(s.directionToAngle(0));
                        System.out.println((s.x+150)/75+1 + ": "
                            + Math.round((s.angle/Math.PI)*180));
                        for (Spool.Cell c : s.cells){
                            c.draw(s.angle);
                        }
                    }
                }
            }
        });
    }
}, 0, 10);
</code>```

Pure JavaFX Style:

You can also use a JavaFX Timeline and not have to worry about the thread issues:

```<code>Timeline timer = new Timeline(new KeyFrame(
        Duration.millis(10),
        event -> {//Same for loop as above}
));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();
</code>```

Title: JavaFX not redrawing properly

Body:
I am trying to make a cryptex program using JavaFX, but sometimes the rendering gets corrupted.

What it should be showing:

However, sometimes the rotation snags it show this:

Why is this happening? What can I do to fix this? I've found lots of other posts saying that JavaFX should handle all of the rendering for you, but forcing a redraw seems like the only solution, and I couldn't figure out how to do that either.

Here is my code:

import java.awt.Image;
import java.util.Timer;
import java.util.TimerTask;

import javafx.application.Application;
import javafx.scene.effect.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.StrokeType;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.*;
import javafx.stage.Stage;

public class Cryptex extends Application{
    private Spool[] spools;
    private double radius = 100, perspectiveScale = 0.1;
    Stage stage;
    Scene scene;

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage primaryStage){
        stage = primaryStage;
        stage.setTitle("Criptex");

        Group root = new Group();
        scene = new Scene(root, 550, 400);
        stage.setScene(scene);
        stage.show();

        spools = new Spool[5];
        spools[0] = new Spool("jdkwndityc", -150);
        spools[1] = new Spool("lqhmnxfgso", -75);
        spools[2] = new Spool("usjnzuvbid", 0);
        spools[3] = new Spool("ihgkewobde", 75);
        spools[4] = new Spool("cdelsprkar", 150);
        for (Spool sp : spools){
            sp.angle = Math.random()*Math.PI*2;
            root.getChildren().add(sp);
        }

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                for (Spool s : spools){
                    if (s.angle != 0){
                        if (Math.abs(s.distToAngle(0)) < Math.toRadians(1)){
                            System.out.println("snap");
                            s.snapToAngle(0);
                            for (Spool.Cell c : s.cells){
                                c.draw(s.angle);
                            }
                        }
                        else {
                            s.rotate(s.directionToAngle(0));
                            System.out.println((s.x+150)/75+1 + ": "+Math.round((s.angle/Math.PI)*180));
                            for (Spool.Cell c : s.cells){
                                c.draw(s.angle);
                            }
                        }
                    }
                }
                //System.out.println("--");
            }
        }, 0, 10);
    }

    public class Spool extends Group{
        double angle;
        char[] chars;
        Image[] letters;
        int x;
        Cell[] cells;
        public Spool(String charList, int x){
            chars = charList.toCharArray();
            letters = new Image[chars.length];
            this.x = x;
            angle = 0;
            cells = new Cell[chars.length];
            for (int i = 0; i < chars.length; i++){
                cells[i] = new Cell(i);
                this.getChildren().add(cells[i]);
            }
        }

        public void rotate(double distance){
            angle += Math.toRadians(distance);
            if (angle >= Math.PI*2){
                angle -= Math.PI*2;
            }
            if (angle < 0){
                angle += Math.PI*2;
            }
        }
        //TODO: check if this is way off
        public double distToAngle(double angle){
            rotate(0);
            if ((this.angle > angle && this.angle - angle > Math.PI) ||
                    (this.angle < angle && angle - this.angle > Math.PI)){
                return Math.abs(this.angle - angle);
            }
            else {
                return -Math.abs(this.angle - angle);
            }
        }
        public double closestAngle(){
            int closest = 0;
            for (int i = 0; i < chars.length; i++){
                if (Math.abs(distToAngle(i*((Math.PI*2)/chars.length)))
                        < Math.abs(distToAngle(closest*((Math.PI*2)/chars.length)))){
                    closest = i;
                }
            }
            return closest;
        }
        public boolean snapToAngle(double angle){
            if (Math.abs(this.distToAngle(angle)) > Math.toRadians(1)){
                if (this.distToAngle(angle) > 0){
                    this.rotate(-1);
                }
                else {
                    this.rotate(1);
                }
                return false;
            }
            else if (this.angle != angle){
                this.angle = angle;
            }
            return true;
        }
        public double indexToAngle(int index){
            return ((Math.PI*2)/chars.length)*index;
        }
        public double perspectiveWidth(double d){
            return Math.sqrt(Math.pow(radius, 2) - Math.pow(d, 2)) * perspectiveScale;
        }
        public double toAngle(int index){
            return ((Math.PI*2)/chars.length)*(index) + angle + ((Math.PI*2)/(chars.length*2));
        }
        public int directionToAngle(double angle){
            return (int) Math.signum(this.distToAngle(angle));
        }

        public class Cell extends Group {
            private int index;
            PerspectiveTransform pt = new PerspectiveTransform();
            public Cell(int index){//, double angle, Stage stage){
                this.index = index;

                Text text = new Text();
                //System.out.println("char: " + String.valueOf(chars[c]));
                text.setText(String.valueOf(chars[index]).toUpperCase());
                text.setFont(Font.font("Monospaced", FontWeight.BOLD, 36));
                text.setFill(Color.BLACK);
                text.setX(9);
                text.setY(32);

                Rectangle rect = new Rectangle(40, 40);
                rect.setFill(Color.BEIGE);
                rect.setStrokeType(StrokeType.OUTSIDE);
                rect.setStrokeWidth(3);
                rect.setStroke(Color.BLACK);

                this.draw(angle);
                this.setCache(true);
                this.getChildren().addAll(rect, text);
            }

            public void draw(double angle){
                double cx = stage.getWidth()/2 + x;
                double cy = (stage.getHeight()-100)/2;
                if (cy + radius*Math.sin(toAngle(index)+angle) <= cy + radius*Math.sin(toAngle(index+1)+angle)){
                    this.setVisible(true);
                    pt.setUlx(cx - 20 - perspectiveWidth(radius*Math.sin(toAngle(index)+angle)));
                    pt.setUrx(cx + 20 + perspectiveWidth(radius*Math.sin(toAngle(index)+angle)));
                    pt.setLrx(cx + 20 + perspectiveWidth(radius*Math.sin(toAngle(index+1)+angle)));
                    pt.setLlx(cx - 20 - perspectiveWidth(radius*Math.sin(toAngle(index+1)+angle)));

                    pt.setUly(cy + radius*Math.sin(toAngle(index)+angle));
                    pt.setUry(cy + radius*Math.sin(toAngle(index)+angle));
                    pt.setLry(cy + radius*Math.sin(toAngle(index+1)+angle));
                    pt.setLly(cy + radius*Math.sin(toAngle(index+1)+angle));
                    this.setEffect(pt);
                }
                else {
                    this.setVisible(false);
                }
            }
        }
    }
}

Body:
Your issue is the same as the one seen here, using a java.util.Timer directly inside JavaFX is not thread safe.

This is because timer uses it's own background thread, but if you want to do any updates to the GUI, you need to be using the JavaFX GUI thread (a special thread JavaFX creates and handles). Trying to touch the GUI from another thread creates problems like the ones you are seeing.

You can pass changes to JavaFX components to the special JavaFX thread by wrapping the changes in a Platform.runLater block.

The code looks like this:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        Platform.runLater(() -> { //Lambda for Runnable
            for (Spool s : spools){
                if (s.angle != 0){
                    if (Math.abs(s.distToAngle(0)) < Math.toRadians(1)){
                        System.out.println("snap");
                        s.snapToAngle(0);
                        for (Spool.Cell c : s.cells){
                            c.draw(s.angle);
                        }
                    }
                    else {
                        s.rotate(s.directionToAngle(0));
                        System.out.println((s.x+150)/75+1 + ": "
                            + Math.round((s.angle/Math.PI)*180));
                        for (Spool.Cell c : s.cells){
                            c.draw(s.angle);
                        }
                    }
                }
            }
        });
    }
}, 0, 10);

Pure JavaFX Style:

You can also use a JavaFX Timeline and not have to worry about the thread issues:

Timeline timer = new Timeline(new KeyFrame(
        Duration.millis(10),
        event -> {//Same for loop as above}
));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();


问:
python selenium - selecting option from dropdown
I am attempting to use the below code to use selenium (python) to select an option from a dropdown on a webpage.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

path_to_chromedriver = 'C:/Users/User_1/chromedriver/chromedriver'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

url = 'https://lifeinsurance.rac.com.au/rac/get-a-quote?productid=51'
browser.get(url)

wait = WebDriverWait(browser, 10)

# residence listbox
drop_down = browser.find_element_by_xpath('//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')

browser.execute_script('arguments[0].style.display="inline";', drop_down)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')))

wait.until(EC.element_to_be_clickable((By.XPATH, r'//*[@id="ddResidentialStatusId__1_listbox"]/li[1]'))).click()
</code>```

There are occasions where it works (and an option from the dropdown is selected), but on other occasions an option from the dropdown is NOT selected (and no error raised either).

I would appreciate any feedback on how to consistently select an option from the dropdown noted in the code provided.

答:
```<code>def select_resident_status(resident_status):
    // click the arrow down to make all options list out
    driver.find_element_by_css_selector('span[aria-owns*="ResidentialStatus"] span.k-select').click()

    // select option by pass-in option text
    driver.find_element_by_css_selector('div[id*="ResidentialStatus"][style*="display: block"] ul')
          .find_element_by_xpath('./li[text()="'+resident_status+'"]').click()
</code>```

Body:
I am attempting to use the below code to use selenium (python) to select an option from a dropdown on a webpage.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

path_to_chromedriver = 'C:/Users/User_1/chromedriver/chromedriver'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

url = 'https://lifeinsurance.rac.com.au/rac/get-a-quote?productid=51'
browser.get(url)

wait = WebDriverWait(browser, 10)

# residence listbox
drop_down = browser.find_element_by_xpath('//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')

browser.execute_script('arguments[0].style.display="inline";', drop_down)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')))

wait.until(EC.element_to_be_clickable((By.XPATH, r'//*[@id="ddResidentialStatusId__1_listbox"]/li[1]'))).click()

There are occasions where it works (and an option from the dropdown is selected), but on other occasions an option from the dropdown is NOT selected (and no error raised either).

I would appreciate any feedback on how to consistently select an option from the dropdown noted in the code provided.


问:
Handle an event in a form created in a class in C #
Please help me,

I need  to use in a form the OnTickHistoryResponse event so when the event happens I can show information in a control.

The event OnTickHistoryResponse comes with an API called ActivetickFeed and this event OnTickHistoryResponse is already in the API, please your help, I do not know how I can use the event.

Only this appears in the documentation:Image

The class where the event is defined and assigned a method is this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ActiveTickFeedCOMCSExample
{
    class ActiveTickFeed
    {
        public static ActiveTickFeedLib.Feed feed;
        public static ActiveTickFeed instance;

        public ActiveTickFeed()
        {
            //create new instance of IFeed
            feed = new ActiveTickFeedLib.Feed();

            feed.PrimaryServerHostname = "activetick1.activetick.com";
            feed.BackupServerHostname = "activetick2.activetick.com";

            feed.ServerPort = 443;

            //connect all IFeedEvents events to local methods

            feed.OnTickHistoryResponse += feed_OnTickHistoryResponse;

            }

            void feed_OnTickHistoryResponse(int originalRequestId, short tickHistoryResponseCode, string symbol, short symbolStatusCode, object records)
        {
            Form1.instance.AddData("Processing OnTickHistoryResponse........");

            Form1.instance.AddData("ATTickHistoryResponseType: " + ((ActiveTickFeedLib.ATTickHistoryResponseEnum)tickHistoryResponseCode).ToString());
            Form1.instance.AddData("ATSymbolStatus: " + ((ActiveTickFeedLib.ATSymbolStatusEnum)symbolStatusCode).ToString());

            switch ((ActiveTickFeedLib.ATTickHistoryResponseEnum)tickHistoryResponseCode)
            {
                case ActiveTickFeedLib.ATTickHistoryResponseEnum.ATTickHistoryResponseSuccess:
                case ActiveTickFeedLib.ATTickHistoryResponseEnum.ATTickHistoryResponseMaxLimitReached:
                    {
                        if ((ActiveTickFeedLib.ATSymbolStatusEnum)symbolStatusCode == ActiveTickFeedLib.ATSymbolStatusEnum.ATSymbolStatusSuccess)
                        {
                            if (records != null)
                            {
                                string[] recordsArray = (string[])records;
                                foreach (string s in recordsArray)
                                    Form1.instance.AddData(s);
                            }
                        }
                    }
                    break;
                case ActiveTickFeedLib.ATTickHistoryResponseEnum.ATTickHistoryResponseInvalidRequest:
                    break;
                case ActiveTickFeedLib.ATTickHistoryResponseEnum.ATTickHistoryResponseDenied:
                    break;
            }
        }

        ```

答: Whenever you send the "SendTickHistoryRequest", as a response you will get "OnTickHistoryResponse" event. So event subscribing is not enough, please send a request (SendTickHistoryRequest) you will get a response event.</p>