问:
Which is the best encryption and decryption algorithm in c#?
I wanna very good encryption and decryption algorithm in c#?.

I googled Some page,.. I got one,..

```<code> private string base64Encode(string sData)
        {
            try
            {
                byte[] encData_byte = new byte[sData.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Encode" + ex.Message);
            }
        }

  public string base64Decode(string sData)
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(sData);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }
</code>```

Is it good?. else suggest a good one.

thanks in advance!.

答:
First encoding is not encryption.

The choice of encryption algorithm will depend on the requirements of solution. There is no abstract best.

You must consider the level of protection you require, the time you have to perform the operation and how you will transmit the key.

Body:
I wanna very good encryption and decryption algorithm in c#?.

I googled Some page,.. I got one,..

 private string base64Encode(string sData)
        {
            try
            {
                byte[] encData_byte = new byte[sData.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Encode" + ex.Message);
            }
        }

  public string base64Decode(string sData)
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(sData);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }

Is it good?. else suggest a good one.

thanks in advance!.


来源: stackexchange

问:
Does anyone know why my function is converted to type tuple when i call it in another function?
I have written the following function to calculate the probability of a single reaction in a system fires and output the probability of each reaction in the system firing as an array:

```<code>def propensity_calc(LHS, popul_num, stoch_rate):
    propensity = np.zeros(len(LHS))
    for row in range(len(LHS)):
            a = stoch_rate[row]
            for i in range(len(popul_num)):
                if (popul_num[i] >= LHS[row, i]):
                    binom_rxn = binom(popul_num[i], LHS[row, i])
                    a = a*binom_rxn
                else:
                    a = 0
                    break
            propensity[row] = a
    return propensity
</code>```

The inputs for this function are 3 arrays popul_num has the discrete number of molecules of each reactant, LHS is a 2D array with the ratios between each reactant and stoch_rate is the rate of each reaction.

I now want to call the function with the scipy.misc.derivative method in a different function to calculate the partial derivative:

```<code>def time_step_calc(popul_num, state_change_array, a0):
    # equation 22:
    expctd_net_change = a0*state_change_array
    print("expected net change:\n", expctd_net_change)
    # equation 24 partial differentiation:
    for x in range(len(popul_num)):
        part_propensity_diff = derivative(func=propensity_calc(LHS, popul_num, stoch_rate), x0=popul_num[x])    <-- Error here, propensity_calc is converted into a tuple object?
        print("partial diff:\n", type(part_propensity_diff))
        # popul_num = numpy.ndarray --> derivative function needs a float to work
    # equation 26:
    t_step = epsi*a0 / sum(expctd_net_change*part_propensity_diff)
    delta_t = optimize.fmin(t_step, 0.00012) # take the minimum value of the partial derivative
    print("calculated delta_t:\n", delta_t)
    return delta_t
</code>```

But the but when I supply the function argument with the propensity_calc function, the line indicated throws the following error TypeError: 'tuple' object is not callable

I dont understand where the tuple is coming from or why propensity_calc is converted into it?

EDIT: heres the traceback

```<code>File "C:\Users\Mike\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\misc\common.py", line 119, in derivative
val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: 'tuple' object is not callable
</code>```

Any suggestions?
Cheers

答:
When you say:

```<code>func=propensity_calc(LHS, popul_num, stoch_rate)
</code>```

I do not believe you need the

```<code>func=
</code>```

propensity_calc(LHS, popul_num, stoch_rate) calls propensity_calc

func=propensity_calc(LHS, popul_num, stoch_rate) defines a tuple, or immutable sequence of objects. Think of an array of objects you cannot change.

Here is more on tuples: https://www.tutorialspoint.com/python/python_tuples.htm

ContentLicense: CC BY-SA 4.0

Body:
I have written the following function to calculate the probability of a single reaction in a system fires and output the probability of each reaction in the system firing as an array:

def propensity_calc(LHS, popul_num, stoch_rate):
    propensity = np.zeros(len(LHS))
    for row in range(len(LHS)):
            a = stoch_rate[row]
            for i in range(len(popul_num)):
                if (popul_num[i] >= LHS[row, i]):
                    binom_rxn = binom(popul_num[i], LHS[row, i])
                    a = a*binom_rxn
                else:
                    a = 0
                    break
            propensity[row] = a
    return propensity

The inputs for this function are 3 arrays popul_num has the discrete number of molecules of each reactant, LHS is a 2D array with the ratios between each reactant and stoch_rate is the rate of each reaction.

I now want to call the function with the scipy.misc.derivative method in a different function to calculate the partial derivative:

def time_step_calc(popul_num, state_change_array, a0):
    # equation 22:
    expctd_net_change = a0*state_change_array
    print("expected net change:\n", expctd_net_change)
    # equation 24 partial differentiation:
    for x in range(len(popul_num)):
        part_propensity_diff = derivative(func=propensity_calc(LHS, popul_num, stoch_rate), x0=popul_num[x])    <-- Error here, propensity_calc is converted into a tuple object?
        print("partial diff:\n", type(part_propensity_diff))
        # popul_num = numpy.ndarray --> derivative function needs a float to work
    # equation 26:
    t_step = epsi*a0 / sum(expctd_net_change*part_propensity_diff)
    delta_t = optimize.fmin(t_step, 0.00012) # take the minimum value of the partial derivative
    print("calculated delta_t:\n", delta_t)
    return delta_t

But the but when I supply the function argument with the propensity_calc function, the line indicated throws the following error TypeError: 'tuple' object is not callable

I dont understand where the tuple is coming from or why propensity_calc is converted into it?

EDIT: heres the traceback

File "C:\Users\Mike\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\misc\common.py", line 119, in derivative
val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: 'tuple' object is not callable

Any suggestions?
Cheers

Body:
When you say:

func=propensity_calc(LHS, popul_num, stoch_rate)

I do not believe you need the

func=

propensity_calc(LHS, popul_num, stoch_rate) calls propensity_calc

func=propensity_calc(LHS, popul_num, stoch_rate) defines a tuple, or immutable sequence of objects. Think of an array of objects you cannot change.

Here is more on tuples: https://www.tutorialspoint.com/python/python_tuples.htm


问:
rails form - 2 fields with same id in a form - how to disable second field when first field is selected
I have in my rails form the following code:

```<code><label>Fruit: </label>  <%= f.select(:IST_FRUIT, [['Apple', 'Apple'],
                          ['Orange', 'Orange'],
                          ['Kiwi', 'Kiwi'],
                          ['Other', 'Other']
                          ],{ :prompt => "Please select"},{:onchange => "if (this.value == 'Other')
                                                                         {document.getElementById('otherTissue').style.display = 'block';
                                                                         } "}
                          ) %>

<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :IST_FRUIT, :size => 10  %></span>
</code>```

User can select a fruit form the listbox but if user selects 'Other', a textfield is diaplayed allowing user to input his value.

The problem is that when user selects a fruit and save the form, the fruit field in blank in the table and the reason is that the form is saving the second field 'IST_FRUIT' found in the span with id 'IST_FRUIT'.

I would be really grateful if someone could show me a way how to disable the second field when 'other' is not selected and enable it when 'Other' is selected from the dropdown list.

Many many thanks for any suggestion provided.

答:
I have another advice. Instead of disabling a HTML input (by the way - an ID must be unique in a HTML document) just make another attribute in your model, name it 'other_fruit' for example, and use this value if the 'fruit' is set to 'other' or is empty. For example you may write something like this:

```<code>class TheModel
  attr :other_fruit

  # Overwritten accessor for the fruit attribute.
  # Returns the values of :other_fruit if :fruit is blank.
  #
  def fruit
    if self[:fruit].blank?
      other_fruit
    else
      self[:fruit]
    end
  end
end
</code>```

Now the HTML part. In your JavaScript you set 'display' to block, but you do not reset it when user selects another option.

If you want to prevent the field from being sent to the server, you should set the 'disabled' attribute. Setting the 'style' only hides the control from the user's eyes.

ContentLicense: CC BY-SA 3.0

Body:
I have in my rails form the following code:

Fruit:   <%= f.select(:IST_FRUIT, [['Apple', 'Apple'],
                          ['Orange', 'Orange'],
                          ['Kiwi', 'Kiwi'],
                          ['Other', 'Other']
                          ],{ :prompt => "Please select"},{:onchange => "if (this.value == 'Other')
                                                                         {document.getElementById('otherTissue').style.display = 'block';
                                                                         } "}
                          ) %>

 If other, please state: <%= f.text_field :IST_FRUIT, :size => 10  %>

User can select a fruit form the listbox but if user selects 'Other', a textfield is diaplayed allowing user to input his value.

The problem is that when user selects a fruit and save the form, the fruit field in blank in the table and the reason is that the form is saving the second field 'IST_FRUIT' found in the span with id 'IST_FRUIT'.

I would be really grateful if someone could show me a way how to disable the second field when 'other' is not selected and enable it when 'Other' is selected from the dropdown list.

Many many thanks for any suggestion provided.

Body:
I have another advice. Instead of disabling a HTML input (by the way - an ID must be unique in a HTML document) just make another attribute in your model, name it 'other_fruit' for example, and use this value if the 'fruit' is set to 'other' or is empty. For example you may write something like this:

class TheModel
  attr :other_fruit

  # Overwritten accessor for the fruit attribute.
  # Returns the values of :other_fruit if :fruit is blank.
  #
  def fruit
    if self[:fruit].blank?
      other_fruit
    else
      self[:fruit]
    end
  end
end

Now the HTML part. In your JavaScript you set 'display' to block, but you do not reset it when user selects another option.

If you want to prevent the field from being sent to the server, you should set the 'disabled' attribute. Setting the 'style' only hides the control from the user's eyes.


问:
QnA maker Context Only does not work: Follow up question Is understood outside of contextual flow
So I follow every step that the Microsoft Docs say and what this person said on Stackoverflow. I make sure that I check the Add Follow-up Prompt add the Q and A, then I check the Context Only box. Once I do that I save and train my bot. When I go to test it, I put the Context Only Q in the test environment and it still shows even though it specifies that Context-only (this follow-up will not be understood out of the contextual flow).

What am I doing wrong?

答:
So I contacted their support and it was an issue on their end.
After talking with Microsoft they rolled out an update to fix this bug.
Context only works as stated now. </p>


问:
How to do undo in Azure Data Factory
I am new to Azure Data factory. While developing the pipeline I could not find undo operation in Azure Data Factory. ctrl+z did not work. What is the keyboard shortcut for the undo?

答: There is no undo shortcut for ADF. Max you can do is the Discard All option.

Title: How to do undo in Azure Data Factory


问:
Convert a list of string into a comma separated string without duplications
I have a list of strings in Java. I would like to to insert it into a string with commas, something like:

```<code>Input: [option1,option2,option3,option1,option4]
Output: option1,option2,option3,option4
</code>```

I saw this topic and I really liked this one:

```<code>        StringBuilder result = new StringBuilder();
        String delimiter= "";
        for (String i : list) {
            result.append(delimiter).append(i);
            delimiter = ",";
        }
        return result.toString();
</code>```

But what would be the best way to add support for unique only items? How can I return a string without any duplicates? I could remove duplication from list first but it feels like there is a better solution here.

答:
The best to avoid duplicates is to use a Set

TreeSet for alphabetical order

LinkedHashSet to keep insertion order (initial order)

```<code>StringBuilder result = new StringBuilder();
String delimiter= "";
for (String i : new LinkedHashSet<String>(list)) {
    result.append(delimiter).append(i);
    delimiter = ",";
}
return result.toString();
</code>```

But you can just do String.join(',', new LinkedHashSet<String>(list))

Back to List

```<code>List<String> inputList = (unique) ? new ArrayList<>(new HashSet<>(list)) : list;
</code>```

Case-insensitive

```<code>Set<String> check = new HashSet<String>();
StringBuilder result = new StringBuilder();
String delimiter= "";
for (String i : list) {
    if(!check.contains(i.toLowerCase())){
        result.append(delimiter).append(i);
        delimiter = ",";
        check.add(i.toLowerCase());
    }
}
return result.toString();
</code>```

Body:
I have a list of strings in Java. I would like to to insert it into a string with commas, something like:

Input: [option1,option2,option3,option1,option4]
Output: option1,option2,option3,option4

I saw this topic and I really liked this one:

        StringBuilder result = new StringBuilder();
        String delimiter= "";
        for (String i : list) {
            result.append(delimiter).append(i);
            delimiter = ",";
        }
        return result.toString();

But what would be the best way to add support for unique only items? How can I return a string without any duplicates? I could remove duplication from list first but it feels like there is a better solution here.

Body:
The best to avoid duplicates is to use a Set

TreeSet for alphabetical order

LinkedHashSet to keep insertion order (initial order)

StringBuilder result = new StringBuilder();
String delimiter= "";
for (String i : new LinkedHashSet<String>(list)) {
    result.append(delimiter).append(i);
    delimiter = ",";
}
return result.toString();

But you can just do String.join(',', new LinkedHashSet<String>(list))

Back to List

List<String> inputList = (unique) ? new ArrayList<>(new HashSet<>(list)) : list;

Case-insensitive

Set<String> check = new HashSet<String>();
StringBuilder result = new StringBuilder();
String delimiter= "";
for (String i : list) {
    if(!check.contains(i.toLowerCase())){
        result.append(delimiter).append(i);
        delimiter = ",";
        check.add(i.toLowerCase());
    }
}
return result.toString();


问:
Spring boot: Inclusion of external jar dependency with scanBasePackages
I'll first describe the problem, files referenced here can be found below.

I am trying to use an external library in the form of a jar file. This library contains code that I use in my Spring @Configuration file. As such I have included it as an implementation dependency in my build.gradle (see code below).

All of the library files are contained in the package com.rusticisoftware.tincan. My own code resides under de.my.example.

Leaving the @SpringBootApplication at its default (which is the same as de.my.example as this is where the Application.java class resides works when assembling the project with the Gradle assemble task. I can then start the project from my IDE and everything works as expected.

However, both when running the Gradle test task and when executing the bootJar created by spring boot's bootJar task the following error is thrown:

```<code>    java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:798
            Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:656
                Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
                    Caused by: java.lang.NoClassDefFoundError at Config.java:29
                        Caused by: java.lang.ClassNotFoundException at BuiltinClassLoader.java:581
</code>```

Where Caused by: java.lang.NoClassDefFoundError at Config.java:29 is referencing this line in the code: RemoteLRS lrs = new RemoteLRS(); RemoteLRS is the class from the jar-library contained in com.rusticisoftware.tincan.

I was able to rid myself of this error by specifiying the scanBasePackages in the @SpringBootApplication annotation like so: @SpringBootApplication(scanBasePackages = {"com.rusticisoftware.tincan"}). Doing this will however then no longer scan and find MyResource.java leading the REST service to not load.

To fix this issue, I tried manually adding my own package to @SpringBootApplication together with the package from the jar, leading to this: @SpringBootApplication(scanBasePackages = {"com.rusticisoftware.tincan", "de.my.example"}).

This once again loads the REST service, but runs into the same problem as before when running the test task or executing the jar generated by the bootJar task. I have also manually inspected the generated bootJar and can confirm that the library jar is included within.

Project structure

```<code>Project
 |
 +-- build.gradle
 |
 +-- src
 |    |
 |    +-- main/java/
 |    |        |
 |    |        +-- de/my/example
 |    |                   |
 |    |                   +-- Application.java
 |    |                   |
 |    |                   +-- Config.java
 |    |                   |
 |    |                   +-- controller
 |    |                           |
 |    |                           +-- MyResource.java
 |    +-- test/java/
 |             |
 |             +-- de/my/example
 |                        |
 |                        +-- ApplicationTests.java
 +-- libs
      |
      +-- tincan-1.1.0.jar
</code>```

build.gradle

```<code>plugins {
    id "java"
    id "idea"
    id 'org.springframework.boot' version '2.3.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
}

// project settings
group 'de.my.example'
version '1.0'
sourceCompatibility = 11

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    // spring
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }

    // tin-can xAPI
    implementation files('libs/tincan-1.1.0.jar')
}

test {
    useJUnitPlatform()
}
</code>```

Application.java

```<code>@SpringBootApplication(scanBasePackages = {"com.rusticisoftware.tincan", "de.my.example"})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
</code>```

ApplicationTests.java

```<code>@SpringBootTest
class ApplicationTests {

    @Test
    void contextLoads() {
    }

}
</code>```

TestResource.java

```<code>public class TestResource {

    private final LearningRecordStore learningRecordStore;

    public TestResource(LearningRecordStore learningRecordStore) {
        this.learningRecordStore = learningRecordStore;
    }

    @GetMapping(value = "/ping", produces = MediaType.TEXT_PLAIN_VALUE)
    public String ping() {
        return "pong";
    }
}
</code>```

Config.java

```<code>@Configuration
public class Config {

    @Bean
    public LearningRecordStore learningData() {
        RemoteLRS lrs = new RemoteLRS();
        return new LearningRecordStore(lrs);
    }

}
</code>```

答: The simplest way to check is to explore build file after Gradle build to ensure it's present in build package. This way, you will make sure, it is getting included and should not throw class-not-found exception. Also, you might need to include both the packages in the scanBasePackage.</p>

Body:
I'll first describe the problem, files referenced here can be found below.

I am trying to use an external library in the form of a jar file. This library contains code that I use in my Spring @Configuration file. As such I have included it as an implementation dependency in my build.gradle (see code below).

All of the library files are contained in the package com.rusticisoftware.tincan. My own code resides under de.my.example.

Leaving the @SpringBootApplication at its default (which is the same as de.my.example as this is where the Application.java class resides works when assembling the project with the Gradle assemble task. I can then start the project from my IDE and everything works as expected.

However, both when running the Gradle test task and when executing the bootJar created by spring boot's bootJar task the following error is thrown:

    java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:798
            Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:656
                Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
                    Caused by: java.lang.NoClassDefFoundError at Config.java:29
                        Caused by: java.lang.ClassNotFoundException at BuiltinClassLoader.java:581

Where Caused by: java.lang.NoClassDefFoundError at Config.java:29 is referencing this line in the code: RemoteLRS lrs = new RemoteLRS(); RemoteLRS is the class from the jar-library contained in com.rusticisoftware.tincan.

I was able to rid myself of this error by specifiying the scanBasePackages in the @SpringBootApplication annotation like so: @SpringBootApplication(scanBasePackages = {"com.rusticisoftware.tincan"}). Doing this will however then no longer scan and find MyResource.java leading the REST service to not load.

To fix this issue, I tried manually adding my own package to @SpringBootApplication together with the package from the jar, leading to this: @SpringBootApplication(scanBasePackages = {"com.rusticisoftware.tincan", "de.my.example"}).

This once again loads the REST service, but runs into the same problem as before when running the test task or executing the jar generated by the bootJar task. I have also manually inspected the generated bootJar and can confirm that the library jar is included within.

Project structure

Project
 |
 +-- build.gradle
 |
 +-- src
 |    |
 |    +-- main/java/
 |    |        |
 |    |        +-- de/my/example
 |    |                   |
 |    |                   +-- Application.java
 |    |                   |
 |    |                   +-- Config.java
 |    |                   |
 |    |                   +-- controller
 |    |                           |
 |    |                           +-- MyResource.java
 |    +-- test/java/
 |             |
 |             +-- de/my/example
 |                        |
 |                        +-- ApplicationTests.java
 +-- libs
      |
      +-- tincan-1.1.0.jar

build.gradle

plugins {
    id "java"
    id "idea"
    id 'org.springframework.boot' version '2.3.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
}

// project settings
group 'de.my.example'
version '1.0'
sourceCompatibility = 11

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    // spring
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }

    // tin-can xAPI
    implementation files('libs/tincan-1.1.0.jar')
}

test {
    useJUnitPlatform()
}

Application.java

@SpringBootApplication(scanBasePackages = {"com.rusticisoftware.tincan", "de.my.example"})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

ApplicationTests.java

@SpringBootTest
class ApplicationTests {

    @Test
    void contextLoads() {
    }

}

TestResource.java

public class TestResource {

    private final LearningRecordStore learningRecordStore;

    public TestResource(LearningRecordStore learningRecordStore) {
        this.learningRecordStore = learningRecordStore;
    }

    @GetMapping(value = "/ping", produces = MediaType.TEXT_PLAIN_VALUE)
    public String ping() {
        return "pong";
    }
}

Config.java

@Configuration
public class Config {

    @Bean
    public LearningRecordStore learningData() {
        RemoteLRS lrs = new RemoteLRS();
        return new LearningRecordStore(lrs);
    }

}


问:
Passing Data from Delegate Swift Class to EnvironmentObject in SwiftUI Struct
How do I pass incoming data from a method triggered by a delegate in a Swift class to an EnvironmentObject?

I am aware that for this to work my Swift class needs to be called/initialized from the SwiftUI struct (be a child of the parent SwiftUI struct). However, I initialise my Swift class in the ExtensionDelegate of the Apple Watch app. I would like to see the UI Text element change when the name is updated.

The following code runs on the Apple Watch:

```<code>class User: ObservableObject {

    @Published var id: UUID?
    @Published var name: String?
}
</code>```
```<code>//SwiftUI struct
struct UI: View {

@EnvironmentObject var userEnv: User

var body: some View {
   Text(userEnv.name)
 }
}
</code>```
```<code>// Swift class
class WatchConnectivityProvider: NSObject, WCSessionDelegate {

 static let shared = WatchConnectivityProvider()
 private let session: WCSession

    init(session: WCSession = .default) {
        self.session = session
        super.init()
    }

    func activateSession() {
        if WCSession.isSupported() {
            session.delegate = self
            session.activate()
        }
    }

    //This func gets triggered when data is sent from the iPhone
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {

        let list = message["list"]

        let jsonDecoder = JSONDecoder()
        if let data = try? jsonDecoder.decode(User.self, from: list as! Data) {

        // !!! This is where I would like to update the EnvironmentObject userEnv !!!
        // What is the best way to do this? Remember, this class has already been initialised within the ExtensionDelegate.
        }
    }
}
</code>```
```<code>//ExtensionDelegate of Apple Watch app, initialising the WatchConnectivityProvider
class ExtensionDelegate: NSObject, WKExtensionDelegate {

    func applicationDidFinishLaunching() {
        // Perform any final initialization of your application.
        WatchConnectivityProvider.shared.activateSession()
    }
}
</code>```

答:
Dependency Injection

One of the solutions could be to store the reference to your @EnvironmentObject globally, eg. in some dependency container.

```<code>enum Dependencies {
    struct Name: Equatable {
        let rawValue: String
        static let `default` = Name(rawValue: "__default__")
        static func == (lhs: Name, rhs: Name) -> Bool { lhs.rawValue == rhs.rawValue }
    }

    final class Container {
        private var dependencies: [(key: Dependencies.Name, value: Any)] = []

        static let `default` = Container()

        func register(_ dependency: Any, for key: Dependencies.Name = .default) {
            dependencies.append((key: key, value: dependency))
        }

        func resolve<T>(_ key: Dependencies.Name = .default) -> T {
            return (dependencies
                .filter { (dependencyTuple) -> Bool in
                    return dependencyTuple.key == key
                        && dependencyTuple.value is T
                }
                .first)?.value as! T
        }
    }
}
</code>```

Then you create your object like this:

```<code>Dependencies.Container.default.register(User())
</code>```

And you can access it from anywhere in your code:

```<code>let user: User = Dependencies.Container.default.resolve()
user.modify()
</code>```

A more detailed explanation of Dependency Injection for Swift can be found here.

Singleton

Alternatively you can use standard Singleton pattern to make your User data available globally. A more detailed explanation can be found here.

Final thoughts

Clean Architecture for SwiftUI is a good example (in my opinion at least) of how to write an iOS app in the clean way. It's a little bit complicated, but you can pick up some parts.

Body:
How do I pass incoming data from a method triggered by a delegate in a Swift class to an EnvironmentObject?

I am aware that for this to work my Swift class needs to be called/initialized from the SwiftUI struct (be a child of the parent SwiftUI struct). However, I initialise my Swift class in the ExtensionDelegate of the Apple Watch app. I would like to see the UI Text element change when the name is updated.

The following code runs on the Apple Watch:

class User: ObservableObject {

    @Published var id: UUID?
    @Published var name: String?
}

//SwiftUI struct
struct UI: View {

@EnvironmentObject var userEnv: User

var body: some View {
   Text(userEnv.name)
 }
}

// Swift class
class WatchConnectivityProvider: NSObject, WCSessionDelegate {

 static let shared = WatchConnectivityProvider()
 private let session: WCSession

    init(session: WCSession = .default) {
        self.session = session
        super.init()
    }

    func activateSession() {
        if WCSession.isSupported() {
            session.delegate = self
            session.activate()
        }
    }

    //This func gets triggered when data is sent from the iPhone
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {

        let list = message["list"]

        let jsonDecoder = JSONDecoder()
        if let data = try? jsonDecoder.decode(User.self, from: list as! Data) {

        // !!! This is where I would like to update the EnvironmentObject userEnv !!!
        // What is the best way to do this? Remember, this class has already been initialised within the ExtensionDelegate.
        }
    }
}

//ExtensionDelegate of Apple Watch app, initialising the WatchConnectivityProvider
class ExtensionDelegate: NSObject, WKExtensionDelegate {

    func applicationDidFinishLaunching() {
        // Perform any final initialization of your application.
        WatchConnectivityProvider.shared.activateSession()
    }
}

Body:
Dependency Injection

One of the solutions could be to store the reference to your @EnvironmentObject globally, eg. in some dependency container.

enum Dependencies {
    struct Name: Equatable {
        let rawValue: String
        static let `default` = Name(rawValue: "__default__")
        static func == (lhs: Name, rhs: Name) -> Bool { lhs.rawValue == rhs.rawValue }
    }

    final class Container {
        private var dependencies: [(key: Dependencies.Name, value: Any)] = []

        static let `default` = Container()

        func register(_ dependency: Any, for key: Dependencies.Name = .default) {
            dependencies.append((key: key, value: dependency))
        }

        func resolve<T>(_ key: Dependencies.Name = .default) -> T {
            return (dependencies
                .filter { (dependencyTuple) -> Bool in
                    return dependencyTuple.key == key
                        && dependencyTuple.value is T
                }
                .first)?.value as! T
        }
    }
}

Then you create your object like this:

Dependencies.Container.default.register(User())

And you can access it from anywhere in your code:

let user: User = Dependencies.Container.default.resolve()
user.modify()

A more detailed explanation of Dependency Injection for Swift can be found here.

Singleton

Alternatively you can use standard Singleton pattern to make your User data available globally. A more detailed explanation can be found here.

Final thoughts

Clean Architecture for SwiftUI is a good example (in my opinion at least) of how to write an iOS app in the clean way. It's a little bit complicated, but you can pick up some parts.


问:
Redistributing files in a folder
I need to do some job with my files and the steps are as follow:

Delete from the selection all folders where there is a mention of test in json.json file

Delete folders without wav files

I have written the below script and don't understand why it doesn't echo for empty directory?

#!/bin/bash

for obj in rom/*; do

        if [ -d "$obj" ]; then

              if
                 grep -w test $obj/*.json; then
                 echo $PWD/$obj
                 rm -rf $PWD/$obj
              fi

              if
                  find $obj -type f -name "*.wav"; then
                  echo "ok"
               else
                  echo "In this dir you haven't .wav files"
#                 rm -rf $PWD/$obj
              fi
        fi

done
```

答:
I written like this</p>

```<code>#!/bin/bash

for obj in folder/*; do

        if [ -d "$obj" ]; then

              if
                 grep -w test $obj/*.json &>/dev/null; then
                 rm -rf $PWD/$obj
              fi
        fi
done

for obj in folder/*; do

         if [ -d "$obj" ]; then
             if
                 ls $obj/*.wav &>/dev/null; then
                   echo "" &>/dev/null
                 else
                   rm -rf $obj
             fi
         fi

done
</code>```

Title: Redistributing files in a folder

Body:
I written like this

#!/bin/bash

for obj in folder/*; do

        if [ -d "$obj" ]; then

              if
                 grep -w test $obj/*.json &>/dev/null; then
                 rm -rf $PWD/$obj
              fi
        fi
done

for obj in folder/*; do

         if [ -d "$obj" ]; then
             if
                 ls $obj/*.wav &>/dev/null; then
                   echo "" &>/dev/null
                 else
                   rm -rf $obj
             fi
         fi

done


问:
State list of world with country-code
Where can I found the list of all the states of world with their country code (ISO2 or ISO3).

I have to insert all these states in my database. If the list is available in the .sql will be great.

I need state list of world with country-code not the country list.

Do you know where can I found?

Thanks in Advance.

答:
Search google for: php country abbreviations list

Here's the first link: http://27.org/isocountrylist/

Title: State list of world with country-code


问:
What should a Traversable instance look like for a Tree datatype with a nested Maybe value?
I have a Haskell exam in three days, so I thought I should practice a little and pulled up past exams, one of which features the following Tree datatype:

```<code>data Tree a = Leaf1 a | Leaf2 a a | Node (Tree a) (Maybe (Tree a)) deriving (Eq, Ord, Show)
</code>```

It didn't seem that challenging at first, but then I realized I have to write a Traversable instance for this Tree. Dealing with the leaves were easy enough:

```<code>instance Traversable Tree where
  traverse f (Leaf1 a)   = Leaf1 <$> f a
  traverse f (Leaf2 a b) = Leaf2 <$> f a <*> f b
</code>```

However, I started running into problems with the Node.

```<code>  traverse f (Node t Nothing)  = Node <$> traverse f t <*> Nothing
  traverse f (Node l (Just r)) = Node <$> traverse f l <*> Just (traverse f r)
</code>```

Naturally, these don't work, and I can't wrap my head around what should come after the second <*>. I tried using holes, but the messages given to me by ghci didn't help much (I get that the problem is with types, but I have no idea how I'm supposed to fix it).

Here's the error message I got when I tried to compile it:

```<code>* Couldn't match type `f' with `Maybe'
  `f' is a rigid type variable bound by
    the type signature for:
      traverse :: forall (f :: * -> *) a b.
                  Applicative f =>
                  (a -> f b) -> Tree a -> f (Tree b)
    at exam.hs:92:3-10
  Expected type: f (Maybe (Tree b))
    Actual type: Maybe (Maybe (Tree b))
* In the second argument of `(<*>)', namely `Nothing'
  In the expression: Node <$> traverse f t <*> Nothing
  In an equation for `traverse':
      traverse f (Node t Nothing) = Node <$> traverse f t <*> Nothing
* Relevant bindings include
    f :: a -> f b (bound at exam.hs:94:12)
    traverse :: (a -> f b) -> Tree a -> f (Tree b)
      (bound at exam.hs:92:3)
   |
94 |   traverse f (Node t Nothing)  = Node <$> traverse f t <*> Nothing
   |                                                            ^^^^^^^
</code>```

Could someone please give me some pointers or a possible fix for this issue?

答:
traverse lets you apply a "function with an effect" to every "slot" of a data structure, maintaining the structure's shape. It has the type:

```<code>traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
</code>```

It relies crucially on the fact that the type of the "effects" is an Applicative. What operations does Applicatve provide?

it lets us lift pure functions and apply them to effectful actions with <$>.

it lets us combine effectful actions with (<*>) :: f (a -> b) -> f a -> f b. Notice that the second parameter is an effectful action, not a pure value.

it lets us take any pure value and put it in an effectful context, using pure :: a -> f a.

Now, when the node has a Nothing, there's no effect to perform because there aren't any values, but the <*> still requires an effectful action on the right. We can use pure Nothing to make the types fit.

When the node has a Just t, we can traverse the subtree t of type Tree a with the function a -> f b and end up with an action f (Tree b). But the <*> is actually expecting an f (Maybe (Tree b)). The lifted Node constructor makes us expect that. What can we do?

The solution is to lift the Just constructor into the action using <$>, which is another name for fmap.

Notice that we haven't changed the overall "shape" of the value: the Nothing is still Nothing, the Just is still Just. The structure of the subtrees didn't change either: we traversed them recursively but didn't modify them otherwise.

Body:
I have a Haskell exam in three days, so I thought I should practice a little and pulled up past exams, one of which features the following Tree datatype:

data Tree a = Leaf1 a | Leaf2 a a | Node (Tree a) (Maybe (Tree a)) deriving (Eq, Ord, Show)

It didn't seem that challenging at first, but then I realized I have to write a Traversable instance for this Tree. Dealing with the leaves were easy enough:

instance Traversable Tree where
  traverse f (Leaf1 a)   = Leaf1 <$> f a
  traverse f (Leaf2 a b) = Leaf2 <$> f a <*> f b

However, I started running into problems with the Node.

  traverse f (Node t Nothing)  = Node <$> traverse f t <*> Nothing
  traverse f (Node l (Just r)) = Node <$> traverse f l <*> Just (traverse f r)

Naturally, these don't work, and I can't wrap my head around what should come after the second <*>. I tried using holes, but the messages given to me by ghci didn't help much (I get that the problem is with types, but I have no idea how I'm supposed to fix it).

Here's the error message I got when I tried to compile it:

* Couldn't match type `f' with `Maybe'
  `f' is a rigid type variable bound by
    the type signature for:
      traverse :: forall (f :: * -> *) a b.
                  Applicative f =>
                  (a -> f b) -> Tree a -> f (Tree b)
    at exam.hs:92:3-10
  Expected type: f (Maybe (Tree b))
    Actual type: Maybe (Maybe (Tree b))
* In the second argument of `(<*>)', namely `Nothing'
  In the expression: Node <$> traverse f t <*> Nothing
  In an equation for `traverse':
      traverse f (Node t Nothing) = Node <$> traverse f t <*> Nothing
* Relevant bindings include
    f :: a -> f b (bound at exam.hs:94:12)
    traverse :: (a -> f b) -> Tree a -> f (Tree b)
      (bound at exam.hs:92:3)
   |
94 |   traverse f (Node t Nothing)  = Node <$> traverse f t <*> Nothing
   |                                                            ^^^^^^^

Could someone please give me some pointers or a possible fix for this issue?

Body:
traverse lets you apply a "function with an effect" to every "slot" of a data structure, maintaining the structure's shape. It has the type:

traverse :: Applicative f => (a -> f b) -> t a -> f (t b)

It relies crucially on the fact that the type of the "effects" is an Applicative. What operations does Applicatve provide?

it lets us lift pure functions and apply them to effectful actions with <$>.

it lets us combine effectful actions with (<*>) :: f (a -> b) -> f a -> f b. Notice that the second parameter is an effectful action, not a pure value.

it lets us take any pure value and put it in an effectful context, using pure :: a -> f a.

Now, when the node has a Nothing, there's no effect to perform because there aren't any values, but the <*> still requires an effectful action on the right. We can use pure Nothing to make the types fit.

When the node has a Just t, we can traverse the subtree t of type Tree a with the function a -> f b and end up with an action f (Tree b). But the <*> is actually expecting an f (Maybe (Tree b)). The lifted Node constructor makes us expect that. What can we do?

The solution is to lift the Just constructor into the action using <$>, which is another name for fmap.

Notice that we haven't changed the overall "shape" of the value: the Nothing is still Nothing, the Just is still Just. The structure of the subtrees didn't change either: we traversed them recursively but didn't modify them otherwise.


问:
GraphQL schema - is it possible to set constraints on a custom type field
Here is a simplified snippet out of a GraphQL Schema I work with. There are - an enum, type Contributor and type Review.

```<code>enum CONTRIBUTOR_TYPE {
  AUTHOR
  EDITOR
}

type Contributor {
  name: String
  role: CONTRIBUTOR_TYPE
}

type Article {
  text: String
  authors: [Contributor]
}
</code>```

What I want to describe, is that the "authors" field is not just array of type Contributor, but Contributor with specific job role.  In pseudocode it would look like

```<code> authors: [Contributor{type: CONTRIBUTOR_TYPE.AUTHOR}]!
</code>```

Is there a way to describe this constraint in GraphQL Schema?

答: You should be able to use schema directives to describe / enforce the constraint.  For apollo server check out https://www.apollographql.com/docs/apollo-server/schema/creating-directives/, for graphql-java check out https://www.graphql-java.com/documentation/v15/sdl-directives/, for other server implementations check their corresponding documentation.  </p>

Body:
Here is a simplified snippet out of a GraphQL Schema I work with. There are - an enum, type Contributor and type Review.

enum CONTRIBUTOR_TYPE {
  AUTHOR
  EDITOR
}

type Contributor {
  name: String
  role: CONTRIBUTOR_TYPE
}

type Article {
  text: String
  authors: [Contributor]
}

What I want to describe, is that the "authors" field is not just array of type Contributor, but Contributor with specific job role.  In pseudocode it would look like

 authors: [Contributor{type: CONTRIBUTOR_TYPE.AUTHOR}]!

Is there a way to describe this constraint in GraphQL Schema?


问:
What is the difference using NOP and stalls in MIPS
What difference does it make to use NOP instead of stall.
Both happen to do the same task in case of pipelining. I cant understand</p>

答:
We should not use NOP in place of the stall and vice-versa.

We will use the stall when there is a dependency causing hazard which results in the particular stage of the pipeline to wait until it gets the data required whereas by using NOP in case of stall it will just pass that stage of the instruction without doing anything. However, after the completion of the stage by using NOP the data required by the stage is available and we need to start the instruction from the beginning which will increase the average CPI of the processor results in performance reduction. Also, in some cases the data required by that instruction might be modified by another instruction before restarting the instruction which will result in faulty execution.

Also, in the same way if we use the stall in the place of the NOP.
whenever a non-mask-able interrupt occurs like (divide by zero) in execution stage we need to pass the stages after the exception without changing the state of the processor here we use NOP to pass the remaining stages of the pipeline without any changes to the processor state (like writing something into the register or the memory which is a false value generated to the exception).

Here, we cannot use stall because the next instruction will wait for the stall to be completed and the stall will not be completed as it is a non-mask-able interrupt (user cannot control these type of instructions) and the pipeline enters deadlock.


问:
Errors when running "network.sh up" with Hyperledger Fabric Samples in test-network
I met errors when setting up blockchain network(test network) using Hyperledger Fabric Sample.
Actually, when I run the scripts ./network.sh up, the docker images start but immediately shut down. And I check the logs found some errors reported.
And here are my errors shown:

1. when setting orderer：

2020-06-01 06:43:02.784 UTC [orderer.common.server] loadLocalMSP -> PANI 004 Failed to setup local msp with config: KeyMaterial not found in SigningIdentityInfo

panic: Failed to setup local msp with config: KeyMaterial not found in SigningIdentityInfo

goroutine 1 [running]:

github.com/hyperledger/fabric/vendor/go.uber.org/zap/zapcore.(*CheckedEntry).Write(0xc000254dc0, 0x0, 0x0, 0x0)

/go/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/zapcore/entry.go:229 +0x546

github.com/hyperledger/fabric/vendor/go.uber.org/zap.(*SugaredLogger).log(0xc00010e338, 0xc000094904, 0x1066d69, 0x29, 0xc00029f610, 0x1, 0x1, 0x0, 0x0, 0x0)

/go/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/sugar.go:234 +0x100

github.com/hyperledger/fabric/vendor/go.uber.org/zap.(*SugaredLogger).Panicf(...)

/go/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/sugar.go:159

github.com/hyperledger/fabric/common/flogging.(*FabricLogger).Panicf(...)

/go/src/github.com/hyperledger/fabric/common/flogging/zap.go:74

github.com/hyperledger/fabric/orderer/common/server.loadLocalMSP(0xc00019a480, 0xc00026fe50, 0x0)

/go/src/github.com/hyperledger/fabric/orderer/common/server/main.go:677 +0x314

github.com/hyperledger/fabric/orderer/common/server.Main()

/go/src/github.com/hyperledger/fabric/orderer/common/server/main.go:91 +0x232

main.main()

/go/src/github.com/hyperledger/fabric/cmd/orderer/main.go:15 +0x20

2. when setting up peers:

2020-06-01 06:43:02.778 UTC [main] InitCmd -> ERRO 001 Cannot run peer because error when setting up MSP of type bccsp from directory /etc/hyperledger/fabric/msp: KeyMaterial not found in SigningIdentityInfo

is there anyone that may be able to help solve the problems?

best regards

答:
Seems like you have not set the right PATH. Set the Correct path of Go in environment variable.</p>

```<code>sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt-get update
sudo apt-get install -y golang-go make
cd $GOPATH/src/github.com/hyperledger/fabric
make docker
</code>```

Body:
Seems like you have not set the right PATH. Set the Correct path of Go in environment variable.

sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt-get update
sudo apt-get install -y golang-go make
cd $GOPATH/src/github.com/hyperledger/fabric
make docker


问:
Python checking if all item in nested list are the same
Simple question how would you find that all the elements in a nested list are equal to 0 or specific value
my code goes like this

```<code>a = [[0,0,0],[0,0,0]]
def checkall(a):
    zeros = 0
    for i in a:
        for b in i:
            if b==0:
                zeros+=1
            else:
                break
</code>```

is there any other better way to do this? without importing any libraries

答:
You could use list comprehension:

```<code>b = [True if d==0 else False for i in a for d in i]
all(b)
</code>```

The first line creates a list of boolean values (True if the element is zero, False otherwise). Then the second line checks if all the list consists of True values.

Body:
Simple question how would you find that all the elements in a nested list are equal to 0 or specific value
my code goes like this

a = [[0,0,0],[0,0,0]]
def checkall(a):
    zeros = 0
    for i in a:
        for b in i:
            if b==0:
                zeros+=1
            else:
                break

is there any other better way to do this? without importing any libraries

Body:
You could use list comprehension:

b = [True if d==0 else False for i in a for d in i]
all(b)

The first line creates a list of boolean values (True if the element is zero, False otherwise). Then the second line checks if all the list consists of True values.


问:
Is it possible to do load testing with Selenium with many instances of cloud-based virtual machines?
Suppose we have a simple Selenium script where the tool queries a website's search field and records the response time. </p>

<p>Would it be possible to have 100*n virtual machines replicate this same action simultaneously, and record their respective response times? Our end-goal is to determine at what user count the response time begins to slow significantly. </p>

答:
Up to certain extent you can perform load testing using Selenium via i.e. Selenium Grid or your client programming language multi-threading features however it's not the best idea.

I would rather recommend converting your Selenium tests into load tests, for example if you set your Selenium tests to use i.e. Apache JMeter's HTTP(S) Test Script Recorder as the proxy and run your tests JMeter will capture the HTTP requests made by the browser and create HTTP Request samplers out of it.

Most probably you will need to perform the correlation of dynamic parameters and parameterization of the requests (i.e. each virtual user should have its own credentials, etc.) but on the other hand you will get nice looking HTML report and will be able to simulate your 100 users (in fact much more) from only one mid-range modern computer

Body:
Suppose we have a simple Selenium script where the tool queries a website's search field and records the response time.

Would it be possible to have 100*n virtual machines replicate this same action simultaneously, and record their respective response times? Our end-goal is to determine at what user count the response time begins to slow significantly.


问:
swapon: /swapfile: swapon failed: Function not implemented When enabling swap
I tried to enable swap according to this website: https://linuxize.com/post/create-a-linux-swap-file/

When I ran sudo swapon /swapfile, it returned this error:

swapon: /swapfile: swapon failed: Function not implemented

答:
It looks like CONFIG_SWAP is not enabled in the kernel you are using.
Please enable it and try.</p>


问:
How do I avoid "Access Violation" during asynchronous database connections?

Goal: Using ExecuteAsync correctly.

I know my application itself is at least pretty close to correct because it executes correctly once, so I know I can eliminate the usual suspects of firewalls, wrong database passwords, procedure names, etc.

```<code>private async Task<T> executeAsyncHelper<T>(Func<IDataReader, T> then)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(name, conn))
        {
            parameters.Select(p => cmd.Parameters.Add(p))
                .ToImmutableList();
            cmd.CommandType = CommandType.StoredProcedure;
            using (IDataReader rdr = await cmd.ExecuteReaderAsync())
            {
                return then(rdr);
            }
        }
    }
}
</code>```

The Issue: Access Violation on the Second SqlConnection.Open()

The method gets called twice on the same procedure. The first time, it successfully updates the database. The second time, the whole thing dumps out on conn.Open() with "Access violation." Importantly, it's not throwing an exception. Rather, the whole debugger exits with a negative status code.

These are the last two lines of the debugger output (The rest of the debugger output looks normal):

```<code>The program '[6904] dotnet.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
The program '[6904] dotnet.exe: Program Trace' has exited with code 0 (0x0).
</code>```

This behavior is 100% repeatable.

Hypothesis: Connection Pooling and Asynchronicity

As far as I can see, the most probable cause is that there's some problem with opening two connections asynchronously, but I don't immediately know what to do with that hypothesis. I've written the method as safely as I know how.

Secondarily, I checked to see if my Azure SQL Server instance had any unusual limitations on it. It's a basic instance, but I doubt that's the issue since I would expect a SQL exception (that the debugger will break on and show a normal stack trace) if that were the problem.

Environmental information

Azure SQL Server 2016

Windows 10

.NET Core 2.1

Visual Studio 2017

Conclusion

Does anyone see any problem with the way I've implemented this or have any suggestions to learn more about the error?

答:
Try this:

```<code>private async Task<T> executeAsyncHelper<T>(Func<IDataReader, Task<T>> then)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(name, conn))
        {
            parameters.Select(p => cmd.Parameters.Add(p))
                .ToImmutableList();
            cmd.CommandType = CommandType.StoredProcedure;
            using (IDataReader rdr = await cmd.ExecuteReaderAsync())
            {
                return await then(rdr);
            }
        }
    }
}
</code>```

Note the changes to the signature, and awaiting on return.

Body:
Goal: Using ExecuteAsync correctly.

I know my application itself is at least pretty close to correct because it executes correctly once, so I know I can eliminate the usual suspects of firewalls, wrong database passwords, procedure names, etc.

private async Task<T> executeAsyncHelper<T>(Func<IDataReader, T> then)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(name, conn))
        {
            parameters.Select(p => cmd.Parameters.Add(p))
                .ToImmutableList();
            cmd.CommandType = CommandType.StoredProcedure;
            using (IDataReader rdr = await cmd.ExecuteReaderAsync())
            {
                return then(rdr);
            }
        }
    }
}

The Issue: Access Violation on the Second SqlConnection.Open()

The method gets called twice on the same procedure. The first time, it successfully updates the database. The second time, the whole thing dumps out on conn.Open() with "Access violation." Importantly, it's not throwing an exception. Rather, the whole debugger exits with a negative status code.

These are the last two lines of the debugger output (The rest of the debugger output looks normal):

The program '[6904] dotnet.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
The program '[6904] dotnet.exe: Program Trace' has exited with code 0 (0x0).

This behavior is 100% repeatable.

Hypothesis: Connection Pooling and Asynchronicity

As far as I can see, the most probable cause is that there's some problem with opening two connections asynchronously, but I don't immediately know what to do with that hypothesis. I've written the method as safely as I know how.

Secondarily, I checked to see if my Azure SQL Server instance had any unusual limitations on it. It's a basic instance, but I doubt that's the issue since I would expect a SQL exception (that the debugger will break on and show a normal stack trace) if that were the problem.

Environmental information

Azure SQL Server 2016

Windows 10

.NET Core 2.1

Visual Studio 2017

Conclusion

Does anyone see any problem with the way I've implemented this or have any suggestions to learn more about the error?

Body:
Try this:

private async Task<T> executeAsyncHelper<T>(Func<IDataReader, Task<T>> then)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(name, conn))
        {
            parameters.Select(p => cmd.Parameters.Add(p))
                .ToImmutableList();
            cmd.CommandType = CommandType.StoredProcedure;
            using (IDataReader rdr = await cmd.ExecuteReaderAsync())
            {
                return await then(rdr);
            }
        }
    }
}

Note the changes to the signature, and awaiting on return.


问:
IBM MQ CLOUD CONNECTION
I am trying to setup ssl/tls between the app and the cloud following this https://cloud.ibm.com/docs/mqcloud?topic=mqcloud-mqoc_jms_tls.

When the sslauth is set to optional on the cloud mq app channel CLOUD.APP.SVRCONN I am able to send and receive message.

Ii downloaded the certificate and added it to a trust store using the following command.

```<code>keytool -importcert -alias DigiCertRootCA -file qmgrcert.pem -keystore truststore.jks
</code>```

I am passing this to the connection factory through sslcontext. (note that this whole setup worked with docker instance of ibmmq)

The code i am trying this with is the following..

```<code>            // Load in the keystore for SSL certificates
            FileInputStream keyStoreInputStream = new FileInputStream("/other/dev/MQ/keystore.jks");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(keyStoreInputStream, ("changeit").toCharArray());

            keyStoreInputStream.close();

            // Create a keyManager that can select the certificate with the correct alias
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, ("changeit").toCharArray());
            // final X509KeyManager defaultKm = (X509KeyManager)keyManagerFactory.getKeyManagers()[0];
            // X509KeyManager aliasKeyManager = new AliasKeyManagerWrapper(defaultKm, "server-certificate");

            // Create an SSLSocketFactory
            FileInputStream myKeys = new FileInputStream("truststore.jks");

            // Do the same with your trust store this time
            // Adapt how you load the keystore to your needs
            KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            myTrustStore.load(myKeys, "changeit".toCharArray());

            myKeys.close();
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(myTrustStore);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

            // Get an SSLSocketFactory to pass to WMQ
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            MQConnectionFactory cf = new MQConnectionFactory();
            // set "client" connection mode for remote queue manager, as opposed to attempting to connect to a local queue manager
            cf.setTransportType(WMQConstants.WMQ_CM_CLIENT);

            cf.setSSLSocketFactory(sslSocketFactory);
</code>```

I get the following error:

```<code>yatish.kadam@YKADAM-LT01:/other/dev/MQ$ java -Dcom.ibm.mq.cfg.useIBMCipherMappings=false -cp ./com.ibm.mq.allclient-9.1.4.0.jar:./javax.jms-api-2.0.1.jar:. com.ibm.mq.samples.jms.JmsPutGet
com.ibm.msg.client.jms.DetailedIllegalStateRuntimeException: JMSWMQ0018: Failed to connect to queue manager 'removed' with connection mode 'Client' and host name 'host name removed(31201)'.
Check the queue manager is started and if running in client mode, check there is a listener running. Please see the linked exception for more information.
</code>```

I use oracle java.. 1.8 ..
ibmmq version9...

The command i use to run the program...

```<code>java -Dcom.ibm.mq.cfg.useIBMCipherMappings=false -cp ./com.ibm.mq.allclient-9.1.4.0.jar:./javax.jms-api-2.0.1.jar:. com.ibm.mq.samples.jms.JmsPutGet
</code>```

error on the ibmmq

```<code>----- amqrmrsa.c : 961 --------------------------------------------------------
05/31/20 18:57:58 - Process(984.8768) User(mqm) Program(amqrmppa)
                    Host() Installation(Installation1)
                    VRMF(9.1.5.0) QMgr()
                    Time(2020-05-31T18:57:58.942Z)
                    RemoteHost()
                    ArithInsert1(414)
                    CommentInsert1(????)
                    CommentInsert2(????)
                    CommentInsert3()

AMQ9633E: Bad SSL certificate for channel '????'.
EXPLANATION:
A certificate encountered during SSL handshaking is regarded as bad for one of
the following reasons:
(a) it was formatted incorrectly and could not be validated
(b) it was formatted correctly but failed validation against the Certification
  Authority (CA) root and other certificates held on the local system
(c) it was found in a Certification Revocation List (CRL) on an LDAP server
(d) a CRL was specified but the CRL could not be found on the LDAP server
(e) an OCSP responder has indicated that it is revoked
The channel is '????'; in some cases its name cannot be determined and so is
shown as '????'. The remote host is ''. The channel did not start.
The details of the certificate which could not be validated are '????'.
The certificate validation error was 0.
ACTION:
Check which of the possible causes applies on your system. Correct the error,
and restart the channel.
This error might indicate that the remote end of the channel is configured to
send the wrong certificate. Check the certificate label configuration at the
remote end of the channel and ensure that the local key repository contains all
of the necessary CA certificates.
----- amqccisa.c : 8421 ---------------------------
</code>```

The key store contents:

```<code>Keystore type: jks
Keystore provider: SUN

Your keystore contains 3 entries

digicertrootca, May 31, 2020, trustedCertEntry,
Certificate fingerprint (SHA1): 1F:B8:6B:11:68:EC:74:31:54:06:2E:8C:9C:C5:B1:71:A4:B7:CC:B4
digicertrootca11, May 31, 2020, trustedCertEntry,
Certificate fingerprint (SHA1): 26:26:F7:42:08:95:39:27:8D:66:B6:51:49:12:D3:93:CA:2E:E1:9E
digicertrootca3, May 31, 2020, trustedCertEntry,
Certificate fingerprint (SHA1): A8:98:5D:3A:65:E5:E5:C4:B2:D7:D6:6D:40:C6:DD:2F:B1:9C:54:36
</code>```

答:
@joshmc Thanks..
Finally got it working..
The client key that is created needs to be with specific algorithm SHA256withRSA.

the link to the source i found..
Digital certificates and CipherSpec compatibility in IBM MQ

use the following to create a new self signed cert..

```<code>keytool -genkey -alias clientcert -keyalg RSA -sigalg SHA256withRSA -keysize 2048 -validity 3650 -keystore keystore.jks
</code>```

Title: IBM MQ CLOUD CONNECTION

Body:
I am trying to setup ssl/tls between the app and the cloud following this https://cloud.ibm.com/docs/mqcloud?topic=mqcloud-mqoc_jms_tls.

When the sslauth is set to optional on the cloud mq app channel CLOUD.APP.SVRCONN I am able to send and receive message.

Ii downloaded the certificate and added it to a trust store using the following command.

keytool -importcert -alias DigiCertRootCA -file qmgrcert.pem -keystore truststore.jks

I am passing this to the connection factory through sslcontext. (note that this whole setup worked with docker instance of ibmmq)

The code i am trying this with is the following..

            // Load in the keystore for SSL certificates
            FileInputStream keyStoreInputStream = new FileInputStream("/other/dev/MQ/keystore.jks");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(keyStoreInputStream, ("changeit").toCharArray());

            keyStoreInputStream.close();

            // Create a keyManager that can select the certificate with the correct alias
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, ("changeit").toCharArray());
            // final X509KeyManager defaultKm = (X509KeyManager)keyManagerFactory.getKeyManagers()[0];
            // X509KeyManager aliasKeyManager = new AliasKeyManagerWrapper(defaultKm, "server-certificate");

            // Create an SSLSocketFactory
            FileInputStream myKeys = new FileInputStream("truststore.jks");

            // Do the same with your trust store this time
            // Adapt how you load the keystore to your needs
            KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            myTrustStore.load(myKeys, "changeit".toCharArray());

            myKeys.close();
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(myTrustStore);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

            // Get an SSLSocketFactory to pass to WMQ
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            MQConnectionFactory cf = new MQConnectionFactory();
            // set "client" connection mode for remote queue manager, as opposed to attempting to connect to a local queue manager
            cf.setTransportType(WMQConstants.WMQ_CM_CLIENT);

            cf.setSSLSocketFactory(sslSocketFactory);

I get the following error:

yatish.kadam@YKADAM-LT01:/other/dev/MQ$ java -Dcom.ibm.mq.cfg.useIBMCipherMappings=false -cp ./com.ibm.mq.allclient-9.1.4.0.jar:./javax.jms-api-2.0.1.jar:. com.ibm.mq.samples.jms.JmsPutGet
com.ibm.msg.client.jms.DetailedIllegalStateRuntimeException: JMSWMQ0018: Failed to connect to queue manager 'removed' with connection mode 'Client' and host name 'host name removed(31201)'.
Check the queue manager is started and if running in client mode, check there is a listener running. Please see the linked exception for more information.

I use oracle java.. 1.8 ..
ibmmq version9...

The command i use to run the program...

java -Dcom.ibm.mq.cfg.useIBMCipherMappings=false -cp ./com.ibm.mq.allclient-9.1.4.0.jar:./javax.jms-api-2.0.1.jar:. com.ibm.mq.samples.jms.JmsPutGet

error on the ibmmq

----- amqrmrsa.c : 961 --------------------------------------------------------
05/31/20 18:57:58 - Process(984.8768) User(mqm) Program(amqrmppa)
                    Host() Installation(Installation1)
                    VRMF(9.1.5.0) QMgr()
                    Time(2020-05-31T18:57:58.942Z)
                    RemoteHost()
                    ArithInsert1(414)
                    CommentInsert1(????)
                    CommentInsert2(????)
                    CommentInsert3()

AMQ9633E: Bad SSL certificate for channel '????'.
EXPLANATION:
A certificate encountered during SSL handshaking is regarded as bad for one of
the following reasons:
(a) it was formatted incorrectly and could not be validated
(b) it was formatted correctly but failed validation against the Certification
  Authority (CA) root and other certificates held on the local system
(c) it was found in a Certification Revocation List (CRL) on an LDAP server
(d) a CRL was specified but the CRL could not be found on the LDAP server
(e) an OCSP responder has indicated that it is revoked
The channel is '????'; in some cases its name cannot be determined and so is
shown as '????'. The remote host is ''. The channel did not start.
The details of the certificate which could not be validated are '????'.
The certificate validation error was 0.
ACTION:
Check which of the possible causes applies on your system. Correct the error,
and restart the channel.
This error might indicate that the remote end of the channel is configured to
send the wrong certificate. Check the certificate label configuration at the
remote end of the channel and ensure that the local key repository contains all
of the necessary CA certificates.
----- amqccisa.c : 8421 ---------------------------

The key store contents:

Keystore type: jks
Keystore provider: SUN

Your keystore contains 3 entries

digicertrootca, May 31, 2020, trustedCertEntry,
Certificate fingerprint (SHA1): 1F:B8:6B:11:68:EC:74:31:54:06:2E:8C:9C:C5:B1:71:A4:B7:CC:B4
digicertrootca11, May 31, 2020, trustedCertEntry,
Certificate fingerprint (SHA1): 26:26:F7:42:08:95:39:27:8D:66:B6:51:49:12:D3:93:CA:2E:E1:9E
digicertrootca3, May 31, 2020, trustedCertEntry,
Certificate fingerprint (SHA1): A8:98:5D:3A:65:E5:E5:C4:B2:D7:D6:6D:40:C6:DD:2F:B1:9C:54:36

Body:
@joshmc Thanks..
Finally got it working..
The client key that is created needs to be with specific algorithm SHA256withRSA.

the link to the source i found..
Digital certificates and CipherSpec compatibility in IBM MQ

use the following to create a new self signed cert..

keytool -genkey -alias clientcert -keyalg RSA -sigalg SHA256withRSA -keysize 2048 -validity 3650 -keystore keystore.jks


答:
You could try this:

```<code>def checkNested(ls,n):
    total = 0
    for i in ls:
        total += i.count(n)
    return total
</code>```

Where ln is the list (must have nested lists) and n is the number you are checking. It returns the total n's found in your nested lists. checkNested([[0,0,0],[0,0,0]]) returns 6.

Title: Python checking if all item in nested list are the same

Body:
You could try this:

def checkNested(ls,n):
    total = 0
    for i in ls:
        total += i.count(n)
    return total

Where ln is the list (must have nested lists) and n is the number you are checking. It returns the total n's found in your nested lists. checkNested([[0,0,0],[0,0,0]]) returns 6.


问:
Store String variable to String Array
this like a string array {hi, hi, hello}, but if I have a string that is shaped like that, can i do this by entering a string variable into the string array ?

like this:

String animal = "kangaroo, rabbit, dog, cat, elephant";

String[] array = { animal };

the result is:

array[0] : kangaroo

array[1] : rabbit

答:
```<code>   String animal = "kangaroo, rabbit, dog, cat, elephant";
   String[] array = animal.split(", ");
   System.out.println(Arrays.toString(array));
</code>```

Title: Store String variable to String Array


问:
Can't create handler inside thread that has not called Looper.prepare()
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

```<code>public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });
</code>```

StartPayment Method:

```<code>    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}
</code>```

答:
I've found that most thread handling can be replaced by AsyncTasks like this:

```<code>public class TestStuff extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonBank = (Button) findViewById(R.id.button);
        buttonBank.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new StartPaymentAsyncTask(TestStuff.this).execute((Void []) null);
            }
        });
    }

    private class StartPaymentAsyncTask extends AsyncTask<Void, Void, String> {
        private ProgressDialog dialog;
        private final Context context;

        public StartPaymentAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(context);
            // setup your dialog here
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setMessage(context.getString(R.string.doing_db_work));
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected String doInBackground(Void... ignored) {
            String returnMessage = null;
            try {
                startPayment("Bank");
            } catch (Exception e) {
                returnMessage = e.getMessage();
            }
            return returnMessage;
        }

        @Override
        protected void onPostExecute(String message) {
            dialog.dismiss();
            if (message != null) {
                // process the error (show alert etc)
                Log.e("StartPaymentAsyncTask", String.format("I received an error: %s", message));
            } else {
                Log.i("StartPaymentAsyncTask", "No problems");
            }
        }
    }

    public void startPayment(String string) throws Exception {
        SystemClock.sleep(2000); // pause for 2 seconds for dialog
        Log.i("PaymentStuff", "I am pretending to do some work");
        throw new Exception("Oh dear, database error");
    }
}
</code>```

I pass in the Application Context to the Async so it can create dialogs from it.

The advantage of doing it this way is you know exactly which methods are run in your UI and which are in a separate background thread. Your main UI thread isn't delayed, and the separation into small async tasks is quite nice.

The code assumes your startPayment() method does nothing with the UI, and if it does, move it into the onPostExecute of the AsyncTask so it's done in the UI thread.

Body:
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });

StartPayment Method:

    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}

Body:
I've found that most thread handling can be replaced by AsyncTasks like this:

public class TestStuff extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonBank = (Button) findViewById(R.id.button);
        buttonBank.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new StartPaymentAsyncTask(TestStuff.this).execute((Void []) null);
            }
        });
    }

    private class StartPaymentAsyncTask extends AsyncTask<Void, Void, String> {
        private ProgressDialog dialog;
        private final Context context;

        public StartPaymentAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(context);
            // setup your dialog here
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setMessage(context.getString(R.string.doing_db_work));
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected String doInBackground(Void... ignored) {
            String returnMessage = null;
            try {
                startPayment("Bank");
            } catch (Exception e) {
                returnMessage = e.getMessage();
            }
            return returnMessage;
        }

        @Override
        protected void onPostExecute(String message) {
            dialog.dismiss();
            if (message != null) {
                // process the error (show alert etc)
                Log.e("StartPaymentAsyncTask", String.format("I received an error: %s", message));
            } else {
                Log.i("StartPaymentAsyncTask", "No problems");
            }
        }
    }

    public void startPayment(String string) throws Exception {
        SystemClock.sleep(2000); // pause for 2 seconds for dialog
        Log.i("PaymentStuff", "I am pretending to do some work");
        throw new Exception("Oh dear, database error");
    }
}

I pass in the Application Context to the Async so it can create dialogs from it.

The advantage of doing it this way is you know exactly which methods are run in your UI and which are in a separate background thread. Your main UI thread isn't delayed, and the separation into small async tasks is quite nice.

The code assumes your startPayment() method does nothing with the UI, and if it does, move it into the onPostExecute of the AsyncTask so it's done in the UI thread.


问:
How to make a list of numbers from a txt file in python?
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

```<code>L=[52,2,103,592,2090,34452,0,1]
</code>```

The best I have managed to do so far is:

```<code>txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)
</code>```

which returns:

```<code>L=['52','2','103','592','2090','34452','0','1']

</code>```

but the ' around the numbers bother me.

Any help is appreciated.

答:
You should try using list comprehension and "with" keyword to make sure you don't forget to close the file.</p>

```<code>with open('test.txt') as f:
    l = [int(line) for line in f]
print(l)
</code>```

Body:
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

L=[52,2,103,592,2090,34452,0,1]

The best I have managed to do so far is:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)

which returns:

L=['52','2','103','592','2090','34452','0','1']

but the ' around the numbers bother me.

Any help is appreciated.

Body:
You should try using list comprehension and "with" keyword to make sure you don't forget to close the file.

with open('test.txt') as f:
    l = [int(line) for line in f]
print(l)


问:
Why array_unique does not detect duplicate objects?
I can't seem to figure out what magic is happening behind the PHP scene and why array_unique cannot detect my duplicates.

In my specific situation, I have 2 collections of users, which I am merging into one and then keeping only unique entries. For that I am converting both collections into arrays, array_merge() them and then based on parameter apply array_unique(..., SORT_REGULAR) so that they are compared as objects without any conversions. I realise that comparing objects is a slippery slope, but in this case it's weirder than I though.

After merge but before the uniqueness check I have this state:

As you can see, items 4 and 11 are the same User entity (both non-strict and strict comparison agree on that). Yet after array_unique() they both remain in the list for some reason:

As you can see, items 7-10 were detected and removed, but 11 wasn't.

How is that possible? What am I not seeing here?

Currently running PHP 7.4.5

Code is from project using Symfony 4.4.7 and Doctrine ORM 2.7.2 (although I think this should be irrelevant, if the objects are equal both by == and === comparisons).

Fun fact for bonus points - applying array_unique twice in a row gives actually unique results:

Mind = blown

UPDATE: I have added throw new \RuntimeException() in my User::__toString() method, to be extra sure noone is doing conversion to string.

Please do not suggest converting to string - that is neither a solution to my problem, nor what this question is about.

答:
Without knowing about your entity class its hard to guess why this is happening. But I guess your main issue here is __toString() method . If you have not defined it, you should add one such that it returns a unique/distinct string for each entity object. If its already defined make sure it returns distinct string.

```<code>class User{
   private $name;

   function __construct($name){
      $this->name=$name;
   }

   function __toString(){
     return $this->name;
   }
}

$user = [];
$users[] = new User("User1");
$users[] = new User("User2");
$users[] = new User("User3");

$user1= $users[0];
$users[]=$user1; //duplicate

echo(count(array_unique($users))); // output should be 3
</code>```

Given the limited information about entity class I can guess this far.

Edit:

After reading your edits I guess you are locking yourself into this. Since array_unique will try to convert an entity object to either string or number depending on the sort_flag you pass.  More on array_unique. So either you need to implement __toString() or add some public properties which define the uniqueness of your object to entity e.g

```<code>class User{
       public $id;
       private $name;

       function __construct($id,$name){
          $this->id=$id;
          $this->name=$name;
       }
}

$user = [];
$users[] = new User(1,"User1");
$users[] = new User(2,"User2");
$users[] = new User(3,"User3");

$user1= $users[0];
$users[]=$user1; //duplicate
echo(count(array_unique($users, SORT_REGULAR))); // output should be 3
</code>```

Please note the public property $id and SORT_REGULAR flag.

Body:
Without knowing about your entity class its hard to guess why this is happening. But I guess your main issue here is __toString() method . If you have not defined it, you should add one such that it returns a unique/distinct string for each entity object. If its already defined make sure it returns distinct string.

class User{
   private $name;

   function __construct($name){
      $this->name=$name;
   }

   function __toString(){
     return $this->name;
   }
}

$user = [];
$users[] = new User("User1");
$users[] = new User("User2");
$users[] = new User("User3");

$user1= $users[0];
$users[]=$user1; //duplicate

echo(count(array_unique($users))); // output should be 3

Given the limited information about entity class I can guess this far.

Edit:

After reading your edits I guess you are locking yourself into this. Since array_unique will try to convert an entity object to either string or number depending on the sort_flag you pass.  More on array_unique. So either you need to implement __toString() or add some public properties which define the uniqueness of your object to entity e.g

class User{
       public $id;
       private $name;

       function __construct($id,$name){
          $this->id=$id;
          $this->name=$name;
       }
}

$user = [];
$users[] = new User(1,"User1");
$users[] = new User(2,"User2");
$users[] = new User(3,"User3");

$user1= $users[0];
$users[]=$user1; //duplicate
echo(count(array_unique($users, SORT_REGULAR))); // output should be 3

Please note the public property $id and SORT_REGULAR flag.


问:
How to get the desired outpout from the following list?
Suppose the is a list with following values

```<code>A=[1,2,3,4,5,6,7]
</code>```

The Required Output is

print

```<code>1
1+2
1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7
</code>```

Please help me to get the above answer..

答:
We use a for loop to iterate over the array, and concatenate each consecutive element along with a +.

In the first iteration we start with only the first element in the array

In the i'th iteration, we concatenate all the elements until i

Here's a piece of code that does that:

```<code>A=[1,2,3,4,5,6,7]

for i in range(len(A)):
    s = str(A[0])
    for j in range(1,i+1):
        s += "+" + str(A[j])
    print(s)
</code>```

Body:
Suppose the is a list with following values

A=[1,2,3,4,5,6,7]

The Required Output is

print

1
1+2
1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7

Please help me to get the above answer..

Body:
We use a for loop to iterate over the array, and concatenate each consecutive element along with a +.

In the first iteration we start with only the first element in the array

In the i'th iteration, we concatenate all the elements until i

Here's a piece of code that does that:

A=[1,2,3,4,5,6,7]

for i in range(len(A)):
    s = str(A[0])
    for j in range(1,i+1):
        s += "+" + str(A[j])
    print(s)


问:
Executing function for lower iOS versions
Is there an way for executing functions only for lower iOS versions.
I mean we can execute always using the available attribute for iOS versions greater than the specific one ; but is there any way to do the other way round?</p>

答:
It's simple. You can use this:

if #available(iOS 10, *) {} else {
    print("Code only for versions below iOS 10")
}
```


问:
multiple conditions + regex in awk command
I'm using the following awk command to replace strings in a swift source file:

```<code>awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" "$file" > ./temp
</code>```

Trying not to edit commented out values. At a minimum, need to ignore lines that start with "//" but it seems possible to ignore inline comments (e.g. when the line is only partially commented like "MATCH // <- Ok" or "foo // MATCH <- Not Ok").

Something like...

```<code>    s=index($0,old) && !($0 =~ "^//") { ... }
</code>```

Sample Input:

```<code>old="\"Some \(value) with %@ special \n characters\""
new="\"some_key\".localized"

file {contents}...
    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "Some \(value) with %@ special \n characters" // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters"
</code>```

Expected Output:

```<code>    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "some_key".localized // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters"
</code>```

EDIT

Although @RavinderSingh13's answer did not match expected output, it was close and I used it to modify my command like so:

```<code>BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
s=index($0,old) { if (!(match($0,/.*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }' "$old" "$new" "$file"
</code>```

This meets the original requirement, but ignores ANY line that has two slashes. This is problematic, because it doesn't support in line comments (e.g. the above command would not edit any of the sample input; unless the "// <-- This should change" comment is removed. If no one replies, I'll use this as the answer, but I'll wait a day or so in case someone posts a version of the command that meets all the requirements. Will accept that answer.

It would be something like this...

```<code>s=index($0,old) { if (!(match($0,/.*\/\//)) || (match($0,/"$old".*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }
</code>```

答:
Considering that you want skip all lines which start from // and also you want to print contents which comes before // for in between inline comments. Fair warning not tested since NO samples given.

```<code>awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    /^\/\//{ next }
    match($0,/.*\/\//){ $0 = substr($0,RSTART,RLENGTH-2) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" "$file" > ./temp
</code>```

Above will neglect lines which are starting with // if you want to print them then do following.

```<code>awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    /^\/\//{ print; next }
    match($0,/.*\/\//){ $0 = substr($0,RSTART,RLENGTH-2) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" "$file" > ./temp
</code>```

Body:
I'm using the following awk command to replace strings in a swift source file:

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" "$file" > ./temp

Trying not to edit commented out values. At a minimum, need to ignore lines that start with "//" but it seems possible to ignore inline comments (e.g. when the line is only partially commented like "MATCH // <- Ok" or "foo // MATCH <- Not Ok").

Something like...

    s=index($0,old) && !($0 =~ "^//") { ... }

Sample Input:

old="\"Some \(value) with %@ special \n characters\""
new="\"some_key\".localized"

file {contents}...
    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "Some \(value) with %@ special \n characters" // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters"

Expected Output:

    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "some_key".localized // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters"

EDIT

Although @RavinderSingh13's answer did not match expected output, it was close and I used it to modify my command like so:

BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
s=index($0,old) { if (!(match($0,/.*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }' "$old" "$new" "$file"

This meets the original requirement, but ignores ANY line that has two slashes. This is problematic, because it doesn't support in line comments (e.g. the above command would not edit any of the sample input; unless the "// <-- This should change" comment is removed. If no one replies, I'll use this as the answer, but I'll wait a day or so in case someone posts a version of the command that meets all the requirements. Will accept that answer.

It would be something like this...

s=index($0,old) { if (!(match($0,/.*\/\//)) || (match($0,/"$old".*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }

Body:
Considering that you want skip all lines which start from // and also you want to print contents which comes before // for in between inline comments. Fair warning not tested since NO samples given.

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    /^\/\//{ next }
    match($0,/.*\/\//){ $0 = substr($0,RSTART,RLENGTH-2) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" "$file" > ./temp

Above will neglect lines which are starting with // if you want to print them then do following.

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    /^\/\//{ print; next }
    match($0,/.*\/\//){ $0 = substr($0,RSTART,RLENGTH-2) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" "$file" > ./temp