问:
How to create this layout using LinearLayout?
I want to construct below layout using LinearLayout.
<img src="https://i.stack.imgur.com/AqBgH.png" alt="enter image description here">
I created that using ConstraintLayout,but it was too long for me. And now I am wondering how this layout could be created via LinearLayout? Is it possible? And also pictures have to have their own size,because I suppose that if it is match_parent or wrap_content,quality of image will be bad. This is how I tried to construct via LinearLayout,but result is too different. So,what I have to do? </p>

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.abay.myeleven.MyTeamActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/attacks"
        android:orientation="horizontal"
        android:layout_marginTop="25dp"
        android:layout_weight="1"
        >

        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/midfields"
        android:orientation="horizontal"
        android:layout_marginTop="25dp"
        android:layout_weight="1"
        >
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

        </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/defenders"
        android:orientation="horizontal"
        android:layout_marginTop="25dp"
        android:layout_weight="1"

        >
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

    </LinearLayout>

    <ImageButton
        android:layout_width="@dimen/player_width"
        android:layout_height="@dimen/player_height"
        android:src="@drawable/player_default"
        android:layout_weight="1"
        android:background="#FFF"
        android:layout_gravity="center"
        />

</LinearLayout>
</code>```

答:
Just add another LinearLayout around those groups and some padding for ImageView.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.abay.myeleven.MyTeamActivity">

<LinearLayout
    android:id="@+id/attacks"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:id="@+id/midfields"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:orientation="vertical"

    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:id="@+id/defenders"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:orientation="vertical"

    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

    </LinearLayout>
</LinearLayout>

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="25dp"
    android:background="#FFF"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:src="@drawable/player_default" />

</LinearLayout>
</code>```

Body:
I want to construct below layout using LinearLayout.

I created that using ConstraintLayout,but it was too long for me. And now I am wondering how this layout could be created via LinearLayout? Is it possible? And also pictures have to have their own size,because I suppose that if it is match_parent or wrap_content,quality of image will be bad. This is how I tried to construct via LinearLayout,but result is too different. So,what I have to do?

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.abay.myeleven.MyTeamActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/attacks"
        android:orientation="horizontal"
        android:layout_marginTop="25dp"
        android:layout_weight="1"
        >

        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/midfields"
        android:orientation="horizontal"
        android:layout_marginTop="25dp"
        android:layout_weight="1"
        >
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

        </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/defenders"
        android:orientation="horizontal"
        android:layout_marginTop="25dp"
        android:layout_weight="1"

        >
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />
        <ImageButton
            android:layout_width="@dimen/player_width"
            android:layout_height="@dimen/player_height"
            android:src="@drawable/player_default"
            android:layout_weight="1"
            android:background="#FFF"
            />

    </LinearLayout>

    <ImageButton
        android:layout_width="@dimen/player_width"
        android:layout_height="@dimen/player_height"
        android:src="@drawable/player_default"
        android:layout_weight="1"
        android:background="#FFF"
        android:layout_gravity="center"
        />

</LinearLayout>

Body:
Just add another LinearLayout around those groups and some padding for ImageView.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.abay.myeleven.MyTeamActivity">

<LinearLayout
    android:id="@+id/attacks"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:id="@+id/midfields"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:orientation="vertical"

    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:id="@+id/defenders"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:orientation="vertical"

    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFF"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:src="@drawable/player_default" />

    </LinearLayout>
</LinearLayout>

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="25dp"
    android:background="#FFF"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:src="@drawable/player_default" />

</LinearLayout>


来源: stackexchange

问:
Unknown encoding (\x001, not ASCII) to float in Python
I have this string in Python '\x005\x003\x00.\x000\x005\x006\x00' that represents the number 53.056.

I am trying to convert that to a float (float()) but if I try to cast it to a float I get ValueError: could not convert string to float:.

I read that every character beginning with \x is an ASCII character but I also know that in ASCII 5 is \x05 and not \x005 and that \x00 is the number 0 and not a null value like in this case.

I also tried to encode that in UTF-8 but with no result.

What encoding is that and and how do I convert that string to a float?

答:
It seems that chars are separated by a null byte \x00.
A solution would be:

```<code>s = b'\x005\x003\x00.\x000\x005\x006\x00'
float(s.replace(b'\x00',b''))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It seems that chars are separated by a null byte \x00.
A solution would be:

s = b'\x005\x003\x00.\x000\x005\x006\x00'
float(s.replace(b'\x00',b''))


问:
deleting ipv4 address belongs to the same subnet from linux interface using netlink API
I am using netlink API rtnl_addr_delete to delete the ipv4 address configured on interface in Linux. Two IPs belonging to the same subnet are configured to an interface.

When i delete the first configured IP, both IPs are getting deleted which is unexpected. But vice versa is not true, when I delete the second configured IP, the first one does not getting deleted which is expected.

Suppose if 2 IPs belonging to the different subnet, issue is not seen. That is, if i delete first then only first one is deleting.

Any idea weather it is how this rtnl_addr_delete behaves or any resolutions can be made to fix this issue?

答:
When you remove the first added IP address from one subnet (the «primary» address), all the subnet is being deleted. That's the default kernel behaviour in some distributions. To change that, you have to set sysctl on the interface you work with:

```<code>$ sysctl -a | grep promote_secondaries
</code>```

Say, you want to change that on eth0:

```<code>$ sudo sysctl -w net.ipv4.conf.eth0.promote_secondaries=1
</code>```

With promote_secondaries the rest of the subnet will not be removed, but instead one of the addresses will be promoted as the new primary.

Docs: https://www.kernel.org/doc/Documentation/networking/ip-sysctl.txt

Body:
When you remove the first added IP address from one subnet (the «primary» address), all the subnet is being deleted. That's the default kernel behaviour in some distributions. To change that, you have to set sysctl on the interface you work with:

$ sysctl -a | grep promote_secondaries

Say, you want to change that on eth0:

$ sudo sysctl -w net.ipv4.conf.eth0.promote_secondaries=1

With promote_secondaries the rest of the subnet will not be removed, but instead one of the addresses will be promoted as the new primary.

Docs: https://www.kernel.org/doc/Documentation/networking/ip-sysctl.txt


问:
NGINX proxy_pass to ELB with Variable
I am trying to setup a proxy rule for nginx that will hit an internal loadbalancer in front of some node boxes serving an API. I want to use a variable in the address to force it to resolve because of how dynamic the addresses are in aws.

The original setup works fine but occasionally was pointing to an addresss that was no longer there which caused intermittent problems as would be expected:

```<code>location /protected/ {
  proxy_pass http://my-internal-aws-loadbalancer.com:8083/protected/;
}
</code>```

This however produces gives a 404 error when I hit the same route:

```<code>location /protected/ {
  set $node "my-internal-aws-loadbalancer";
  proxy_pass http://$node:8083/protected/;
}
</code>```

Also one thing to note is this is a post request. I guess I am just very confused as to why the addition of the variable breaks this.

答:
So ... after a lot of looking and reading I believe I have this solved. When using a variable in the proxy_pass nginx does in fact not behave the same.

This article was extremely helpful. TLDR of the whole article in regards to this case is the addition of the variable does cause nginx to behave differently on the proxy_pass so removing the trailing slash from the variable URL and rewriting any thing that could come after it solves the issue.

```<code>location ~ ^/protected/(.*)$ {
  resolver 8.8.8.8;
  set $node "http:///my-internal-aws-loadbalancer.com:8083/";
  proxy_pass $node/protected/$1;
}
</code>```

Title: NGINX proxy_pass to ELB with Variable

Body:
I am trying to setup a proxy rule for nginx that will hit an internal loadbalancer in front of some node boxes serving an API. I want to use a variable in the address to force it to resolve because of how dynamic the addresses are in aws.

The original setup works fine but occasionally was pointing to an addresss that was no longer there which caused intermittent problems as would be expected:

location /protected/ {
  proxy_pass http://my-internal-aws-loadbalancer.com:8083/protected/;
}

This however produces gives a 404 error when I hit the same route:

location /protected/ {
  set $node "my-internal-aws-loadbalancer";
  proxy_pass http://$node:8083/protected/;
}

Also one thing to note is this is a post request. I guess I am just very confused as to why the addition of the variable breaks this.

Body:
So ... after a lot of looking and reading I believe I have this solved. When using a variable in the proxy_pass nginx does in fact not behave the same.

This article was extremely helpful. TLDR of the whole article in regards to this case is the addition of the variable does cause nginx to behave differently on the proxy_pass so removing the trailing slash from the variable URL and rewriting any thing that could come after it solves the issue.

location ~ ^/protected/(.*)$ {
  resolver 8.8.8.8;
  set $node "http:///my-internal-aws-loadbalancer.com:8083/";
  proxy_pass $node/protected/$1;
}


问:
Is there a RegExp.escape function in JavaScript?
I just want to create a regular expression out of any possible string.

```<code>var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);
</code>```

Is there a built-in method for that? If not, what do people use? Ruby has RegExp.escape. I don't feel like I'd need to write my own, there have got to be something standard out there.

答:
XRegExp has an escape function:

XRegExp.escape('Escaped? <.>');
// -> 'Escaped\?\ <\.>'

More on: http://xregexp.com/api/#escape

ContentLicense: CC BY-SA 4.0

Body:
I just want to create a regular expression out of any possible string.

var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);

Is there a built-in method for that? If not, what do people use? Ruby has RegExp.escape. I don't feel like I'd need to write my own, there have got to be something standard out there.


问:
Error with NSBundle.mainBundle when adding sound
I've trying to create a simple sound board for when a button is pressed a sound is made, however when I used this code

```<code>let url = NSURL(fileURLWithPath: Bundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
</code>```

I get an error with "Bundle.mainBundle" orginally it told me to change "Bundle" from "NSBundle" because it has be renamed but when I correct that I get another error saying "Cannot call value for non-function type 'Bundle' "

my entire code:

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController {

let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for sound in soundFilenames {

        do {

            let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
            let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

            audioPlayer.append(audioPlayer())
        }
        catch {

            audioPlayers.append(AVAudioPlayer())

        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(_ sender: UIButton) {

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}
</code>```

}

can anyone help me with this please.

答:
First of all in Swift 3 mainBundle() became main but why not the real short way:

```<code>let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
</code>```

And the init method has been renamed to

```<code>let audioPlayer = try AVAudioPlayer(contentsOf: url)
</code>```

and change the next line to:

```<code>audioPlayers.append(audioPlayer)
</code>```

Body:
I've trying to create a simple sound board for when a button is pressed a sound is made, however when I used this code

let url = NSURL(fileURLWithPath: Bundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

I get an error with "Bundle.mainBundle" orginally it told me to change "Bundle" from "NSBundle" because it has be renamed but when I correct that I get another error saying "Cannot call value for non-function type 'Bundle' "

my entire code:

import UIKit
import AVFoundation

class ViewController: UIViewController {

let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for sound in soundFilenames {

        do {

            let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
            let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

            audioPlayer.append(audioPlayer())
        }
        catch {

            audioPlayers.append(AVAudioPlayer())

        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(_ sender: UIButton) {

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}

}

can anyone help me with this please.

Body:
First of all in Swift 3 mainBundle() became main but why not the real short way:

let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!

And the init method has been renamed to

let audioPlayer = try AVAudioPlayer(contentsOf: url)

and change the next line to:

audioPlayers.append(audioPlayer)


问:
Easiest way to read in numbers with script
I am dealing with a .txt file with the following content:

```<code>###################################################
Optimization for H260_ptyy275tau42.475C1.08_Analyzed.root

SOME TEXT

ptyy > -25
Significance: 1.79789e-05 +- 7.31008e-08
N_sig: 3.30335e-05 +- 3.15914e-05; N_SMbkg: 1.61124 +- 0.0612171; N_yyBackground: 1.76462 +- 0.469689
Fit function f=exp(a+b*x) with a = 0.567933 +- 0.266166 and b = -1.58821e-09 +- 0.00982024
Fit = 1.76462+-0.469689, sbL = 21+-4.58258 & sbT = 1+-1

MORE TEXT AND NUMBERS
</code>```

I now want to read in the numbers after N_sig until 0.469689, each in a different variable. What is the easiest way doint this with a .sh or python script?

Body:
I am dealing with a .txt file with the following content:

###################################################
Optimization for H260_ptyy275tau42.475C1.08_Analyzed.root

SOME TEXT

ptyy > -25
Significance: 1.79789e-05 +- 7.31008e-08
N_sig: 3.30335e-05 +- 3.15914e-05; N_SMbkg: 1.61124 +- 0.0612171; N_yyBackground: 1.76462 +- 0.469689
Fit function f=exp(a+b*x) with a = 0.567933 +- 0.266166 and b = -1.58821e-09 +- 0.00982024
Fit = 1.76462+-0.469689, sbL = 21+-4.58258 & sbT = 1+-1

MORE TEXT AND NUMBERS

I now want to read in the numbers after N_sig until 0.469689, each in a different variable. What is the easiest way doint this with a .sh or python script?

Body:
With GNU grep, bash and an array:

mapfile -t array < <(grep ^N_sig file | grep -oE '[0-9.e-]{2,}')

declare -p array

Output:

declare -a array='([0]="3.30335e-05" [1]="3.15914e-05" [2]="1.61124" [3]="0.0612171" [4]="1.76462" [5]="0.469689")'


问:
Android Dialog with CountDown TImer
In my app, I show the push notification as a Dialog that has two buttons named Yes and No. I need to  show a timer (20 seconds) running in the dialog's title.

If the user clicks Yes, it should go to an activity.

If the user clicks No, the dialog gets canceled before timer ends.

When the countdown finishes,the Dialog should disappear. How should I implement this?

Here is my Alert dialog Method

```<code>public void showAlertDialog(final Context context, String title, String message,
                            Boolean status) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting Icon to Dialog
    //alertDialog.setIcon(R.drawable.fail);

    // Setting Positive "Yes" Button
    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();

        }
    });

    // Setting Negative "NO" Button
    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();

            dialog.cancel();
        }
    });

    // Showing Alert Message
    //alertDialog.setIcon(R.drawable.counter);
    alertDialog.show();
}
</code>```

答:
I wouldn't recommend adding the countdown into the dialog's title. If you instead add it to the No button, it is more obvious for the user what will happen when the countdown finishes.

Here's code for an AlertDialog that does just that.

```<code>AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Notification Title")
        .setMessage("Do you really want to delete the file?")
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO: Add positive button action code here
            }
        })
        .setNegativeButton(android.R.string.no, null)
        .create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    private static final int AUTO_DISMISS_MILLIS = 6000;
    @Override
    public void onShow(final DialogInterface dialog) {
        final Button defaultButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
        final CharSequence negativeButtonText = defaultButton.getText();
        new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                defaultButton.setText(String.format(
                        Locale.getDefault(), "%s (%d)",
                        negativeButtonText,
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1 //add one so it never displays zero
                ));
            }
            @Override
            public void onFinish() {
                if (((AlertDialog) dialog).isShowing()) {
                    dialog.dismiss();
                }
            }
        }.start();
    }
});
dialog.show();
</code>```

Title: Android Dialog with CountDown TImer

Body:
In my app, I show the push notification as a Dialog that has two buttons named Yes and No. I need to  show a timer (20 seconds) running in the dialog's title.

If the user clicks Yes, it should go to an activity.

If the user clicks No, the dialog gets canceled before timer ends.

When the countdown finishes,the Dialog should disappear. How should I implement this?

Here is my Alert dialog Method

public void showAlertDialog(final Context context, String title, String message,
                            Boolean status) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting Icon to Dialog
    //alertDialog.setIcon(R.drawable.fail);

    // Setting Positive "Yes" Button
    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();

        }
    });

    // Setting Negative "NO" Button
    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();

            dialog.cancel();
        }
    });

    // Showing Alert Message
    //alertDialog.setIcon(R.drawable.counter);
    alertDialog.show();
}

Body:
I wouldn't recommend adding the countdown into the dialog's title. If you instead add it to the No button, it is more obvious for the user what will happen when the countdown finishes.

Here's code for an AlertDialog that does just that.

AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Notification Title")
        .setMessage("Do you really want to delete the file?")
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO: Add positive button action code here
            }
        })
        .setNegativeButton(android.R.string.no, null)
        .create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    private static final int AUTO_DISMISS_MILLIS = 6000;
    @Override
    public void onShow(final DialogInterface dialog) {
        final Button defaultButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
        final CharSequence negativeButtonText = defaultButton.getText();
        new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                defaultButton.setText(String.format(
                        Locale.getDefault(), "%s (%d)",
                        negativeButtonText,
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1 //add one so it never displays zero
                ));
            }
            @Override
            public void onFinish() {
                if (((AlertDialog) dialog).isShowing()) {
                    dialog.dismiss();
                }
            }
        }.start();
    }
});
dialog.show();


问:
'wget' full web site based on frames
I have a little problem. I want recursively download that web page, but it based on "frames". Standard methods can't help me. I try different variants, but nothing. Maximum I can download one recursion, I found example there. How can I grab that web site fully, and than use it offline? Thx.</p>

答: What are you using for the commands? Are you on MSWindows? E.g. "wget --mirror –w 2 –p --HTML-extension –-convert-links –P c:\wget_files\example1 http://base.safework.ru/iloenc"</p>

ContentLicense: CC BY-SA 2.5

Title: 'wget' full web site based on frames


问:
BigQuery "view is self-referencing"?
I have two views. Each runs fine alone; i.e.

select * from x ...and... select * from y

But when I run

```<code>select * from x join y using (a,b)
</code>```

I get:

```<code>Error: View project.z is self-referencing.
Job ID: project:bquijob_36210f49_15c3d9bce56
</code>```

I'm sure that z isn't self-referencing, because even when I change it to reference a single table, I still get this error.

Any idea what's going on?

答: To close this: Google Support let me know they identified the issue and will release a fix soon</p>

Title: BigQuery "view is self-referencing"?

Body:
I have two views. Each runs fine alone; i.e.

select * from x ...and... select * from y

But when I run

select * from x join y using (a,b)

I get:

Error: View project.z is self-referencing.
Job ID: project:bquijob_36210f49_15c3d9bce56

I'm sure that z isn't self-referencing, because even when I change it to reference a single table, I still get this error.

Any idea what's going on?


问:
UIButton as titleview in UINavigationBar weird stretch bug?
I'm trying to get a UIButton as titleview for a UINavigationBar (in a UINavigationController), but when adding an image to the button it seems to stretch the entire titleview:

Am I doing something wrong here or is this a bug? Is there a workaround for this? I am running iOS 11 beta 2 so it could just be a beta bug, can't test on iOS10 though.. Any help would be greatly appreciated! :)

code:

```<code>let titleButton = UIButton(type: .system)
titleButton.sizeToFit()
titleButton.tintColor = UFOGREENTHEMECOLOR
titleButton.setTitleColor(BLACKTEXTCOLOR, for: .normal)
titleButton.setTitle("John Doe", for: .normal)
titleButton.titleLabel?.font = UIFont(name: "Avenir-Book", size: 20)

titleButton.setImage(UIImage(named: "Default Avatar.png"), for: .normal)
self.navigationItem.titleView = titleButton
</code>```

EDIT: Tried this on IOS10, same behaviour. Adding titleButton.imageView?.contentMode = .scaleAspectFit
as suggested by CoderAzreal Does seem to fix the image being stretched, but the title is still way off to the right.

答:
You can add width constraint to your UIButton</p>

```<code>    [self.search_button addConstraint:[NSLayoutConstraint constraintWithItem:self.search_button
                                                             attribute:NSLayoutAttributeWidth
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:nil
                                                             attribute:NSLayoutAttributeNotAnAttribute
                                                            multiplier:1.0
                                                              constant:32]];
</code>```

Body:
I'm trying to get a UIButton as titleview for a UINavigationBar (in a UINavigationController), but when adding an image to the button it seems to stretch the entire titleview:

Am I doing something wrong here or is this a bug? Is there a workaround for this? I am running iOS 11 beta 2 so it could just be a beta bug, can't test on iOS10 though.. Any help would be greatly appreciated! :)

code:

let titleButton = UIButton(type: .system)
titleButton.sizeToFit()
titleButton.tintColor = UFOGREENTHEMECOLOR
titleButton.setTitleColor(BLACKTEXTCOLOR, for: .normal)
titleButton.setTitle("John Doe", for: .normal)
titleButton.titleLabel?.font = UIFont(name: "Avenir-Book", size: 20)

titleButton.setImage(UIImage(named: "Default Avatar.png"), for: .normal)
self.navigationItem.titleView = titleButton

EDIT: Tried this on IOS10, same behaviour. Adding titleButton.imageView?.contentMode = .scaleAspectFit
as suggested by CoderAzreal Does seem to fix the image being stretched, but the title is still way off to the right.

Body:
You can add width constraint to your UIButton

    [self.search_button addConstraint:[NSLayoutConstraint constraintWithItem:self.search_button
                                                             attribute:NSLayoutAttributeWidth
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:nil
                                                             attribute:NSLayoutAttributeNotAnAttribute
                                                            multiplier:1.0
                                                              constant:32]];


问:
Using AddOnPageChangeListener to return page as Toast-Message
I am using ViewPager to swipe between fragments.
Since onPageSelectedListner() method is deprecated, I have to use AddOnPageChangeListener

So my code looks like this:

```<code> // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
</code>```

Question: My intent was to return the page  where the user is. Like, when you swipe from page 1 to 2, you get a Toast-Message that tells you ,you are at page 2. If you swipe forward, it tells you, you are at page 3 and so on.

But my methods in the OnClickListener are returning voids. How can I get the page position?

答:
Use this :-

```<code>mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

           Toast.makeText(getApplicationContext(),"You're on page " + String.valueOf(position), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
</code>```

In this, position is the argument of the onPageSelected selected method. This position is set when the page is changed.

Body:
I am using ViewPager to swipe between fragments.
Since onPageSelectedListner() method is deprecated, I have to use AddOnPageChangeListener

So my code looks like this:

 // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

Question: My intent was to return the page  where the user is. Like, when you swipe from page 1 to 2, you get a Toast-Message that tells you ,you are at page 2. If you swipe forward, it tells you, you are at page 3 and so on.

But my methods in the OnClickListener are returning voids. How can I get the page position?

Body:
Use this :-

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

           Toast.makeText(getApplicationContext(),"You're on page " + String.valueOf(position), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

In this, position is the argument of the onPageSelected selected method. This position is set when the page is changed.


问:
Regex for validating a pattern in Java
I have to validate a pattern like : abc.123456789.123 (example) where I have to check for these things:

First three should be letters only of fixed length (case insensitive)

Followed by dot (.)

Numbers in range 0-9, length should be 9

Followed by dot (.) and Numbers in range 0-9, length should be 3 (optional)

Valid Example:

```<code> abc.1
 Abc.123456789
 aBc.123.123
 ABC.123456789.12
</code>```

Invalid Exmples:

```<code> abc.1.
 abc..1.123
 .123
 abc.123w45678.123
 abc.
</code>```

What I've tried :

```<code>^[a-zA-Z]{3}\\.\\d{0,9}\\.\\d{0,3}|[a-zA-Z]{3}\\.\\d{0,9}$
</code>```

As I am new in Regex, I tried the above Regex but it is failing to pass abc.1. and abc...

答:
The regular expression you want is ^[a-zA-Z]{3}\.[0-9]{1,9}(\.[0-9]{1,3})?$.  It matches your test cases, rather than the rules you gave, because I found your rules to be a bit vague.

I made this regular expression using regexr, it's a good free tool for constructing and testing regular expressions.

EDIT:
Since you intend to use this regular expression for Java, here is the same regular expression, with escaped backslashes.  ^[a-zA-Z]{3}\\.[0-9]{1,9}(\\.[0-9]{1,3})?$.

Title: Regex for validating a pattern in Java

Body:
I have to validate a pattern like : abc.123456789.123 (example) where I have to check for these things:

First three should be letters only of fixed length (case insensitive)

Followed by dot (.)

Numbers in range 0-9, length should be 9

Followed by dot (.) and Numbers in range 0-9, length should be 3 (optional)

Valid Example:

 abc.1
 Abc.123456789
 aBc.123.123
 ABC.123456789.12

Invalid Exmples:

 abc.1.
 abc..1.123
 .123
 abc.123w45678.123
 abc.

What I've tried :

^[a-zA-Z]{3}\\.\\d{0,9}\\.\\d{0,3}|[a-zA-Z]{3}\\.\\d{0,9}$

As I am new in Regex, I tried the above Regex but it is failing to pass abc.1. and abc...


问:
C# Delegate Type As Generic Constraint
I have a function:

```<code>private void SetupCallbacks()
{
        Type actionType = Type.GetType(CardData.ActionFile);
        if (actionType == null)
            return;

        // To get any particular method from actionType, I have to do the following
        MethodInfo turnStarted = actionType.GetMethod(CardData.TurnStartedMethod);
        if (turnStarted != null)
        {
            Delegate d = Delegate.CreateDelegate(typeof(Action<bool>), turnStarted);
            Action<bool> turnStartedAction = (Action<bool>)d;
            TurnManager.Instance.OnTurnStarted += turnStartedAction;
        }

        ...
}
</code>```

actionType is a class that contains several static methods. These methods are stored as strings in the CardData object. I provided an example using the OnTurnStarted callback. It is very clunky to write out all that code repeatedly each time I want to add another callback. I've tried creating a function:

```<code>private void SetupCallback<TDelegate>(Type actionType, string method, TDelegate delagateToAddThisTo) where TDelegate : Delegate
{
    MethodInfo methodInfo = actionsContainerClass.GetMethod(method);
        if (methodInfo != null)
        {
            Delegate d = Delegate.CreateDelegate(typeof(Action<Card>), methodInfo);
            TDelegate t = (TDelegate)d;
            delagateToAddThisTo += t;
        }
}
</code>```

However, where TDelegate : Delegate doesn't work. I can't just do some type checking in the method (ie:

```<code>if(typeof(TDelegate).IsSubclassOf(typeof(Delegate)) == false)
{
  throw new InvalidOperationException("Card::SetupCallback - " + typeof(TDelegate).Name + " is not a delegate");
}
</code>```

because delagateToAddThisTowhich is of type TDelegate and needs to be able to be added to.

Thank you in advance.

答:
C# doesn't allow constraining generic type parameters with delegate types. Your only option to validate delegate types is at runtime.

For the same reason, you won't be able to use the += operator inside the CreateCallback method. But if += is moved to the caller (SetupCallbacks), and the CreateCallback only creates and returns the delegate, it can still look quite elegant:

```<code>// this code is in SetupCallbacks method
// Action<...> delegates are just examples

TurnManager.Instance.OnTurnStarted +=
    CreateCallback<Action<string, int>>(actionType, CardData.TurnStartedMethod);

TurnManager.Instance.OnTurnStopped +=
    CreateCallback<Action<string, int, TimeSpan>>(actionType, CardData.TurnStoppedMethod);
</code>```

Where the CreateCallback method is as follows:

```<code>private TDelegate CreateCallback<TDelegate>(Type actionType, string method)
    where TDelegate : class
{
    if (!typeof(Delegate).IsAssignableFrom(typeof(TDelegate)))
    {
        throw new InvalidOperationException("Card::SetupCallback - " + typeof(TDelegate).Name + " is not a delegate");
    }

    MethodInfo methodInfo = actionType.GetMethod(method);

    if (methodInfo != null)
    {
        // the following line will also validate compatibility of delegate types
        Delegate nonTypedDelegate =  methodInfo.CreateDelegate(typeof(TDelegate));
        TDelegate typedDelegate = (TDelegate)(object)nonTypedDelegate;
        return typedDelegate;
    }

    return null;
}
</code>```

Provided that in my example, TurnManager class looks like this:

```<code>public class TurnManager
{
    public static TurnManager Instance
    {
        get { /* ....... */ }
    }

    public Action<string, int> OnTurnStarted { get; set; }
    public Action<string, int, TimeSpan> OnTurnStopped { get; set; }

    //... other members ...
}
</code>```

Title: C# Delegate Type As Generic Constraint

Body:
I have a function:

private void SetupCallbacks()
{
        Type actionType = Type.GetType(CardData.ActionFile);
        if (actionType == null)
            return;

        // To get any particular method from actionType, I have to do the following
        MethodInfo turnStarted = actionType.GetMethod(CardData.TurnStartedMethod);
        if (turnStarted != null)
        {
            Delegate d = Delegate.CreateDelegate(typeof(Action<bool>), turnStarted);
            Action<bool> turnStartedAction = (Action<bool>)d;
            TurnManager.Instance.OnTurnStarted += turnStartedAction;
        }

        ...
}

actionType is a class that contains several static methods. These methods are stored as strings in the CardData object. I provided an example using the OnTurnStarted callback. It is very clunky to write out all that code repeatedly each time I want to add another callback. I've tried creating a function:

private void SetupCallback<TDelegate>(Type actionType, string method, TDelegate delagateToAddThisTo) where TDelegate : Delegate
{
    MethodInfo methodInfo = actionsContainerClass.GetMethod(method);
        if (methodInfo != null)
        {
            Delegate d = Delegate.CreateDelegate(typeof(Action<Card>), methodInfo);
            TDelegate t = (TDelegate)d;
            delagateToAddThisTo += t;
        }
}

However, where TDelegate : Delegate doesn't work. I can't just do some type checking in the method (ie:

if(typeof(TDelegate).IsSubclassOf(typeof(Delegate)) == false)
{
  throw new InvalidOperationException("Card::SetupCallback - " + typeof(TDelegate).Name + " is not a delegate");
}

because delagateToAddThisTowhich is of type TDelegate and needs to be able to be added to.

Thank you in advance.

Body:
C# doesn't allow constraining generic type parameters with delegate types. Your only option to validate delegate types is at runtime.

For the same reason, you won't be able to use the += operator inside the CreateCallback method. But if += is moved to the caller (SetupCallbacks), and the CreateCallback only creates and returns the delegate, it can still look quite elegant:

// this code is in SetupCallbacks method
// Action<...> delegates are just examples

TurnManager.Instance.OnTurnStarted +=
    CreateCallback<Action<string, int>>(actionType, CardData.TurnStartedMethod);

TurnManager.Instance.OnTurnStopped +=
    CreateCallback<Action<string, int, TimeSpan>>(actionType, CardData.TurnStoppedMethod);

Where the CreateCallback method is as follows:

private TDelegate CreateCallback<TDelegate>(Type actionType, string method)
    where TDelegate : class
{
    if (!typeof(Delegate).IsAssignableFrom(typeof(TDelegate)))
    {
        throw new InvalidOperationException("Card::SetupCallback - " + typeof(TDelegate).Name + " is not a delegate");
    }

    MethodInfo methodInfo = actionType.GetMethod(method);

    if (methodInfo != null)
    {
        // the following line will also validate compatibility of delegate types
        Delegate nonTypedDelegate =  methodInfo.CreateDelegate(typeof(TDelegate));
        TDelegate typedDelegate = (TDelegate)(object)nonTypedDelegate;
        return typedDelegate;
    }

    return null;
}

Provided that in my example, TurnManager class looks like this:

public class TurnManager
{
    public static TurnManager Instance
    {
        get { /* ....... */ }
    }

    public Action<string, int> OnTurnStarted { get; set; }
    public Action<string, int, TimeSpan> OnTurnStopped { get; set; }

    //... other members ...
}


问:
Is it possible to create product keys for my electron application?
I want to build a desktop application and be able to publish product keys or serial numbers.Before the user can use the application he will be requested to enter the product key/serial number.

Similar to Microsoft Office when they provide keys like XXXX-XXXX-XXXX-XXXX

The idea I have is to sell the app based on licenses and providing product key for every device seems more professional than accounts (usernames and passwords).

so my questions are:

1) Is it possible to accomplish this with electron?

2) Can you advice me wether I should go for serial numbers (if it is doable) or accounts? or are there better options?

3) if you answered the second question. Please state why?

答:
Edit for 2021: I'd like to revise this answer, as it has generated a lot of inquiries on the comparison I made between license keys and user accounts. I previously would almost always recommended utilizing user accounts for licensing Electron apps, but I've since changed my position to be a little more nuanced. For most Electron apps, license keys will do just fine.

Adding license key (synonymous with product key) validation to an Electron app can be pretty straight forward. First, you would want to somehow generate a license key for each user. This can be done using cryptography, or it can be done by generating a 'random' license key string and storing it in a database and then building a CRUD licensing server that can verify that a given license key is "valid."

For cryptographic license keys, you can take some information from the customer, e.g. their order number or an email address, and create a 'signature' of it using RSA cryptography. Using Node, that would look something like this:

```<code>const crypto = require('crypto')

// Generate a new keypair
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  // Using a larger key size, such as 2048, would be more secure
  // but will result in longer signatures.
  modulusLength: 512,
  privateKeyEncoding: { type: 'pkcs1', format: 'pem' },
  publicKeyEncoding: { type: 'pkcs1', format: 'pem' },
})

// Some data we're going to use to generate a license key from
const data = 'user@store.example'

// Create a RSA signer
const signer = crypto.createSign('rsa-sha256')
signer.update(data)

// Encode the original data
const encoded = Buffer.from(data).toString('base64')

// Generate a signature for the data
const signature = signer.sign(privateKey, 'hex')

// Combine the encoded data and signature to create a license key
const licenseKey = `${encoded}.${signature}`

console.log({ privateKey, publicKey, licenseKey })
</code>```

Then, to validate the license key within your Electron app, you would want to cryptographically 'verify' the key's authenticity by embedding the public (not the private!) key generated above into your application code base:

```<code>// Split the license key's data and the signature
const [encoded, signature] = licenseKey.split('.')
const data = Buffer.from(encoded, 'base64').toString()

// Create an RSA verifier
const verifier = crypto.createVerify('rsa-sha256')
verifier.update(data)

// Verify the signature for the data using the public key
const valid = verifier.verify(publicKey, signature, 'hex')

console.log({ valid, data })
</code>```

Generating and verifying the authenticity of cryptographically signed license keys like this will work great for a lot of simple licensing needs. They're relatively simple, and they work great offline, but sometimes verifying that a license key is 'valid' isn't enough. Sometimes requirements dictate that license keys are not perpetual (i.e. 'valid' forever), or they call for more complicated licensing systems, such as one where only a limited number of devices (or seats) can use the app at one time. Or perhaps the license key needs a renewable expiration date. That's where a license server can come in.

A license server can help manage a license's activation, expirations, among other things, such as user accounts used to associate multiple licenses or feature-licenses with a single user or team. I don't recommend user accounts unless you have a specific need for them, e.g. you need additional user profile information, or you need to associate multiple licenses with a single user.

But in case you aren't particularly keen on writing and maintaining your own in-house licensing system, or you just don't want to deal with writing your own license key generator like the one above, I’m the founder of a software licensing API called Keygen which can help you get up and running quickly without having to write and host your own license server. :)

Keygen is a typical HTTP JSON API service (i.e. there’s no software that you need to package with your app). It can be used in any programming language and with frameworks like Electron.

In its simplest form, validating a license key with Keygen is as easy as hitting a single JSON API endpoint (feel free to run this in a terminal):

```<code>curl -X POST https://api.keygen.sh/v1/accounts/demo/licenses/actions/validate-key \
  -d '{
        "meta": {
          "key": "C1B6DE-39A6E3-DE1529-8559A0-4AF593-V3"
        }
      }'
</code>```

I recently put together an example of adding license key validation, as well as device activation and management, to an Electron app. You can check out that repo on GitHub: https://github.com/keygen-sh/example-electron-license-activation.

I hope that answers your question and gives you a few insights. Happy to answer any other questions you have, as I've implemented licensing a few times now for Electron apps. :)

Body:
Edit for 2021: I'd like to revise this answer, as it has generated a lot of inquiries on the comparison I made between license keys and user accounts. I previously would almost always recommended utilizing user accounts for licensing Electron apps, but I've since changed my position to be a little more nuanced. For most Electron apps, license keys will do just fine.

Adding license key (synonymous with product key) validation to an Electron app can be pretty straight forward. First, you would want to somehow generate a license key for each user. This can be done using cryptography, or it can be done by generating a 'random' license key string and storing it in a database and then building a CRUD licensing server that can verify that a given license key is "valid."

For cryptographic license keys, you can take some information from the customer, e.g. their order number or an email address, and create a 'signature' of it using RSA cryptography. Using Node, that would look something like this:

const crypto = require('crypto')

// Generate a new keypair
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  // Using a larger key size, such as 2048, would be more secure
  // but will result in longer signatures.
  modulusLength: 512,
  privateKeyEncoding: { type: 'pkcs1', format: 'pem' },
  publicKeyEncoding: { type: 'pkcs1', format: 'pem' },
})

// Some data we're going to use to generate a license key from
const data = 'user@store.example'

// Create a RSA signer
const signer = crypto.createSign('rsa-sha256')
signer.update(data)

// Encode the original data
const encoded = Buffer.from(data).toString('base64')

// Generate a signature for the data
const signature = signer.sign(privateKey, 'hex')

// Combine the encoded data and signature to create a license key
const licenseKey = `${encoded}.${signature}`

console.log({ privateKey, publicKey, licenseKey })

Then, to validate the license key within your Electron app, you would want to cryptographically 'verify' the key's authenticity by embedding the public (not the private!) key generated above into your application code base:

// Split the license key's data and the signature
const [encoded, signature] = licenseKey.split('.')
const data = Buffer.from(encoded, 'base64').toString()

// Create an RSA verifier
const verifier = crypto.createVerify('rsa-sha256')
verifier.update(data)

// Verify the signature for the data using the public key
const valid = verifier.verify(publicKey, signature, 'hex')

console.log({ valid, data })

Generating and verifying the authenticity of cryptographically signed license keys like this will work great for a lot of simple licensing needs. They're relatively simple, and they work great offline, but sometimes verifying that a license key is 'valid' isn't enough. Sometimes requirements dictate that license keys are not perpetual (i.e. 'valid' forever), or they call for more complicated licensing systems, such as one where only a limited number of devices (or seats) can use the app at one time. Or perhaps the license key needs a renewable expiration date. That's where a license server can come in.

A license server can help manage a license's activation, expirations, among other things, such as user accounts used to associate multiple licenses or feature-licenses with a single user or team. I don't recommend user accounts unless you have a specific need for them, e.g. you need additional user profile information, or you need to associate multiple licenses with a single user.

But in case you aren't particularly keen on writing and maintaining your own in-house licensing system, or you just don't want to deal with writing your own license key generator like the one above, I’m the founder of a software licensing API called Keygen which can help you get up and running quickly without having to write and host your own license server. :)

Keygen is a typical HTTP JSON API service (i.e. there’s no software that you need to package with your app). It can be used in any programming language and with frameworks like Electron.

In its simplest form, validating a license key with Keygen is as easy as hitting a single JSON API endpoint (feel free to run this in a terminal):

curl -X POST https://api.keygen.sh/v1/accounts/demo/licenses/actions/validate-key \
  -d '{
        "meta": {
          "key": "C1B6DE-39A6E3-DE1529-8559A0-4AF593-V3"
        }
      }'

I recently put together an example of adding license key validation, as well as device activation and management, to an Electron app. You can check out that repo on GitHub: https://github.com/keygen-sh/example-electron-license-activation.

I hope that answers your question and gives you a few insights. Happy to answer any other questions you have, as I've implemented licensing a few times now for Electron apps. :)


问:
Printing index of duplicate numbers in array javascript
I need to find the first duplicate number in array and then print index of this number in console. In my code below I reach the moment when code finds the duplicate but prints its index. In simple words, 2 is duplictaing in array but it's stands in first place so I need to print index "0".

var sameNum = [2, 4, 5, 2, 3, 5, 1, 2, 4];
var firstIndex = [];

for (var i = 0; i < sameNum.length; i++) {
  for (var j = i; j < sameNum.length; j++) {
    if (i != j && sameNum[i] == sameNum[j]) {
      firstIndex = [i];
    }
  }
}
console.log(firstIndex);```

答:
You can first sort the array if required.On doing this it will in ascending order.Then use forEach to loop over the array, and get the index

var sameNum = [1, 3, 2, 4, 5, 6, 6, 6, 7, 7, 7, 8, 9];
var firstIndex = [];
// sorting the array and iterating over it
// forEach array method accepts three parameter of which index is one of the parameter
sameNum.sort().forEach(function(item, index) {
  if (sameNum[index + 1] == sameNum[index]) {
    console.log(index + 1);
  }
})```


问:
Only on submit send data to datatable
I have datatable which I set as follows.On the page load the datagrid is showing as processing but I have not set it to be on load.

```<code>var oTable = $('#dataGrid').dataTable({
                    "order": [[ 1, "asc" ]],
                    "aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0,1 ] }],
                        "processing": true,
                        "serverSide": true,
                        "ajax": "getReport.php",
                        "fnServerData": function ( sSource, aoData, fnCallback ) {
                $.ajax( {
                    "dataType": 'json',
                    "type": "POST",
                    "url": "getReport.php",
                    "data": 'val1=' + $("value1").val()+'&val2=' + $("value2").val(),
                    "success": fnCallback
                } );
                        }
                      });

 $("#submit").click(function(){
                        oTable.fnReloadAjax();
                     });
</code>```

I am getting error Uncaught TypeError: oTable.fnReloadAjax is not a function. I want the datatable only populate when the submit button is clicked?

答: The error is very clear - the function fnReloadAjax does not exist. What you need to call instead is oTable.ajax.reload(); See documentation here.

Title: Only on submit send data to datatable

Body:
I have datatable which I set as follows.On the page load the datagrid is showing as processing but I have not set it to be on load.

var oTable = $('#dataGrid').dataTable({
                    "order": [[ 1, "asc" ]],
                    "aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0,1 ] }],
                        "processing": true,
                        "serverSide": true,
                        "ajax": "getReport.php",
                        "fnServerData": function ( sSource, aoData, fnCallback ) {
                $.ajax( {
                    "dataType": 'json',
                    "type": "POST",
                    "url": "getReport.php",
                    "data": 'val1=' + $("value1").val()+'&val2=' + $("value2").val(),
                    "success": fnCallback
                } );
                        }
                      });

 $("#submit").click(function(){
                        oTable.fnReloadAjax();
                     });

I am getting error Uncaught TypeError: oTable.fnReloadAjax is not a function. I want the datatable only populate when the submit button is clicked?


问:
Reading specific portions of a file
I am currently working on creating an admin tool in Powershell and I am relatively new to the language, so I apologize if this is a dumb question. I am creating a list box using system.windows.forms. I am calling the information that will be in the list box from a .cfg file which will point to the directories where each of the items (in this case batch files) are located. I am also going to be including a description when an Item is selected, so I will need to call this as well. If its possible, how do you independently select two strings of text from the same line in a file?</p>

答:
You can use -match to check for specific strings within a block of text. As BenH mentioned above though using something like JSON or even XML would be much easier to pull information out of.

If you go the route of using -match you can us $matches to see what has been matched and use that information.

Title: Reading specific portions of a file


问:
How to integrate FCM in a PhoneGap App
i'm trying to add FCM functionalities to my PhoneGap app:
i've added   in my config.xml and i've got my google-services.json, but when i try to build my app, i have an error like this:

*Execution failed for task ':processDebugGoogleServices'.

File google-services.json is missing. The Google Services Plugin cannot function without it.     Searched Location:

    /project/src/debug/google-services.json

    /project/google-services.json*

Is there a way to resolve this problem?
The .json file is at the same level of my config.xml file, in the www folder.
Thanks for your interest.

答:
The files need to be alongside the www folder, problem is that Phonegap Build only lets you upload the contents of said folder, so you can't upload the files.

Fortunately there's something you can do; Build installs the plugins directly from npm, and plugins can work thought the whole project, so what you need is a plugin that copies the files [google-services.json, GoogleService-Info.plist] for you.

Most of the work has already been done: cordova-plugin-fcm-config.

This plugin copies the required FCM configurations in the project root folders and Xcode project. It is used in combination with the great cordova-plugin-fcm plugin.
It wasn't built for this purpose but works wonderfully.

There's an added complexity though; since you can't upload plugins (you can only add a reference to it in your config.xml), and this plugin needs your own app configuration files, you'll have to:

Clone/Fork the plugin into your own repository.
Replace the configuration files.
Upload it somewhere Build can find.
Where do you upload it? That might be tricky. The infrastructure is built around the idea that plugins are for general purposes and can be configured in each project xml, so npm makes sense. But in this case your plugin will contain very specific data to your project, so uploading to npm would pollute the namespace in my opinion.

I don't know about you, but I have a paid account, so I publish the plugin in my own repository and submit as a private plugin. This is what I recommend.

Title: How to integrate FCM in a PhoneGap App


问:
What CSS selector do I need here?
I'm trying to center the title text on my Alert control. I'm using the following CSS right now:

```<code>mx|Alert{
  text-align: center;
}
</code>```

The problem is that the above code centers my alert content as well, not just the title text. What selector do I need to access just the title of the alert control?

Edit:

I'm using the 4.x SDK and Spark.

Code:

Alert.Show();

答:
Use titleStyleName to declare a CSS class that can be used to style the title, then add styles to that class:

```<code>mx|Alert {
    titleStyleName: 'alertTitle';
}

.alertTitle {
    text-align: center;
}
</code>```

Should work for Spark if I'm not wrong.

Title: What CSS selector do I need here?

Body:
I'm trying to center the title text on my Alert control. I'm using the following CSS right now:

mx|Alert{
  text-align: center;
}

The problem is that the above code centers my alert content as well, not just the title text. What selector do I need to access just the title of the alert control?

Edit:

I'm using the 4.x SDK and Spark.

Code:

Alert.Show();

Body:
Use titleStyleName to declare a CSS class that can be used to style the title, then add styles to that class:

mx|Alert {
    titleStyleName: 'alertTitle';
}

.alertTitle {
    text-align: center;
}

Should work for Spark if I'm not wrong.


答:
Try this one:-</p>

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<input id="input" type="time">
<button onclick="live()">run</button>
<!---->
<p id="output">Output</p>
<script>
       function live() {

  var sameNum = [1, 2 ,3 ,4 ,6 ,6 ,7 ,8 ,9];
  var firstIndex;

  for(var i = 0; i < sameNum.length; i++) {
      for(var j = i; j < sameNum.length; j++) {
        if(i != j && sameNum[i] == sameNum[j]) {
        firstIndex = i;
        }
        if (firstIndex != null){break;}
      }
  }

if (firstIndex == null){
  alert("No repeating element");
}
else{
  alert(firstIndex);
}
       }
</script>
</body>
</html>
</code>```

Title: Printing index of duplicate numbers in array javascript

Body:
I need to find the first duplicate number in array and then print index of this number in console. In my code below I reach the moment when code finds the duplicate but prints its index. In simple words, 2 is duplictaing in array but it's stands in first place so I need to print index "0".

var sameNum = [2, 4, 5, 2, 3, 5, 1, 2, 4];
var firstIndex = [];

for (var i = 0; i < sameNum.length; i++) {
  for (var j = i; j < sameNum.length; j++) {
    if (i != j && sameNum[i] == sameNum[j]) {
      firstIndex = [i];
    }
  }
}
console.log(firstIndex);

Body:
Try this one:-

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<input id="input" type="time">
<button onclick="live()">run</button>
<!---->
<p id="output">Output</p>
<script>
       function live() {

  var sameNum = [1, 2 ,3 ,4 ,6 ,6 ,7 ,8 ,9];
  var firstIndex;

  for(var i = 0; i < sameNum.length; i++) {
      for(var j = i; j < sameNum.length; j++) {
        if(i != j && sameNum[i] == sameNum[j]) {
        firstIndex = i;
        }
        if (firstIndex != null){break;}
      }
  }

if (firstIndex == null){
  alert("No repeating element");
}
else{
  alert(firstIndex);
}
       }
</script>
</body>
</html>


问:
How to rename files in subfolder into a specific format
I have files named as RabcdYYMMKKACCOUNT.TXT in the Subfolders of a folder where YYMM is year, month this will change. KK is another identifier, I want all the files to be renamed to MSFKKDNB.ABC, the KK is the identifier in the input file.

Below is the one i tried and the result of it:

```<code>FOR /R %%f IN (*account.txt) DO REN "%%f" *dnb.abc
</code>```

R00531706AUAccount.txt is renamed to R00531706AUAccount.txtdnb.abc

but the output should be MSFAUDNB.abc

答:
Try this:

@Echo Off
For %%A In ("*account.txt") Do (Set "_=%%~nA"
    SetLocal EnableDelayedExpansion
    Ren "%%A" "MSF!_:~-9,2!DNB.abc"
    EndLocal)
```

Body:
I have files named as RabcdYYMMKKACCOUNT.TXT in the Subfolders of a folder where YYMM is year, month this will change. KK is another identifier, I want all the files to be renamed to MSFKKDNB.ABC, the KK is the identifier in the input file.

Below is the one i tried and the result of it:

FOR /R %%f IN (*account.txt) DO REN "%%f" *dnb.abc

R00531706AUAccount.txt is renamed to R00531706AUAccount.txtdnb.abc

but the output should be MSFAUDNB.abc


问:
How do I get the values as an NSDictionary in Swift 3?
How do I get the values as an NSDictionary in Swift 3 whit Alamofire?
I would like to take values like json in NSDictionary, and save them to default, then to see everything in a TableView

PHP CODE

```<code>public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $i=0;
    $prodotti = array();
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $prodotti[$i]['username'] = $row['username'];
        $prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
        $prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
        $prodotti[$i]['categoria'] = $row['categoria'];
        $prodotti[$i]['quantita'] = $row['quantita'];
        $i++;
    }
 return $prodotti;
 }

 }
</code>```

That's what I get

```<code>    {"error":false,"user":{"id":3,"username":"anto","email":"a@a","nome":"Anto","cognome":"xxx","telefono":"1234567892"},"prodotti":[{"username":"anto","id_prodotto":57,"nome_prodotto":"milk","categoria":"milk","quantita":"2"},{"username":"anto","id_prodotto":58,"nome_prodotto":"farina","categoria":"alimento","quantita":"2"}]}
</code>```

SWIFT CODE

```<code> import Alamofire
 import UIKit
 import AVFoundation

 class LoginController1: UIViewController {

//The login script url make sure to write the ip instead of localhost
//you can get the ip using ifconfig command in terminal
let URL_USER_LOGIN = "http://........login.php"

//the defaultvalues to store user data
let defaultValues = UserDefaults.standard

//the connected views
//don't copy instead connect the views using assistant editor
@IBOutlet weak var labelMessage: UILabel!
@IBOutlet weak var username: UITextField!

@IBOutlet weak var password: UITextField!

//the button action function
@IBAction func buttonLogin(_ sender: UIButton) {

    //getting the username and password
    let parameters: Parameters=[
        "username":username.text!,
        "password":password.text!
    ]

    //making a post request
    Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
        {
            response in
            //printing response
            print(response)

            //getting the json value from the server
            if let result = response.result.value {
                let jsonData = result as! NSDictionary

                //if there is no error
                if(!(jsonData.value(forKey: "error") as! Bool)){

                    //getting the user from response
                    let user = jsonData.value(forKey: "user") as! NSDictionary

                    //getting user values
                    let userId = user.value(forKey: "id") as! Int
                    let userName = user.value(forKey: "username") as! String
                    let userEmail = user.value(forKey: "email") as! String
                    let userNome = user.value(forKey: "nome") as! String
                    let userCognome = user.value(forKey: "cognome") as! String
                    let userTelefono = user.value(forKey: "telefono") as! String

                    //saving user values to defaults
                    self.defaultValues.set(userId, forKey: "userid")
                    self.defaultValues.set(userName, forKey: "username")
                    self.defaultValues.set(userEmail, forKey: "useremail")
                    self.defaultValues.set(userNome, forKey: "usernome")
                    self.defaultValues.set(userCognome, forKey: "usercognome")
                    self.defaultValues.set(userTelefono, forKey: "usertelefono")

                    ///prende i valori dei prodotti dalla cella legata a quel username
                    let row = jsonData.value(forKey: "row") as! NSDictionary

                    let rowNome_prodotto = prodotti.value(forKey: "nome_prodotto") as! String
                    let rowCategoria = prodotti.value(forKey: "categoria") as! String
                    let rowQuantita = prodotti.value(forKey: "quantita") as! String

                    //saving i valori di questo username

                    self.defaultValues.set(prodottiNome_prodotto, forKey: "nome_prodotto")
                    self.defaultValues.set(prodottiCategoria, forKey: "categoria")
                    self.defaultValues.set(prodottiQuantita, forKey: "quantita")

                    //Go to the HomeViewController if the login is sucessful
                    let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
                    self.navigationController?.pushViewController(ProfiloController, animated: true)

                    self.dismiss(animated: false, completion: nil)

                    }else{
                                            //error message in case of invalid credential
                    let alertController = UIAlertController(title: "Error", message: "Username e password sbagliati", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                    }
            }
                }
}

override func viewDidLoad() {
    super.viewDidLoad()
    if defaultValues.string(forKey: "username") != nil{
        let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
        self.navigationController?.pushViewController(ProfiloController, animated: true)

    }
}

    var player: AVPlayer?
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    let tap = UITapGestureRecognizer(target: self, action: #selector(LoginController1.dismissKeyboard))
    view.addGestureRecognizer(tap)
    let path = Bundle.main.path(forResource: "introoiphone 7 plus", ofType: "mp4")
    player = AVPlayer(url: URL(fileURLWithPath: path!))
    player!.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.insertSublayer(playerLayer, at: 0)
    NotificationCenter.default.addObserver(self, selector: #selector(LoginController1.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
    player!.seek(to: kCMTimeZero)
    player!.play()

}

func playerItemDidReachEnd() {
    player!.seek(to: kCMTimeZero)
}

func dismissKeyboard(tap: UITapGestureRecognizer) {
    print("Keyboard Dismiss Again")
    view.endEditing(true)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

 }
</code>```

答:
You need to convert your string to JSON and then get value out. Here is an example to get user level information. Don't forget to handle unwrapping :)</p>

```<code>let str = "{\"error\":false,\"user\":{\"id\":3,\"username\":\"anto\",\"email\":\"a@a\",\"nome\":\"Anto\",\"cognome\":\"xxx\",\"telefono\":\"1234567892\"},\"prodotti\":[{\"username\":\"anto\",\"id_prodotto\":57,\"nome_prodotto\":\"milk\",\"categoria\":\"milk\",\"quantita\":\"2\"},{\"username\":\"anto\",\"id_prodotto\":58,\"nome_prodotto\":\"farina\",\"categoria\":\"alimento\",\"quantita\":\"2\"}]}"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

    let userDic = json?["user"] as? [String: Any]
    dump(userDic?["id"])
    dump(userDic?["username"])
}catch let error{

}
</code>```

Body:
How do I get the values as an NSDictionary in Swift 3 whit Alamofire?
I would like to take values like json in NSDictionary, and save them to default, then to see everything in a TableView

PHP CODE

public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $i=0;
    $prodotti = array();
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $prodotti[$i]['username'] = $row['username'];
        $prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
        $prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
        $prodotti[$i]['categoria'] = $row['categoria'];
        $prodotti[$i]['quantita'] = $row['quantita'];
        $i++;
    }
 return $prodotti;
 }

 }

That's what I get

    {"error":false,"user":{"id":3,"username":"anto","email":"a@a","nome":"Anto","cognome":"xxx","telefono":"1234567892"},"prodotti":[{"username":"anto","id_prodotto":57,"nome_prodotto":"milk","categoria":"milk","quantita":"2"},{"username":"anto","id_prodotto":58,"nome_prodotto":"farina","categoria":"alimento","quantita":"2"}]}

SWIFT CODE

 import Alamofire
 import UIKit
 import AVFoundation

 class LoginController1: UIViewController {

//The login script url make sure to write the ip instead of localhost
//you can get the ip using ifconfig command in terminal
let URL_USER_LOGIN = "http://........login.php"

//the defaultvalues to store user data
let defaultValues = UserDefaults.standard

//the connected views
//don't copy instead connect the views using assistant editor
@IBOutlet weak var labelMessage: UILabel!
@IBOutlet weak var username: UITextField!

@IBOutlet weak var password: UITextField!

//the button action function
@IBAction func buttonLogin(_ sender: UIButton) {

    //getting the username and password
    let parameters: Parameters=[
        "username":username.text!,
        "password":password.text!
    ]

    //making a post request
    Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
        {
            response in
            //printing response
            print(response)

            //getting the json value from the server
            if let result = response.result.value {
                let jsonData = result as! NSDictionary

                //if there is no error
                if(!(jsonData.value(forKey: "error") as! Bool)){

                    //getting the user from response
                    let user = jsonData.value(forKey: "user") as! NSDictionary

                    //getting user values
                    let userId = user.value(forKey: "id") as! Int
                    let userName = user.value(forKey: "username") as! String
                    let userEmail = user.value(forKey: "email") as! String
                    let userNome = user.value(forKey: "nome") as! String
                    let userCognome = user.value(forKey: "cognome") as! String
                    let userTelefono = user.value(forKey: "telefono") as! String

                    //saving user values to defaults
                    self.defaultValues.set(userId, forKey: "userid")
                    self.defaultValues.set(userName, forKey: "username")
                    self.defaultValues.set(userEmail, forKey: "useremail")
                    self.defaultValues.set(userNome, forKey: "usernome")
                    self.defaultValues.set(userCognome, forKey: "usercognome")
                    self.defaultValues.set(userTelefono, forKey: "usertelefono")

                    ///prende i valori dei prodotti dalla cella legata a quel username
                    let row = jsonData.value(forKey: "row") as! NSDictionary

                    let rowNome_prodotto = prodotti.value(forKey: "nome_prodotto") as! String
                    let rowCategoria = prodotti.value(forKey: "categoria") as! String
                    let rowQuantita = prodotti.value(forKey: "quantita") as! String

                    //saving i valori di questo username

                    self.defaultValues.set(prodottiNome_prodotto, forKey: "nome_prodotto")
                    self.defaultValues.set(prodottiCategoria, forKey: "categoria")
                    self.defaultValues.set(prodottiQuantita, forKey: "quantita")

                    //Go to the HomeViewController if the login is sucessful
                    let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
                    self.navigationController?.pushViewController(ProfiloController, animated: true)

                    self.dismiss(animated: false, completion: nil)

                    }else{
                                            //error message in case of invalid credential
                    let alertController = UIAlertController(title: "Error", message: "Username e password sbagliati", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                    }
            }
                }
}

override func viewDidLoad() {
    super.viewDidLoad()
    if defaultValues.string(forKey: "username") != nil{
        let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
        self.navigationController?.pushViewController(ProfiloController, animated: true)

    }
}

    var player: AVPlayer?
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    let tap = UITapGestureRecognizer(target: self, action: #selector(LoginController1.dismissKeyboard))
    view.addGestureRecognizer(tap)
    let path = Bundle.main.path(forResource: "introoiphone 7 plus", ofType: "mp4")
    player = AVPlayer(url: URL(fileURLWithPath: path!))
    player!.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.insertSublayer(playerLayer, at: 0)
    NotificationCenter.default.addObserver(self, selector: #selector(LoginController1.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
    player!.seek(to: kCMTimeZero)
    player!.play()

}

func playerItemDidReachEnd() {
    player!.seek(to: kCMTimeZero)
}

func dismissKeyboard(tap: UITapGestureRecognizer) {
    print("Keyboard Dismiss Again")
    view.endEditing(true)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

 }

Body:
You need to convert your string to JSON and then get value out. Here is an example to get user level information. Don't forget to handle unwrapping :)

let str = "{\"error\":false,\"user\":{\"id\":3,\"username\":\"anto\",\"email\":\"a@a\",\"nome\":\"Anto\",\"cognome\":\"xxx\",\"telefono\":\"1234567892\"},\"prodotti\":[{\"username\":\"anto\",\"id_prodotto\":57,\"nome_prodotto\":\"milk\",\"categoria\":\"milk\",\"quantita\":\"2\"},{\"username\":\"anto\",\"id_prodotto\":58,\"nome_prodotto\":\"farina\",\"categoria\":\"alimento\",\"quantita\":\"2\"}]}"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

    let userDic = json?["user"] as? [String: Any]
    dump(userDic?["id"])
    dump(userDic?["username"])
}catch let error{

}


问:
Problem when assigning a pointer to an enum variable in C
I am getting a warning of "assigment from incompatible pointer type".  I don't understand why this warning is happening. I don't know what else to declare "the_go_status" variable to other than an integer. (Note: this is not all the code, but just a simplified version I posted to illustrate the problem.)

The warning occurs on the last line of the example I included below.

```<code>//In a header file
enum error_type
{
    ERR_1 = 0,
    ERR_2 = 1,
    ERR_3 = 2,
    ERR_4 = 4,
};

//In a header file
struct error_struct
{
   int value;
   enum error_type *status;
};

//In a C file
int the_go_status;

the_go_status = ERR_1;

//Have the error_struct "status" point to the address of "the_go_status"
error_struct.status = &the_go_status;    //WARNING HERE!
</code>```

答:
you should declare a pointer if you want to use a pointer:

```<code>int * the_go_status
</code>```

otherwise you declare a primitive, which is not placed on the heap, but on the stack. (please correct my when being wrong on that)

However, I don't get why you want to use a pointer at all. Just do something like this in your struct definition:

```<code>enum error_type status;
</code>```

and change your last line to:

```<code>error_struct.status = the_go_status;
</code>```

Body:
I am getting a warning of "assigment from incompatible pointer type".  I don't understand why this warning is happening. I don't know what else to declare "the_go_status" variable to other than an integer. (Note: this is not all the code, but just a simplified version I posted to illustrate the problem.)

The warning occurs on the last line of the example I included below.

//In a header file
enum error_type
{
    ERR_1 = 0,
    ERR_2 = 1,
    ERR_3 = 2,
    ERR_4 = 4,
};

//In a header file
struct error_struct
{
   int value;
   enum error_type *status;
};

//In a C file
int the_go_status;

the_go_status = ERR_1;

//Have the error_struct "status" point to the address of "the_go_status"
error_struct.status = &the_go_status;    //WARNING HERE!

Body:
you should declare a pointer if you want to use a pointer:

int * the_go_status

otherwise you declare a primitive, which is not placed on the heap, but on the stack. (please correct my when being wrong on that)

However, I don't get why you want to use a pointer at all. Just do something like this in your struct definition:

enum error_type status;

and change your last line to:

error_struct.status = the_go_status;


问:
Change login for report deployment
I'm trying to deploy a report to one of my servers but I get an error stating The permissions granted to user 'User A' are insufficient for performing this operation.  However, I am logged into the machine as User B who does have access to deploy the report.

How can I force BIDS to prompt me again for login so that I can login as User B instead of User A?

答:
If anyone is not able to find the right account in Credentials Manager, is possible to add the correct credentials in Credentials Manager by clicking on 'add a windows credential' option;

Note: in the Internet or network address field type just the base address of the URL.

Title: Change login for report deployment