问:
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?

答:
I am marking djv answer as the answer.

That being said I look around further and found this

https://msdn.microsoft.com/en-us/library/28e2e18x%28VS.100%29.aspx?f=255&MSPPError=-2147217396

You can use a private member to implement an interface member. When a
  private member implements a member of an interface, that member
  becomes available by way of the interface even though it is not
  available directly on object variables for the class.

So, interface can be private, which I think is a bit strange.

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?


来源: stackexchange

问:
store an array of files in an already existing session array
i have a session array called $_SESSION['CART'] i already use it to store details of cart items
now i want to store multiple uploaded files names of files that user uploads while adding this item to cart as part of the session cart.i want to store them with key files. this is what am doing but its not working. is there a way for me to achieve this </p>

```<code>$_SESSION['cart'][] =
    array(
            'id'=>$productid,
            'quantity'=>$quantity,
            'detail'=>$detail,
            'files'=>$files
    );
</code>```

答:
Nothing much to explain here. if you want to store multiple array inside of array to store multiple file names. I assume that $files is a single file name only.
Try this.</p>

```<code>$_SESSION['cart'] = array(
    array(
        'id'=>$productid,
        'quantity'=>$quantity,
        'detail'=>$detail,
        'files'=>$files
    )
);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have a session array called $_SESSION['CART'] i already use it to store details of cart items
now i want to store multiple uploaded files names of files that user uploads while adding this item to cart as part of the session cart.i want to store them with key files. this is what am doing but its not working. is there a way for me to achieve this

$_SESSION['cart'][] =
    array(
            'id'=>$productid,
            'quantity'=>$quantity,
            'detail'=>$detail,
            'files'=>$files
    );

Body:
Nothing much to explain here. if you want to store multiple array inside of array to store multiple file names. I assume that $files is a single file name only.
Try this.

$_SESSION['cart'] = array(
    array(
        'id'=>$productid,
        'quantity'=>$quantity,
        'detail'=>$detail,
        'files'=>$files
    )
);


问:
Access multiple instances in SQL Server
There are two instances of SQL Server installed on my PC.

Version 11 and 13.

for accessing version 11, I enter .\ in a server name

for accessing version 13, I enter (LocalDB)\MSSQLLocalDB

When it comes to IP address I enter 192.168.1.104 (my IP) in the server name and it directly opens SQL Server Express (v11)

So what I need to enter in server name so I can access SQL Server (v13) through IP address?

答:
LocalDB only works local via named pipes and does not support connections via TCP/IP, thus you won't be able to connect via IP-address.

Remark: There was a declined feature request some years ago.

Title: Access multiple instances in SQL Server


问:
CORS issue with AngularJS and ASP Controller API hosted in other server within local network
I have an ASP application hosted in a server within a local network. When I call an OPTION request from AngularJS, it returns with a 200 status but with an error.

This is my GET code in Angular:

```<code>var config = {
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT,DELETE',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Accept',
        'Content-Type': 'application/json',
        'ZUMO-API-VERSION': '2.0.0'
    },

};

function getNames() {
    $http.get('http://<ipAddress>/tables', config)
 .then(function (res) {
     console.log(res);
     $scope.people = res.data;
 });
}
</code>```

Then this is how I return JSON data from my ASP application:

```<code>    public class TablesController : Controller
    {
        // GET: Tables
        [System.Web.Http.HttpGet]
        public ActionResult Index()
        {
            Database db = new Database();
            Result res = new Result();
            res = db.Get();

            if (Response != null)
            {
                Response.AddHeader("Access-Control-Allow-Origin", "*");
                Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
            }

            return new JsonResult()
            {
                Data = res,
                ContentType = "application/json",
                MaxJsonLength = Int32.MaxValue,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            //return View();
        }
    }
</code>```

I tried to add custom headers in my Web.config:

```<code><httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>
</code>```

Then it is giving me this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:///tables. (Reason: CORS header >‘Access-Control-Allow-Origin’ does not match ‘(null)’).

When I removed it, it is giving me this error:

(Reason: missing token
‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’
from CORS preflight channel).

And I have this included in my WebAppConfig.cs:

```<code>        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);
</code>```

I can't seem to make it work to return data to Angular. Any suggestions are appreciated.

UPDATE:

Can make it to work with GET, but now having problems with POST:

Angular:

```<code>function addName(user) {
    alert("about to post!")
    $http.post('http://<IPAddress>/tables/create', user, config)
      .then(function (res) {
          $scope.getNames();
      });
}
</code>```

ASP.Net

```<code>   [System.Web.Http.HttpPost]
    public ActionResult Create([FromBody] Users2 value)
    {
        Database db = new Helpers.Database();
        Result res = new Helpers.Result();

        res = db.Post(value.Name, value.Location);

        if (Response != null)
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
            Response.AddHeader("Access-Control-Allow-Headers", "Origin, ZUMO-API-VERSION, Content-Type, Accept, Authorization");
        }

        return Json(res, JsonRequestBehavior.AllowGet);
    }
</code>```

error:

(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

答:
remove the access allow headers from the angular request.

```<code>var config = {
    headers: {
        'Content-Type': 'application/json',
        'ZUMO-API-VERSION': '2.0.0'
    },

};

function getNames() {
    $http.get('http://<ipAddress>/tables', config)
 .then(function (res) {
     console.log(res);
     $scope.people = res.data;
 });
}
</code>```

Add the access allow methods in the asp

```<code> Response.AddHeader("Access-Control-Allow-Origin", "*");
 Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
 Response.AddHeader("Access-Control-Allow-Headers", "Origin, ZUMO-API-VERSION, Content-Type, Accept, Authorization");
</code>```

Body:
I have an ASP application hosted in a server within a local network. When I call an OPTION request from AngularJS, it returns with a 200 status but with an error.

This is my GET code in Angular:

var config = {
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT,DELETE',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Accept',
        'Content-Type': 'application/json',
        'ZUMO-API-VERSION': '2.0.0'
    },

};

function getNames() {
    $http.get('http://<ipAddress>/tables', config)
 .then(function (res) {
     console.log(res);
     $scope.people = res.data;
 });
}

Then this is how I return JSON data from my ASP application:

    public class TablesController : Controller
    {
        // GET: Tables
        [System.Web.Http.HttpGet]
        public ActionResult Index()
        {
            Database db = new Database();
            Result res = new Result();
            res = db.Get();

            if (Response != null)
            {
                Response.AddHeader("Access-Control-Allow-Origin", "*");
                Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
            }

            return new JsonResult()
            {
                Data = res,
                ContentType = "application/json",
                MaxJsonLength = Int32.MaxValue,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            //return View();
        }
    }

I tried to add custom headers in my Web.config:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

Then it is giving me this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:///tables. (Reason: CORS header >‘Access-Control-Allow-Origin’ does not match ‘(null)’).

When I removed it, it is giving me this error:

(Reason: missing token
‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’
from CORS preflight channel).

And I have this included in my WebAppConfig.cs:

        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);

I can't seem to make it work to return data to Angular. Any suggestions are appreciated.

UPDATE:

Can make it to work with GET, but now having problems with POST:

Angular:

function addName(user) {
    alert("about to post!")
    $http.post('http://<IPAddress>/tables/create', user, config)
      .then(function (res) {
          $scope.getNames();
      });
}

ASP.Net

   [System.Web.Http.HttpPost]
    public ActionResult Create([FromBody] Users2 value)
    {
        Database db = new Helpers.Database();
        Result res = new Helpers.Result();

        res = db.Post(value.Name, value.Location);

        if (Response != null)
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
            Response.AddHeader("Access-Control-Allow-Headers", "Origin, ZUMO-API-VERSION, Content-Type, Accept, Authorization");
        }

        return Json(res, JsonRequestBehavior.AllowGet);
    }

error:

(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Body:
remove the access allow headers from the angular request.

var config = {
    headers: {
        'Content-Type': 'application/json',
        'ZUMO-API-VERSION': '2.0.0'
    },

};

function getNames() {
    $http.get('http://<ipAddress>/tables', config)
 .then(function (res) {
     console.log(res);
     $scope.people = res.data;
 });
}

Add the access allow methods in the asp

 Response.AddHeader("Access-Control-Allow-Origin", "*");
 Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
 Response.AddHeader("Access-Control-Allow-Headers", "Origin, ZUMO-API-VERSION, Content-Type, Accept, Authorization");


问:
Use external fonts in android
I want to use external fonts in my app. I have tried adding new fonts using AssetManager but it did not work. Below is my code:

```<code>Typeface face;

face = Typeface.createFromAsset(getAssets(), "font.otf");

textview.setTypeface(face);
</code>```

but its not showing the text...

Please help me with this.

答: Android does support OTF (I'm not sure from which SDK version but it definitely works with 1.6), I was using a typewriter OTF font for a while but the rendering is nowhere near as accurate as with the TTF version I ended up using (via online font converter). The baseline was all over the place (some letters were a full 2 pixels higher than others), and on LDPI phones like the HTC Wildfire the problem is greatly magnified due to the larger pixels.</p>

Title: Use external fonts in android

Body:
I want to use external fonts in my app. I have tried adding new fonts using AssetManager but it did not work. Below is my code:

Typeface face;

face = Typeface.createFromAsset(getAssets(), "font.otf");

textview.setTypeface(face);

but its not showing the text...

Please help me with this.

ContentLicense: CC BY-SA 2.5


问:
SQL Server displaying query output in certain format
Question:

How can I display the student name, the department name and the course name of every course that the student has not taken?

I have tried using generating a cartesian product like this:

```<code>SELECT
    NAME, student.dept_name, title
FROM
    student
JOIN
    (SELECT
         id, title
     FROM
         takes, course
     WHERE
         takes.course_id <> course.course_id) a ON student.id = a.id
ORDER BY
    NAME ASC, title ASC
</code>```

And it works fine as long as the student only takes 1 course, but not if he attends to more than one

Can you guys provide a solution ? Thanks in advance

Database relations

The desired output is a connection of the values in this format

```<code>| name | dept_name | title (course name) |
</code>```

答:
Do a query that gets all combos of student and courses by doing Cartesian join, then remove all the courses a student has done by doing the 2nd query below the except. This handles a student who has not done any courses yet, which is why a not exists doesn’t work.</p>

```<code>Select s.id, c.title
From student s cross join courses c
Except
Select t.id, c.title
From takes t join courses c on t.course_id = c.course_id
</code>```

Body:
Question:

How can I display the student name, the department name and the course name of every course that the student has not taken?

I have tried using generating a cartesian product like this:

SELECT
    NAME, student.dept_name, title
FROM
    student
JOIN
    (SELECT
         id, title
     FROM
         takes, course
     WHERE
         takes.course_id <> course.course_id) a ON student.id = a.id
ORDER BY
    NAME ASC, title ASC

And it works fine as long as the student only takes 1 course, but not if he attends to more than one

Can you guys provide a solution ? Thanks in advance

Database relations

The desired output is a connection of the values in this format

| name | dept_name | title (course name) |

Body:
Do a query that gets all combos of student and courses by doing Cartesian join, then remove all the courses a student has done by doing the 2nd query below the except. This handles a student who has not done any courses yet, which is why a not exists doesn’t work.

Select s.id, c.title
From student s cross join courses c
Except
Select t.id, c.title
From takes t join courses c on t.course_id = c.course_id


问:
Redirect user from TabBar to login viewController if he's not logged in (Swift)
I want to redirect user after clicking on a TabBar item based on his status (logged in or not). If he's logged in he'll get the standard view that goes with the tabBar, if he's not he'll get the login ViewController instead.
With some searches I found that the solution is to implement a custom TabBarController class however I couldn't find any clue about how to achieve that.

A more developed explanation or example would be highly appreciated.

答:
Create a custom class for your UITabBarController and set the UITabBarControllerDelegate to self

Then just implement the following function

```<code>func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  // Your code here
}
</code>```

Body:
Create a custom class for your UITabBarController and set the UITabBarControllerDelegate to self

Then just implement the following function

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  // Your code here
}


问:
Convert XML file to a table in the database, including column names
I have the following xml file

```<code><Questions>
  <QuestionId=1>
  Which is a reserved word in the Java programming language?
    <Option1>
      method
    </Option1>
    <Option2>
      native
    </Option2>
    <Option3>
      subclass
    </Option3>
    <Option4>
      reference
    </Option4>
    <Answer>
    reference
    </Answer>
  </Question>
</Questions>
</code>```

I need to create a table in the database where the value of Question becomes the column name and the Answers come in the row using C# and ASP.NET

Any help would be appreciated.

This is the format expected.

```<code>|A_ID||Which is a reserved word in the Java programming language?||Q2  |
________________________________________________________________________
|01  ||Reference                                                 ||A2  |
</code>```

答:
If I understand correct, you need 2 tables. 1 for the questions, and 1 for the answers. For simplicity I'm thinking of:

```<code>public class Question
{
    public int Id { get; set; }
    public string Question { get; set; }

    //relations
    public List<Answer> Answers { get; set; }
}

public class Answer
{
    public int Id { get; set; }
    public string Answer { get; set; }
    public bool Correct { get; set; }
    public int QuestionId { get; set; }

    //relations
    public Question Question { get; set; }
}
</code>```

Then with entityframework you can create migrations and your context and create your questions etc.

Makes any sense?

if your new to entity framework: check out: https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db

Body:
I have the following xml file

<Questions>
  <QuestionId=1>
  Which is a reserved word in the Java programming language?
    <Option1>
      method
    </Option1>
    <Option2>
      native
    </Option2>
    <Option3>
      subclass
    </Option3>
    <Option4>
      reference
    </Option4>
    <Answer>
    reference
    </Answer>
  </Question>
</Questions>

I need to create a table in the database where the value of Question becomes the column name and the Answers come in the row using C# and ASP.NET

Any help would be appreciated.

This is the format expected.

|A_ID||Which is a reserved word in the Java programming language?||Q2  |
________________________________________________________________________
|01  ||Reference                                                 ||A2  |

Body:
If I understand correct, you need 2 tables. 1 for the questions, and 1 for the answers. For simplicity I'm thinking of:

public class Question
{
    public int Id { get; set; }
    public string Question { get; set; }

    //relations
    public List<Answer> Answers { get; set; }
}

public class Answer
{
    public int Id { get; set; }
    public string Answer { get; set; }
    public bool Correct { get; set; }
    public int QuestionId { get; set; }

    //relations
    public Question Question { get; set; }
}

Then with entityframework you can create migrations and your context and create your questions etc.

Makes any sense?

if your new to entity framework: check out: https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db


问:
From binary to charcode to text javascript
i'm in the freecodecamp's bonfire "binary agents" and I almost got it. It returns the correct answer but with an "undefined" first and I don't see why..</p>

```<code>function binaryAgent(str) {

var arr = str.split(" ");
var charcoded = [];
var finalStr;

for (var i=0; i<arr.length; i++) {

finalStr += String.fromCharCode((parseInt(arr[i], 2)));

}

return finalStr;

}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
</code>```

Body:
i'm in the freecodecamp's bonfire "binary agents" and I almost got it. It returns the correct answer but with an "undefined" first and I don't see why..

function binaryAgent(str) {

var arr = str.split(" ");
var charcoded = [];
var finalStr;

for (var i=0; i<arr.length; i++) {

finalStr += String.fromCharCode((parseInt(arr[i], 2)));

}

return finalStr;

}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

Body:
This is how I made it :)

function binaryAgent(str) {
      str = str.split(" ");
      var  final = '';

      for (var i = 0; i < str.length; i++) {
          final += String.fromCharCode((parseInt(str[i], 2)));
      }
      return final;
    }

    binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");


问:
Connecting to Sybase using sqsh
I am new to sybase.  I am trying to connect to the database using sqsh.

```<code>sqsh -Ddatabasename -Hservername -Uusername
or
sqsh -D databasename -H servername -U username
</code>```

I get the following error.  server name not found in configuration file.  unknown host machine name.
I am trying to connect using the command line.  Wouldn't that bypass a config file.

答:
I'm on Linux and I use sqsh like this:

```<code>sqsh -I /etc/freetds/freetds.conf -Smyserver  -Uknb -Pverysecret -Dmydb
</code>```

-D  argument is optional

and in the /etc/freetds/freetds.conf
there is an entry

```<code>[myserver]
        host = 123.456.78.90
        port = 1433
        tds version = 7.2
        client charset = UTF-8
</code>```

This used to work for many years. Right now I have some connectivity problems (segfaults), but this can be due to library configuration issues on my PC.

Title: Connecting to Sybase using sqsh

Body:
I am new to sybase.  I am trying to connect to the database using sqsh.

sqsh -Ddatabasename -Hservername -Uusername
or
sqsh -D databasename -H servername -U username

I get the following error.  server name not found in configuration file.  unknown host machine name.
I am trying to connect using the command line.  Wouldn't that bypass a config file.

Body:
I'm on Linux and I use sqsh like this:

sqsh -I /etc/freetds/freetds.conf -Smyserver  -Uknb -Pverysecret -Dmydb

-D  argument is optional

and in the /etc/freetds/freetds.conf
there is an entry

[myserver]
        host = 123.456.78.90
        port = 1433
        tds version = 7.2
        client charset = UTF-8

This used to work for many years. Right now I have some connectivity problems (segfaults), but this can be due to library configuration issues on my PC.


问:
Updating state on first render only?
Using react-native, I'm creating sub-Components within the parent App and providing their position to the array this.state.objLocation within the parent App.

I can get the initial location data into the array straight after the render, but because my subcomponents are draggable, each time they re-render on drag, it adds a new position object to the array.

I'd like to avoid this, and I thought that creating this.state = { firstRender: true } in the constructor and then using componentDidMount = () => { this.setState({ firstRender: false }) } after the first render would allow me to create a 'gate' to stop the addition of the extra position objects.

I can see that if I comment out //componentDidMount = () => { this.setState({ firstRender: false }) } then I will get multiple entries to my array but if it's included in the class I get absolutely none.

So possibly my interpretation of the render lifecycle and componentDidMount is incorrect?

Here is my code.

// App

```<code>import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

const dataArray = [{num: 1,id: 'A',},{num: 2,id: 'B',},{num: 3,id: 'Z',}]

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
            objLocation: [],
            firstRender: true,
        };
    }
    render(){
        return (
            <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                    <Text>Draggable Container</Text> {dataArray.map( d => { return(
                    <Draggable
                        id={d.id}
                        onLayout={ e=> this.onLayout(e)}
                        onPanResponderGrant={(dID) =>this.setState({ dID })}
                        onPanResponderRelease={() => this.setState({dID: null})} /> ) })}
                        <View style={[styles.findPoint ]} />
                </View>
                <View style={styles.infoBar}>
                    <Text>{this.state.dID ? this.state.dID : ''}</Text>{this.compFrame()}
                </View>
            </View>
        );
    }
    onLayout = (e) => {
      if ( e && this.state.firstRender) {
        const n = e.nativeEvent.layout;
            const position = {
              width: n.width,
              height: n.height,
              x: n.x,
              y: n.y
            }
        console.log(position);
        this.setState({
          objLocation: this.state.objLocation.concat([position])
        });
      }
    }
    componentWillMount = () => {
      console.log("START");
    }
    compFrame = () => {
      return(
        this.state.objLocation.map( d => {<View style={[styles.findPoint2,{left: d.x, top: d.y, width: d.width, height: d.height} ]} ></View>})
        )
    }
    componentDidMount = () => {
      this.setState({firstRender: true })
      console.log(this.state.objLocation.length);
    }
}
</code>```

// Draggable

```<code>import React, { Component } from 'react';
import { Text, PanResponder, Animated } from 'react-native';
import styles from './styles';

class Draggable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
    };
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        this.props.onPanResponderGrant(this.props.id);
      },
      onPanResponderMove: Animated.event([ null, {
          dx: this.state.pan.x,
          dy: this.state.pan.y,
        },
      ]),
      onPanResponderRelease: () => {
        Animated.spring(this.state.pan, { toValue: { x: 0, y: 0 } }).start();
        this.props.onPanResponderRelease();
      },
    });
  }
  render() {
    return (
      <Animated.View
        onLayout={ (e) => this.props.onLayout(e) }
        {...this.panResponder.panHandlers}
        style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
        <Text style={styles.textAlt}>Drag me!</Text>
        <Text style={styles.textNum}>{this.props.id}</Text>
      </Animated.View>
    );
  }
  componentDidMount = () => {
    this.props.onLayout(this.props.dragEvent)
  }
}
export default Draggable;
</code>```

// Output of console.log

```<code>START xxx
0
{width:108,height:108,x:133.5,y:376.5}
{width:108,height:108,x:133.5,y:78.5}
{width:108,height:108,x:133.5,y:227.5}
</code>```

答:
You could set the firstRender state in onLayout function </p>

```<code>     onLayout = (e) => {
          if ( e && this.state.firstRender) {
            const n = e.nativeEvent.layout;
            const position = {
                  width: n.width,
                  height: n.height,
                  x: n.x,
                  y: n.y
            }
    console.log(position);
    this.setState({
         firstRender: false,
         objLocation: this.state.objLocation.concat([position])
    });
  }
</code>```

<p>}</p>

Title: Updating state on first render only?

Body:
Using react-native, I'm creating sub-Components within the parent App and providing their position to the array this.state.objLocation within the parent App.

I can get the initial location data into the array straight after the render, but because my subcomponents are draggable, each time they re-render on drag, it adds a new position object to the array.

I'd like to avoid this, and I thought that creating this.state = { firstRender: true } in the constructor and then using componentDidMount = () => { this.setState({ firstRender: false }) } after the first render would allow me to create a 'gate' to stop the addition of the extra position objects.

I can see that if I comment out //componentDidMount = () => { this.setState({ firstRender: false }) } then I will get multiple entries to my array but if it's included in the class I get absolutely none.

So possibly my interpretation of the render lifecycle and componentDidMount is incorrect?

Here is my code.

// App

import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

const dataArray = [{num: 1,id: 'A',},{num: 2,id: 'B',},{num: 3,id: 'Z',}]

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
            objLocation: [],
            firstRender: true,
        };
    }
    render(){
        return (
            <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                    <Text>Draggable Container</Text> {dataArray.map( d => { return(
                    <Draggable
                        id={d.id}
                        onLayout={ e=> this.onLayout(e)}
                        onPanResponderGrant={(dID) =>this.setState({ dID })}
                        onPanResponderRelease={() => this.setState({dID: null})} /> ) })}
                        <View style={[styles.findPoint ]} />
                </View>
                <View style={styles.infoBar}>
                    <Text>{this.state.dID ? this.state.dID : ''}</Text>{this.compFrame()}
                </View>
            </View>
        );
    }
    onLayout = (e) => {
      if ( e && this.state.firstRender) {
        const n = e.nativeEvent.layout;
            const position = {
              width: n.width,
              height: n.height,
              x: n.x,
              y: n.y
            }
        console.log(position);
        this.setState({
          objLocation: this.state.objLocation.concat([position])
        });
      }
    }
    componentWillMount = () => {
      console.log("START");
    }
    compFrame = () => {
      return(
        this.state.objLocation.map( d => {<View style={[styles.findPoint2,{left: d.x, top: d.y, width: d.width, height: d.height} ]} ></View>})
        )
    }
    componentDidMount = () => {
      this.setState({firstRender: true })
      console.log(this.state.objLocation.length);
    }
}

// Draggable

import React, { Component } from 'react';
import { Text, PanResponder, Animated } from 'react-native';
import styles from './styles';

class Draggable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
    };
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        this.props.onPanResponderGrant(this.props.id);
      },
      onPanResponderMove: Animated.event([ null, {
          dx: this.state.pan.x,
          dy: this.state.pan.y,
        },
      ]),
      onPanResponderRelease: () => {
        Animated.spring(this.state.pan, { toValue: { x: 0, y: 0 } }).start();
        this.props.onPanResponderRelease();
      },
    });
  }
  render() {
    return (
      <Animated.View
        onLayout={ (e) => this.props.onLayout(e) }
        {...this.panResponder.panHandlers}
        style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
        <Text style={styles.textAlt}>Drag me!</Text>
        <Text style={styles.textNum}>{this.props.id}</Text>
      </Animated.View>
    );
  }
  componentDidMount = () => {
    this.props.onLayout(this.props.dragEvent)
  }
}
export default Draggable;

// Output of console.log

START xxx
0
{width:108,height:108,x:133.5,y:376.5}
{width:108,height:108,x:133.5,y:78.5}
{width:108,height:108,x:133.5,y:227.5}

Body:
You could set the firstRender state in onLayout function

     onLayout = (e) => {
          if ( e && this.state.firstRender) {
            const n = e.nativeEvent.layout;
            const position = {
                  width: n.width,
                  height: n.height,
                  x: n.x,
                  y: n.y
            }
    console.log(position);
    this.setState({
         firstRender: false,
         objLocation: this.state.objLocation.concat([position])
    });
  }

}


问:
fwrite, fread - problems with fread
I have following code:

```<code>int main()
{
    char* pedal[20];
    char* pedal2[20];
    for (int i = 0; i < 20; i++)
    {
        pedal[i] = "Pedal";
    }
    FILE* plik;
    plik = fopen("teraz.txt","wb");
    for (int i = 0; i < 20; i++)
    {
       fwrite(pedal[i],strlen(pedal[i]),1,plik);
    }
    system("pause");
    fclose(plik);
    plik = fopen("teraz.txt","rb");
    for (int i = 0; i < 20; i++)
    {
        fread(pedal2[i],5,1,plik); //I know for now that every element has 5 bytes
    }
    for (int i = 0; i < 20; i++)
    {
        std::cout << pedal2[i] << std::endl;
    }
    fclose(plik);
    system("pause");
    return 0;
}
</code>```

It's crashing at reading and second question let's assume that I have structure where I keep like integers, floats and also char* array and how can I easly write whole structure to the file? Normal fwrite with sizeof structure is not working

答:
Your problem that you didn't allocate buffer for reading. In fact line

```<code>fread(pedal2[i],5,1,plik)
</code>```

reads to unknown place. You need allocate memory (in your case it is 5 + 1 bytes for zero terminated string).

```<code>pedal2[i] = malloc(5+1);
fread(pedal2[i],5,1,plik)
</code>```

Don't forget to release it after usage.

Title: fwrite, fread - problems with fread

Body:
I have following code:

int main()
{
    char* pedal[20];
    char* pedal2[20];
    for (int i = 0; i < 20; i++)
    {
        pedal[i] = "Pedal";
    }
    FILE* plik;
    plik = fopen("teraz.txt","wb");
    for (int i = 0; i < 20; i++)
    {
       fwrite(pedal[i],strlen(pedal[i]),1,plik);
    }
    system("pause");
    fclose(plik);
    plik = fopen("teraz.txt","rb");
    for (int i = 0; i < 20; i++)
    {
        fread(pedal2[i],5,1,plik); //I know for now that every element has 5 bytes
    }
    for (int i = 0; i < 20; i++)
    {
        std::cout << pedal2[i] << std::endl;
    }
    fclose(plik);
    system("pause");
    return 0;
}

It's crashing at reading and second question let's assume that I have structure where I keep like integers, floats and also char* array and how can I easly write whole structure to the file? Normal fwrite with sizeof structure is not working

Body:
Your problem that you didn't allocate buffer for reading. In fact line

fread(pedal2[i],5,1,plik)

reads to unknown place. You need allocate memory (in your case it is 5 + 1 bytes for zero terminated string).

pedal2[i] = malloc(5+1);
fread(pedal2[i],5,1,plik)

Don't forget to release it after usage.


问:
C# Unity Sharing Class Instances VS Many Instances: Which is best performance?
I am currently working on an Ability system for a rpg game in Unity.

I have decided I was going to have an Ability system made of Ability class instances which each contain an array of Effects.

On an ability use a Use() method on the Ability is called which loops through the Effect[] array and calls an Apply() method on each.

The way I see it is that I will have to make sure that each effect can fetch the information it needs and store it in variables on its own class, as I cannot pass specific arguments to effects via the Apply() > Use() calls.

Assuming that I can find a way to do that, would it be more efficient to have only one instance of each Effect shared amongst all the Abilities or separate instances.

I can see drawbacks for both:

1) What I would expect is that with shared instances the Use() calls would have to be queued (am I right in thinking that ?) which could slow the game down when many calls are made.

2) With individual instances, I would not have that problem but I would constantly have a lot more instances loaded in memory.

Which is best ? In terms of general programming practice and performance ?

答:
I'm actually in a similar situation and thought I would share some of my thoughts.

I don't think that using a Use() function would really slow anything down, as the same basic code is going to have to be run in either implementation, and I don't think that a queue would be necessary, as you could make the functions static, not requiring any instances of the class to call the class methods.

I think the answer mainly depends on what kind of information you need passed into the Use() function. If each character needs to store parameters specific to each ability, then having individual instances won't really save memory, it just changes how the memory is organized, so I would go for individual instances for ease of use. If all the parameters are character specific rather than ability specific, then I think the other implementation would be the better one for memory, as you would only need to store something to point you to the proper Use() function.

I hope this helps! I don't really know that this the type of answer you were looking for, but I figured it's better than no answer. I would love to know what you choose to use!


答:
The fact that there is no connection between courses an student is not an issue you need to know all the courses a student could take so given

student

```<code>Name       CourseId
---------- ----------
Zishan     1,2,3
Ellen      2,3,4

(2 row(s) affected)
</code>```

Course

```<code>courseid    coursename
----------- ----------
1           java
2           C++
3           oracle
4           dot net
</code>```

Courses_taken

```<code>sid                  cid
-------------------- -----------
zishan               1
zishan               2

(2 row(s) affected)
</code>```

a cross join like this

```<code>select s.Name Studentname, c.courseid cid,c.coursename CourseNAme
from student s
cross join course c
</code>```

Results in

```<code>Studentname cid         CourseNAme
----------- ----------- ----------
Zishan      1           java
Zishan      2           C++
Zishan      3           oracle
Zishan      4           dot net
Ellen       1           java
Ellen       2           C++
Ellen       3           oracle
Ellen       4           dot net
</code>```

Joining to courses_taken

```<code>select sc.Studentname,sc.Coursename,ct.cid
from
(
select s.Name Studentname, c.courseid cid,c.coursename CourseNAme
from student s
cross join course c
) sc
left join courses_taken  ct on sc.StudentName = ct.sid and sc.cid = ct.cid
</code>```

results in this

```<code>Studentname Coursename cid
----------- ---------- -----------
Zishan      java       1
Zishan      C++        2
Zishan      oracle     NULL
Zishan      dot net    NULL
Ellen       java       NULL
Ellen       C++        NULL
Ellen       oracle     NULL
Ellen       dot net    NULL
</code>```

To exclude the courses taken a null where condition

```<code>select sc.Studentname,sc.Coursename,ct.cid
from
(
select s.Name Studentname, c.courseid cid,c.coursename CourseNAme
from student s
cross join course c
) sc
left join courses_taken  ct on sc.StudentName = ct.sid and sc.cid = ct.cid
where ct.cid is null
</code>```

Results in

```<code>Studentname Coursename cid
----------- ---------- -----------
Zishan      oracle     NULL
Zishan      dot net    NULL
Ellen       java       NULL
Ellen       C++        NULL
Ellen       oracle     NULL
Ellen       dot net    NULL

(6 row(s) affected)
</code>```

Title: SQL Server displaying query output in certain format

Body:
The fact that there is no connection between courses an student is not an issue you need to know all the courses a student could take so given

student

Name       CourseId
---------- ----------
Zishan     1,2,3
Ellen      2,3,4

(2 row(s) affected)

Course

courseid    coursename
----------- ----------
1           java
2           C++
3           oracle
4           dot net

Courses_taken

sid                  cid
-------------------- -----------
zishan               1
zishan               2

(2 row(s) affected)

a cross join like this

select s.Name Studentname, c.courseid cid,c.coursename CourseNAme
from student s
cross join course c

Results in

Studentname cid         CourseNAme
----------- ----------- ----------
Zishan      1           java
Zishan      2           C++
Zishan      3           oracle
Zishan      4           dot net
Ellen       1           java
Ellen       2           C++
Ellen       3           oracle
Ellen       4           dot net

Joining to courses_taken

select sc.Studentname,sc.Coursename,ct.cid
from
(
select s.Name Studentname, c.courseid cid,c.coursename CourseNAme
from student s
cross join course c
) sc
left join courses_taken  ct on sc.StudentName = ct.sid and sc.cid = ct.cid

results in this

Studentname Coursename cid
----------- ---------- -----------
Zishan      java       1
Zishan      C++        2
Zishan      oracle     NULL
Zishan      dot net    NULL
Ellen       java       NULL
Ellen       C++        NULL
Ellen       oracle     NULL
Ellen       dot net    NULL

To exclude the courses taken a null where condition

select sc.Studentname,sc.Coursename,ct.cid
from
(
select s.Name Studentname, c.courseid cid,c.coursename CourseNAme
from student s
cross join course c
) sc
left join courses_taken  ct on sc.StudentName = ct.sid and sc.cid = ct.cid
where ct.cid is null

Results in

Studentname Coursename cid
----------- ---------- -----------
Zishan      oracle     NULL
Zishan      dot net    NULL
Ellen       java       NULL
Ellen       C++        NULL
Ellen       oracle     NULL
Ellen       dot net    NULL

(6 row(s) affected)


问:
getting exception while trying to query xdocument
I am trying to extract the data from Web response having XML format using the below code
but I am getting null reference exception here at this line  var status = html.Element("Status");

```<code>if (oHttpWebResponse.StatusCode.ToString().ToLower() == "ok")
    {
        string contentType = oHttpWebResponse.ContentType;
        Stream content = oHttpWebResponse.GetResponseStream();
        XDocument xDoc = new XDocument(XDocument.Load(content));
        var html = xDoc.Root.Element("html");
        var status = html.Element("Status"); // getting System.NullReferenceException here
       var statusValue = status.Value;
        var lice = html.Element("LicenseKey").Value;

    }
</code>```

I am not why i am getting this error and xml format looks like this ..

```<code><html>
<Status>
200
</Status>
<LicenseKey>
FXOZ-HTTEKG-3QYB-MP2NPQ-AC7I3C-76SX-DVN4BA-C55RMK-RV2P-O5NSOQ
</LicenseKey>
<CustomerId>
U2N3XCAV
</CustomerId>
</html>
</code>```

I am not sure why i am getting this error, If any one please help on this query that would be very grateful to me ..

Thanks in advance..

答: xDoc.Root is the "html" tag in this xml document, so you are looking for an "html" child element under this "html" tag that is why it is null.

Body:
I am trying to extract the data from Web response having XML format using the below code
but I am getting null reference exception here at this line  var status = html.Element("Status");

if (oHttpWebResponse.StatusCode.ToString().ToLower() == "ok")
    {
        string contentType = oHttpWebResponse.ContentType;
        Stream content = oHttpWebResponse.GetResponseStream();
        XDocument xDoc = new XDocument(XDocument.Load(content));
        var html = xDoc.Root.Element("html");
        var status = html.Element("Status"); // getting System.NullReferenceException here
       var statusValue = status.Value;
        var lice = html.Element("LicenseKey").Value;

    }

I am not why i am getting this error and xml format looks like this ..

<Status>
200
</Status>
<LicenseKey>
FXOZ-HTTEKG-3QYB-MP2NPQ-AC7I3C-76SX-DVN4BA-C55RMK-RV2P-O5NSOQ
</LicenseKey>
<CustomerId>
U2N3XCAV
</CustomerId>

I am not sure why i am getting this error, If any one please help on this query that would be very grateful to me ..

Thanks in advance..


问:
Parent view model that contains both models
I have two separate child models which I have created and I want to be able to create a parent model which would allow me to use both child models in one View.

The problem that I am running into is that I keep getting errors from my View which is informing me that Parent Model isn't accessing the variable.
"MainPageModel does not contain a defintion..."

My end goal from this is to be able to have a form that uses input and has the ability to upload an image all in one model. This creates a simple profile with an image. On submission, you would be brought to another View, with what your profile would look like.

MODEL 1:

```<code>namespace Profile.Models
{
    public class Profiler
    {
        public string FName { get; set; }
        public string Address { get; set; }
        public string BirthDate { get; set; }
        public string PhoneNumber { get; set; }
        public string Comments { get; set; }
    }
}
</code>```

Model 2:

```<code>namespace Profile.Models
{
    public interface IFormFile
    {
        string ContentType { get; }
        string ContentDisposition { get; }
        IHeaderDictionary Headers { get; }
        long Length { get; }
        string Name { get; }
        string FileName { get; }
        Stream OpenReadStream();
        void CopyTo(Stream target);
        Task CopyToAsync(Stream target, CancellationToken cancellationToken);
    }
}
</code>```

Parent Model:

```<code>namespace Profile.Models
{
    public class MainPageModel
    {
        public Profiler Profiler { get; set; }
        public IFormFile IFormFile { get; set; }

        public MainPageModel(Profiler Profiler)
        {
            Profiler = Profiler;
        }
    }
}
</code>```

View:

```<code>@model Profile.Models.MainPageModel
@{
    ViewData["Title"] = "Profiler";
}
<h2>Create your Profile using the form below</h2>
<h3>On Submission, your profile will be created for you to see.</h3>

<form asp-action="Profiler" >
    <label asp-for="FName"></label>
    <input asp-for="FName" /> <br /><br />
    <label asp-for="Address"></label>
    <input asp-for="Address" /> <br /><br />
    <label asp-for="BirthDate"></label>
    <input asp-for="BirthDate" /> <br /><br />
    <label asp-for="PhoneNumber"></label>
    <input asp-for="PhoneNumber" /> <br /><br />
    <label asp-for="Comments"></label>
    <input asp-for="Comments" /> <br /><br />
    <input type="submit" value="Submit" />
</form>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple />
    <input type="submit" value="Upload" />
</form>
</code>```

HomeController:

```<code>public IActionResult Profiler([Bind("FName,Address,BirthDate,PhoneNumber,Comments")] Profiler Profiles)
    {
        return View(new MainPageModel (Profiles));
    }
</code>```

答:
Add parameter constructor to MainPageModel

```<code>namespace Profile.Models
{
    public class MainPageModel
    {
        public MainPageModel () {}

        public MainPageModel(Profiler profiler)
        {
            Profiler = profiler;
        }

        public Profiler Profiler { get; set; }

        public IFormFile Image{ get; set; }

    }
}
</code>```

then add Profile prefix to inputs name in profile form and change file input name to Image:

```<code>@model Profile.Models.MainPageModel
@{
    ViewData["Title"] = "Profiler";
}
<h2>Create your Profile using the form below</h2>
<h3>On Submission, your profile will be created for you to see.</h3>

<form asp-action="Profiler" method="post">
    <label asp-for="Profile.FName"></label>
    <input asp-for="Profile.FName" /> <br /><br />
    <label asp-for="Profile.Address"></label>
    <input asp-for="Profile.Address" /> <br /><br />
    <label asp-for="Profile.BirthDate"></label>
    <input asp-for="Profile.BirthDate" /> <br /><br />
    <label asp-for="Profile.PhoneNumber"></label>
    <input asp-for="Profile.PhoneNumber" /> <br /><br />
    <label asp-for="Profile.Comments"></label>
    <input asp-for="Profile.Comments" /> <br /><br />
    <input type="submit" value="Submit" />
</form>

<form asp-action="Profiler" method="post" enctype="multipart/form-data">
    <input type="file" name="Image" />
    <input type="submit" value="Upload" />
</form>
</code>```

and controller

```<code>[HttpGet]
public IActionResult Profiler()
{
    return View(new MainPageModel(profile));
}

[HttpPost]
public IActionResult Profiler(MainPageModel viewModel)
{
    if(viewModel.Profile != null )
    {
        // Save profile
    }
    else if(viewModel.Image != null)
    {
        // Save image
    }
}
</code>```

Body:
I have two separate child models which I have created and I want to be able to create a parent model which would allow me to use both child models in one View.

The problem that I am running into is that I keep getting errors from my View which is informing me that Parent Model isn't accessing the variable.
"MainPageModel does not contain a defintion..."

My end goal from this is to be able to have a form that uses input and has the ability to upload an image all in one model. This creates a simple profile with an image. On submission, you would be brought to another View, with what your profile would look like.

MODEL 1:

namespace Profile.Models
{
    public class Profiler
    {
        public string FName { get; set; }
        public string Address { get; set; }
        public string BirthDate { get; set; }
        public string PhoneNumber { get; set; }
        public string Comments { get; set; }
    }
}

Model 2:

namespace Profile.Models
{
    public interface IFormFile
    {
        string ContentType { get; }
        string ContentDisposition { get; }
        IHeaderDictionary Headers { get; }
        long Length { get; }
        string Name { get; }
        string FileName { get; }
        Stream OpenReadStream();
        void CopyTo(Stream target);
        Task CopyToAsync(Stream target, CancellationToken cancellationToken);
    }
}

Parent Model:

namespace Profile.Models
{
    public class MainPageModel
    {
        public Profiler Profiler { get; set; }
        public IFormFile IFormFile { get; set; }

        public MainPageModel(Profiler Profiler)
        {
            Profiler = Profiler;
        }
    }
}

View:

@model Profile.Models.MainPageModel
@{
    ViewData["Title"] = "Profiler";
}

Create your Profile using the form below

On Submission, your profile will be created for you to see.

<form asp-action="Profiler" >

    <input asp-for="FName" />

    <input asp-for="Address" />

    <input asp-for="BirthDate" />

    <input asp-for="PhoneNumber" />

    <input asp-for="Comments" />

    <input type="submit" value="Submit" />
</form>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple />
    <input type="submit" value="Upload" />
</form>

HomeController:

public IActionResult Profiler([Bind("FName,Address,BirthDate,PhoneNumber,Comments")] Profiler Profiles)
    {
        return View(new MainPageModel (Profiles));
    }

Body:
Add parameter constructor to MainPageModel

namespace Profile.Models
{
    public class MainPageModel
    {
        public MainPageModel () {}

        public MainPageModel(Profiler profiler)
        {
            Profiler = profiler;
        }

        public Profiler Profiler { get; set; }

        public IFormFile Image{ get; set; }

    }
}

then add Profile prefix to inputs name in profile form and change file input name to Image:

@model Profile.Models.MainPageModel
@{
    ViewData["Title"] = "Profiler";
}
<h2>Create your Profile using the form below</h2>
<h3>On Submission, your profile will be created for you to see.</h3>

<form asp-action="Profiler" method="post">
    <label asp-for="Profile.FName"></label>
    <input asp-for="Profile.FName" /> <br /><br />
    <label asp-for="Profile.Address"></label>
    <input asp-for="Profile.Address" /> <br /><br />
    <label asp-for="Profile.BirthDate"></label>
    <input asp-for="Profile.BirthDate" /> <br /><br />
    <label asp-for="Profile.PhoneNumber"></label>
    <input asp-for="Profile.PhoneNumber" /> <br /><br />
    <label asp-for="Profile.Comments"></label>
    <input asp-for="Profile.Comments" /> <br /><br />
    <input type="submit" value="Submit" />
</form>

<form asp-action="Profiler" method="post" enctype="multipart/form-data">
    <input type="file" name="Image" />
    <input type="submit" value="Upload" />
</form>

and controller

[HttpGet]
public IActionResult Profiler()
{
    return View(new MainPageModel(profile));
}

[HttpPost]
public IActionResult Profiler(MainPageModel viewModel)
{
    if(viewModel.Profile != null )
    {
        // Save profile
    }
    else if(viewModel.Image != null)
    {
        // Save image
    }
}


问:
Remove first char from string - Regex
I have started using Workflow on iOS to help speed up tasks at work. One of those is entering delivery records into the computer (via the iPad barcode scan function) instead of manually writting down the ref code and then typing it in.

Workflow has a "Replace Text" function that can be used with regexs to strip out characters etc.

I have managed to find a regex to get rid of the last digit in a scan (a checksum digit, always a capital letter).

The regex is simple.

```<code>.{0}-$.
</code>```

This goes in the "Find Text" field. The "Replace With" is left empty. It works wonderfully.

How can adapt this to work with other scan types with other scan types where I want to specically get rid of the FIRST character only?  I've searched the forums but can only find long and difficult to interpret regexes that I am sure won't do what I am trying to achive, something simple by comparison.

An example is of what I mean is to convert "Y300006944" to "300006944"

答:
You can use the following regex:

```<code>^.(.*)$
</code>```

with a backreference $1 that you can use as replacement.

Good luck.

Title: Remove first char from string - Regex

Body:
I have started using Workflow on iOS to help speed up tasks at work. One of those is entering delivery records into the computer (via the iPad barcode scan function) instead of manually writting down the ref code and then typing it in.

Workflow has a "Replace Text" function that can be used with regexs to strip out characters etc.

I have managed to find a regex to get rid of the last digit in a scan (a checksum digit, always a capital letter).

The regex is simple.

.{0}-$.

This goes in the "Find Text" field. The "Replace With" is left empty. It works wonderfully.

How can adapt this to work with other scan types with other scan types where I want to specically get rid of the FIRST character only?  I've searched the forums but can only find long and difficult to interpret regexes that I am sure won't do what I am trying to achive, something simple by comparison.

An example is of what I mean is to convert "Y300006944" to "300006944"

Body:
You can use the following regex:

^.(.*)$

with a backreference $1 that you can use as replacement.

Good luck.


问:
Concatenate lists with LINQ
Is it possible to concatenate a List<List<T>> into a List<T> with a single operation in a way which isn't horrible slow, i.e:

```<code>List<List<int>> listOfLists = new List<List<int>>();
List<int> concatenatedList = listOfLists.Something...
</code>```

?

答:
Something like this:</p>

```<code>listOfLists.Aggregate(new int[0], (res, list) => res.Concat(list));
</code>```

Title: Concatenate lists with LINQ

Body:
Is it possible to concatenate a List<List<T>> into a List<T> with a single operation in a way which isn't horrible slow, i.e:

List<List<int>> listOfLists = new List<List<int>>();
List<int> concatenatedList = listOfLists.Something...

?

Body:
Something like this:

listOfLists.Aggregate(new int[0], (res, list) => res.Concat(list));


问:
how to integrate Assently api for e-signature transaction in PHP
In my wp project, I am using Assently for e-signature implementation. Though I have an account and created a pdf form file to be filled by the user I just am not able to proceed a bit. I am finding documentation not clear.
Also, I am not clear about what needs to be done so that the user will be shown form to process the transaction.

So, any help/suggestions to proceed forward is appreciated.

I have tried the following based on assently-laravel. But it's asking me to login. What is an error here?
Code:

```<code>define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');

include_once('assently/Assently.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);

$url = 'https://test.assently.com/api/v2/createcasefromtemplate';
$default = array(
    'Id' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce'
);
$data = array(
    'auth' => $assently->auth(),
    'templateId'    => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
    'newCaseId'     => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce',
    'agentUsername' => ''
);

$data = array(
    'json' => $data
);
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json; charset=utf-8\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo '```';
print_r($result);
die;
```

答:
create this class inside assently folder

```<code>use Assently\AssentlyCase;
use Exception;

class  CustomAssentlyCase extends AssentlyCase
{
    public function createFromTemplate($data)
    {
        $default = [
            'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce'
        ];

        $json = array_merge($default, $data);

        try{
            $response = $this->client->post($this->url('createcasefromtemplate'), [
                'auth' => $this->assently->auth(),
                'json' => $json
            ]);

        }catch(Exception $e){
            print_r($e->getMessage());
        }
        return $response;
    }
}
</code>```

Use

```<code>define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');

include_once('assently/Assently.php');
include_once('assently/CustomAssentlyCase.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);

$data = array(
    'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
    'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce',
    'agentUsername' => 'agentUsername' // PUT your agent username here it is required
);

$customAssentlyCase = new CustomAssentlyCase($assently);
$result = $customAssentlyCase->createFromTemplate($data);
print_r($result);
</code>```

Try this, though not tested but should work. Good luck.

ContentLicense: CC BY-SA 4.0

Body:
In my wp project, I am using Assently for e-signature implementation. Though I have an account and created a pdf form file to be filled by the user I just am not able to proceed a bit. I am finding documentation not clear.
Also, I am not clear about what needs to be done so that the user will be shown form to process the transaction.

So, any help/suggestions to proceed forward is appreciated.

I have tried the following based on assently-laravel. But it's asking me to login. What is an error here?
Code:

define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');

include_once('assently/Assently.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);

$url = 'https://test.assently.com/api/v2/createcasefromtemplate';
$default = array(
    'Id' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce'
);
$data = array(
    'auth' => $assently->auth(),
    'templateId'    => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
    'newCaseId'     => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce',
    'agentUsername' => ''
);

$data = array(
    'json' => $data
);
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json; charset=utf-8\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo '
';
print_r($result);
die;

Body:
create this class inside assently folder

use Assently\AssentlyCase;
use Exception;

class  CustomAssentlyCase extends AssentlyCase
{
    public function createFromTemplate($data)
    {
        $default = [
            'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce'
        ];

        $json = array_merge($default, $data);

        try{
            $response = $this->client->post($this->url('createcasefromtemplate'), [
                'auth' => $this->assently->auth(),
                'json' => $json
            ]);

        }catch(Exception $e){
            print_r($e->getMessage());
        }
        return $response;
    }
}

Use

define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');

include_once('assently/Assently.php');
include_once('assently/CustomAssentlyCase.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);

$data = array(
    'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
    'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce',
    'agentUsername' => 'agentUsername' // PUT your agent username here it is required
);

$customAssentlyCase = new CustomAssentlyCase($assently);
$result = $customAssentlyCase->createFromTemplate($data);
print_r($result);

Try this, though not tested but should work. Good luck.