问:
Run Bash Command At X Time and Terminate for X Time
Hi im working on a simple bash coding i don't know how to accomplish this and this might be easy for you guys please help.

I have a simple program on file.sh

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

./program
</code>```

This ./program is a compiled version of C program which i complied using GCC im trying to use at in bash script to execute this program for few seconds and then terminate that after x interval time and restart again.

I hope you got my point?

Example: Run file.sh for 10 sec and I'll display the result from ./program C program and then after 10 sec it will restart again.

答:
You can use the sleep command. For example: exec ./program && sleep n where n is the time you want the command to sleep. If you want you could put it in a while loop inside an sh script and run it continuously.

To run it continuously until you close the terminal:

```<code>while true
do
   echo "[CTRL+C] to stop..."
   timeout 10s ./program
done
</code>```

Body:
Hi im working on a simple bash coding i don't know how to accomplish this and this might be easy for you guys please help.

I have a simple program on file.sh

#!/bin/bash

./program

This ./program is a compiled version of C program which i complied using GCC im trying to use at in bash script to execute this program for few seconds and then terminate that after x interval time and restart again.

I hope you got my point?

Example: Run file.sh for 10 sec and I'll display the result from ./program C program and then after 10 sec it will restart again.

Body:
You can use the sleep command. For example: exec ./program && sleep n where n is the time you want the command to sleep. If you want you could put it in a while loop inside an sh script and run it continuously.

To run it continuously until you close the terminal:

while true
do
   echo "[CTRL+C] to stop..."
   timeout 10s ./program
done


来源: stackexchange

问:
Strength Pareto Evolutionary Algorithm (SPEA 3)
I am working on optimization using evolutionary algorithm, specifically SPEA-II. I was curious if there is any algorithm named SPEA-III. I tried googling but I could only find a proposed modification of the SPEA-II using reference search direction. Is it same as SPEA-III, in case of NSGA-III, this is the probably only difference from NSGA-II.</p>

答: I was able find a reference paper on SPEA3, the authors have proposed what they called a generalization of SPEA2 algorithm and name it as SPEA3.</p>

ContentLicense: CC BY-SA 3.0


问:
How to affect order of targets, add additional steps etc. for Makefile.am?
Can I manage Makefile.am as I got used to manage Makefile?

Usually I create targets which calls each other in order to make the project built.

But in Makefile.am I have some mysterious libqqq_la_SOURCES = ... which I don't know what is it doing exactly.

Where to write what compiler should it use for the given source? Where to add a step that "qqq.c is generated from qqq.vala"?

How to write Makefile.am as just Makefile?

答:
Automake in 1.11 does have Vala support.

configure.ac:

```
AM_PROG_VALAC
```

Makefile.am:

```
AM_VALAFLAGS = whateverelse
whatever_SOURCES = xxx.vala
```

ContentLicense: CC BY-SA 2.5

Body:
Automake in 1.11 does have Vala support.

configure.ac:

AM_PROG_VALAC

Makefile.am:

AM_VALAFLAGS = whateverelse
whatever_SOURCES = xxx.vala


问:
Original class name can be found after running proguard
I am new in proguard and I use http://www.javadecompilers.com to verify my progurd setting.

The class name have been obfuscated. But the original class name can be found in javadecompiler.

Is there any setting to hide the original class name?

java decompiler output

File : proguard-project.txt

```<code>-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
#-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

#-keep public class * extends android.app.Activity

-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.util.Log

-keepclasseswithmembernames class * {
 native <methods>;
}

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}

-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep class com.actionbarsherlock.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keepattributes *Annotation*,SourceFile,LineNumberTable

# goolge map
-keep class android.location.** { *; }

-keepnames class com.google.android.maps.** {*;}
-keep public class com.google.android.maps.** {*;}

-dontwarn com.google.android.maps.GeoPoint
-dontwarn com.google.android.maps.MapActivity
-dontwarn com.google.android.maps.MapView
-dontwarn com.google.android.maps.MapController
-dontwarn com.google.android.maps.Overlay
-dontwarn com.google.**

-keep class com.google.** { *; }
-keep interface com.google.** { *; }
</code>```

答:
The reason why you can determine the original file name is due to the SourceFile attribute in this line:

```<code>-keepattributes *Annotation*,SourceFile,LineNumberTable
</code>```

You can change that behavior by removing it:

```<code>-keepattributes *Annotation*,LineNumberTable
</code>```

or by forcing ProGuard to use a placeholder instead of the original file name:

```<code>-keepattributes *Annotation*,SourceFile,LineNumberTable
-renamesourcefileattribute SourceFile
</code>```

Body:
I am new in proguard and I use http://www.javadecompilers.com to verify my progurd setting.

The class name have been obfuscated. But the original class name can be found in javadecompiler.

Is there any setting to hide the original class name?

java decompiler output

File : proguard-project.txt

-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
#-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

#-keep public class * extends android.app.Activity

-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.util.Log

-keepclasseswithmembernames class * {
 native <methods>;
}

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}

-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep class com.actionbarsherlock.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keepattributes *Annotation*,SourceFile,LineNumberTable

# goolge map
-keep class android.location.** { *; }

-keepnames class com.google.android.maps.** {*;}
-keep public class com.google.android.maps.** {*;}

-dontwarn com.google.android.maps.GeoPoint
-dontwarn com.google.android.maps.MapActivity
-dontwarn com.google.android.maps.MapView
-dontwarn com.google.android.maps.MapController
-dontwarn com.google.android.maps.Overlay
-dontwarn com.google.**

-keep class com.google.** { *; }
-keep interface com.google.** { *; }

Body:
The reason why you can determine the original file name is due to the SourceFile attribute in this line:

-keepattributes *Annotation*,SourceFile,LineNumberTable

You can change that behavior by removing it:

-keepattributes *Annotation*,LineNumberTable

or by forcing ProGuard to use a placeholder instead of the original file name:

-keepattributes *Annotation*,SourceFile,LineNumberTable
-renamesourcefileattribute SourceFile


问:
Ansible Synchronize Parallel Remote-To-Remote
I am trying to use Ansible-synchronize to deploy a bunch of files to multiple sets of servers at the same time. Right now we have a hand crafted sequential solution that does SCP and obviously doesn't scale very well. Since Ansible uses SSH multiplexing, I assumed this would serve my purpose. Here is representative description of my setup:

remotefileserver.x:

```<code>/storage/path/to/versions/component1/versionid-1/{file1,file2,file3,dir1/file1,dir2/file1,...}
/storage/path/to/versions/component1/versionid-2/{file1,file2,file3,dir1/file1,dir2/file1,...}
/storage/path/to/versions/component2/versionid-1/{file1,file2,file3,dir1/file1,...}
/storage/path/to/versions/component3/versionid-1/{file1,file2,file3,dir1/file1,...}
...
</code>```

remotetargetservers:

```<code>target1.x
target2.x
...
target10.x
</code>```

ansible.cfg:

```<code>pipelining = True
forks = 20
</code>```

I originally had the following playbook setup:

hosts: {{ remotetargetservers }}
tasks:
    - name: deploying site-specific files
      synchronize:
        src: "{{ src_path }}"
        dest: "{{ dest_dir }}/{{ item }}"
        checksum: yes
      delegate_to: remotefileserver.x
      with_items: "{{ files_list }}"```
</div>
</div>
</p>

<p>This technically worked, but my speedup was just 1.25x (not much of an improvement) where as I was hoping to get <em>near</em> 'n' or at least something over 'n/2' speedup. I read somewhere that synchronize in pull mode should work better and I assumed as such since (at least theoretically) in pull mode we would delegate the responsibility of copying, to the individual target hosts => near 'n' speedup.</p>

<p>So I changed my playbook to the following:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>hosts: {{ remotetargetservers }}
tasks:
    - name: deploying site-specific files
        synchronize:
          mode: pull
          src: "rsync://remotefileserver.x/{{ src_path }}"
          dest: "{{ dest_dir }}/{{ item }}"
          checksum: yes
        delegate_to: "{{ inventory_hostname }}"
        with_items: "{{ files_list }}"</code>```

When I run this, I get the following error:

"..., msg": "rsync: failed to connect to remotefileserver.x: Connection refused (111)\nrsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.6]\n", "rc": 10}

Elsewhere on the internet, someone suggested that I make sure that rsync daemon was running on both hosts. My system administrator won't run rsync daemon and suggested I use rsync-over-ssh feature of rsync. I have verified that, this command:

```<code>rsync -av remotefileserver.x:/path/to/files /my/destination
</code>```

worked successfully from one of the target servers.

And so I tried:

```<code>src: "remotefileserver.x/{{ path }}"
</code>```

and got a whole bunch of other security errors

"POSSIBLE BREAK-IN ATTEMPT!
  failed: No such file or directory (2)\nrsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1505) [receiver=3.0.6]\n", "rc": 23

Here are my questions:

Is Ansible even suited for my purposes?

Are my expectations from Ansible incorrect?

Are my assumptions about 'synchronize' incorrect?

Is there anything I can change in my playbook that would make push mode faster(forks = 20) or fix my pull mode setup?

Is there a correct way to ask Ansible to pull files using rsync over ssh?

Is there anything else I can do short of handcrafting my own custom Python based parallel file-pull solution?

(No, Chef/Puppet/Salt are not options because we wouldn't like to run agent-like-things on the target boxes)

Thank you!

答:
by forcing rsync to use ssh, you should be able to overcome this issue.
rsync_opts: "-e ssh -p 22"

hosts: {{ remotetargetservers }}
tasks:
    - name: deploying site-specific files
        synchronize:
          mode: pull
          src: "rsync://remotefileserver.x/{{ src_path }}"
          dest: "{{ dest_dir }}/{{ item }}"
          checksum: yes
          rsync_opts: "-e ssh -p 22"
        delegate_to: "{{ inventory_hostname }}"
        with_items: "{{ files_list }}"```

Body:
I am trying to use Ansible-synchronize to deploy a bunch of files to multiple sets of servers at the same time. Right now we have a hand crafted sequential solution that does SCP and obviously doesn't scale very well. Since Ansible uses SSH multiplexing, I assumed this would serve my purpose. Here is representative description of my setup:

remotefileserver.x:

/storage/path/to/versions/component1/versionid-1/{file1,file2,file3,dir1/file1,dir2/file1,...}
/storage/path/to/versions/component1/versionid-2/{file1,file2,file3,dir1/file1,dir2/file1,...}
/storage/path/to/versions/component2/versionid-1/{file1,file2,file3,dir1/file1,...}
/storage/path/to/versions/component3/versionid-1/{file1,file2,file3,dir1/file1,...}
...

remotetargetservers:

target1.x
target2.x
...
target10.x

ansible.cfg:

pipelining = True
forks = 20

I originally had the following playbook setup:

hosts: {{ remotetargetservers }}
tasks:
    - name: deploying site-specific files
      synchronize:
        src: "{{ src_path }}"
        dest: "{{ dest_dir }}/{{ item }}"
        checksum: yes
      delegate_to: remotefileserver.x
      with_items: "{{ files_list }}"

This technically worked, but my speedup was just 1.25x (not much of an improvement) where as I was hoping to get near 'n' or at least something over 'n/2' speedup. I read somewhere that synchronize in pull mode should work better and I assumed as such since (at least theoretically) in pull mode we would delegate the responsibility of copying, to the individual target hosts => near 'n' speedup.

So I changed my playbook to the following:

hosts: {{ remotetargetservers }}
tasks:
    - name: deploying site-specific files
        synchronize:
          mode: pull
          src: "rsync://remotefileserver.x/{{ src_path }}"
          dest: "{{ dest_dir }}/{{ item }}"
          checksum: yes
        delegate_to: "{{ inventory_hostname }}"
        with_items: "{{ files_list }}"

When I run this, I get the following error:

"..., msg": "rsync: failed to connect to remotefileserver.x: Connection refused (111)\nrsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.6]\n", "rc": 10}

Elsewhere on the internet, someone suggested that I make sure that rsync daemon was running on both hosts. My system administrator won't run rsync daemon and suggested I use rsync-over-ssh feature of rsync. I have verified that, this command:

rsync -av remotefileserver.x:/path/to/files /my/destination

worked successfully from one of the target servers.

And so I tried:

src: "remotefileserver.x/{{ path }}"

and got a whole bunch of other security errors

"POSSIBLE BREAK-IN ATTEMPT!
  failed: No such file or directory (2)\nrsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1505) [receiver=3.0.6]\n", "rc": 23

Here are my questions:

Is Ansible even suited for my purposes?

Are my expectations from Ansible incorrect?

Are my assumptions about 'synchronize' incorrect?

Is there anything I can change in my playbook that would make push mode faster(forks = 20) or fix my pull mode setup?

Is there a correct way to ask Ansible to pull files using rsync over ssh?

Is there anything else I can do short of handcrafting my own custom Python based parallel file-pull solution?

(No, Chef/Puppet/Salt are not options because we wouldn't like to run agent-like-things on the target boxes)

Thank you!


问:
why I can't use var value in my button action?
I want value send to my button...

why I can't use quizWord in my button action??

it occurs "use of unsolved identifier..." error...

```<code>    import UIKit

extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}
// random

class QuizViewController: UIViewController {

    var tasks : [Task] = []
    var limitRe:Int = 0
    var cards: [Character] = []
    var quizName = [String]()
    var quizfileName = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //get the data from core data
        getData()

        for q in 0...tasks.count-1 {
            let quiz = tasks[q]
            quizName.append(quiz.name!)
            quizfileName.append(quiz.filename!)
            print(quizName, quizfileName)
        }
        var quizWord = quizName[0]
        var countText: Int = (quizWord.characters.count) - 1

        for _ in 0...countText
        {let index1 = quizWord.index(quizWord.startIndex, offsetBy: limitRe)

            cards.append(quizWord[index1])
            limitRe = limitRe + 1
        }
        cards.shuffle()
        quizPhotoView.image = UIImage(named: "1.jpg")

        if countText >= 0 {lblChar1.text = "\(cards[0])"} else {lblChar1.text = ""}
        if countText >= 1 {lblChar2.text = "\(cards[1])"} else {lblChar2.text = ""}
        if countText >= 2 {lblChar3.text = "\(cards[2])"} else {lblChar3.text = ""}
        if countText >= 3 {lblChar4.text = "\(cards[3])"} else {lblChar4.text = ""}
        if countText >= 4 {lblChar5.text = "\(cards[4])"} else {lblChar5.text = ""}
        if countText >= 5 {lblChar6.text = "\(cards[5])"} else {lblChar6.text = ""}
        if countText >= 6 {lblChar7.text = "\(cards[6])"} else {lblChar7.text = ""}
        if countText >= 7 {lblChar8.text = "\(cards[7])"} else {lblChar8.text = ""}

    }

    @IBOutlet weak var lblChar1: UILabel!
    @IBOutlet weak var lblChar2: UILabel!
    @IBOutlet weak var lblChar3: UILabel!
    @IBOutlet weak var lblChar4: UILabel!
    @IBOutlet weak var lblChar5: UILabel!
    @IBOutlet weak var lblChar6: UILabel!
    @IBOutlet weak var lblChar7: UILabel!
    @IBOutlet weak var lblChar8: UILabel!
    @IBOutlet weak var lblTyped: UILabel!
    @IBOutlet weak var quizPhotoView: UIImageView!

    func getData() {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {
            tasks = try context.fetch(Task.fetchRequest())
        }
        catch {
            print("Failed")
        }
    }

    @IBAction func butChar1(_ sender: UIButton) {
    if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar1.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar2(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar2.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}
    }
    @IBAction func butChar3(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar3.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar4(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar4.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar5(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar5.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar6(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar6.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar7(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar7.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar8(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar8.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}

}
</code>```

答:
Due to local scope of variable you can use in only viewDidLoad() method you need to declare as top of class not in viewDidLoad() method

```<code>class QuizViewController: UIViewController {

var quizWord  : String = ""

}
</code>```

Body:
I want value send to my button...

why I can't use quizWord in my button action??

it occurs "use of unsolved identifier..." error...

    import UIKit

extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}
// random

class QuizViewController: UIViewController {

    var tasks : [Task] = []
    var limitRe:Int = 0
    var cards: [Character] = []
    var quizName = [String]()
    var quizfileName = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //get the data from core data
        getData()

        for q in 0...tasks.count-1 {
            let quiz = tasks[q]
            quizName.append(quiz.name!)
            quizfileName.append(quiz.filename!)
            print(quizName, quizfileName)
        }
        var quizWord = quizName[0]
        var countText: Int = (quizWord.characters.count) - 1

        for _ in 0...countText
        {let index1 = quizWord.index(quizWord.startIndex, offsetBy: limitRe)

            cards.append(quizWord[index1])
            limitRe = limitRe + 1
        }
        cards.shuffle()
        quizPhotoView.image = UIImage(named: "1.jpg")

        if countText >= 0 {lblChar1.text = "\(cards[0])"} else {lblChar1.text = ""}
        if countText >= 1 {lblChar2.text = "\(cards[1])"} else {lblChar2.text = ""}
        if countText >= 2 {lblChar3.text = "\(cards[2])"} else {lblChar3.text = ""}
        if countText >= 3 {lblChar4.text = "\(cards[3])"} else {lblChar4.text = ""}
        if countText >= 4 {lblChar5.text = "\(cards[4])"} else {lblChar5.text = ""}
        if countText >= 5 {lblChar6.text = "\(cards[5])"} else {lblChar6.text = ""}
        if countText >= 6 {lblChar7.text = "\(cards[6])"} else {lblChar7.text = ""}
        if countText >= 7 {lblChar8.text = "\(cards[7])"} else {lblChar8.text = ""}

    }

    @IBOutlet weak var lblChar1: UILabel!
    @IBOutlet weak var lblChar2: UILabel!
    @IBOutlet weak var lblChar3: UILabel!
    @IBOutlet weak var lblChar4: UILabel!
    @IBOutlet weak var lblChar5: UILabel!
    @IBOutlet weak var lblChar6: UILabel!
    @IBOutlet weak var lblChar7: UILabel!
    @IBOutlet weak var lblChar8: UILabel!
    @IBOutlet weak var lblTyped: UILabel!
    @IBOutlet weak var quizPhotoView: UIImageView!

    func getData() {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {
            tasks = try context.fetch(Task.fetchRequest())
        }
        catch {
            print("Failed")
        }
    }

    @IBAction func butChar1(_ sender: UIButton) {
    if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar1.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar2(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar2.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}
    }
    @IBAction func butChar3(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar3.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar4(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar4.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar5(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar5.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar6(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar6.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar7(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar7.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar8(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar8.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}

}

Body:
Due to local scope of variable you can use in only viewDidLoad() method you need to declare as top of class not in viewDidLoad() method

class QuizViewController: UIViewController {

var quizWord  : String = ""

}


问:
How can I install *.apk from jenkins on real device with Appium and run tests written in python?
I have a BDD test automation framework with cucumber and python with behave for android mobile app testing.
I want to set up a jenkins job wherein I can Start the appium server and launch the android mobile app and trigger the test execution.
Can someone please help on this ?
Thanks in advance.</p>

答:
Step 1: Install Jenkins in your system visit the Jenkins url in browser.
In my local I access Jenkins using "http://localhost:8080"

Step 2: Tap "New Item" > "Freestyle Project" > 'OK'

Step 3: Scroll to 'Build' section > Add Build Step > 'Execute Shell' and enter the below commands:

```<code>#!/bin/bash --login -x
appium &
sleep 5s
</code>```

Step 4: Click on 'Build Now'.

Step 5: Open the running job > 'Console Output' to ensure Appium server is running.

The following text should be displayed in console logs:

```<code>[Appium] Welcome to Appium v1.6.4
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
</code>```

Step 6: All the test scripts should be placed inside 'workspace' directory of Jenkins. My scripts are in this location:
    /Users/Shared/Jenkins/Home/workspace/appium-android/

Step 7: I use pytest, so my command is as follows:

```<code>cd $WORKSPACE
pytest /Users/Shared/Jenkins/Home/workspace/appium-android/tests/listings/test_listing_create.py
</code>```

For behave run the command accordingly.

to answer this:
launch the android mobile app

Appium should take care of launching the app

Ensure you have all dependencies installed in Jenkins machine, like Python, Appium python client, Appium server, behave etc

Body:
Step 1: Install Jenkins in your system visit the Jenkins url in browser.
In my local I access Jenkins using "http://localhost:8080"

Step 2: Tap "New Item" > "Freestyle Project" > 'OK'

Step 3: Scroll to 'Build' section > Add Build Step > 'Execute Shell' and enter the below commands:

#!/bin/bash --login -x
appium &
sleep 5s

Step 4: Click on 'Build Now'.

Step 5: Open the running job > 'Console Output' to ensure Appium server is running.

The following text should be displayed in console logs:

[Appium] Welcome to Appium v1.6.4
[Appium] Appium REST http interface listener started on 0.0.0.0:4723

Step 6: All the test scripts should be placed inside 'workspace' directory of Jenkins. My scripts are in this location:
    /Users/Shared/Jenkins/Home/workspace/appium-android/

Step 7: I use pytest, so my command is as follows:

cd $WORKSPACE
pytest /Users/Shared/Jenkins/Home/workspace/appium-android/tests/listings/test_listing_create.py

For behave run the command accordingly.

to answer this:
launch the android mobile app

Appium should take care of launching the app

Ensure you have all dependencies installed in Jenkins machine, like Python, Appium python client, Appium server, behave etc


问:
Nested array error
I know this is a really newbie question but it has thrown me for days and I can't seem to find a solution that I actually understand.

I am trying to make a nested array to store latitude and longitude, however it Xcode/playground throws a EXC_BAD_INSTRUCTION error.

I want to declare, initialise and print the contents of an array. What am I doing wrong?

```<code>var arrayLocations:[[Float]] = []

arrayLocations[0] = [27.1750199, 78.0399665]

print("\(arrayLocations[0][0]) and \(arrayLocations[0][1])")
</code>```

答:
You cannot assign a value to index 0 because there is no index 0 if the array is empty.

You have to append or insert the item:

```<code>arrayLocations.append([27.1750199, 78.0399665])
</code>```

Title: Nested array error

Body:
I know this is a really newbie question but it has thrown me for days and I can't seem to find a solution that I actually understand.

I am trying to make a nested array to store latitude and longitude, however it Xcode/playground throws a EXC_BAD_INSTRUCTION error.

I want to declare, initialise and print the contents of an array. What am I doing wrong?

var arrayLocations:[[Float]] = []

arrayLocations[0] = [27.1750199, 78.0399665]

print("\(arrayLocations[0][0]) and \(arrayLocations[0][1])")

Body:
You cannot assign a value to index 0 because there is no index 0 if the array is empty.

You have to append or insert the item:

arrayLocations.append([27.1750199, 78.0399665])


问:
Scrapy a hidden content in source code
Hi I want to crawl some contents which I cannot see from the page source code while they are there by seeing the page.
A example site : https://bangumi.bilibili.com/anime/index#p=1&v=1&area=2&stat=0&y=0&q=0&tag=&t=1&sort=0
(I want to get the anime info)

Could anyone can give me any hint to do this?

Thanks

答:
Since all info on this page populated via json you can make a direct request to json endpoint and if you use for loop you can extract all desired info.

```<code>import scrapy
import json

class BiliSpider(scrapy.Spider):
    name = "bilispider"

    def start_requests(self):
        url = "https://bangumi.bilibili.com/web_api/season/index_global?page={}&page_size=20&version=1&is_finish=0&start_year=0&tag_id=&index_type=1&index_sort=0&area=2&quarter=0"
        for i in range(1, 99):
            yield scrapy.Request(url.format(i), callback=self.parse)

    def parse(self, response):
        res = json.loads(response.text)
        item = dict()
        for el in res['result']['list']:
            item['title'] = el['title']
            item['url'] = el['url']
            yield item

# Output:
# 2017-07-05 09:11:46 [scrapy.core.scraper] DEBUG: Scraped from <200 https://bangumi.bilibili.com/web_api/season/index_glo
# bal?page=96&page_size=20&version=1&is_finish=0&start_year=0&tag_id=&index_type=1&index_sort=0&area=2&quarter=0>
# {'title': '激斗战车（国语）', 'url': 'http://bangumi.bilibili.com/anime/5380'}
# 2017-07-05 09:11:46 [scrapy.core.scraper] DEBUG: Scraped from <200 https://bangumi.bilibili.com/web_api/season/index_glo
# bal?page=96&page_size=20&version=1&is_finish=0&start_year=0&tag_id=&index_type=1&index_sort=0&area=2&quarter=0>
# {'title': '银河漂流VIFAM', 'url': 'http://bangumi.bilibili.com/anime/2437'}
</code>```

Title: Scrapy a hidden content in source code

Body:
Since all info on this page populated via json you can make a direct request to json endpoint and if you use for loop you can extract all desired info.

import scrapy
import json

class BiliSpider(scrapy.Spider):
    name = "bilispider"

    def start_requests(self):
        url = "https://bangumi.bilibili.com/web_api/season/index_global?page={}&page_size=20&version=1&is_finish=0&start_year=0&tag_id=&index_type=1&index_sort=0&area=2&quarter=0"
        for i in range(1, 99):
            yield scrapy.Request(url.format(i), callback=self.parse)

    def parse(self, response):
        res = json.loads(response.text)
        item = dict()
        for el in res['result']['list']:
            item['title'] = el['title']
            item['url'] = el['url']
            yield item

# Output:
# 2017-07-05 09:11:46 [scrapy.core.scraper] DEBUG: Scraped from <200 https://bangumi.bilibili.com/web_api/season/index_glo
# bal?page=96&page_size=20&version=1&is_finish=0&start_year=0&tag_id=&index_type=1&index_sort=0&area=2&quarter=0>
# {'title': '激斗战车（国语）', 'url': 'http://bangumi.bilibili.com/anime/5380'}
# 2017-07-05 09:11:46 [scrapy.core.scraper] DEBUG: Scraped from <200 https://bangumi.bilibili.com/web_api/season/index_glo
# bal?page=96&page_size=20&version=1&is_finish=0&start_year=0&tag_id=&index_type=1&index_sort=0&area=2&quarter=0>
# {'title': '银河漂流VIFAM', 'url': 'http://bangumi.bilibili.com/anime/2437'}


问:
Get the context of an Activity in a Serializable class
I have a class that implements 'Serializable' but i am unable to get the context of my main activity in it. Here is my code for this class:

```<code>public class Game implements Serializable{
private String name;
private ColorTheme theme;
private int distance = 0;
private int score = 0;
boolean boom = false;
protected Context context;

public Game(MainActivity context){
this.context = context.getApplicationContext();
}
</code>```

I want to close my game inside this condition but it is not giving me any option to finish the context. Please help me where i am wrong. I think the context is not successfully implemented in this Serializable class. Help needed

答:
I have a simple way to exit the app. Try it like

```<code>Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("Exit me", true);
((Activity)context).startActivity(intent);
((Activity)context).finish();
</code>```

Here MainActivity is depends on your project requirement. You can change it as per your need.

Body:
I have a class that implements 'Serializable' but i am unable to get the context of my main activity in it. Here is my code for this class:

public class Game implements Serializable{
private String name;
private ColorTheme theme;
private int distance = 0;
private int score = 0;
boolean boom = false;
protected Context context;

public Game(MainActivity context){
this.context = context.getApplicationContext();
}

I want to close my game inside this condition but it is not giving me any option to finish the context. Please help me where i am wrong. I think the context is not successfully implemented in this Serializable class. Help needed

Body:
I have a simple way to exit the app. Try it like

Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("Exit me", true);
((Activity)context).startActivity(intent);
((Activity)context).finish();

Here MainActivity is depends on your project requirement. You can change it as per your need.


问:
"org.eclipse.m2e.jdt.JarLifecycleMapping" is not available
How do I deal with this m2e plugin problem with Eclipse:

Description   Resource    Path    Location    Type Lifecycle mapping
  "org.eclipse.m2e.jdt.JarLifecycleMapping" is not available. To enable
  full functionality, install the lifecycle mapping and run
  Maven->Update Project Configuration.  pom.xml /vosao-web  line 11 Maven
  Project Build Lifecycle Mapping Problem

Does anyone have fixed this issue? Or this plugin is simply not supported in Eclipse?

答: I restart my STS. Then right click on the maven project -> Maven -> Update project</p>


问:
Google Assistant SDK
This is for a graduation project. I had troubles with installing Google Assistant SDK, thanks to a lot of helpful people I made my next step. But my next step is sadly my next dead end.

This is the next step:

```<code>python3 -m googlesamples.assistant.auth_helpers –client-secrets path\to\your\client_secret_XXX.apps.googleusercontent.com.json
</code>```

There is a return:

No module named googlesamples.assistant.auth_helpers

So I Googled that and tried the steps that are suggested:

```<code>pip install --upgrade google-auth-oauthlib[tool]
google-oauthlib-tool --client-secrets path/to/client_secret_XXXXX.json --scope https://www.googleapis.com/auth/assistant-sdk-prototype --save --headless
</code>```

The first one worked well, the second one sadly not. I read in another forum that if its in terminal I should do it without --headless.

```<code>(myenvname) Firass-MacBook-Pro:myenvname firashachem$ python3 -m googlesamples.assistant.auth_helpers
-–client-secrets
Users/firashachem/Desktop/client_secret_*****ntent.com.json
/Users/firashachem/myproject/myenvname/bin/python3: No module named googlesamples.assistant.auth_helpers
google-oauthlib-tool --client-secrets /Users/firashachem/Desktop/googleassistant/client_secret_*****.apps.googleusercontent.com.json
Usage: google-oauthlib-tool [OPTIONS]
Error: Missing option "--scope".
(myenvname) Firass-MacBook-Pro:myenvname firashachem$ google-oauthlib-tool --client-secrets /Users/firashachem/Desktop/googleassistant/client_secret_****.apps.googleusercontent.com.json
Usage: google-oauthlib-tool [OPTIONS]
(myenvname) Firass-MacBook-Pro:myenvname firashachem$ google-oauthlib-tool --client-secrets /Users/firashachem/Desktop/googleassistant/client_secret_****.apps.googleusercontent.com.json
Usage: google-oauthlib-tool [OPTIONS]

Error: Missing option "--scope".
(myenvname) Firass-MacBook-Pro:myenvname firashachem$  --scope
 https://www.googleapis.com/auth/assistant-sdk-prototype --save
</code>```

答:
Try the below command.

```<code>(myenvname) Firass-MacBook-Pro:myenvname firashachem$ google-oauthlib-tool --client-secrets /Users/firashachem/Desktop/googleassistant/client_secret_****.apps.googleusercontent.com.json --scope https://www.googleapis.com/auth/assistant-sdk-prototype --save --headless
</code>```

Terminal asked for a authorization code ("Enter the authorization code: ").

You can see a link above this line(ex:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=1****=offline).
 open this link in browser and log in to the google account and authenicate.
now you can see  a authorization code in your browser copy this code and paste it on terminal and press enter.
Now everything will work fine and you will get the file "credentials.json".

Title: Google Assistant SDK

Body:
This is for a graduation project. I had troubles with installing Google Assistant SDK, thanks to a lot of helpful people I made my next step. But my next step is sadly my next dead end.

This is the next step:

python3 -m googlesamples.assistant.auth_helpers –client-secrets path\to\your\client_secret_XXX.apps.googleusercontent.com.json

There is a return:

No module named googlesamples.assistant.auth_helpers

So I Googled that and tried the steps that are suggested:

pip install --upgrade google-auth-oauthlib[tool]
google-oauthlib-tool --client-secrets path/to/client_secret_XXXXX.json --scope https://www.googleapis.com/auth/assistant-sdk-prototype --save --headless

The first one worked well, the second one sadly not. I read in another forum that if its in terminal I should do it without --headless.

(myenvname) Firass-MacBook-Pro:myenvname firashachem$ python3 -m googlesamples.assistant.auth_helpers
-–client-secrets
Users/firashachem/Desktop/client_secret_*****ntent.com.json
/Users/firashachem/myproject/myenvname/bin/python3: No module named googlesamples.assistant.auth_helpers
google-oauthlib-tool --client-secrets /Users/firashachem/Desktop/googleassistant/client_secret_*****.apps.googleusercontent.com.json
Usage: google-oauthlib-tool [OPTIONS]
Error: Missing option "--scope".
(myenvname) Firass-MacBook-Pro:myenvname firashachem$ google-oauthlib-tool --client-secrets /Users/firashachem/Desktop/googleassistant/client_secret_****.apps.googleusercontent.com.json
Usage: google-oauthlib-tool [OPTIONS]
(myenvname) Firass-MacBook-Pro:myenvname firashachem$ google-oauthlib-tool --client-secrets /Users/firashachem/Desktop/googleassistant/client_secret_****.apps.googleusercontent.com.json
Usage: google-oauthlib-tool [OPTIONS]

Error: Missing option "--scope".
(myenvname) Firass-MacBook-Pro:myenvname firashachem$  --scope
 https://www.googleapis.com/auth/assistant-sdk-prototype --save

Body:
Try the below command.

(myenvname) Firass-MacBook-Pro:myenvname firashachem$ google-oauthlib-tool --client-secrets /Users/firashachem/Desktop/googleassistant/client_secret_****.apps.googleusercontent.com.json --scope https://www.googleapis.com/auth/assistant-sdk-prototype --save --headless

Terminal asked for a authorization code ("Enter the authorization code: ").

You can see a link above this line(ex:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=1****=offline).
 open this link in browser and log in to the google account and authenicate.
now you can see  a authorization code in your browser copy this code and paste it on terminal and press enter.
Now everything will work fine and you will get the file "credentials.json".


问:
Separate padding values for checkbox and text inside CheckedTextView
Im trying to build my multiple choice layout according to latest material design guidelines with CheckedTextView widget. But I can't find the way to set left padding for checkbox and textview separately (16dp for icon, 72 for text).
The most acceptable solution i could find is to use android:drawablePadding attribute but i think it is not quite right.
Is it possible to set padding values separately inside CheckedTextView?</p>

```<code><?xml version="1.0" encoding="utf-8"?>

    <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"

        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:gravity="center_vertical"
        android:textSize="16sp"
        android:textColor="#000000"
        android:paddingLeft="16dp"
        android:drawableLeft="?android:attr/listChoiceIndicatorMultiple"
        android:drawablePadding="36dp"/>
</code>```

答:
I'm late to the party, but just in case someone is looking for a solution, here is how I did it using the CheckBox widget:

```<code>    <CheckBox
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:minHeight="30dp"
        android:textColor="#ffffff"
        android:layout_centerVertical="true"

        android:layout_marginStart="16dp"
        android:paddingStart="56dp"/>
</code>```

android:layout_marginStart="16dp" sets margin to both icon and text, while android:paddingStart="56dp" sets padding between text and icon.

Body:
Im trying to build my multiple choice layout according to latest material design guidelines with CheckedTextView widget. But I can't find the way to set left padding for checkbox and textview separately (16dp for icon, 72 for text).
The most acceptable solution i could find is to use android:drawablePadding attribute but i think it is not quite right.
Is it possible to set padding values separately inside CheckedTextView?

<?xml version="1.0" encoding="utf-8"?>

    <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"

        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:gravity="center_vertical"
        android:textSize="16sp"
        android:textColor="#000000"
        android:paddingLeft="16dp"
        android:drawableLeft="?android:attr/listChoiceIndicatorMultiple"
        android:drawablePadding="36dp"/>

Body:
I'm late to the party, but just in case someone is looking for a solution, here is how I did it using the CheckBox widget:

    <CheckBox
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:minHeight="30dp"
        android:textColor="#ffffff"
        android:layout_centerVertical="true"

        android:layout_marginStart="16dp"
        android:paddingStart="56dp"/>

android:layout_marginStart="16dp" sets margin to both icon and text, while android:paddingStart="56dp" sets padding between text and icon.


问:
Android Internet connectivity check better method
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

答:
Maybe this can help you:</p>

```<code>private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
        // Test for connection
        if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    }
    else {
        return false;
    }
}
</code>```

Body:
Maybe this can help you:

private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
        // Test for connection
        if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    }
    else {
        return false;
    }
}


问:
How to check MySQL performance?
i have mysql that is used on production server for php webshop application.

sometimes it works very slow. so, i will change indexes for several tables.

but before that, i have to make some kind of "snapshot" of current performances (several times per day). after that, i will change indexes, and create new "performance snapshot". then i will made some more changes in database, and made another "performance snapshot".

how can i make that "performance snapshot"? is it possible to use some kind of tool, or to ckeck some logs, or...?

if you can help me how to do that.

thank you in advance!

答:
Slow query log and queries not using indexes

query cache hit rate

innodb monitor

and of course your database hard-disk I/O, memory usage ...

Title: How to check MySQL performance?


问:
how to select id from one table and insert into other table
```<code> $select = "SELECT MAX(order_id) FROM `order`";
       mysql_query($select);

   foreach ($_COOKIE['item'] as $key12 => $value) {
        $value22 = explode("__", $value);

        $query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
        $result2 = mysql_query($query1);
</code>```

The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id

答:
Recommendation:

Use only one batch INSERT query. It gives you the opportunity to insert multiple rows at once, e.g. by running only one query. And is a lot faster.

Used method:

Extract maximum of order_id from order and assign to $maxOrderId.

Iterate through cookie items and build corresponding rows
part of the INSERT sql statement. Then add it to the array $insertRowValues.

In the end implode the $insertRowValues array into the batch INSERT statement.

Run the batch INSERT query - only once.

```<code><?php

$select = "SELECT MAX(order_id) FROM `order`";
$maxOrderId = mysql_query($select);

$insertRowValues = array();

foreach ($_COOKIE['item'] as $key12 => $value) {
    $value22 = explode("__", $value);

    $insertRowValues[] = "('', " . $value22[5] . ", '" . $maxOrderId . "', '" . $value22[3] . "', '" . $value22[4] . "')";
}

$query1 = "INSERT INTO `cart`
            (`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`)
            VALUES " . implode(', ', $insertRowValues);

$result2 = mysql_query($query1);
</code>```

Other recommendations:

Use mysqli or PDO instead of mysql, because mysql is already removed as of PHP 5.5.0 (see MySQL Library - Introduction);

Use exception handling;

Use prepared statements to avoid MySQL injection.

P.S: I couldn't test anything.

Good luck!

Body:
 $select = "SELECT MAX(order_id) FROM `order`";
       mysql_query($select);

   foreach ($_COOKIE['item'] as $key12 => $value) {
        $value22 = explode("__", $value);

        $query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
        $result2 = mysql_query($query1);

The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id

Body:
Recommendation:

Use only one batch INSERT query. It gives you the opportunity to insert multiple rows at once, e.g. by running only one query. And is a lot faster.

Used method:

Extract maximum of order_id from order and assign to $maxOrderId.

Iterate through cookie items and build corresponding rows
part of the INSERT sql statement. Then add it to the array $insertRowValues.

In the end implode the $insertRowValues array into the batch INSERT statement.

Run the batch INSERT query - only once.

<?php

$select = "SELECT MAX(order_id) FROM `order`";
$maxOrderId = mysql_query($select);

$insertRowValues = array();

foreach ($_COOKIE['item'] as $key12 => $value) {
    $value22 = explode("__", $value);

    $insertRowValues[] = "('', " . $value22[5] . ", '" . $maxOrderId . "', '" . $value22[3] . "', '" . $value22[4] . "')";
}

$query1 = "INSERT INTO `cart`
            (`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`)
            VALUES " . implode(', ', $insertRowValues);

$result2 = mysql_query($query1);

Other recommendations:

Use mysqli or PDO instead of mysql, because mysql is already removed as of PHP 5.5.0 (see MySQL Library - Introduction);

Use exception handling;

Use prepared statements to avoid MySQL injection.

P.S: I couldn't test anything.

Good luck!


问:
powershell unable to recognize parameter
I am working on powershell script for connecting to server. If I am passing server name inside script without param it's working, but if I am using input as server name it is saying "server not found". See script below:

```<code>clear

#param([string]$servername)

$filePath = "c:\temp\result.txt"
$Servername= "cx-siscsqltest\sqlinst"

#$SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0)) as

#'ProductVer';"

$SqlQuery="select * from sys.sysaltfiles"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection

$SqlConnection.ConnectionString = "Server = '$Servername'; Database = master; Integrated Security = SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | out-file "C:\temp\version.csv"

#$version=System.Data.DataSet.Tables[0].Rows[0][0]
write-host $version
</code>```

Above code works well without parameters, if I take servername as parameter i get the following errors:

```<code>The term 'param' is not recognized as the name of a cmdlet, function, script fi
le, or operable program. Check the spelling of the name, or if a path was inclu
ded, verify that the path is correct and try again.
At D:\sysdba\install_sp.ps1:4 char:6
+ param <<<< ([string]$servername)
    + CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFou
   ndException
    + FullyQualifiedErrorId : CommandNotFoundException

Exception calling "Fill" with "1" argument(s): "A network-related or instance-s
pecific error occurred while establishing a connection to SQL Server. The serve
r was not found or was not accessible. Verify that the instance name is correct
 and that SQL Server is configured to allow remote connections. (provider: Name
d Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
At D:\sysdba\install_sp.ps1:25 char:17
+ $SqlAdapter.Fill <<<< ($DataSet)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
</code>```

Can you please help me out?

答: Param() must be the first line in your script. Remove the clear and you will see in your ISE that the colour of param() will change

Body:
I am working on powershell script for connecting to server. If I am passing server name inside script without param it's working, but if I am using input as server name it is saying "server not found". See script below:

clear

#param([string]$servername)

$filePath = "c:\temp\result.txt"
$Servername= "cx-siscsqltest\sqlinst"

#$SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0)) as

#'ProductVer';"

$SqlQuery="select * from sys.sysaltfiles"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection

$SqlConnection.ConnectionString = "Server = '$Servername'; Database = master; Integrated Security = SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | out-file "C:\temp\version.csv"

#$version=System.Data.DataSet.Tables[0].Rows[0][0]
write-host $version

Above code works well without parameters, if I take servername as parameter i get the following errors:

The term 'param' is not recognized as the name of a cmdlet, function, script fi
le, or operable program. Check the spelling of the name, or if a path was inclu
ded, verify that the path is correct and try again.
At D:\sysdba\install_sp.ps1:4 char:6
+ param <<<< ([string]$servername)
    + CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFou
   ndException
    + FullyQualifiedErrorId : CommandNotFoundException

Exception calling "Fill" with "1" argument(s): "A network-related or instance-s
pecific error occurred while establishing a connection to SQL Server. The serve
r was not found or was not accessible. Verify that the instance name is correct
 and that SQL Server is configured to allow remote connections. (provider: Name
d Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
At D:\sysdba\install_sp.ps1:25 char:17
+ $SqlAdapter.Fill <<<< ($DataSet)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Can you please help me out?


问:
How to do something when a CheckBox is unchecked
I want a select all CheckBox which when Checked, checks all other CheckBoxes and when Unchecked, unchecks the others. I have written this code:

```<code>private void all_CheckedChanged(object sender, RoutedEventArgs e)
{
    if (all.IsChecked == true)//this is working
    {
        issue.IsChecked = true;
        summary.IsChecked = true;
        type.IsChecked = true;
        status.IsChecked = true;
        label.IsChecked = true;
        components.IsChecked = true;
        empty.IsChecked = true;
        reporter.IsChecked = true;
        requester.IsChecked = true;
        team.IsChecked = true;
        assignee.IsChecked = true;
    }
    else if (all.IsChecked == false)//this is not doing anything
    {
        issue.IsChecked = false;
        summary.IsChecked = false;
        type.IsChecked = false;
        //same for other checkboxes
    }
}
</code>```

when I debug it I see that the event takes places when I check the CheckBox but nothing happens when I uncheck it. Someone, please suggest me how to do this in case I am doing something wrong.

答:
This is assuming you already have the checkboxes in the XAML file.

Be sure to add the Checked and Unchecked events to the SelectAll checkbox in the XAML file.

Then, populate what you want each event to do. In your case, you want the Checked event to check all the other checkboxes and the Unchecked event to do the opposite.

Try this...

MainPage.xaml.cs file

```<code>private void SelectAll_Checked(object sender, RoutedEventArgs e)
{
   issue.IsChecked = true;
   // Do the rest for all other checkboxes you want to check
}

private void SelectAll_Unchecked(object sender, RoutedEventArgs e)
{
    issue.IsChecked = false;
   // Do the rest for all other checkboxes you want to uncheck
}
</code>```

MainPage.xaml file

```<code><CheckBox x:Name="SelectAll" Content="Select All" HorizontalAlignment="Left" Margin="107,125,0,0" VerticalAlignment="Top"
    Checked="SelectAll_Checked"
    Unchecked="SelectAll_Unchecked" />
<!-- Other checkboxes ... -->
</code>```

Check out my Gist link for this example.

Body:
I want a select all CheckBox which when Checked, checks all other CheckBoxes and when Unchecked, unchecks the others. I have written this code:

private void all_CheckedChanged(object sender, RoutedEventArgs e)
{
    if (all.IsChecked == true)//this is working
    {
        issue.IsChecked = true;
        summary.IsChecked = true;
        type.IsChecked = true;
        status.IsChecked = true;
        label.IsChecked = true;
        components.IsChecked = true;
        empty.IsChecked = true;
        reporter.IsChecked = true;
        requester.IsChecked = true;
        team.IsChecked = true;
        assignee.IsChecked = true;
    }
    else if (all.IsChecked == false)//this is not doing anything
    {
        issue.IsChecked = false;
        summary.IsChecked = false;
        type.IsChecked = false;
        //same for other checkboxes
    }
}

when I debug it I see that the event takes places when I check the CheckBox but nothing happens when I uncheck it. Someone, please suggest me how to do this in case I am doing something wrong.

Body:
This is assuming you already have the checkboxes in the XAML file.

Be sure to add the Checked and Unchecked events to the SelectAll checkbox in the XAML file.

Then, populate what you want each event to do. In your case, you want the Checked event to check all the other checkboxes and the Unchecked event to do the opposite.

Try this...

MainPage.xaml.cs file

private void SelectAll_Checked(object sender, RoutedEventArgs e)
{
   issue.IsChecked = true;
   // Do the rest for all other checkboxes you want to check
}

private void SelectAll_Unchecked(object sender, RoutedEventArgs e)
{
    issue.IsChecked = false;
   // Do the rest for all other checkboxes you want to uncheck
}

MainPage.xaml file

<CheckBox x:Name="SelectAll" Content="Select All" HorizontalAlignment="Left" Margin="107,125,0,0" VerticalAlignment="Top"
    Checked="SelectAll_Checked"
    Unchecked="SelectAll_Unchecked" />
<!-- Other checkboxes ... -->

Check out my Gist link for this example.


问:
Use ng2-adal to get access token for Microsoft Graph Client
I'm trying to create an Angular application that uses the Angular 2 ADAL library to login into Azure Active Directory and afterwards call Microsoft Graph Client to retrieve some informations about the current user.

Unfortunately the Graph client always returns InvalidAuthenticationToken and I don't know how to further investigate to find the root cause.

my.component.ts

```<code>import { Component, Inject, OnInit } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';
import { Client } from '@microsoft/microsoft-graph-client';

import { SecretService } from '../../shared/secret.service';
import { AdalService } from 'ng2-adal/services/adal.service';

@Component({
    selector: 'my',
    templateUrl: './my.component.html'
})
export class MyComponent implements OnInit {
    isBrowser: boolean;
    private graphClient: Client;
    private userProfile: any;

    constructor(
        @Inject(PLATFORM_ID) platformId: Object,
        private adalService: AdalService,
        private secretService: SecretService) {
        this.isBrowser = isPlatformBrowser(platformId);
        adalService.init(secretService.adalConfig);

        // Don't initialize graph client in server-side-rendering
        if (this.isBrowser) {
            this.graphClient = Client.init({
                authProvider: (done) => {
                    done(undefined, this.adalService.getCachedToken(this.secretService.adalConfig.clientId));
                }
            });
        }
    }

    get isLoggedIn(): boolean {
        if (!this.isBrowser)
            return false;

        return this.adalService.userInfo.isAuthenticated;
    }

    ngOnInit() {
        // Fast exit on server-side-rendering
        if (!this.isBrowser)
            return;

        // Initialize ADAL service
        this.adalService.handleWindowCallback();
        this.adalService.getUser();

        // If we are already logged in (cause reply url is called from login)
        // use Graph API to get some data about the current user
        if (this.isLoggedIn) {
            this.graphClient.api('/me').get().then((value) => {
                this.userProfile = value;
            }).catch((error) => {
                // Currently I'm always getting here, but never in the above then() call.
                console.log(error);
            });
        }
    }

    onLogin() {
        this.adalService.login();
    }

    onLogout() {
        this.adalService.logOut();
    }
}
</code>```

my.component.html

```<code><md-toolbar>
    <md-toolbar-row>
        <button color="primary" md-button *ngIf="!isLoggedIn" (click)="onLogin()">
            Login
        </button>
        <button color="accent" md-button *ngIf="isLoggedIn" (click)="onLogout()">
            Logout
        </button>
    </md-toolbar-row>
</md-toolbar>
<md-card>
    <md-card-content>
        <section>
            {{userProfile}}
        </section>
    </md-card-content>
</md-card>
</code>```

答:
Based on the code, you were calling the Microsoft Graph using the id_token issued from Azure AD. To call the Microsoft Graph, we need to use the access_token and its audience should be https://graph.microsoft.com.

You need to acquire the access_token for the Microsoft Graph using the code like below:

```<code>this.adalService.acquireToken("https://graph.microsoft.com").subscribe(function(token){
          this.graphClient = Client.init({
            authProvider: (done) => {
                done(undefined, token);
            }
        });
</code>```

More detail about authentication of Microsoft Graph, you can refer the link below:

Get access tokens to call Microsoft Graph

Body:
I'm trying to create an Angular application that uses the Angular 2 ADAL library to login into Azure Active Directory and afterwards call Microsoft Graph Client to retrieve some informations about the current user.

Unfortunately the Graph client always returns InvalidAuthenticationToken and I don't know how to further investigate to find the root cause.

my.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';
import { Client } from '@microsoft/microsoft-graph-client';

import { SecretService } from '../../shared/secret.service';
import { AdalService } from 'ng2-adal/services/adal.service';

@Component({
    selector: 'my',
    templateUrl: './my.component.html'
})
export class MyComponent implements OnInit {
    isBrowser: boolean;
    private graphClient: Client;
    private userProfile: any;

    constructor(
        @Inject(PLATFORM_ID) platformId: Object,
        private adalService: AdalService,
        private secretService: SecretService) {
        this.isBrowser = isPlatformBrowser(platformId);
        adalService.init(secretService.adalConfig);

        // Don't initialize graph client in server-side-rendering
        if (this.isBrowser) {
            this.graphClient = Client.init({
                authProvider: (done) => {
                    done(undefined, this.adalService.getCachedToken(this.secretService.adalConfig.clientId));
                }
            });
        }
    }

    get isLoggedIn(): boolean {
        if (!this.isBrowser)
            return false;

        return this.adalService.userInfo.isAuthenticated;
    }

    ngOnInit() {
        // Fast exit on server-side-rendering
        if (!this.isBrowser)
            return;

        // Initialize ADAL service
        this.adalService.handleWindowCallback();
        this.adalService.getUser();

        // If we are already logged in (cause reply url is called from login)
        // use Graph API to get some data about the current user
        if (this.isLoggedIn) {
            this.graphClient.api('/me').get().then((value) => {
                this.userProfile = value;
            }).catch((error) => {
                // Currently I'm always getting here, but never in the above then() call.
                console.log(error);
            });
        }
    }

    onLogin() {
        this.adalService.login();
    }

    onLogout() {
        this.adalService.logOut();
    }
}

my.component.html

<md-toolbar>
    <md-toolbar-row>
        <button color="primary" md-button *ngIf="!isLoggedIn" (click)="onLogin()">
            Login
        </button>
        <button color="accent" md-button *ngIf="isLoggedIn" (click)="onLogout()">
            Logout
        </button>
    </md-toolbar-row>
</md-toolbar>
<md-card>
    <md-card-content>

            {{userProfile}}

    </md-card-content>
</md-card>

Body:
Based on the code, you were calling the Microsoft Graph using the id_token issued from Azure AD. To call the Microsoft Graph, we need to use the access_token and its audience should be https://graph.microsoft.com.

You need to acquire the access_token for the Microsoft Graph using the code like below:

this.adalService.acquireToken("https://graph.microsoft.com").subscribe(function(token){
          this.graphClient = Client.init({
            authProvider: (done) => {
                done(undefined, token);
            }
        });

More detail about authentication of Microsoft Graph, you can refer the link below:

Get access tokens to call Microsoft Graph


问:
Jquery Cool Drag and Drop snap to position
Anyone know how you do that cool thing in JQuery where you can drag and drop divs and it snaps to position and saves location?</p>

答: Try checking out jQuery UI - more relevantly the Draggable feature.</p>


问:
How to invoke c# function from another project without adding reference?
There is a C#.net library project whose DLL name is customer.dll. It has a class name customer with a function name show(). I want to call this function from another project but don't want to add the reference to the caller project. Can this be done? Is there any C#.net class that can achieve this?

答:
Yes, you can load assemblies dynamically using Assembly.LoadFile

```<code>Assembly.LoadFile("c:\\somefolder\\Path\\To\\Code.dll");
</code>```

You are then going to need to use Reflection to get the methodinfo for the function you want to invoke or use the Dynamic keyword to invoke it.

```<code>var externalDll = Assembly.LoadFile("c:\\somefolder\\Customer.dll");
var externalTypeByName = externalDll.GetType("CustomerClassNamespace.Customer");

// If you don't know the full type name, use linq
var externalType = externalDll.ExportedTypes.FirstOrDefault(x => x.Name == "Customer");

//if the method is not static create an instance.
//using dynamic
dynamic dynamicInstance = Activator.CreateInstance(externalType);
var dynamicResult = dynamicInstance.show();

// or using reflection
var reflectionInstance = Activator.CreateInstance(externalType);
var methodInfo = theType.GetMethod("show");
var result = methodInfo.Invoke(reflectionInstance, null);

// Again you could also use LINQ to get the method
var methodLINQ = externalType.GetMethods().FirstOrDefault(x => x.Name == "show");
var resultLINQ = methodLINQ.Invoke(reflectionInstance, null);
</code>```

Body:
Yes, you can load assemblies dynamically using Assembly.LoadFile

Assembly.LoadFile("c:\\somefolder\\Path\\To\\Code.dll");

You are then going to need to use Reflection to get the methodinfo for the function you want to invoke or use the Dynamic keyword to invoke it.

var externalDll = Assembly.LoadFile("c:\\somefolder\\Customer.dll");
var externalTypeByName = externalDll.GetType("CustomerClassNamespace.Customer");

// If you don't know the full type name, use linq
var externalType = externalDll.ExportedTypes.FirstOrDefault(x => x.Name == "Customer");

//if the method is not static create an instance.
//using dynamic
dynamic dynamicInstance = Activator.CreateInstance(externalType);
var dynamicResult = dynamicInstance.show();

// or using reflection
var reflectionInstance = Activator.CreateInstance(externalType);
var methodInfo = theType.GetMethod("show");
var result = methodInfo.Invoke(reflectionInstance, null);

// Again you could also use LINQ to get the method
var methodLINQ = externalType.GetMethods().FirstOrDefault(x => x.Name == "show");
var resultLINQ = methodLINQ.Invoke(reflectionInstance, null);

ContentLicense: CC BY-SA 4.0


问:
Convert data with one column and multiple rows into multi column multi row data
I have an output of web scraped data in R which looks as follows

```<code>Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3
</code>```

Some names may not have email or location. I want convert above data into tabular format. The output should look like

```<code>Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com
</code>```

答:
The input data offer several challenges:

Data are given as a straight character vector, not a as data.frame with predefined columns.

The rows partly consist of key/value pairs which are separated by ": "

The other rows act as section headers. All key/value pairs in the rows below belong to one section until the next header is reached.

The code below is relying only on two assumptions:

key/value pairs contain one and only one ": "

section headers none at all.

Multiple keys in a section, e.g., multiple rows with email adresses are handled by specifying toString() as aggregation function to dcast().

```<code>library(data.table)
# coerce to data.table
data.table(text = txt)[
  # split key/value pairs in columns
  , tstrsplit(text, ": ")][
    # pick section headers and create new column
    is.na(V2), Name := V1][
      # fill in Name into the rows below
      , Name := zoo::na.locf(Name)][
        # reshape key/value pairs from long to wide format using Name as row id
        !is.na(V2), dcast(.SD, Name ~ V1, fun = toString, value.var = "V2")]
</code>```

```<code>    Name City/Town          Email
1: Name1 Location1 email1@xyz.com
2: Name2 Location2 email2@abc.com
3: Name3 Location3 email3@pqr.com
4: Name4 Location4             NA
5: Name5        NA email5@abc.com
</code>```

Data

```<code>txt <- c("Name1", "Email: email1@xyz.com", "City/Town: Location1", "Name2",
"Email: email2@abc.com", "City/Town: Location2", "Name3", "Email: email3@pqr.com",
"City/Town: Location3", "Name4", "City/Town: Location4", "Name5",
"Email: email5@abc.com")
</code>```

Or, try somewhat more "realistic" names

```<code>txt1 <- c("John Doe", "Email: email1@xyz.com", "City/Town: Location1", "Save the World Fund",
"Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com",
"City/Town: Location3", "Mother", "City/Town: Location4", "Jane",
"Email: email5@abc.com")
</code>```

which will result in:

```<code>                  Name City/Town          Email
1:     Best Shoes Ltd. Location3 email3@pqr.com
2:                Jane        NA email5@abc.com
3:            John Doe Location1 email1@xyz.com
4:              Mother Location4             NA
5: Save the World Fund Location2 email2@abc.com
</code>```

Or, with multiple keys per section

```<code>txt2 <- c("John Doe", "Email: email1@xyz.com", "Email: email1@abc.com", "City/Town: Location1", "Save the World Fund",
"Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com",
"City/Town: Location3", "Mother", "City/Town: Location4", "City/Town: everywhere", "Jane",
"Email: email5@abc.com")
</code>```

```<code>                  Name             City/Town                          Email
1:     Best Shoes Ltd.             Location3                 email3@pqr.com
2:                Jane                                       email5@abc.com
3:            John Doe             Location1 email1@xyz.com, email1@abc.com
4:              Mother Location4, everywhere
5: Save the World Fund             Location2                 email2@abc.com
</code>```

Body:
I have an output of web scraped data in R which looks as follows

Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3

Some names may not have email or location. I want convert above data into tabular format. The output should look like

Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com

Body:
The input data offer several challenges:

Data are given as a straight character vector, not a as data.frame with predefined columns.

The rows partly consist of key/value pairs which are separated by ": "

The other rows act as section headers. All key/value pairs in the rows below belong to one section until the next header is reached.

The code below is relying only on two assumptions:

key/value pairs contain one and only one ": "

section headers none at all.

Multiple keys in a section, e.g., multiple rows with email adresses are handled by specifying toString() as aggregation function to dcast().

library(data.table)
# coerce to data.table
data.table(text = txt)[
  # split key/value pairs in columns
  , tstrsplit(text, ": ")][
    # pick section headers and create new column
    is.na(V2), Name := V1][
      # fill in Name into the rows below
      , Name := zoo::na.locf(Name)][
        # reshape key/value pairs from long to wide format using Name as row id
        !is.na(V2), dcast(.SD, Name ~ V1, fun = toString, value.var = "V2")]

    Name City/Town          Email
1: Name1 Location1 email1@xyz.com
2: Name2 Location2 email2@abc.com
3: Name3 Location3 email3@pqr.com
4: Name4 Location4             NA
5: Name5        NA email5@abc.com

Data

txt <- c("Name1", "Email: email1@xyz.com", "City/Town: Location1", "Name2",
"Email: email2@abc.com", "City/Town: Location2", "Name3", "Email: email3@pqr.com",
"City/Town: Location3", "Name4", "City/Town: Location4", "Name5",
"Email: email5@abc.com")

Or, try somewhat more "realistic" names

txt1 <- c("John Doe", "Email: email1@xyz.com", "City/Town: Location1", "Save the World Fund",
"Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com",
"City/Town: Location3", "Mother", "City/Town: Location4", "Jane",
"Email: email5@abc.com")

which will result in:

                  Name City/Town          Email
1:     Best Shoes Ltd. Location3 email3@pqr.com
2:                Jane        NA email5@abc.com
3:            John Doe Location1 email1@xyz.com
4:              Mother Location4             NA
5: Save the World Fund Location2 email2@abc.com

Or, with multiple keys per section

txt2 <- c("John Doe", "Email: email1@xyz.com", "Email: email1@abc.com", "City/Town: Location1", "Save the World Fund",
"Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com",
"City/Town: Location3", "Mother", "City/Town: Location4", "City/Town: everywhere", "Jane",
"Email: email5@abc.com")

                  Name             City/Town                          Email
1:     Best Shoes Ltd.             Location3                 email3@pqr.com
2:                Jane                                       email5@abc.com
3:            John Doe             Location1 email1@xyz.com, email1@abc.com
4:              Mother Location4, everywhere
5: Save the World Fund             Location2                 email2@abc.com


问:
How to remove docker container even if root filesystem does not exists?
I have one container that is dead, but I can't remove it, as you can see below.

How can I remove it? Or how can I clean my system manually to remove it?

```<code>:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
78b0dcaffa89        ubuntu:latest       "bash -c 'while tr..."   30 hours ago        Dead                                    leo.1.bkbjt6w08vgeo39rt1nmi7ock

:~$ docker rm --force 78b0dcaffa89
Error response from daemon: driver "aufs" failed to remove root filesystem for 78b0dcaffa89ac1e532748d44c9b2f57b940def0e34f1f0d26bf7ea1a10c222b: no such file or directory
</code>```

答:
As the error message states, docker was configured to use AUFS as storage driver, but they recommend to use Overlay2 instead, as you can read on this link:
https://github.com/moby/moby/issues/21704#issuecomment-312934372

So I changed my configuration to use Overlay2 as docker storage driver. When we do that it removes EVERYTHING from old storage drive, it means that my "Dead" container was gone also.

It is not exactly a solution for my original question, but the result was accomplished.

Body:
I have one container that is dead, but I can't remove it, as you can see below.

How can I remove it? Or how can I clean my system manually to remove it?

:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
78b0dcaffa89        ubuntu:latest       "bash -c 'while tr..."   30 hours ago        Dead                                    leo.1.bkbjt6w08vgeo39rt1nmi7ock

:~$ docker rm --force 78b0dcaffa89
Error response from daemon: driver "aufs" failed to remove root filesystem for 78b0dcaffa89ac1e532748d44c9b2f57b940def0e34f1f0d26bf7ea1a10c222b: no such file or directory


问:
CSP Refuse to load base64 image
I am working on an ionic 2 application and receiving error message from the console stating that refuse to load image and script because it violates the CSP rules.

As for the image, it is being stored is the database as blob. I am able to get the base64 values but could not display it on the application.

Index.html

```<code><head>
    <meta http-equiv="Content-Security-Policy" content="
       img-src 'self' data: https://s-media-cache-ak0.pinimg.com;
    " />
</head>
</code>```

Component Html

```<code><ion-card>
<img src="data:image/png;base64,{{storePhoto}}">
</ion-card>
</code>```

Error Message : Refused to load the image 'unsafe:data:image/png;base64,' because it violates the following Content Security Policy directive: "img-src 'self' data: https://s-media-cache-ak0.pinimg.com".

Update

I tried using DomSanitizer from angular but hits another error. This is my updated code.

Component ts

```<code>import { DomSanitizer } from '@angular/platform-browser';
constructor(public DomSanitizerService : DomSanitizer){}
</code>```

Component ts

```<code><img [src]="_DomSanitizationService.bypassSecurityTrustUrl(data:image/png;base64,{{storePhoto}})" />
</code>```

Uncaught(in promise):Error: Template parse errors:Parser Error: Got interpolation ({{}})

答:
The message indicates you need to add https://s-media-cache-ak0.pinimg.com to your policy:

<meta http-equiv="Content-Security-Policy" content="
img-src 'self' data: https://s-media-cache-ak0.pinimg.com;
script-src 'self' https://maps.googleapis.com;
" />
```

Title: CSP Refuse to load base64 image

Body:
I am working on an ionic 2 application and receiving error message from the console stating that refuse to load image and script because it violates the CSP rules.

As for the image, it is being stored is the database as blob. I am able to get the base64 values but could not display it on the application.

Index.html

    <meta http-equiv="Content-Security-Policy" content="
       img-src 'self' data: https://s-media-cache-ak0.pinimg.com;
    " />

Component Html

<ion-card>

</ion-card>

Error Message : Refused to load the image 'unsafe:data:image/png;base64,' because it violates the following Content Security Policy directive: "img-src 'self' data: https://s-media-cache-ak0.pinimg.com".

Update

I tried using DomSanitizer from angular but hits another error. This is my updated code.

Component ts

import { DomSanitizer } from '@angular/platform-browser';
constructor(public DomSanitizerService : DomSanitizer){}

Component ts

Uncaught(in promise):Error: Template parse errors:Parser Error: Got interpolation ({{}})


问:
Entity Framework DELETE statement conflicted with the REFERENCE constraint
I’m pretty new to EF and I have a little problem.

I just want to delete an item in my database. I’m using SQL Server 2012 Express, VS2012, AdventureWorks 2012.

The query that I execute is the following:

```<code>context = new AWEntities();
            var removedItem = context.Addresses
                .Include("StateProvince")
                .Include("SalesOrderHeaders")
                .Include("BusinessEntityAddresses").Single(d => d.AddressID == 11);
            context.Addresses.Remove(removedItem);

context.SaveChanges();
</code>```

The error that I get is

The DELETE statement conflicted with the REFERENCE constraint "FK_SalesOrderHeader_Address_ShipToAddressID". The conflict occurred in database "AdventureWorks2012", table "Sales.SalesOrderHeader", column 'ShipToAddressID'.
      The statement has been terminated.

Is this actually a good way to delete items and the according entries in the other tables?

Please point me into the right direction.

```<code>   public partial class Address
    {
        public Address()
        {
            this.BusinessEntityAddresses = new HashSet<BusinessEntityAddress>();
            this.SalesOrderHeaders = new HashSet<SalesOrderHeader>();
        }

        public int AddressID { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
        public int StateProvinceID { get; set; }
        public string PostalCode { get; set; }
        public System.Data.Spatial.DbGeography SpatialLocation { get; set; }
        public System.Guid rowguid { get; set; }
        public System.DateTime ModifiedDate { get; set; }

        public virtual StateProvince StateProvince { get; set; }
        public virtual ICollection<BusinessEntityAddress> BusinessEntityAddresses { get; set; }
        public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; }
    }

public partial class StateProvince
    {
        public StateProvince()
        {
            this.Addresses = new HashSet<Address>();
            this.SalesTaxRates = new HashSet<SalesTaxRate>();
        }

        public int StateProvinceID { get; set; }
        public string StateProvinceCode { get; set; }
        public string CountryRegionCode { get; set; }
        public bool IsOnlyStateProvinceFlag { get; set; }
        public string Name { get; set; }
        public int TerritoryID { get; set; }
        public System.Guid rowguid { get; set; }
        public System.DateTime ModifiedDate { get; set; }

        public virtual ICollection<Address> Addresses { get; set; }
        public virtual CountryRegion CountryRegion { get; set; }
        public virtual ICollection<SalesTaxRate> SalesTaxRates { get; set; }
        public virtual SalesTerritory SalesTerritory { get; set; }
    }
}

public partial class BusinessEntityAddress
{
    public int BusinessEntityID { get; set; }
    public int AddressID { get; set; }
    public int AddressTypeID { get; set; }
    public System.Guid rowguid { get; set; }
    public System.DateTime ModifiedDate { get; set; }

    public virtual Address Address { get; set; }
    public virtual AddressType AddressType { get; set; }
    public virtual BusinessEntity BusinessEntity { get; set; }
}

public partial class SalesOrderHeader
    {
        public SalesOrderHeader()
        {
            this.SalesOrderDetails = new HashSet<SalesOrderDetail>();
            this.SalesOrderHeaderSalesReasons = new HashSet<SalesOrderHeaderSalesReason>();
        }

        public int SalesOrderID { get; set; }
        public byte RevisionNumber { get; set; }
        public System.DateTime OrderDate { get; set; }
        public System.DateTime DueDate { get; set; }
        public Nullable<System.DateTime> ShipDate { get; set; }
        public byte Status { get; set; }
        public bool OnlineOrderFlag { get; set; }
        public string SalesOrderNumber { get; set; }
        public string PurchaseOrderNumber { get; set; }
        public string AccountNumber { get; set; }
        public int CustomerID { get; set; }
        public Nullable<int> SalesPersonID { get; set; }
        public Nullable<int> TerritoryID { get; set; }
        public int BillToAddressID { get; set; }
        public int ShipToAddressID { get; set; }
        public int ShipMethodID { get; set; }
        public Nullable<int> CreditCardID { get; set; }
        public string CreditCardApprovalCode { get; set; }
        public Nullable<int> CurrencyRateID { get; set; }
        public decimal SubTotal { get; set; }
        public decimal TaxAmt { get; set; }
        public decimal Freight { get; set; }
        public decimal TotalDue { get; set; }
        public string Comment { get; set; }
        public System.Guid rowguid { get; set; }
        public System.DateTime ModifiedDate { get; set; }

        public virtual Address Address { get; set; }
        public virtual ShipMethod ShipMethod { get; set; }
        public virtual CreditCard CreditCard { get; set; }
        public virtual CurrencyRate CurrencyRate { get; set; }
        public virtual Customer Customer { get; set; }
        public virtual ICollection<SalesOrderDetail> SalesOrderDetails { get; set; }
        public virtual SalesPerson SalesPerson { get; set; }
        public virtual SalesTerritory SalesTerritory { get; set; }
        public virtual ICollection<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; }
    }
</code>```

答:
```<code>  modelBuilder.Entity<Parent>()
  .HasMany<Child>(c => c.Children)
  .WithOptional(x => x.Parent)
  .WillCascadeOnDelete(true);
</code>```

or use Include

```<code>  var adv = db.Adv.Include(b => b.Features)
                  .Include(b => b.AdvDetails)
                  .Include(b => b.AdvGallery)
                  .FirstOrDefault(b => b.Id == id);
  db.Adv.Remove(adv);
</code>```

for .HasMany(...).WithMany(...) Include is ok

Body:
I’m pretty new to EF and I have a little problem.

I just want to delete an item in my database. I’m using SQL Server 2012 Express, VS2012, AdventureWorks 2012.

The query that I execute is the following:

context = new AWEntities();
            var removedItem = context.Addresses
                .Include("StateProvince")
                .Include("SalesOrderHeaders")
                .Include("BusinessEntityAddresses").Single(d => d.AddressID == 11);
            context.Addresses.Remove(removedItem);

context.SaveChanges();

The error that I get is

The DELETE statement conflicted with the REFERENCE constraint "FK_SalesOrderHeader_Address_ShipToAddressID". The conflict occurred in database "AdventureWorks2012", table "Sales.SalesOrderHeader", column 'ShipToAddressID'.
      The statement has been terminated.

Is this actually a good way to delete items and the according entries in the other tables?

Please point me into the right direction.

   public partial class Address
    {
        public Address()
        {
            this.BusinessEntityAddresses = new HashSet<BusinessEntityAddress>();
            this.SalesOrderHeaders = new HashSet<SalesOrderHeader>();
        }

        public int AddressID { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
        public int StateProvinceID { get; set; }
        public string PostalCode { get; set; }
        public System.Data.Spatial.DbGeography SpatialLocation { get; set; }
        public System.Guid rowguid { get; set; }
        public System.DateTime ModifiedDate { get; set; }

        public virtual StateProvince StateProvince { get; set; }
        public virtual ICollection<BusinessEntityAddress> BusinessEntityAddresses { get; set; }
        public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; }
    }

public partial class StateProvince
    {
        public StateProvince()
        {
            this.Addresses = new HashSet<Address>();
            this.SalesTaxRates = new HashSet<SalesTaxRate>();
        }

        public int StateProvinceID { get; set; }
        public string StateProvinceCode { get; set; }
        public string CountryRegionCode { get; set; }
        public bool IsOnlyStateProvinceFlag { get; set; }
        public string Name { get; set; }
        public int TerritoryID { get; set; }
        public System.Guid rowguid { get; set; }
        public System.DateTime ModifiedDate { get; set; }

        public virtual ICollection<Address> Addresses { get; set; }
        public virtual CountryRegion CountryRegion { get; set; }
        public virtual ICollection<SalesTaxRate> SalesTaxRates { get; set; }
        public virtual SalesTerritory SalesTerritory { get; set; }
    }
}

public partial class BusinessEntityAddress
{
    public int BusinessEntityID { get; set; }
    public int AddressID { get; set; }
    public int AddressTypeID { get; set; }
    public System.Guid rowguid { get; set; }
    public System.DateTime ModifiedDate { get; set; }

    public virtual Address Address { get; set; }
    public virtual AddressType AddressType { get; set; }
    public virtual BusinessEntity BusinessEntity { get; set; }
}

public partial class SalesOrderHeader
    {
        public SalesOrderHeader()
        {
            this.SalesOrderDetails = new HashSet<SalesOrderDetail>();
            this.SalesOrderHeaderSalesReasons = new HashSet<SalesOrderHeaderSalesReason>();
        }

        public int SalesOrderID { get; set; }
        public byte RevisionNumber { get; set; }
        public System.DateTime OrderDate { get; set; }
        public System.DateTime DueDate { get; set; }
        public Nullable<System.DateTime> ShipDate { get; set; }
        public byte Status { get; set; }
        public bool OnlineOrderFlag { get; set; }
        public string SalesOrderNumber { get; set; }
        public string PurchaseOrderNumber { get; set; }
        public string AccountNumber { get; set; }
        public int CustomerID { get; set; }
        public Nullable<int> SalesPersonID { get; set; }
        public Nullable<int> TerritoryID { get; set; }
        public int BillToAddressID { get; set; }
        public int ShipToAddressID { get; set; }
        public int ShipMethodID { get; set; }
        public Nullable<int> CreditCardID { get; set; }
        public string CreditCardApprovalCode { get; set; }
        public Nullable<int> CurrencyRateID { get; set; }
        public decimal SubTotal { get; set; }
        public decimal TaxAmt { get; set; }
        public decimal Freight { get; set; }
        public decimal TotalDue { get; set; }
        public string Comment { get; set; }
        public System.Guid rowguid { get; set; }
        public System.DateTime ModifiedDate { get; set; }

        public virtual Address Address { get; set; }
        public virtual ShipMethod ShipMethod { get; set; }
        public virtual CreditCard CreditCard { get; set; }
        public virtual CurrencyRate CurrencyRate { get; set; }
        public virtual Customer Customer { get; set; }
        public virtual ICollection<SalesOrderDetail> SalesOrderDetails { get; set; }
        public virtual SalesPerson SalesPerson { get; set; }
        public virtual SalesTerritory SalesTerritory { get; set; }
        public virtual ICollection<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; }
    }

Body:
  modelBuilder.Entity<Parent>()
  .HasMany<Child>(c => c.Children)
  .WithOptional(x => x.Parent)
  .WillCascadeOnDelete(true);

or use Include

  var adv = db.Adv.Include(b => b.Features)
                  .Include(b => b.AdvDetails)
                  .Include(b => b.AdvGallery)
                  .FirstOrDefault(b => b.Id == id);
  db.Adv.Remove(adv);

for .HasMany(...).WithMany(...) Include is ok


问:
How to make shell script executable after decompress without chmod
I am studying linux, and I have to make all shell scripts executable by this command:

```<code>find ./ -name "*.sh" -exec chmod u+x {} \;
</code>```

But when I download Logstash.tar.gz and extract it to /opt, all shell scripts were executable, no chmod needed. And /opt is not in $PATH.

```<code>echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
</code>```

How do I build an app like logstash works?

===updated test steps for verification===

```<code>mkdir testtar && cd testtar
## create a executable script
echo test_with_x >> test_with_x.sh
chmod u+x test_with_x.sh
## create a not executable script
echo test_without_x >> test_without_x.sh
cd ..
## compress with gzip
tar -zcvf testtar.tar.gz ./testtar

mkdir testextract
mv testtar.tar.gz ./testextract
cd ./testextract
tar -zxvf testtar.tar.gz
## decompressed and see a executable and not executable script
</code>```

答:
You have two solution:

Add /opt to the PATH:

```<code>export PATH=${PATH}:/opt
</code>```

call logstash with full path:

```<code>/opt/<anywhere.it.may.be>/logstash
</code>```

Body:
I am studying linux, and I have to make all shell scripts executable by this command:

find ./ -name "*.sh" -exec chmod u+x {} \;

But when I download Logstash.tar.gz and extract it to /opt, all shell scripts were executable, no chmod needed. And /opt is not in $PATH.

echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin

How do I build an app like logstash works?

===updated test steps for verification===

mkdir testtar && cd testtar
## create a executable script
echo test_with_x >> test_with_x.sh
chmod u+x test_with_x.sh
## create a not executable script
echo test_without_x >> test_without_x.sh
cd ..
## compress with gzip
tar -zcvf testtar.tar.gz ./testtar

mkdir testextract
mv testtar.tar.gz ./testextract
cd ./testextract
tar -zxvf testtar.tar.gz
## decompressed and see a executable and not executable script

Body:
You have two solution:

Add /opt to the PATH:

export PATH=${PATH}:/opt

call logstash with full path:

/opt/<anywhere.it.may.be>/logstash


问:
How to get radio button selected value from dynamically generated radio buttons?
Hi I am developing web application in angularjs. I am generating radiobuttons dynamically using ng-repeat as below.

```<code><ul>
    <li ng-repeat="level in permissions">
        <input name="level.perm_levelname" type="radio" ng-model="level.perm_levelname" value="{{level.perm_levelname}}"> {{level.perm_levelname}}
        <a ng-click="gotopermMap({permisssionID: level.id})">View</a>
    </li>
</ul>
<input type="button" value="APPLY" ng-click="apply()" />
</code>```

I am trying to get selected radio button as below.

```<code> $scope.apply=function()
        {
            var permname = $scope.name;
            console.log($scope.level.perm_levelname);
        }
</code>```

I am getting error  Cannot read property 'perm_levelname' of undefined. May i get help here to get selected radio button? Thank you

答:
group radio buttons by a name and specify a common scope variable for radio buttons ng-modal

```<code>   <ul>
     <li ng-repeat="level in permissions">
       <input name="myradiobtn" type="radio" ng-model="myradioBtnValue" ng-value="level.perm_levelname">
       {{level.perm_levelname}}
       <a ng-click="gotopermMap({permisssionID: level.id})">View</a>
     </li>
   </ul>
   <input type="button" value="APPLY" ng-click="apply()"/>
</code>```

Body:
Hi I am developing web application in angularjs. I am generating radiobuttons dynamically using ng-repeat as below.

        <input name="level.perm_levelname" type="radio" ng-model="level.perm_levelname" value="{{level.perm_levelname}}"> {{level.perm_levelname}}
        View

<input type="button" value="APPLY" ng-click="apply()" />

I am trying to get selected radio button as below.

 $scope.apply=function()
        {
            var permname = $scope.name;
            console.log($scope.level.perm_levelname);
        }

I am getting error  Cannot read property 'perm_levelname' of undefined. May i get help here to get selected radio button? Thank you

Body:
group radio buttons by a name and specify a common scope variable for radio buttons ng-modal

   <ul>
     <li ng-repeat="level in permissions">
       <input name="myradiobtn" type="radio" ng-model="myradioBtnValue" ng-value="level.perm_levelname">
       {{level.perm_levelname}}
       <a ng-click="gotopermMap({permisssionID: level.id})">View</a>
     </li>
   </ul>
   <input type="button" value="APPLY" ng-click="apply()"/>