问:
Why I can't call interface function directly?
```<code>    For Each jt In json
        Dim jo1 = CType(jt, JObject)
        Dim id = jo1.Item("MarketID").ToString
        Dim basequote = dict(id)
        Dim jo2 As IDictionary(Of String, JToken) = jo1

        If Not (jo2.ContainsKey(jsonHelper.SpecialKeyForDictoToArray)) Then
            jo1.Add(jsonHelper.SpecialKeyForDictoToArray, dict(id))
            Dim b = 1
        End If
    Next
</code>```

The idea is Jobject implements  IDictionary(Of String, JToken) and hence I can do

```<code>        Dim jo2 As IDictionary(Of String, JToken) = jo1
</code>```

However, I must be missing something here.

If Jobject implements some interface, should I be able to do

```<code>        If Not (jo1.ContainsKey(jsonHelper.SpecialKeyForDictoToArray))
</code>```

right away?

Where did I went wrong?

Trying to do so yield this screenshot

I tried to check definition of JObject. It clearly states that it implements

IDictionary(Of String, JToken)

However, nowhere does I see it implements functions like containskey.

```<code>   '
' Summary:
'     Represents a JSON object.
<DefaultMember("Item")>
Public Class JObject
    Inherits JContainer
    Implements IDictionary(Of String, JToken), ICollection(Of KeyValuePair(Of String, JToken)), IEnumerable(Of KeyValuePair(Of String, JToken)), IEnumerable, INotifyPropertyChanged, ICustomTypeDescriptor, INotifyPropertyChanging
    '
    ' Summary:
    '     Initializes a new instance of the Newtonsoft.Json.Linq.JObject class.
    Public Sub New()
    '
    ' Summary:
    '     Initializes a new instance of the Newtonsoft.Json.Linq.JObject class from another
    '     Newtonsoft.Json.Linq.JObject object.
    '
    ' Parameters:
    '   other:
    '     A Newtonsoft.Json.Linq.JObject object to copy from.
    Public Sub New(other As JObject)
    '
    ' Summary:
    '     Initializes a new instance of the Newtonsoft.Json.Linq.JObject class with the
    '     specified content.
    '
    ' Parameters:
    '   content:
    '     The contents of the object.
    Public Sub New(ParamArray content() As Object)
    '
    ' Summary:
    '     Initializes a new instance of the Newtonsoft.Json.Linq.JObject class with the
    '     specified content.
    '
    ' Parameters:
    '   content:
    '     The contents of the object.
    Public Sub New(content As Object)

    '
    ' Summary:
    '     Gets or sets the Newtonsoft.Json.Linq.JToken with the specified property name.
    Default Public Property Item(propertyName As String) As JToken
    '
    ' Summary:
    '     Gets the Newtonsoft.Json.Linq.JToken with the specified key.
    Default Public Overrides Property Item(key As Object) As JToken
    '
    ' Summary:
    '     Gets the node type for this Newtonsoft.Json.Linq.JToken.
    Public Overrides ReadOnly Property Type As JTokenType
    '
    ' Summary:
    '     Gets the container's children tokens.
    Protected Overrides ReadOnly Property ChildrenTokens As IList(Of JToken)

    '
    ' Summary:
    '     Occurs when a property value is changing.
    Public Event PropertyChanging As PropertyChangingEventHandler
    '
    ' Summary:
    '     Occurs when a property value changes.
    Public Event PropertyChanged As PropertyChangedEventHandler

    '
    ' Summary:
    '     Adds the specified property name.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    '   value:
    '     The value.
    Public Sub Add(propertyName As String, value As JToken)
    '
    ' Summary:
    '     Writes this token to a Newtonsoft.Json.JsonWriter.
    '
    ' Parameters:
    '   writer:
    '     A Newtonsoft.Json.JsonWriter into which this method will write.
    '
    '   converters:
    '     A collection of Newtonsoft.Json.JsonConverter which will be used when writing
    '     the token.
    Public Overrides Sub WriteTo(writer As JsonWriter, ParamArray converters() As JsonConverter)
    '
    ' Summary:
    '     Raises the Newtonsoft.Json.Linq.JObject.PropertyChanging event with the provided
    '     arguments.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    Protected Overridable Sub OnPropertyChanging(propertyName As String)
    '
    ' Summary:
    '     Raises the Newtonsoft.Json.Linq.JObject.PropertyChanged event with the provided
    '     arguments.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    Protected Overridable Sub OnPropertyChanged(propertyName As String)

    '
    ' Summary:
    '     Load a Newtonsoft.Json.Linq.JObject from a string that contains JSON.
    '
    ' Parameters:
    '   json:
    '     A System.String that contains JSON.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject populated from the string that contains JSON.
    '
    ' Exceptions:
    '   T:Newtonsoft.Json.JsonReaderException:
    '     json is not valid JSON.
    Public Shared Function Parse(json As String) As JObject
    '
    ' Summary:
    '     Load a Newtonsoft.Json.Linq.JObject from a string that contains JSON.
    '
    ' Parameters:
    '   json:
    '     A System.String that contains JSON.
    '
    '   settings:
    '     The Newtonsoft.Json.Linq.JsonLoadSettings used to load the JSON. If this is null,
    '     default load settings will be used.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject populated from the string that contains JSON.
    '
    ' Exceptions:
    '   T:Newtonsoft.Json.JsonReaderException:
    '     json is not valid JSON.
    Public Shared Function Parse(json As String, settings As JsonLoadSettings) As JObject
    '
    ' Summary:
    '     Creates a Newtonsoft.Json.Linq.JObject from an object.
    '
    ' Parameters:
    '   o:
    '     The object that will be used to create Newtonsoft.Json.Linq.JObject.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject with the values of the specified object.
    Public Shared Function FromObject(o As Object) As JObject
    '
    ' Summary:
    '     Creates a Newtonsoft.Json.Linq.JObject from an object.
    '
    ' Parameters:
    '   o:
    '     The object that will be used to create Newtonsoft.Json.Linq.JObject.
    '
    '   jsonSerializer:
    '     The Newtonsoft.Json.JsonSerializer that will be used to read the object.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject with the values of the specified object.
    Public Shared Function FromObject(o As Object, jsonSerializer As JsonSerializer) As JObject
    '
    ' Summary:
    '     Loads a Newtonsoft.Json.Linq.JObject from a Newtonsoft.Json.JsonReader.
    '
    ' Parameters:
    '   reader:
    '     A Newtonsoft.Json.JsonReader that will be read for the content of the Newtonsoft.Json.Linq.JObject.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject that contains the JSON that was read from the
    '     specified Newtonsoft.Json.JsonReader.
    '
    ' Exceptions:
    '   T:Newtonsoft.Json.JsonReaderException:
    '     reader is not valid JSON.
    Public Shared Function Load(reader As JsonReader) As JObject
    '
    ' Summary:
    '     Asynchronously loads a Newtonsoft.Json.Linq.JObject from a Newtonsoft.Json.JsonReader.
    '
    ' Parameters:
    '   reader:
    '     A Newtonsoft.Json.JsonReader that will be read for the content of the Newtonsoft.Json.Linq.JObject.
    '
    '   cancellationToken:
    '     The token to monitor for cancellation requests. The default value is System.Threading.CancellationToken.None.
    '
    ' Returns:
    '     A System.Threading.Tasks.Task`1 that represents the asynchronous load. The System.Threading.Tasks.Task`1.Result
    '     property returns a Newtonsoft.Json.Linq.JObject that contains the JSON that was
    '     read from the specified Newtonsoft.Json.JsonReader.
    Public Shared Function LoadAsync(reader As JsonReader, Optional cancellationToken As CancellationToken = Nothing) As Task(Of JObject)
    '
    ' Summary:
    '     Asynchronously loads a Newtonsoft.Json.Linq.JObject from a Newtonsoft.Json.JsonReader.
    '
    ' Parameters:
    '   reader:
    '     A Newtonsoft.Json.JsonReader that will be read for the content of the Newtonsoft.Json.Linq.JObject.
    '
    '   settings:
    '     The Newtonsoft.Json.Linq.JsonLoadSettings used to load the JSON. If this is null,
    '     default load settings will be used.
    '
    '   cancellationToken:
    '     The token to monitor for cancellation requests. The default value is System.Threading.CancellationToken.None.
    '
    ' Returns:
    '     A System.Threading.Tasks.Task`1 that represents the asynchronous load. The System.Threading.Tasks.Task`1.Result
    '     property returns a Newtonsoft.Json.Linq.JObject that contains the JSON that was
    '     read from the specified Newtonsoft.Json.JsonReader.
    <AsyncStateMachineAttribute(GetType(<LoadAsync>d__2))>
    Public Shared Function LoadAsync(reader As JsonReader, settings As JsonLoadSettings, Optional cancellationToken As CancellationToken = Nothing) As Task(Of JObject)
    '
    ' Summary:
    '     Loads a Newtonsoft.Json.Linq.JObject from a Newtonsoft.Json.JsonReader.
    '
    ' Parameters:
    '   reader:
    '     A Newtonsoft.Json.JsonReader that will be read for the content of the Newtonsoft.Json.Linq.JObject.
    '
    '   settings:
    '     The Newtonsoft.Json.Linq.JsonLoadSettings used to load the JSON. If this is null,
    '     default load settings will be used.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject that contains the JSON that was read from the
    '     specified Newtonsoft.Json.JsonReader.
    '
    ' Exceptions:
    '   T:Newtonsoft.Json.JsonReaderException:
    '     reader is not valid JSON.
    Public Shared Function Load(reader As JsonReader, settings As JsonLoadSettings) As JObject
    '
    ' Summary:
    '     Gets an System.Collections.Generic.IEnumerable`1 of Newtonsoft.Json.Linq.JProperty
    '     of this object's properties.
    '
    ' Returns:
    '     An System.Collections.Generic.IEnumerable`1 of Newtonsoft.Json.Linq.JProperty
    '     of this object's properties.
    Public Function Properties() As IEnumerable(Of JProperty)
    '
    ' Summary:
    '     Gets a Newtonsoft.Json.Linq.JProperty the specified name.
    '
    ' Parameters:
    '   name:
    '     The property name.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JProperty with the specified name or null.
    Public Function [Property](name As String) As JProperty
    '
    ' Summary:
    '     Tries to get the Newtonsoft.Json.Linq.JToken with the specified property name.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    '   value:
    '     The value.
    '
    ' Returns:
    '     true if a value was successfully retrieved; otherwise, false.
    Public Function TryGetValue(propertyName As String, ByRef value As JToken) As Boolean
    '
    ' Summary:
    '     Removes the property with the specified name.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    ' Returns:
    '     true if item was successfully removed; otherwise, false.
    Public Function Remove(propertyName As String) As Boolean
    '
    ' Summary:
    '     Gets a Newtonsoft.Json.Linq.JEnumerable`1 of Newtonsoft.Json.Linq.JToken of this
    '     object's property values.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JEnumerable`1 of Newtonsoft.Json.Linq.JToken of this object's
    '     property values.
    Public Function PropertyValues() As JEnumerable(Of JToken)
    '
    ' Summary:
    '     Tries to get the Newtonsoft.Json.Linq.JToken with the specified property name.
    '     The exact property name will be searched for first and if no matching property
    '     is found then the System.StringComparison will be used to match a property.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    '   value:
    '     The value.
    '
    '   comparison:
    '     One of the enumeration values that specifies how the strings will be compared.
    '
    ' Returns:
    '     true if a value was successfully retrieved; otherwise, false.
    Public Function TryGetValue(propertyName As String, comparison As StringComparison, ByRef value As JToken) As Boolean
    '
    ' Summary:
    '     Gets the Newtonsoft.Json.Linq.JToken with the specified property name. The exact
    '     property name will be searched for first and if no matching property is found
    '     then the System.StringComparison will be used to match a property.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    '   comparison:
    '     One of the enumeration values that specifies how the strings will be compared.
    '
    ' Returns:
    '     The Newtonsoft.Json.Linq.JToken with the specified property name.
    Public Function GetValue(propertyName As String, comparison As StringComparison) As JToken
    '
    ' Summary:
    '     Gets the Newtonsoft.Json.Linq.JToken with the specified property name.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    ' Returns:
    '     The Newtonsoft.Json.Linq.JToken with the specified property name.
    Public Function GetValue(propertyName As String) As JToken
    '
    ' Summary:
    '     Returns an enumerator that can be used to iterate through the collection.
    '
    ' Returns:
    '     A System.Collections.Generic.IEnumerator`1 that can be used to iterate through
    '     the collection.
    <IteratorStateMachineAttribute(GetType(<GetEnumerator>d__61))>
    Public Function GetEnumerator() As IEnumerator(Of KeyValuePair(Of String, JToken))
    '
    ' Summary:
    '     Writes this token to a Newtonsoft.Json.JsonWriter asynchronously.
    '
    ' Parameters:
    '   writer:
    '     A Newtonsoft.Json.JsonWriter into which this method will write.
    '
    '   cancellationToken:
    '     The token to monitor for cancellation requests.
    '
    '   converters:
    '     A collection of Newtonsoft.Json.JsonConverter which will be used when writing
    '     the token.
    '
    ' Returns:
    '     A System.Threading.Tasks.Task that represents the asynchronous write operation.
    <AsyncStateMachineAttribute(GetType(<WriteToAsync>d__0))>
    Public Overrides Function WriteToAsync(writer As JsonWriter, cancellationToken As CancellationToken, ParamArray converters() As JsonConverter) As Task
    '
    ' Summary:
    '     Returns the System.Dynamic.DynamicMetaObject responsible for binding operations
    '     performed on this object.
    '
    ' Parameters:
    '   parameter:
    '     The expression tree representation of the runtime value.
    '
    ' Returns:
    '     The System.Dynamic.DynamicMetaObject to bind this object.
    Protected Overrides Function GetMetaObject(parameter As Expression) As DynamicMetaObject
End Class
</code>```

You can look things up here

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

There is no implementation of containsKey. Why?

答:
If the interface member is implemented but marked Private, it won't show up in the metadata or intellisense. This is explicit implementation. You can still access it through the interface. This is by design so it doesn't augment the public interface. Remember, Interfaces don't specify access levels though interface members are guaranteed to be available through the interface.

You'll need to cast the object as IDictionary(Of String, JToken) to access the interface member.

```<code>CType(jo1, IDictionary(Of String, JToken))
</code>```

Either of these should work

```<code>If Not (CType(jo1, IDictionary(Of String, JToken)).ContainsKey(jsonHelper.SpecialKeyForDictoToArray)) Then
    jo1.Add(jsonHelper.SpecialKeyForDictoToArray, dict(id))
    Dim b = 1
End If

If Not (jo2.ContainsKey(jsonHelper.SpecialKeyForDictoToArray)) Then
    jo1.Add(jsonHelper.SpecialKeyForDictoToArray, dict(id))
    Dim b = 1
End If
</code>```

In general, when you explicitly implement an interface, you must access the explicitly implemented member through the interface. One reason for this is multiple interface implementation. In the case

```<code>Class Foo
    Implements IBar, IBaz

    Public Sub Run() Implements IBar.Run
        Console.WriteLine("IBar")
    End Sub

    Private Sub IBaz_Run() Implements IBaz.Run
        Console.WriteLine("IBaz")
    End Sub

End Class

Interface IBar
    Sub Run()
End Interface

Interface IBaz
    Sub Run()
End Interface

Module Module1

    Sub Main()
        Dim myFoo As New Foo
        myFoo.Run() ' outputs IBar
        Dim myBaz As IBaz
        myBaz = DirectCast(myFoo, IBaz)
        myBaz.Run() ' outputs IBaz
        Console.ReadLine()
    End Sub

End Module
</code>```

The class Foo implements two interfaces with the same member name but only one can be defined in the class Foo. By default, IBaz.Run() is marked private (explicit implementation). One must access IBaz.Run through the interface. IBaz_Run could be marked public but since the name is different, it won't show up on the public interface of Foo anyway.

This example describes a behavior, but it is a side effect of the language feature explicit implementation.

Body:
    For Each jt In json
        Dim jo1 = CType(jt, JObject)
        Dim id = jo1.Item("MarketID").ToString
        Dim basequote = dict(id)
        Dim jo2 As IDictionary(Of String, JToken) = jo1

        If Not (jo2.ContainsKey(jsonHelper.SpecialKeyForDictoToArray)) Then
            jo1.Add(jsonHelper.SpecialKeyForDictoToArray, dict(id))
            Dim b = 1
        End If
    Next

The idea is Jobject implements  IDictionary(Of String, JToken) and hence I can do

        Dim jo2 As IDictionary(Of String, JToken) = jo1

However, I must be missing something here.

If Jobject implements some interface, should I be able to do

        If Not (jo1.ContainsKey(jsonHelper.SpecialKeyForDictoToArray))

right away?

Where did I went wrong?

Trying to do so yield this screenshot

I tried to check definition of JObject. It clearly states that it implements

IDictionary(Of String, JToken)

However, nowhere does I see it implements functions like containskey.

   '
' Summary:
'     Represents a JSON object.
<DefaultMember("Item")>
Public Class JObject
    Inherits JContainer
    Implements IDictionary(Of String, JToken), ICollection(Of KeyValuePair(Of String, JToken)), IEnumerable(Of KeyValuePair(Of String, JToken)), IEnumerable, INotifyPropertyChanged, ICustomTypeDescriptor, INotifyPropertyChanging
    '
    ' Summary:
    '     Initializes a new instance of the Newtonsoft.Json.Linq.JObject class.
    Public Sub New()
    '
    ' Summary:
    '     Initializes a new instance of the Newtonsoft.Json.Linq.JObject class from another
    '     Newtonsoft.Json.Linq.JObject object.
    '
    ' Parameters:
    '   other:
    '     A Newtonsoft.Json.Linq.JObject object to copy from.
    Public Sub New(other As JObject)
    '
    ' Summary:
    '     Initializes a new instance of the Newtonsoft.Json.Linq.JObject class with the
    '     specified content.
    '
    ' Parameters:
    '   content:
    '     The contents of the object.
    Public Sub New(ParamArray content() As Object)
    '
    ' Summary:
    '     Initializes a new instance of the Newtonsoft.Json.Linq.JObject class with the
    '     specified content.
    '
    ' Parameters:
    '   content:
    '     The contents of the object.
    Public Sub New(content As Object)

    '
    ' Summary:
    '     Gets or sets the Newtonsoft.Json.Linq.JToken with the specified property name.
    Default Public Property Item(propertyName As String) As JToken
    '
    ' Summary:
    '     Gets the Newtonsoft.Json.Linq.JToken with the specified key.
    Default Public Overrides Property Item(key As Object) As JToken
    '
    ' Summary:
    '     Gets the node type for this Newtonsoft.Json.Linq.JToken.
    Public Overrides ReadOnly Property Type As JTokenType
    '
    ' Summary:
    '     Gets the container's children tokens.
    Protected Overrides ReadOnly Property ChildrenTokens As IList(Of JToken)

    '
    ' Summary:
    '     Occurs when a property value is changing.
    Public Event PropertyChanging As PropertyChangingEventHandler
    '
    ' Summary:
    '     Occurs when a property value changes.
    Public Event PropertyChanged As PropertyChangedEventHandler

    '
    ' Summary:
    '     Adds the specified property name.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    '   value:
    '     The value.
    Public Sub Add(propertyName As String, value As JToken)
    '
    ' Summary:
    '     Writes this token to a Newtonsoft.Json.JsonWriter.
    '
    ' Parameters:
    '   writer:
    '     A Newtonsoft.Json.JsonWriter into which this method will write.
    '
    '   converters:
    '     A collection of Newtonsoft.Json.JsonConverter which will be used when writing
    '     the token.
    Public Overrides Sub WriteTo(writer As JsonWriter, ParamArray converters() As JsonConverter)
    '
    ' Summary:
    '     Raises the Newtonsoft.Json.Linq.JObject.PropertyChanging event with the provided
    '     arguments.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    Protected Overridable Sub OnPropertyChanging(propertyName As String)
    '
    ' Summary:
    '     Raises the Newtonsoft.Json.Linq.JObject.PropertyChanged event with the provided
    '     arguments.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    Protected Overridable Sub OnPropertyChanged(propertyName As String)

    '
    ' Summary:
    '     Load a Newtonsoft.Json.Linq.JObject from a string that contains JSON.
    '
    ' Parameters:
    '   json:
    '     A System.String that contains JSON.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject populated from the string that contains JSON.
    '
    ' Exceptions:
    '   T:Newtonsoft.Json.JsonReaderException:
    '     json is not valid JSON.
    Public Shared Function Parse(json As String) As JObject
    '
    ' Summary:
    '     Load a Newtonsoft.Json.Linq.JObject from a string that contains JSON.
    '
    ' Parameters:
    '   json:
    '     A System.String that contains JSON.
    '
    '   settings:
    '     The Newtonsoft.Json.Linq.JsonLoadSettings used to load the JSON. If this is null,
    '     default load settings will be used.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject populated from the string that contains JSON.
    '
    ' Exceptions:
    '   T:Newtonsoft.Json.JsonReaderException:
    '     json is not valid JSON.
    Public Shared Function Parse(json As String, settings As JsonLoadSettings) As JObject
    '
    ' Summary:
    '     Creates a Newtonsoft.Json.Linq.JObject from an object.
    '
    ' Parameters:
    '   o:
    '     The object that will be used to create Newtonsoft.Json.Linq.JObject.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject with the values of the specified object.
    Public Shared Function FromObject(o As Object) As JObject
    '
    ' Summary:
    '     Creates a Newtonsoft.Json.Linq.JObject from an object.
    '
    ' Parameters:
    '   o:
    '     The object that will be used to create Newtonsoft.Json.Linq.JObject.
    '
    '   jsonSerializer:
    '     The Newtonsoft.Json.JsonSerializer that will be used to read the object.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject with the values of the specified object.
    Public Shared Function FromObject(o As Object, jsonSerializer As JsonSerializer) As JObject
    '
    ' Summary:
    '     Loads a Newtonsoft.Json.Linq.JObject from a Newtonsoft.Json.JsonReader.
    '
    ' Parameters:
    '   reader:
    '     A Newtonsoft.Json.JsonReader that will be read for the content of the Newtonsoft.Json.Linq.JObject.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject that contains the JSON that was read from the
    '     specified Newtonsoft.Json.JsonReader.
    '
    ' Exceptions:
    '   T:Newtonsoft.Json.JsonReaderException:
    '     reader is not valid JSON.
    Public Shared Function Load(reader As JsonReader) As JObject
    '
    ' Summary:
    '     Asynchronously loads a Newtonsoft.Json.Linq.JObject from a Newtonsoft.Json.JsonReader.
    '
    ' Parameters:
    '   reader:
    '     A Newtonsoft.Json.JsonReader that will be read for the content of the Newtonsoft.Json.Linq.JObject.
    '
    '   cancellationToken:
    '     The token to monitor for cancellation requests. The default value is System.Threading.CancellationToken.None.
    '
    ' Returns:
    '     A System.Threading.Tasks.Task`1 that represents the asynchronous load. The System.Threading.Tasks.Task`1.Result
    '     property returns a Newtonsoft.Json.Linq.JObject that contains the JSON that was
    '     read from the specified Newtonsoft.Json.JsonReader.
    Public Shared Function LoadAsync(reader As JsonReader, Optional cancellationToken As CancellationToken = Nothing) As Task(Of JObject)
    '
    ' Summary:
    '     Asynchronously loads a Newtonsoft.Json.Linq.JObject from a Newtonsoft.Json.JsonReader.
    '
    ' Parameters:
    '   reader:
    '     A Newtonsoft.Json.JsonReader that will be read for the content of the Newtonsoft.Json.Linq.JObject.
    '
    '   settings:
    '     The Newtonsoft.Json.Linq.JsonLoadSettings used to load the JSON. If this is null,
    '     default load settings will be used.
    '
    '   cancellationToken:
    '     The token to monitor for cancellation requests. The default value is System.Threading.CancellationToken.None.
    '
    ' Returns:
    '     A System.Threading.Tasks.Task`1 that represents the asynchronous load. The System.Threading.Tasks.Task`1.Result
    '     property returns a Newtonsoft.Json.Linq.JObject that contains the JSON that was
    '     read from the specified Newtonsoft.Json.JsonReader.
    <AsyncStateMachineAttribute(GetType(<LoadAsync>d__2))>
    Public Shared Function LoadAsync(reader As JsonReader, settings As JsonLoadSettings, Optional cancellationToken As CancellationToken = Nothing) As Task(Of JObject)
    '
    ' Summary:
    '     Loads a Newtonsoft.Json.Linq.JObject from a Newtonsoft.Json.JsonReader.
    '
    ' Parameters:
    '   reader:
    '     A Newtonsoft.Json.JsonReader that will be read for the content of the Newtonsoft.Json.Linq.JObject.
    '
    '   settings:
    '     The Newtonsoft.Json.Linq.JsonLoadSettings used to load the JSON. If this is null,
    '     default load settings will be used.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JObject that contains the JSON that was read from the
    '     specified Newtonsoft.Json.JsonReader.
    '
    ' Exceptions:
    '   T:Newtonsoft.Json.JsonReaderException:
    '     reader is not valid JSON.
    Public Shared Function Load(reader As JsonReader, settings As JsonLoadSettings) As JObject
    '
    ' Summary:
    '     Gets an System.Collections.Generic.IEnumerable`1 of Newtonsoft.Json.Linq.JProperty
    '     of this object's properties.
    '
    ' Returns:
    '     An System.Collections.Generic.IEnumerable`1 of Newtonsoft.Json.Linq.JProperty
    '     of this object's properties.
    Public Function Properties() As IEnumerable(Of JProperty)
    '
    ' Summary:
    '     Gets a Newtonsoft.Json.Linq.JProperty the specified name.
    '
    ' Parameters:
    '   name:
    '     The property name.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JProperty with the specified name or null.
    Public Function [Property](name As String) As JProperty
    '
    ' Summary:
    '     Tries to get the Newtonsoft.Json.Linq.JToken with the specified property name.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    '   value:
    '     The value.
    '
    ' Returns:
    '     true if a value was successfully retrieved; otherwise, false.
    Public Function TryGetValue(propertyName As String, ByRef value As JToken) As Boolean
    '
    ' Summary:
    '     Removes the property with the specified name.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    ' Returns:
    '     true if item was successfully removed; otherwise, false.
    Public Function Remove(propertyName As String) As Boolean
    '
    ' Summary:
    '     Gets a Newtonsoft.Json.Linq.JEnumerable`1 of Newtonsoft.Json.Linq.JToken of this
    '     object's property values.
    '
    ' Returns:
    '     A Newtonsoft.Json.Linq.JEnumerable`1 of Newtonsoft.Json.Linq.JToken of this object's
    '     property values.
    Public Function PropertyValues() As JEnumerable(Of JToken)
    '
    ' Summary:
    '     Tries to get the Newtonsoft.Json.Linq.JToken with the specified property name.
    '     The exact property name will be searched for first and if no matching property
    '     is found then the System.StringComparison will be used to match a property.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    '   value:
    '     The value.
    '
    '   comparison:
    '     One of the enumeration values that specifies how the strings will be compared.
    '
    ' Returns:
    '     true if a value was successfully retrieved; otherwise, false.
    Public Function TryGetValue(propertyName As String, comparison As StringComparison, ByRef value As JToken) As Boolean
    '
    ' Summary:
    '     Gets the Newtonsoft.Json.Linq.JToken with the specified property name. The exact
    '     property name will be searched for first and if no matching property is found
    '     then the System.StringComparison will be used to match a property.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    '   comparison:
    '     One of the enumeration values that specifies how the strings will be compared.
    '
    ' Returns:
    '     The Newtonsoft.Json.Linq.JToken with the specified property name.
    Public Function GetValue(propertyName As String, comparison As StringComparison) As JToken
    '
    ' Summary:
    '     Gets the Newtonsoft.Json.Linq.JToken with the specified property name.
    '
    ' Parameters:
    '   propertyName:
    '     Name of the property.
    '
    ' Returns:
    '     The Newtonsoft.Json.Linq.JToken with the specified property name.
    Public Function GetValue(propertyName As String) As JToken
    '
    ' Summary:
    '     Returns an enumerator that can be used to iterate through the collection.
    '
    ' Returns:
    '     A System.Collections.Generic.IEnumerator`1 that can be used to iterate through
    '     the collection.
    <IteratorStateMachineAttribute(GetType(<GetEnumerator>d__61))>
    Public Function GetEnumerator() As IEnumerator(Of KeyValuePair(Of String, JToken))
    '
    ' Summary:
    '     Writes this token to a Newtonsoft.Json.JsonWriter asynchronously.
    '
    ' Parameters:
    '   writer:
    '     A Newtonsoft.Json.JsonWriter into which this method will write.
    '
    '   cancellationToken:
    '     The token to monitor for cancellation requests.
    '
    '   converters:
    '     A collection of Newtonsoft.Json.JsonConverter which will be used when writing
    '     the token.
    '
    ' Returns:
    '     A System.Threading.Tasks.Task that represents the asynchronous write operation.
    <AsyncStateMachineAttribute(GetType(<WriteToAsync>d__0))>
    Public Overrides Function WriteToAsync(writer As JsonWriter, cancellationToken As CancellationToken, ParamArray converters() As JsonConverter) As Task
    '
    ' Summary:
    '     Returns the System.Dynamic.DynamicMetaObject responsible for binding operations
    '     performed on this object.
    '
    ' Parameters:
    '   parameter:
    '     The expression tree representation of the runtime value.
    '
    ' Returns:
    '     The System.Dynamic.DynamicMetaObject to bind this object.
    Protected Overrides Function GetMetaObject(parameter As Expression) As DynamicMetaObject
End Class

You can look things up here

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

There is no implementation of containsKey. Why?

Body:
If the interface member is implemented but marked Private, it won't show up in the metadata or intellisense. This is explicit implementation. You can still access it through the interface. This is by design so it doesn't augment the public interface. Remember, Interfaces don't specify access levels though interface members are guaranteed to be available through the interface.

You'll need to cast the object as IDictionary(Of String, JToken) to access the interface member.

CType(jo1, IDictionary(Of String, JToken))

Either of these should work

If Not (CType(jo1, IDictionary(Of String, JToken)).ContainsKey(jsonHelper.SpecialKeyForDictoToArray)) Then
    jo1.Add(jsonHelper.SpecialKeyForDictoToArray, dict(id))
    Dim b = 1
End If

If Not (jo2.ContainsKey(jsonHelper.SpecialKeyForDictoToArray)) Then
    jo1.Add(jsonHelper.SpecialKeyForDictoToArray, dict(id))
    Dim b = 1
End If

In general, when you explicitly implement an interface, you must access the explicitly implemented member through the interface. One reason for this is multiple interface implementation. In the case

Class Foo
    Implements IBar, IBaz

    Public Sub Run() Implements IBar.Run
        Console.WriteLine("IBar")
    End Sub

    Private Sub IBaz_Run() Implements IBaz.Run
        Console.WriteLine("IBaz")
    End Sub

End Class

Interface IBar
    Sub Run()
End Interface

Interface IBaz
    Sub Run()
End Interface

Module Module1

    Sub Main()
        Dim myFoo As New Foo
        myFoo.Run() ' outputs IBar
        Dim myBaz As IBaz
        myBaz = DirectCast(myFoo, IBaz)
        myBaz.Run() ' outputs IBaz
        Console.ReadLine()
    End Sub

End Module

The class Foo implements two interfaces with the same member name but only one can be defined in the class Foo. By default, IBaz.Run() is marked private (explicit implementation). One must access IBaz.Run through the interface. IBaz_Run could be marked public but since the name is different, it won't show up on the public interface of Foo anyway.

This example describes a behavior, but it is a side effect of the language feature explicit implementation.


来源: stackexchange

问:
Need to run multiple instances of the same web application in Tomcat
I am using Tomcat 8.5, with a webapp deployed to the default webapps directory (/var/lib/tomcat8/webpps/MyWebApp.war).

Now I would like to run a second instance of that same webapp. I thought that I could create a new MyWebApp2.xml file in the context directory (/etc/tomcat8/Catalina/localhost/MyWebApp2.xml), and set the appBase="MyWebApp.war", so that I could run the second instance without needing to upload and maintain a separate war file.

However, when I do this, I get this Tomcat error:

```<code>docBase [/var/lib/tomcat8/webapps/MyWebApp.war] inside the host appBase has been specified, and will be ignored
</code>```

It sounds like I could solve this problem by either 1) uploading a separate .war file with a different name, or 2) placing the first .war file outside of the default webapp folder, but I don't like either of these solutions. Shouldn't it be possible to run multiple instances of an application from a single .war file in the default webapps directory?

答:
I am also using Tomcat 8.5 and deploying another instance of the same application is very easy.

All you have to do is make a copy of the war file.
There is no need to mess with any configuration file.
The path and version of the new instance will be derived from the name of the war file.

For instance, if the war file of the original application is myapp.war,
you can simply do this in the webapps directory:

```<code>copy myapp.war foo.war
</code>```

Tomcat will detect the new war file and deploy a new instance at /foo in a few seconds.

To deploy at a deeper path and assign a version, use # and ## respectively.
For instance, this:

```<code>copy myapp.war foo#bar##9.war
</code>```

will deploy the application at path /foo/bar and assign the version 9.

Update

You should have mentioned about using Tomcat Client Deployer in your question because my suggestion already fulfills both of your original conditions: 1) without uploading another war file and 2) without putting the war file outside of the webapps directory.

As far as I know, TCD uses Tomcat Manager as the backend and Tomcat Manager only uploads war files to the webapps directory, which explains TCD's restriction.
The way I see it, you have three options:

Augment TCD with something else to add more functionality.
You mentioned one: ssh.

Use another deployment solution.

Make one.
Because you already know exactly what you want, you can simply write some script to make it happen.

ContentLicense: CC BY-SA 3.0

Body:
I am using Tomcat 8.5, with a webapp deployed to the default webapps directory (/var/lib/tomcat8/webpps/MyWebApp.war).

Now I would like to run a second instance of that same webapp. I thought that I could create a new MyWebApp2.xml file in the context directory (/etc/tomcat8/Catalina/localhost/MyWebApp2.xml), and set the appBase="MyWebApp.war", so that I could run the second instance without needing to upload and maintain a separate war file.

However, when I do this, I get this Tomcat error:

docBase [/var/lib/tomcat8/webapps/MyWebApp.war] inside the host appBase has been specified, and will be ignored

It sounds like I could solve this problem by either 1) uploading a separate .war file with a different name, or 2) placing the first .war file outside of the default webapp folder, but I don't like either of these solutions. Shouldn't it be possible to run multiple instances of an application from a single .war file in the default webapps directory?

Body:
I am also using Tomcat 8.5 and deploying another instance of the same application is very easy.

All you have to do is make a copy of the war file.
There is no need to mess with any configuration file.
The path and version of the new instance will be derived from the name of the war file.

For instance, if the war file of the original application is myapp.war,
you can simply do this in the webapps directory:

copy myapp.war foo.war

Tomcat will detect the new war file and deploy a new instance at /foo in a few seconds.

To deploy at a deeper path and assign a version, use # and ## respectively.
For instance, this:

copy myapp.war foo#bar##9.war

will deploy the application at path /foo/bar and assign the version 9.

Update

You should have mentioned about using Tomcat Client Deployer in your question because my suggestion already fulfills both of your original conditions: 1) without uploading another war file and 2) without putting the war file outside of the webapps directory.

As far as I know, TCD uses Tomcat Manager as the backend and Tomcat Manager only uploads war files to the webapps directory, which explains TCD's restriction.
The way I see it, you have three options:

Augment TCD with something else to add more functionality.
You mentioned one: ssh.

Use another deployment solution.

Make one.
Because you already know exactly what you want, you can simply write some script to make it happen.


问:
'Authorize' only specific routes of a resource
There is this method authorizeResource() which applies specific policies to all routes (except the index route). Is there a way to apply policies only on specific routes, analogous to this function:

```<code>Route::resource('photo', 'PhotoController', ['only' => [
    'index', 'show'
]]);
</code>```

答:
Yes, authorizeResource accepts an $options array as a third parameter. Just pass null for the second argument and the syntax for options is the same as it is for route middleware.

```<code>public function __construct()
{
    $this->authorizeResource(Photo::class, null, [
        'only' => ['create', 'store'],
    ]);
}
</code>```

Body:
There is this method authorizeResource() which applies specific policies to all routes (except the index route). Is there a way to apply policies only on specific routes, analogous to this function:

Route::resource('photo', 'PhotoController', ['only' => [
    'index', 'show'
]]);

Body:
Yes, authorizeResource accepts an $options array as a third parameter. Just pass null for the second argument and the syntax for options is the same as it is for route middleware.

public function __construct()
{
    $this->authorizeResource(Photo::class, null, [
        'only' => ['create', 'store'],
    ]);
}


问:
force rpy2 in conda environment to use the R outside of the conda environment
I started using conda environments. I know that I can open and use R jupiter notebook, but my preferred workflow is to use R within a python notebook, when necessary, with rpy2 and push/pull data between the two languages

```<code>%R push data
%R run something
%R pull output
</code>```

however now when I run rpy2 in a conda environment, it searches for all packages in the R folder within the conda environment. I would like to use the packages installed in my home directory or those from the machine I work on, without the need to reinstall everything for each conda environment. Is that possible?

答:
There are several ways to tell R about package directories (http://stat.ethz.ch/R-manual/R-devel/library/base/html/libPaths.html).

Try setting the environment variable R_LIBS or R_LIBS_USER (before %load_ext rpy2.ipython in the notebook).

Body:
I started using conda environments. I know that I can open and use R jupiter notebook, but my preferred workflow is to use R within a python notebook, when necessary, with rpy2 and push/pull data between the two languages

%R push data
%R run something
%R pull output

however now when I run rpy2 in a conda environment, it searches for all packages in the R folder within the conda environment. I would like to use the packages installed in my home directory or those from the machine I work on, without the need to reinstall everything for each conda environment. Is that possible?


问:
How can I hide my JavaScript functions so that nobody can steal them?

Possible Duplicate:

  How to prevent your JavaScript code from being stolen, copied, and viewed ?

I have a user form that has a submit button. Once clicked, a certain JS function is called and the code does something. I want to hide this so that nobody can see it. What is the best way to do this? I am not using any JS libraries, it is just code that I wrote myself.

Thanks!

答:
You can't. This is anathema to the entirety of the web. For the same reason you can't stop picture theft.

What you could do to help prevent it is not only obfuscation as mentioned before, but also prevent outright downloading, require referrer headers and the like.

In the end tho, if you expose it via HTTP, someone else will be able to steal it. End of story.

ContentLicense: CC BY-SA 2.5


问:
'list' object has no attribute 'encode' when storing list of values in blob on azure
I am trying to enter multiple values in my blob on azure.

I have four values which i want to enter in a blob.

```<code>firstname
lastname
address
contact
</code>```

So I have written code like this:

```<code>from azure.storage.blob import BlockBlobService
from azure.storage.blob import PublicAccess

firstName = u'john'
lastName  = u'doe'
address = u'new york'
contact = u'2222222222'

block_blob_service = BlockBlobService(account_name='myAccountName', account_key='myAccountkey')
block_blob_service.create_container('mycontainer')
block_blob_service.create_blob_from_text('mycontainer','myblockblob',[firstName,lastName,address,contact])
</code>```

But I am getting below error:

```<code>'list' object has no attribute 'encode'
</code>```

Full error:

```<code>Django Version: 1.8
Exception Type: AttributeError
Exception Value:
'list' object has no attribute 'encode'
Exception Location: D:\home\site\wwwroot\env\Lib\site-
packages\azure\storage\blob\blockblobservice.py in create_blob_from_text,
line 773
Python Executable:  D:\Python27\python.exe
Python Version: 2.7.8
Python Path:
[u'D:\\home\\site\\wwwroot\\env\\Lib\\site-packages',
'.',
'D:\\Windows\\SYSTEM32\\python27.zip',
'D:\\Python27\\DLLs',
'D:\\Python27\\lib',
'D:\\Python27\\lib\\plat-win',
'D:\\Python27\\lib\\lib-tk',
'D:\\Python27',
'D:\\Python27\\lib\\site-packages',
'D:\\home\\site\\wwwroot']
Server time:    Wed, 15 Nov 2017 21:43:33 +0000
</code>```

is there a way I can get these values in my blob.

答:
You need to give BlockBlobService.create_blob_from_text a string. You could, for example, use:

```<code>my_list = [firstName, lastName, address, contact]
block_blob_service.create_blob_from_text('mycontainer', 'myblockblob', ','.join(my_list))
</code>```

to create a comma-separated string of the values from your list, then create a blob from that.

Alternatively, as suggested in the comments, serialize your data in a pickle or JSON and then use create_blob_from_bytes.

Body:
I am trying to enter multiple values in my blob on azure.

I have four values which i want to enter in a blob.

firstname
lastname
address
contact

So I have written code like this:

from azure.storage.blob import BlockBlobService
from azure.storage.blob import PublicAccess

firstName = u'john'
lastName  = u'doe'
address = u'new york'
contact = u'2222222222'

block_blob_service = BlockBlobService(account_name='myAccountName', account_key='myAccountkey')
block_blob_service.create_container('mycontainer')
block_blob_service.create_blob_from_text('mycontainer','myblockblob',[firstName,lastName,address,contact])

But I am getting below error:

'list' object has no attribute 'encode'

Full error:

Django Version: 1.8
Exception Type: AttributeError
Exception Value:
'list' object has no attribute 'encode'
Exception Location: D:\home\site\wwwroot\env\Lib\site-
packages\azure\storage\blob\blockblobservice.py in create_blob_from_text,
line 773
Python Executable:  D:\Python27\python.exe
Python Version: 2.7.8
Python Path:
[u'D:\\home\\site\\wwwroot\\env\\Lib\\site-packages',
'.',
'D:\\Windows\\SYSTEM32\\python27.zip',
'D:\\Python27\\DLLs',
'D:\\Python27\\lib',
'D:\\Python27\\lib\\plat-win',
'D:\\Python27\\lib\\lib-tk',
'D:\\Python27',
'D:\\Python27\\lib\\site-packages',
'D:\\home\\site\\wwwroot']
Server time:    Wed, 15 Nov 2017 21:43:33 +0000

is there a way I can get these values in my blob.

Body:
You need to give BlockBlobService.create_blob_from_text a string. You could, for example, use:

my_list = [firstName, lastName, address, contact]
block_blob_service.create_blob_from_text('mycontainer', 'myblockblob', ','.join(my_list))

to create a comma-separated string of the values from your list, then create a blob from that.

Alternatively, as suggested in the comments, serialize your data in a pickle or JSON and then use create_blob_from_bytes.


问:
How does it seem to appear that another thread is able to acquire the lock while one thread having the same lock is sleeping?
Below code - without the wait() and notify() methods:

```<code>package com.jay;

import java.util.Random;

public class Main {

    public static void main(String[] args) {
        Message message = new Message();
        (new Thread(new Writer(message))).start();
        (new Thread(new Reader(message))).start();
    }

}

class Message {
    private String message;
    private boolean empty = true;

    public synchronized String read() {
        while (empty) {

        }
        empty = true;
        return message;
    }

    public synchronized void write(String message) {
        while (!empty) {

        }
        empty = false;
        this.message = message;
    }
}

class Writer implements Runnable {
    private Message message;

    public Writer(Message message) {
        this.message = message;
    }

    public void run() {
        String[] messages = {
            "Humpty Dumpty sat on a wall",
            "Humpty Dumpty had a great fall",
            "All the king's horses and all the king's men",
            "Couldn't put Humpty together again"
        };

        Random random = new Random();

        for(int i=0; i<messages.length; i++) {
            message.write(messages[i]);
            try {
                Thread.sleep(random.nextInt(2000));
            } catch (InterruptedException e) {
                // TODO: handle exception
            }
        }
        message.write("Finished");
    }
}

class Reader implements Runnable {
    private Message message;

    public Reader(Message message) {
        this.message = message;
    }

    public void run() {
        Random random = new Random();

        for(String latestMessage = message.read(); !latestMessage.equals("Finished");
                latestMessage = message.read()) {
            System.out.println(latestMessage);

            try {
                Thread.sleep(random.nextInt(2000));
            } catch (InterruptedException e) {
                // TODO: handle exception
            }
        }
    }
}
</code>```

It prints below on the console - most of the times and hangs:

```<code>Humpty Dumpty sat on a wall

Humpty Dumpty had a great fall
</code>```

and some times it prints all the four messages.

My question is: How is Reader thread able to execute the code in read() method while the Writer thread already has the lock acquired and still looping?

I am confused. Please help me understand!

答: @Oliver Charlesworth's comment cleared my doubts. I failed to notice that the reader can enter a synchronized method every time the writer leaves a synchronized method. The program hangs because there will be stage where in one thread will be sleeping and the value of the "empty" field won't get modified, resulting in one of the loops running infinitely. Once the wait() and notify() methods get implemented, the problem will get solved!</p>

Body:
Below code - without the wait() and notify() methods:

package com.jay;

import java.util.Random;

public class Main {

    public static void main(String[] args) {
        Message message = new Message();
        (new Thread(new Writer(message))).start();
        (new Thread(new Reader(message))).start();
    }

}

class Message {
    private String message;
    private boolean empty = true;

    public synchronized String read() {
        while (empty) {

        }
        empty = true;
        return message;
    }

    public synchronized void write(String message) {
        while (!empty) {

        }
        empty = false;
        this.message = message;
    }
}

class Writer implements Runnable {
    private Message message;

    public Writer(Message message) {
        this.message = message;
    }

    public void run() {
        String[] messages = {
            "Humpty Dumpty sat on a wall",
            "Humpty Dumpty had a great fall",
            "All the king's horses and all the king's men",
            "Couldn't put Humpty together again"
        };

        Random random = new Random();

        for(int i=0; i<messages.length; i++) {
            message.write(messages[i]);
            try {
                Thread.sleep(random.nextInt(2000));
            } catch (InterruptedException e) {
                // TODO: handle exception
            }
        }
        message.write("Finished");
    }
}

class Reader implements Runnable {
    private Message message;

    public Reader(Message message) {
        this.message = message;
    }

    public void run() {
        Random random = new Random();

        for(String latestMessage = message.read(); !latestMessage.equals("Finished");
                latestMessage = message.read()) {
            System.out.println(latestMessage);

            try {
                Thread.sleep(random.nextInt(2000));
            } catch (InterruptedException e) {
                // TODO: handle exception
            }
        }
    }
}

It prints below on the console - most of the times and hangs:

Humpty Dumpty sat on a wall

Humpty Dumpty had a great fall

and some times it prints all the four messages.

My question is: How is Reader thread able to execute the code in read() method while the Writer thread already has the lock acquired and still looping?

I am confused. Please help me understand!


问:
Servlet: forward request to Servlet by its name when using annotations instead of web.xml?
I have an entry servlet (called DispatcherServlet) which redirects all incoming GET and POST requests at /* to other servlets depending on a configuration parameter. In order to dispatch the request to other servlets, I use their name instead of a path, because my DispatcherServlet would end up in an endless loop while listening to /*.

The "old" way was to give servlets a name in the web.xml descriptor:

```<code><servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>mypackage.MyServlet</servlet-class>
</servlet>
</code>```

Afterwards, one is able to address the servlet by its name, for example, when using a RequestDispatcher. The code in my DispatcherServlet looks like this:

RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("MyServlet");
  dispatcher.forward(request, response);

This works perfectly. But, I would like to use the "new" Servlet 3 annotations without the web.xml, hence I do this:

```<code>@WebServlet(name="MyServlet")
public class MyServlet extends HttpServlet {
    ...
</code>```

But now, getServletContext().getNamedDispatcher("MyServlet") within my DispatcherServlet returns null instead of the appropriate dispatcher for MyServlet, although I expect that @WebServlet(name="MyServlet") behaves the same like <servlet-name>MyServlet</servlet-name>

I have tested this on Tomcat 7.
Is this because MyServlet has not been loaded yet by the time when DispatcherServlet is called and hence the name of MyServlet is not known? If so, what sense does the @WebServlet(name="...") annotation make ;)

Please don't answer with something like "why don't you use filters?" etc. This is more about the background of annotations vs. web.xml

Thanks in advance!

(ps. please change the title if you find a more suitable one ;))

答:
By just comment with @WebServlet is not enough to load a Servlet into the Web container; you must include at least one URL pattern, and if you don't want to expose the Servlet to keep it for internal forward only, set the URL to start with '/WEB-INF/'.

And keep in mind that the 'name' property is buggy, so not use it.

```<code>@WebServlet(urlPatterns = "/WEB-INF/thisServlet")
public class FooServlet extends HttpServlet {
...
}
</code>```

and to forward the request, call something like this:

```<code>servletContext.getNamedDispatcher(FooServlet.class.getName()).forward(request, response);
</code>```

Body:
I have an entry servlet (called DispatcherServlet) which redirects all incoming GET and POST requests at /* to other servlets depending on a configuration parameter. In order to dispatch the request to other servlets, I use their name instead of a path, because my DispatcherServlet would end up in an endless loop while listening to /*.

The "old" way was to give servlets a name in the web.xml descriptor:

<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>mypackage.MyServlet</servlet-class>
</servlet>

Afterwards, one is able to address the servlet by its name, for example, when using a RequestDispatcher. The code in my DispatcherServlet looks like this:

RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("MyServlet");
  dispatcher.forward(request, response);

This works perfectly. But, I would like to use the "new" Servlet 3 annotations without the web.xml, hence I do this:

@WebServlet(name="MyServlet")
public class MyServlet extends HttpServlet {
    ...

But now, getServletContext().getNamedDispatcher("MyServlet") within my DispatcherServlet returns null instead of the appropriate dispatcher for MyServlet, although I expect that @WebServlet(name="MyServlet") behaves the same like <servlet-name>MyServlet</servlet-name>

I have tested this on Tomcat 7.
Is this because MyServlet has not been loaded yet by the time when DispatcherServlet is called and hence the name of MyServlet is not known? If so, what sense does the @WebServlet(name="...") annotation make ;)

Please don't answer with something like "why don't you use filters?" etc. This is more about the background of annotations vs. web.xml

Thanks in advance!

(ps. please change the title if you find a more suitable one ;))

Body:
By just comment with @WebServlet is not enough to load a Servlet into the Web container; you must include at least one URL pattern, and if you don't want to expose the Servlet to keep it for internal forward only, set the URL to start with '/WEB-INF/'.

And keep in mind that the 'name' property is buggy, so not use it.

@WebServlet(urlPatterns = "/WEB-INF/thisServlet")
public class FooServlet extends HttpServlet {
...
}

and to forward the request, call something like this:

servletContext.getNamedDispatcher(FooServlet.class.getName()).forward(request, response);


问:
Pygame Error: Unsupported Image Format
Hi I'm trying to follow these instructions from my last question:
Pygame: how to load 150 images and present each one for only .5sec per trial

This is the code I currently have and I'm unsure where I'm going wrong.

```<code>import pygame, glob
pygame.init()
pygame.mixer.init()
clock=pygame.time.Clock()

#### Set up window
window=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
centre=window.get_rect().center
pygame.mouse.set_visible(False)

#colours
black = (0, 0, 0)
white = (255, 255, 255)

types= '*.tif'
artfile_names= []
for files in types:
    artfile_names.extend(glob.glob(files))

image_list = []
for artwork in artfile_names:
    image_list.append(pygame.image.load(artwork).convert())

##Randomizing
index=0
current_image = image_list[index]

if image_list[index]>= 150:
    index=0

stimulus= pygame.image.load('image_list')
soundPlay=True
def artwork():
    window.blit(stimulus,pygame.FULLSCREEN)

while not soundPlay:
    for imageEvent in pygame.event.get():
        artwork()
        pygame.display.update()
        clock.tick()
</code>```

答:
Near the bottom you have the line:

```<code>stimulus= pygame.image.load('image_list')
</code>```

Here you are trying to load an image titled image_list. There's no file extension there, so your OS doesn't recognize the filetype.  But even if you did include a file extension, I think you're trying to load the individual images in the list image_list, and that's a whole other story.

Title: Pygame Error: Unsupported Image Format

Body:
Hi I'm trying to follow these instructions from my last question:
Pygame: how to load 150 images and present each one for only .5sec per trial

This is the code I currently have and I'm unsure where I'm going wrong.

import pygame, glob
pygame.init()
pygame.mixer.init()
clock=pygame.time.Clock()

#### Set up window
window=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
centre=window.get_rect().center
pygame.mouse.set_visible(False)

#colours
black = (0, 0, 0)
white = (255, 255, 255)

types= '*.tif'
artfile_names= []
for files in types:
    artfile_names.extend(glob.glob(files))

image_list = []
for artwork in artfile_names:
    image_list.append(pygame.image.load(artwork).convert())

##Randomizing
index=0
current_image = image_list[index]

if image_list[index]>= 150:
    index=0

stimulus= pygame.image.load('image_list')
soundPlay=True
def artwork():
    window.blit(stimulus,pygame.FULLSCREEN)

while not soundPlay:
    for imageEvent in pygame.event.get():
        artwork()
        pygame.display.update()
        clock.tick()

Body:
Near the bottom you have the line:

stimulus= pygame.image.load('image_list')

Here you are trying to load an image titled image_list. There's no file extension there, so your OS doesn't recognize the filetype.  But even if you did include a file extension, I think you're trying to load the individual images in the list image_list, and that's a whole other story.


问:
Multidex not working only in AndroidTest
I have a project that has MultiDex and it compiles the app just fine... But when I try to run the instrumented tests I get this error:

Error:Execution failed for task ':app:transformDexArchiveWithDexMergerForMinApi16StagingDebugAndroidTest'.

com.android.build.api.transform.TransformException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

I am using

testInstrumentationRunner 'com.android.test.runner.MultiDexTestRunner'

In my gradle file.

How can I make the multdex work?

答: In case for any one looking for a answer to this. It is not currently possible to use multidex in the API 19 and lower with AGP 3.0.0 you can track the issue here: https://issuetracker.google.com/issues/37324038</p>


问:
While loop starts from beginning in tic tac toe game
I am trying to write a tic tac toe game with java. In this game there are two player as A and B. Player A always starts the game(X),
and Player B is (O). I used random method to generate move numbers.

So, I created a while loop but it always start from beginning but I want to print a new board with latest move.

There's code below if you look at it and say what is the point that I am missing I will be glad.

Also singular numbers are belong to player A, plurals are belong to player B
I have to add +1 to whoseTurn for correct move(if random method tries to write X or O to a position has already taken, it must generate another row and column number but I couldn't figure it out as well)

```<code>import java.util.Random;

public class TicTacToe {

final static int SIZE = 5;
private static int row;
private static int column;

static Random number = new Random();
static char [][] array = new char[SIZE][SIZE];

public static void createBoard(){
    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            array[i][j] = '#';
        }
    }

    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            System.out.print(array[i][j] + " ");
        }
        System.out.println();
    }
    System.out.println();
    System.out.println("--------------");
}

public static void move(){
    int whoseTurn =1;
    while(whoseTurn <= (SIZE * SIZE)) {
        row = number.nextInt(6-1) + 1;
        column = number.nextInt(6-1) + 1;
        if ((whoseTurn % 2) != 0) {
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    array[i][j] = '#';
                    array[row-1][column-1] = 'X';
                }
            }
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    System.out.print(array[i][j] + " ");
                }
                System.out.println();
            }
            System.out.println("--------------");
            whoseTurn +=1;
        } else if((whoseTurn % 2) == 0){
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    array[i][j] = '#';
                    array[row-1][column-1] = 'O';
                    System.out.print(array[i][j] + " ");
                }
                System.out.println();
            }
            whoseTurn += 1;
        }
    }
}
</code>```

答:
You loop refilled the board for every move of the user with # and the one move of the user, namely 0 or X. By just replacing the one position in the board instead of modifying the whole board, all the previous moves are safed and will be printed. </p>

```<code>import java.util.Random;

public class TicTacToe {

    final static int SIZE = 5;
    private static int row;
    private static int column;

    static Random number = new Random();
    static char[][] array = new char[SIZE][SIZE];

    public static void createBoard() {

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array.length; j++) {

                array[i][j] = '#';
            }

        }

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array.length; j++) {

                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
        System.out.println("--------------");
    }

    public static void move() {

        int whoseTurn = 1;

        while (whoseTurn <= (SIZE * SIZE)) {

            row = number.nextInt(6 - 1) + 1;

            column = number.nextInt(6 - 1) + 1;

            if ((whoseTurn % 2) != 0) {

                array[row - 1][column - 1] = 'X';

                for (int i = 0; i < array.length; i++) {

                    for (int j = 0; j < array.length; j++) {
                        System.out.print(array[i][j] + " ");
                    }

                    System.out.println();
                }
                System.out.println("--------------");

                whoseTurn += 1;

            } else if ((whoseTurn % 2) == 0) {

                array[row - 1][column - 1] = 'O';

                for (int i = 0; i < array.length; i++) {

                    for (int j = 0; j < array.length; j++) {
                        System.out.print(array[i][j] + " ");
                    }

                    System.out.println();
                }
                System.out.println("--------------");

                whoseTurn += 1;
            }

        }
    }

}
</code>```

Body:
I am trying to write a tic tac toe game with java. In this game there are two player as A and B. Player A always starts the game(X),
and Player B is (O). I used random method to generate move numbers.

So, I created a while loop but it always start from beginning but I want to print a new board with latest move.

There's code below if you look at it and say what is the point that I am missing I will be glad.

Also singular numbers are belong to player A, plurals are belong to player B
I have to add +1 to whoseTurn for correct move(if random method tries to write X or O to a position has already taken, it must generate another row and column number but I couldn't figure it out as well)

import java.util.Random;

public class TicTacToe {

final static int SIZE = 5;
private static int row;
private static int column;

static Random number = new Random();
static char [][] array = new char[SIZE][SIZE];

public static void createBoard(){
    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            array[i][j] = '#';
        }
    }

    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            System.out.print(array[i][j] + " ");
        }
        System.out.println();
    }
    System.out.println();
    System.out.println("--------------");
}

public static void move(){
    int whoseTurn =1;
    while(whoseTurn <= (SIZE * SIZE)) {
        row = number.nextInt(6-1) + 1;
        column = number.nextInt(6-1) + 1;
        if ((whoseTurn % 2) != 0) {
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    array[i][j] = '#';
                    array[row-1][column-1] = 'X';
                }
            }
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    System.out.print(array[i][j] + " ");
                }
                System.out.println();
            }
            System.out.println("--------------");
            whoseTurn +=1;
        } else if((whoseTurn % 2) == 0){
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    array[i][j] = '#';
                    array[row-1][column-1] = 'O';
                    System.out.print(array[i][j] + " ");
                }
                System.out.println();
            }
            whoseTurn += 1;
        }
    }
}

Body:
You loop refilled the board for every move of the user with # and the one move of the user, namely 0 or X. By just replacing the one position in the board instead of modifying the whole board, all the previous moves are safed and will be printed.

import java.util.Random;

public class TicTacToe {

    final static int SIZE = 5;
    private static int row;
    private static int column;

    static Random number = new Random();
    static char[][] array = new char[SIZE][SIZE];

    public static void createBoard() {

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array.length; j++) {

                array[i][j] = '#';
            }

        }

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array.length; j++) {

                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
        System.out.println("--------------");
    }

    public static void move() {

        int whoseTurn = 1;

        while (whoseTurn <= (SIZE * SIZE)) {

            row = number.nextInt(6 - 1) + 1;

            column = number.nextInt(6 - 1) + 1;

            if ((whoseTurn % 2) != 0) {

                array[row - 1][column - 1] = 'X';

                for (int i = 0; i < array.length; i++) {

                    for (int j = 0; j < array.length; j++) {
                        System.out.print(array[i][j] + " ");
                    }

                    System.out.println();
                }
                System.out.println("--------------");

                whoseTurn += 1;

            } else if ((whoseTurn % 2) == 0) {

                array[row - 1][column - 1] = 'O';

                for (int i = 0; i < array.length; i++) {

                    for (int j = 0; j < array.length; j++) {
                        System.out.print(array[i][j] + " ");
                    }

                    System.out.println();
                }
                System.out.println("--------------");

                whoseTurn += 1;
            }

        }
    }

}


问:
How to exit from thread which is suspended by semaphore?
In main function I create one producer thread and two consumer threads.
Producer doing some work, then with "if" statement checks if it should to break and then increments semaphore. Consumers are waiting for semaphore become greater then 0 and do some work, then waiting again. When producer exited, consumers should finish their work and exit too. I don't understand how can i exit threads which are suspended by semaphore? Here is my code:</p>

```<code>sem_t ready;

void *prod_routine(void*){
    while(true){
        //do_something
        //here i have if statement with break.
        sem_post(&ready);
    }
pthread_exit(0);
}

void *cons_routine(void*){
    while(true){
        sem_wait(&ready);
        //do something
    }
pthread_exit(0);
}

int main(int argc, char *argv[]){

pthread_t prod, cons1, cons2;

sem_init(&ready, 0 , 0);

pthread_create(&prod, NULL, &prod_routine, NULL);
pthread_create(&cons1, NULL, &cons_routine, NULL);
pthread_create(&cons2, NULL, &cons_routine, NULL);

pthread_join(prod, NULL);
pthread_join(cons1, NULL);
pthread_join(cons2, NULL);

return 0;
}
</code>```

答:
I don't understand how can i exit threads which are suspended by semaphore?

In the most literal sense, you can't.  A thread that is suspended waiting to acquire a semaphore cannot do anything until it stops waiting, including terminate.  The primary question, then, is really how to make such threads stop waiting.

There are at least four ways you can accomplish this:

increment the semaphore so that the thread can acquire it.  This is the cleanest and best approach.  The trick is then to provide a mechanism by which the thread, when it wakes, can recognize that it should terminate instead of proceeding as normal.

use sem_timedwait() instead of sem_wait(), and wait for the timeout to expire.  This is a bit dodgy, for although you can determine whether sem_timedwait() returned because of a timeout, it's not necessarily clear what the thread should then do about it.

use pthread_cancel() to send a cancellation request to the thread.  This should be effective on a thread blocked in a sem_wait(), but it's rather heavy-handed.  In particular, it starts a chain of events that leads more or less directly to thread termination.

send a signal to the thread via pthread_kill().  Be careful, however, for signal dispositions are process-wide.  In particular, then, if the chosen signal's disposition is "stop" or "terminate" (and it is not blocked) then that will affect the whole process.  This relies on the signal not being configured with the SA_RESTART flag.

Other than pthread_cancel(), all of these have in common the requirement that the thread waiting on the semaphore needs to check when it returns from its wait why it returned.  It must check the return value of sem_[timed]wait() and possibly the value of errno, and it may need to check one or more for-purpose shared variables.

Body:
In main function I create one producer thread and two consumer threads.
Producer doing some work, then with "if" statement checks if it should to break and then increments semaphore. Consumers are waiting for semaphore become greater then 0 and do some work, then waiting again. When producer exited, consumers should finish their work and exit too. I don't understand how can i exit threads which are suspended by semaphore? Here is my code:

sem_t ready;

void *prod_routine(void*){
    while(true){
        //do_something
        //here i have if statement with break.
        sem_post(&ready);
    }
pthread_exit(0);
}

void *cons_routine(void*){
    while(true){
        sem_wait(&ready);
        //do something
    }
pthread_exit(0);
}

int main(int argc, char *argv[]){

pthread_t prod, cons1, cons2;

sem_init(&ready, 0 , 0);

pthread_create(&prod, NULL, &prod_routine, NULL);
pthread_create(&cons1, NULL, &cons_routine, NULL);
pthread_create(&cons2, NULL, &cons_routine, NULL);

pthread_join(prod, NULL);
pthread_join(cons1, NULL);
pthread_join(cons2, NULL);

return 0;
}


问:
Routing with Express when using React
I want to set the routes for my web app using Express, and I'm also using React to handle the front end. The problem is that I don't understand how to route things properly when using React components.

I have in my index.html:

```<code><script> document.getElementById("input").onchange = function() {  ...  } </script>
</code>```

And my App.js:

```<code>class App extends Component {
    render() {
        return ( <div><input id="input" /></div> );
    }

}
</code>```

And router.js:

```<code>app.get('/', function (req, res) {
    res.sendFile(path.resolve('public/index.html'))
})
app.use(express.static('static'));
app.listen(3001, function () {
  console.log('Example app listening on port 3001!')
})
</code>```

And static/index.js:

```<code>ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
</code>```

The problem is that I'm getting "Cannot set property 'onchange' of null". Obviously the App object was not rendered, but I don't understand why. How can I make this work?

答:
Try two things:

Remove the document.getElementById("input").onchange inside of the script tag and instead put console.log('I am running the script tag')

Put a console.log('I am rendering the App via react' inside of yourrendermethod, right abovereturn`.

I am imagining that the script tag gets "evaluated" before react has done anything with the DOM, causing document.getElementById to not return anything, hence your null.

If this is true, you will see your I am running the script tag before your see I am rendering the App.

Title: Routing with Express when using React

Body:
I want to set the routes for my web app using Express, and I'm also using React to handle the front end. The problem is that I don't understand how to route things properly when using React components.

I have in my index.html:

And my App.js:

class App extends Component {
    render() {
        return (
<input id="input" />
 );
    }

}

And router.js:

app.get('/', function (req, res) {
    res.sendFile(path.resolve('public/index.html'))
})
app.use(express.static('static'));
app.listen(3001, function () {
  console.log('Example app listening on port 3001!')
})

And static/index.js:

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

The problem is that I'm getting "Cannot set property 'onchange' of null". Obviously the App object was not rendered, but I don't understand why. How can I make this work?


答: you can always obfuscate and minify your code so that it's only single letters and such.  There is no real way someone can't steal your javascript, but that is the best way you can "hide" it so people can' really read your variable names, etc.</p>

Title: How can I hide my JavaScript functions so that nobody can steal them?

Body:
Possible Duplicate:

  How to prevent your JavaScript code from being stolen, copied, and viewed ?

I have a user form that has a submit button. Once clicked, a certain JS function is called and the code does something. I want to hide this so that nobody can see it. What is the best way to do this? I am not using any JS libraries, it is just code that I wrote myself.

Thanks!


问:
R: Transforming a dataset with the variables "country" and "x" to an adjacency matrix by recoding x
suppose I have following data set CL in R:

```<code>country    x
USA        7
Canada     7
Bahamas    6
Cuba       1
Haiti      2
</code>```

Now, what I intend to do is to create an adjacency matrix where the countries are the nodes, and the strength of the ties are the absolute difference of the values of x. For example, the tie between the Bahamas (x=6) and Cuba (x=1) would have a strength of 6-1=5.

Thus, here the network matrix would look like this:

```<code>country USA Canada Bahamas Cuba Haiti
USA      0    0       -1    -6    -5
Canada   0    0       -1    -6    -5
Bahamas  1    1        0    -5    -4
Cuba     6    6        5     0     4
Haiti    5    5        4    -1     0
</code>```

I have been struggling with this problem for quite a long time, and I just can't come to a decent approach to solve this. My actual data set consists of 150 countries, so it would be really troublesome to do this in Excel. So, does anyone have, how to do this in R? Thank you very much!

Here the R code for reproduction:

```<code>country<- c("USA", "Canada", "Bahamas", "Cuba", "Haiti")
x<- c(7,7,6,1,2)

CL<- data.frame(country=country, x=x)
</code>```

答:
You can use the dist function in base R:

```<code>dist_mat = as.matrix(dist(CL$x, diag = TRUE, upper = TRUE))

dist_mat[upper.tri(dist_mat)] = -dist_mat[upper.tri(dist_mat)]

dimnames(dist_mat) = list(country, country)
</code>```

Result:

```<code>        USA Canada Bahamas Cuba Haiti
USA       0      0      -1   -6    -5
Canada    0      0      -1   -6    -5
Bahamas   1      1       0   -5    -4
Cuba      6      6       5    0    -1
Haiti     5      5       4    1     0
</code>```

Note that the Cuba <-> Haiti relation is actually incorrect, since dist returns absolute distances. To get around that, you can use the following method:

```<code>dist_mat2 = -(outer(x, x, "-"))

dimnames(dist_mat2) = list(country, country)
</code>```

Result:

```<code>        USA Canada Bahamas Cuba Haiti
USA       0      0      -1   -6    -5
Canada    0      0      -1   -6    -5
Bahamas   1      1       0   -5    -4
Cuba      6      6       5    0     1
Haiti     5      5       4   -1     0
</code>```

Equivalent to the dist method, you can also use:

```<code>dist_mat = abs(outer(x, x, "-"))
</code>```

Body:
suppose I have following data set CL in R:

country    x
USA        7
Canada     7
Bahamas    6
Cuba       1
Haiti      2

Now, what I intend to do is to create an adjacency matrix where the countries are the nodes, and the strength of the ties are the absolute difference of the values of x. For example, the tie between the Bahamas (x=6) and Cuba (x=1) would have a strength of 6-1=5.

Thus, here the network matrix would look like this:

country USA Canada Bahamas Cuba Haiti
USA      0    0       -1    -6    -5
Canada   0    0       -1    -6    -5
Bahamas  1    1        0    -5    -4
Cuba     6    6        5     0     4
Haiti    5    5        4    -1     0

I have been struggling with this problem for quite a long time, and I just can't come to a decent approach to solve this. My actual data set consists of 150 countries, so it would be really troublesome to do this in Excel. So, does anyone have, how to do this in R? Thank you very much!

Here the R code for reproduction:

country<- c("USA", "Canada", "Bahamas", "Cuba", "Haiti")
x<- c(7,7,6,1,2)

CL<- data.frame(country=country, x=x)

Body:
You can use the dist function in base R:

dist_mat = as.matrix(dist(CL$x, diag = TRUE, upper = TRUE))

dist_mat[upper.tri(dist_mat)] = -dist_mat[upper.tri(dist_mat)]

dimnames(dist_mat) = list(country, country)

Result:

        USA Canada Bahamas Cuba Haiti
USA       0      0      -1   -6    -5
Canada    0      0      -1   -6    -5
Bahamas   1      1       0   -5    -4
Cuba      6      6       5    0    -1
Haiti     5      5       4    1     0

Note that the Cuba <-> Haiti relation is actually incorrect, since dist returns absolute distances. To get around that, you can use the following method:

dist_mat2 = -(outer(x, x, "-"))

dimnames(dist_mat2) = list(country, country)

Result:

        USA Canada Bahamas Cuba Haiti
USA       0      0      -1   -6    -5
Canada    0      0      -1   -6    -5
Bahamas   1      1       0   -5    -4
Cuba      6      6       5    0     1
Haiti     5      5       4   -1     0

Equivalent to the dist method, you can also use:

dist_mat = abs(outer(x, x, "-"))


问:
Playing two videos in one Video element React
I want to put a short intro video that plays before every video on my web app. This fiddle: http://jsfiddle.net/bnzqkpza/ has a lot of the functionality I'm looking for, but I am using React so I need to rewrite the jquery so it doesn't change the DOM. I'm new to React, can anyone help me with this?

HTML:

```<code><video src="http://www.w3schools.com/html/mov_bbb.mp4" id="myvideo" width="320" height="240" controls style="background:black">
</video>
</code>```

JS:

```<code>var myvid = document.getElementById('myvideo');
var myvids = [
  "http://www.w3schools.com/html/mov_bbb.mp4",
  "http://www.w3schools.com/html/movie.mp4"
  ];
var activeVideo = 0;

myvid.addEventListener('ended', function(e) {
  // update the active video index
  activeVideo = (++activeVideo) % myvids.length;

  // update the video source and play
  myvid.src = myvids[activeVideo];
  myvid.play();
});
</code>```

答:
Edited to use React 16 example.

You can try something like this:

```<code>const urls = [
  "https://www.w3schools.com/html/mov_bbb.mp4",
  "https://www.w3schools.com/html/movie.mp4"
];

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      currentUrlIdx: 0,
    }

    this.handleEnded = this.handleEnded.bind(this);
  }

  handleEnded(e) {
    const nextUrlIdx = (this.state.currentUrlIdx + 1) % urls.length
    this.setState({ currentUrlIdx: nextUrlIdx });
  }

  render() {
    return <div>
      <video src={urls[this.state.currentUrlIdx]} autoPlay onEnded={this.handleEnded}/>
    </div>;
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

https://codepen.io/anon/pen/OOxmjJ?editors=0010

Body:
I want to put a short intro video that plays before every video on my web app. This fiddle: http://jsfiddle.net/bnzqkpza/ has a lot of the functionality I'm looking for, but I am using React so I need to rewrite the jquery so it doesn't change the DOM. I'm new to React, can anyone help me with this?

HTML:

<video src="http://www.w3schools.com/html/mov_bbb.mp4" id="myvideo" width="320" height="240" controls style="background:black">
</video>

JS:

var myvid = document.getElementById('myvideo');
var myvids = [
  "http://www.w3schools.com/html/mov_bbb.mp4",
  "http://www.w3schools.com/html/movie.mp4"
  ];
var activeVideo = 0;

myvid.addEventListener('ended', function(e) {
  // update the active video index
  activeVideo = (++activeVideo) % myvids.length;

  // update the video source and play
  myvid.src = myvids[activeVideo];
  myvid.play();
});

Body:
Edited to use React 16 example.

You can try something like this:

const urls = [
  "https://www.w3schools.com/html/mov_bbb.mp4",
  "https://www.w3schools.com/html/movie.mp4"
];

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      currentUrlIdx: 0,
    }

    this.handleEnded = this.handleEnded.bind(this);
  }

  handleEnded(e) {
    const nextUrlIdx = (this.state.currentUrlIdx + 1) % urls.length
    this.setState({ currentUrlIdx: nextUrlIdx });
  }

  render() {
    return <div>
      <video src={urls[this.state.currentUrlIdx]} autoPlay onEnded={this.handleEnded}/>
    </div>;
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

https://codepen.io/anon/pen/OOxmjJ?editors=0010


问:
SQL (Access): Limiting Results with two Dependents
I am fairly new to SQL and Access, so what I am trying to do might be very simple or maybe not possible the way I intent to do it.

I have made a query which lists all products sold (incl. value and volume) by region and date (month and year). If a product has been sold I would like the query to return all 12 months of the year for that particular product and region. This all works. However, I would like to limit my query by excluding all entries where the sale of a product is "0" in a year for any particular product and region.

Example: If a product has not been sold in a particular region, within a specific year, the query should not return any entries for the product and region in that year. Is this possible?

In below code NationalCode = product, and RegionCode = Region. Everything else should be self-explanatory I hope. :)

I think the solution requires a WHERE statement, I have included a clause which only return values above "0". But this also removes any month which is 0, if there has been sales in a given year I would like to retain months with no sales.

I hope above makes sense. Thank you!

```<code> SELECT IIf(isnull(sum(MonthlyData.[Sales
 Value])),0,(sum(MonthlyData.[Sales Value])/1000)) AS [Value],
 IIf(isnull(sum(MonthlyData.[Sales Units])),0,sum(MonthlyData.[Sales
 Units])) AS Volume, [02-Query-Filter].RegionCode,
 [02-Query-Filter].NationalCode, [02-Query-Filter].Year, [02-Query-Filter].RawMonth

 FROM [02-Query-Filter]

 LEFT JOIN MonthlyData

 ON ([02-Query-Filter].RegionCode=Left(MonthlyData.Region,2)) AND
 ([02-Query-Filter].NationalCode=MonthlyData.[Nordic Code]) AND
 ([02-Query-Filter].RawMonth=MonthlyData.Month)

 WHERE MonthlyData.[Sales Value]>0

 GROUP BY [02-Query-Filter].RegionCode,
 [02-Query-Filter].NationalCode, [02-Query-Filter].Year, [02-Query-Filter].RawMonth
</code>```

答:
You'd create a sub-query that selects all products, regions and all years (summing up as appropriate), and exclude combinations that are summing to 0. Call this X.

Then create another query that returns all products, regions and all year/month, keeping also the year and month fields (or at least the year field) separate. combinations. Call this Y.

Create another query Z that selects all records from Y which can be inner joined to X on product, region and year.

If I have understood the original problem, query Z will give you the data you seek.

Body:
I am fairly new to SQL and Access, so what I am trying to do might be very simple or maybe not possible the way I intent to do it.

I have made a query which lists all products sold (incl. value and volume) by region and date (month and year). If a product has been sold I would like the query to return all 12 months of the year for that particular product and region. This all works. However, I would like to limit my query by excluding all entries where the sale of a product is "0" in a year for any particular product and region.

Example: If a product has not been sold in a particular region, within a specific year, the query should not return any entries for the product and region in that year. Is this possible?

In below code NationalCode = product, and RegionCode = Region. Everything else should be self-explanatory I hope. :)

I think the solution requires a WHERE statement, I have included a clause which only return values above "0". But this also removes any month which is 0, if there has been sales in a given year I would like to retain months with no sales.

I hope above makes sense. Thank you!

 SELECT IIf(isnull(sum(MonthlyData.[Sales
 Value])),0,(sum(MonthlyData.[Sales Value])/1000)) AS [Value],
 IIf(isnull(sum(MonthlyData.[Sales Units])),0,sum(MonthlyData.[Sales
 Units])) AS Volume, [02-Query-Filter].RegionCode,
 [02-Query-Filter].NationalCode, [02-Query-Filter].Year, [02-Query-Filter].RawMonth

 FROM [02-Query-Filter]

 LEFT JOIN MonthlyData

 ON ([02-Query-Filter].RegionCode=Left(MonthlyData.Region,2)) AND
 ([02-Query-Filter].NationalCode=MonthlyData.[Nordic Code]) AND
 ([02-Query-Filter].RawMonth=MonthlyData.Month)

 WHERE MonthlyData.[Sales Value]>0

 GROUP BY [02-Query-Filter].RegionCode,
 [02-Query-Filter].NationalCode, [02-Query-Filter].Year, [02-Query-Filter].RawMonth


问:
Want to fire Save button Modal popup in ASP.NET MVC application
I have Edit form page where if user make any changes then all the changes appear in the Modal popup. For that, I have used Jquery to fire Modal. In the Modal popup, the submit button is not getting fired. If i Put the button in the page then it works fine. I do not have any idea where i am getting wrong. Any suggestion and guidance will be useful to me.

My .cshtml code:

```<code>@model TestProject.Models.Test
@using (Html.BeginForm())
{
      <div class="form-horizontal" >

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.FName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
              @Html.EditorFor(model => model.FName, new { htmlAttributes = new { @class = "form-control",@id = "FName" } })
            </div>
        </div>

 <div class="form-group">
  <button type="button" class="btn btn-primary" id="btnSubmit" data-toggle="modal" data-target="ListofChanges">Next</button>
        </div>
    </div>
}
</code>```

My JavaScript Code  inside .cshtml:

```<code><script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
    var FirstName = "@Html.Raw(ViewBag.FName)";
    $(document).ready(function () {
        $("#btnSubmit").click(function () {

   if ($("#FName").val() != FirstName)
            {
        $("#error").html("First Name changed from:" + FirstName);
          }

            $('#ListofChanges').modal("show");
        });

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

My Modal to popup the changes:

```<code><div id="ListofChanges" tabindex="-1" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">PhoneBook Details changed from</h4>
            </div>
            <div class="modal-body">
                       <p id="error"></p>

            </div>
            <div class="modal-footer">
                <input type="submit" class="btn btn-primary" />
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>
</code>```

Please guide me why submit button in not fired once clicked. Thank you in advance.

答:
If you want to submit the original form, when user clicks on the submit button on the modal dialog, you should wire up the click event on that button and programatically submit your form.

Give your submit button inside the modal an Id , which you can use to wire up the click event.

```<code><input type="submit" id="btn-submit" class="btn btn-primary" />
</code>```

Now, register click event on this button, use the jQuery closest method to get the form where you other button is located (btnSubmit) and submit that form using the jquery submit method.

```<code>$(function () {

    $("#btnSubmit").click(function (e) {
        e.preventDefault();
        //your existing code goes here to set the modal content
        //$("#error").html("First Name changed from Sam" );

        $('#ListofChanges').modal("show");
    });

    $("#btn-submit").click(function() {
        alert("going to submit other form");
        $("#btnSubmit").closest("form").submit();
    });
});
</code>```

Body:
I have Edit form page where if user make any changes then all the changes appear in the Modal popup. For that, I have used Jquery to fire Modal. In the Modal popup, the submit button is not getting fired. If i Put the button in the page then it works fine. I do not have any idea where i am getting wrong. Any suggestion and guidance will be useful to me.

My .cshtml code:

@model TestProject.Models.Test
@using (Html.BeginForm())
{

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

            @Html.LabelFor(model => model.FName, htmlAttributes: new { @class = "control-label col-md-2" })

              @Html.EditorFor(model => model.FName, new { htmlAttributes = new { @class = "form-control",@id = "FName" } })

  <button type="button" class="btn btn-primary" id="btnSubmit" data-toggle="modal" data-target="ListofChanges">Next</button>

}

My JavaScript Code  inside .cshtml:

My Modal to popup the changes:

                <button type="button" class="close" data-dismiss="modal">×</button>

PhoneBook Details changed from

                <input type="submit" class="btn btn-primary" />
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Please guide me why submit button in not fired once clicked. Thank you in advance.

Body:
If you want to submit the original form, when user clicks on the submit button on the modal dialog, you should wire up the click event on that button and programatically submit your form.

Give your submit button inside the modal an Id , which you can use to wire up the click event.

<input type="submit" id="btn-submit" class="btn btn-primary" />

Now, register click event on this button, use the jQuery closest method to get the form where you other button is located (btnSubmit) and submit that form using the jquery submit method.

$(function () {

    $("#btnSubmit").click(function (e) {
        e.preventDefault();
        //your existing code goes here to set the modal content
        //$("#error").html("First Name changed from Sam" );

        $('#ListofChanges').modal("show");
    });

    $("#btn-submit").click(function() {
        alert("going to submit other form");
        $("#btnSubmit").closest("form").submit();
    });
});


问:
Material components for angular with routing
I'm attempting to use Material components for angular (https://blox.src.zone/material#/guides/gettingstarted) in my Angular 4.3 app. I've installed everything and I added a button to my app.component.html file and the button is rendered and behaves like it should here https://blox.src.zone/material#/directives/button.

I've then tried adding a button in one of my routes and the button isn't rendered the same. It's like the bootstrap css has taken over.

Do I have to import anything in the components that I'm routing to?

答:
There's not near enough information to answer your question. (How do you build your project, where did you put the stylesheets for the material components, do you use webpack, angular cli, rollup, or some other build tool, etc.). But since I can't comment (not enough reputation), I will give it a try.

From your description, it sounds like you added the stylesheets (probably css or scss) to a single app component, via a styleUrls declaration in your @Component metadata. Angular by default encapsulates styles for a component, so in that case your styles only apply to your app component.

For a Blox Material project you typically want to add the material components stylesheets as application wide stylesheet, included in your html via a script tag. When your project is an Angular-CLI project this is the file named in the "styles" field for your app as given in the .angular-cli.json file. This is also what the getting started guide for Blox Material describes, see https://blox.src.zone/material#/guides/gettingstarted.

Alternatively you could put the stylesheet in the root component of your app and/or play with encapsulation: ViewEncapsulation.None in your @Component metadata, to make the styles apply to multiple components at the same time.

If this doesn't help, please provide a bit more information, and try to use your developer tools to see what styles (and by which selectors) get applied to your app component. That will probably give you clues as why they don't get applied to your other components. It will also tell you if other styles (such as for bootstrap, are overriding the material component styles).

Finally check that the Blox Material directives are actually being applied to your buttons: An mdcButton should automatically get at least the mdc-button and mdc-ripple-upgraded style. If you don't see these styles on the button, there is something wrong with how you applied the mdcButton directive.


问:
How to hash a string into 8 digits?
Is there anyway that I can hash a random string into a 8 digit number without implementing any algorithms myself?</p>

答:
Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:</p>

```<code>$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to hash a string into 8 digits?

Body:
Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:

$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3