问:
How to display block an element and display in another div?
I have the youtube video and the video thumbnail. By default, videos are hidden.

I want to display related video on click the video thumbnail and display in the another div.

Below is my HTML:

```<code><ul id="result">
    <div class="testt-1">
        <h2 class="t1"> Name Tags </h2>
        <iframe id="video-1" width="220" height="115" src="http://www.youtube.com/embed/2vwBkTRDczc" style="display:none;"></iframe>
        <img id="img-1" src="https://img.youtube.com/vi/2vwBkTRDczc/0.jpg">
    </div>

    <div class="testt-2">
        <h2 class="t1"> Yak Chews </h2>
        <iframe id="video-2" width="220" height="115" src="http://www.youtube.com/embed/JQgFDi-vu1w" style="display:none;"></iframe>
        <img id="img-2" src="https://img.youtube.com/vi/JQgFDi-vu1w/0.jpg">
    </div>

    <div class="testt-3">
        <h2 class="t1"> tags </h2>
        <iframe id="video-3" width="220" height="115" src="http://www.youtube.com/embed/I1K3lrSsde4" style="display:none;"></iframe>
        <img id="img-3" src="https://img.youtube.com/vi/I1K3lrSsde4/0.jpg">
    </div>

    <div class="testt-4">
        <h2 class="t1"> Yak Chews Bone </h2>
        <iframe id="video-4" width="220" height="115" src="http://www.youtube.com/embed/yah872hDA8I" style="display:none;"></iframe>
        <img id="img-4" src="https://img.youtube.com/vi/yah872hDA8I/0.jpg">
    </div>

    <div class="testt-5">
        <h2 class="t1"> test </h2>
        <iframe id="video-5" width="220" height="115" src="http://www.youtube.com/embed/PJQbuIarVgA" style="display:none;"></iframe>
        <img id="img-5" src="https://img.youtube.com/vi/PJQbuIarVgA/0.jpg">
    </div>
</ul>

<div class="large-video" data-id="large-video"></div>
</code>```

Video and thumbnail are listing using for-each loop by PHP code.

答: In your JS file you've to grab the value of the image src attribute of a particular thumbnail onclick and grab the div you want to display it to and then append video tag to the div where the video src value is the value of the grabbed thumbnail image. </p>

Body:
I have the youtube video and the video thumbnail. By default, videos are hidden.

I want to display related video on click the video thumbnail and display in the another div.

Below is my HTML:

 Name Tags

 Yak Chews

 tags

 Yak Chews Bone

 test

Video and thumbnail are listing using for-each loop by PHP code.


来源: stackexchange

问:
Number which occurs only once in the array

Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

```<code>a[1..n] = [1,2,3,4,3,1,2]
</code>```

should return 4

答:
Create new int i = 0

XOR each item with i

After all iterations there will be expected number in i

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

a[1..n] = [1,2,3,4,3,1,2]

should return 4


问:
How do I split and reconstruct a variable name while holding its original value
Is it possible to split variables that have already been assigned values, and re-piece them back together to hold those same previous values?

For Example:

```<code>URLs.QA.Signin = 'https://qa.test.com'
TestEnvironment = 'QA'
CurrentURL = 'URLs.' + TestEnvironment + '.Signin'
print(CurrentURL)
</code>```

Outputs as: 'URLs.QA.Signin'

but I would like it to:

Output as: 'https://qa.test.com'

The purpose is so I can plug in any value to my 'TestEnvironment' variable and thus access any of my massive list of URL's with ease =P

I am green with Python. Your time and efforts are greatly appreciated! =)

Based upon evanrelf's answer, I tried and loved the following code!:

This is exactly what i'm looking for, I might be over complicating it, any suggestions to clean up the code?

```<code>urls = {}
environment = 'qa'
district = 'pleasanthill'
url = environment + district
urls[url] = 'https://' + environment + '.' + district + '.test.com'
print(urls[url])
</code>```

Output is: https://qa.pleasanthill.test.com

答:
I believe to my comprehension that you are trying to input a string and get a new string (the url) back. The simplest answer that I can understand is to use a dictionary. An example of this is by simply doing

```<code>URLS = {'sheep' : 'wool.com', 'cows' : 'beef.com'}
</code>```

either this or by using two arrays and referencing a common index, but who wants to do that :p

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to split variables that have already been assigned values, and re-piece them back together to hold those same previous values?

For Example:

URLs.QA.Signin = 'https://qa.test.com'
TestEnvironment = 'QA'
CurrentURL = 'URLs.' + TestEnvironment + '.Signin'
print(CurrentURL)

Outputs as: 'URLs.QA.Signin'

but I would like it to:

Output as: 'https://qa.test.com'

The purpose is so I can plug in any value to my 'TestEnvironment' variable and thus access any of my massive list of URL's with ease =P

I am green with Python. Your time and efforts are greatly appreciated! =)

Based upon evanrelf's answer, I tried and loved the following code!:

This is exactly what i'm looking for, I might be over complicating it, any suggestions to clean up the code?

urls = {}
environment = 'qa'
district = 'pleasanthill'
url = environment + district
urls[url] = 'https://' + environment + '.' + district + '.test.com'
print(urls[url])

Output is: https://qa.pleasanthill.test.com

Body:
I believe to my comprehension that you are trying to input a string and get a new string (the url) back. The simplest answer that I can understand is to use a dictionary. An example of this is by simply doing

URLS = {'sheep' : 'wool.com', 'cows' : 'beef.com'}

either this or by using two arrays and referencing a common index, but who wants to do that :p


问:
If statement inside a for loop prints all values as true if any are - bash

I want to find a git project containing the project name inputed and auto cd into it. It should be a simple bash function but it behaves strangely.

```<code>project() {
    target=$1"/.git"
    for string in "$(find ~ -name .git -type d -prune)"
    do
        if [[ $string == *"${target}" ]]
        then
            echo $string
        else
            echo 2
        fi
    done
    # cd "$HOME/Work/$1/src"
}
</code>```

If I were to echo all the projects found (the string values), it properly prints out all of the projects. Also, target is also a valid string. The expected result should be echoing of the correct path once, and all other values to be 2.

The problem appears when the code matches target as being part of the string. In that case it prints out ALL projects, instead of the wanted one. If the pattern doesn't match any projects, the code will print the value 2 ONCE. Maybe it has something to do with the fact that I'm using zsh but I really don't know.

答:
There are several problems here:

The shell does not perform word splitting on an expression enclosed within double-quotes, so "$(find ...)" in a loop context is a single word

Even if you remove those double-quotes, the results of find will be subject to word splitting, and that makes it not suitable to use in a for loop

Instead of using [[ ... == ... ]] to match patterns on the result of find, it would be better to use find itself to match patterns, that's what the tool is designed for

Why echo 2, and why echo in a loop? It seems you want to use the result of this function with cd, and that won't go well with multiple outputs

Lastly, and this is just a nitpick, the quoting here is not a problem, but it's weird: target=$1"/.git". You don't actually need the quotes here, this would be just fine: target=$1/.git. If you were using $1/.git in a command line argument, it's the $1 the most important to quote, as .git has certainly no special characters in it. Long story short, you should write "$1"/.git or "$1/.git".

Here's one way to fix the above issues:

```<code>project() {
    local path
    while IFS= read -rd '' path; do
        echo "$path"
        return 0
    done < <(find ~ -type d -path "**/$1/.git" -print0)
    echo "project not found: $1" >&2
    return 1
}
</code>```

Body:
I want to find a git project containing the project name inputed and auto cd into it. It should be a simple bash function but it behaves strangely.

project() {
    target=$1"/.git"
    for string in "$(find ~ -name .git -type d -prune)"
    do
        if [[ $string == *"${target}" ]]
        then
            echo $string
        else
            echo 2
        fi
    done
    # cd "$HOME/Work/$1/src"
}

If I were to echo all the projects found (the string values), it properly prints out all of the projects. Also, target is also a valid string. The expected result should be echoing of the correct path once, and all other values to be 2.

The problem appears when the code matches target as being part of the string. In that case it prints out ALL projects, instead of the wanted one. If the pattern doesn't match any projects, the code will print the value 2 ONCE. Maybe it has something to do with the fact that I'm using zsh but I really don't know.

Body:
There are several problems here:

The shell does not perform word splitting on an expression enclosed within double-quotes, so "$(find ...)" in a loop context is a single word

Even if you remove those double-quotes, the results of find will be subject to word splitting, and that makes it not suitable to use in a for loop

Instead of using [[ ... == ... ]] to match patterns on the result of find, it would be better to use find itself to match patterns, that's what the tool is designed for

Why echo 2, and why echo in a loop? It seems you want to use the result of this function with cd, and that won't go well with multiple outputs

Lastly, and this is just a nitpick, the quoting here is not a problem, but it's weird: target=$1"/.git". You don't actually need the quotes here, this would be just fine: target=$1/.git. If you were using $1/.git in a command line argument, it's the $1 the most important to quote, as .git has certainly no special characters in it. Long story short, you should write "$1"/.git or "$1/.git".

Here's one way to fix the above issues:

project() {
    local path
    while IFS= read -rd '' path; do
        echo "$path"
        return 0
    done < <(find ~ -type d -path "**/$1/.git" -print0)
    echo "project not found: $1" >&2
    return 1
}


问:
close bootstrap modal window using angularjs after submit
I'm creating an inventory app, and the user has the option to add a new product or edit an existing one.  Both options bring up the same modal window, and I want it to close automatically after the user clicks on submit.

Below is part of my code, my entire code is here: http://codepen.io/andresq820/pen/LWGKXW

HTML

```<code>            <div class="modal fade" id="editItemModal" role="dialog">
            <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">{{title(item.code)}}</h4>
                </div>

            <div class="modal-body">
                <form name="myEditForm" ng-submit="editProduct(item)">
                    <div class="form-group">
                        <label for="code">Code:</label>
                        <input type="text" size="5" maxlength="5" minlength="3" class="form-control" name="code" id="code"
                        ng-model="item.code" ng-disabled="false" ng-pattern="/^[a-zA-Z0-9]*$/">
                        <span ng-show="myEditForm.code.$error.pattern">Code can only be alphanumeric.</span> </br>
                        <span ng-show="myEditForm.code.$error.minlength">Code has to be at least 3 characters</span>
                    </div>

                    <div class="form-group">
                        <label for="description">Description:</label>
                        <input type="text" class="form-control" name="description" id="description" ng-model="item.description" required>
                        <span ng-show="myEditForm.description.$touched && myEditForm.description.$invalid">The description is required.</span>
                    </div>

                    <div class="form-group">
                        <label for="amount">Amount:</label>
                        <input type="number" class="form-control" name="amount" id="amount" size="5" maxlength="5"
                        ng-model="item.amount" ng-pattern="/^[0-9]{1,7}$/">
                        <span ng-show="myEditForm.amount.$error.pattern">Only whole numbers are allowed</span>
                    </div>

                    <div class="form-group">
                        <label for="newImage">{{loadImg}}</label>
                        <input type="file" class="form-control" name="newImage" id="newImage" ng-model="item.image">
                    </div>

                    <div class="form-group" ng-show="displayRadioBtns">
                        <label for="radio">Type:</label>
                        <div class="radio">
                            <label><input type="radio" name="optradio" ng-model="item.type" value="in">In</label>
                            <label><input type="radio" name="optradio" ng-model="item.type" value="out">Out</label>
                        </div>
                    </div>

            <div class="modal-footer">
                <input type="button" class="btn btn-default" data-dismiss="modal" value="Close" />
                <input type="submit" class="btn btn-primary pull-right" value="Submit" ng-disabled="myEditForm.$invalid"/>
            </div>
                </form>
            </div>
            </div>
            </div>
        </div>
</code>```

ANGULARJS

```<code> $scope.editProduct = function(item){
    var index = $scope.items.indexOf(item);
    console.log(index);
    console.log(item);
    console.log(item.code.valueOf());
    if(index == -1){
        console.log('new item');
        $scope.item.code = item.code;
        $scope.item.description = item.description;
        $scope.item.in = item.amount;
        $scope.item.out = 0;
        $scope.item.createdOn = Date.now();
        $scope.items.push($scope.item);
        $scope.item = {};

    }else{
        console.log('edit item');
        console.log(item);
        console.log(item.type);
        console.log($scope.item.type);
        console.log(index);
        $scope.items[index].code = item.code;
        console.log($scope.items[index].code);
        $scope.items[index].description = item.description;
        console.log($scope.items[index].description);
        $scope.items[index].image = item.image;

            if($scope.item.type == 'in'){
                console.log($scope.item.type);
                console.log(typeof($scope.items[index].in));
                console.log(typeof($scope.item.amount));
                console.log(typeof(item.amount));
                $scope.items[index].in += item.amount;
                console.log($scope.items[index].in);
                $scope.item = {};
            }else if($scope.item.type == 'out'){
                console.log($scope.item.type);
                $scope.items[index].out += $scope.item.amount;
                $scope.item = {};
            }else{
                alert("Type is a required field");
                return;
            };

    }
};
</code>```

答:
You can make function calls on ngSubmit

form class="well" (ngSubmit)="addUserModal.hide(); addUser(model); userForm.reset()" #userForm="ngForm"

Body:
I'm creating an inventory app, and the user has the option to add a new product or edit an existing one.  Both options bring up the same modal window, and I want it to close automatically after the user clicks on submit.

Below is part of my code, my entire code is here: http://codepen.io/andresq820/pen/LWGKXW

HTML

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

{{title(item.code)}}

                <form name="myEditForm" ng-submit="editProduct(item)">

                        Code:
                        <input type="text" size="5" maxlength="5" minlength="3" class="form-control" name="code" id="code"
                        ng-model="item.code" ng-disabled="false" ng-pattern="/^[a-zA-Z0-9]*$/">
                        Code can only be alphanumeric.

                        Code has to be at least 3 characters

                        Description:
                        <input type="text" class="form-control" name="description" id="description" ng-model="item.description" required>
                        The description is required.

                        Amount:
                        <input type="number" class="form-control" name="amount" id="amount" size="5" maxlength="5"
                        ng-model="item.amount" ng-pattern="/^[0-9]{1,7}$/">
                        Only whole numbers are allowed

                        {{loadImg}}
                        <input type="file" class="form-control" name="newImage" id="newImage" ng-model="item.image">

                        Type:

                            <input type="radio" name="optradio" ng-model="item.type" value="in">In
                            <input type="radio" name="optradio" ng-model="item.type" value="out">Out

                <input type="button" class="btn btn-default" data-dismiss="modal" value="Close" />
                <input type="submit" class="btn btn-primary pull-right" value="Submit" ng-disabled="myEditForm.$invalid"/>

                </form>

ANGULARJS

 $scope.editProduct = function(item){
    var index = $scope.items.indexOf(item);
    console.log(index);
    console.log(item);
    console.log(item.code.valueOf());
    if(index == -1){
        console.log('new item');
        $scope.item.code = item.code;
        $scope.item.description = item.description;
        $scope.item.in = item.amount;
        $scope.item.out = 0;
        $scope.item.createdOn = Date.now();
        $scope.items.push($scope.item);
        $scope.item = {};

    }else{
        console.log('edit item');
        console.log(item);
        console.log(item.type);
        console.log($scope.item.type);
        console.log(index);
        $scope.items[index].code = item.code;
        console.log($scope.items[index].code);
        $scope.items[index].description = item.description;
        console.log($scope.items[index].description);
        $scope.items[index].image = item.image;

            if($scope.item.type == 'in'){
                console.log($scope.item.type);
                console.log(typeof($scope.items[index].in));
                console.log(typeof($scope.item.amount));
                console.log(typeof(item.amount));
                $scope.items[index].in += item.amount;
                console.log($scope.items[index].in);
                $scope.item = {};
            }else if($scope.item.type == 'out'){
                console.log($scope.item.type);
                $scope.items[index].out += $scope.item.amount;
                $scope.item = {};
            }else{
                alert("Type is a required field");
                return;
            };

    }
};


问:
How droping a table from DB affects the views
A veiw is created on table Student.
If i drop the student table will the veiw also drop ? If not what will be the situation ? </p>

答:
When a table gets dropped all data, indexes, and linked information will be deleted as well.It's been like a row in DB which use delete all the relative column and all the information that was linked to it will be deleted as well.

When a table is dropped, privileges granted specifically for the table
  are not automatically dropped. They must be dropped manually.

Be careful with this statement! It removes the table definition and all table data. For a partitioned table, it permanently removes the table definition, all its partitions, and all data stored in those partitions. It also removes partition definitions associated with the dropped table.


问:
Cant draw a shape to a specific panel in a NetBeans GUI
I'm trying to make a simple application to draw shapes to a panel in a jFrame. The GUI is a NetBeans generated jFrame. The application has three panels. the first two hold button groups to select the shape and a color. There's a button to draw the shape to the third panel once the selections are made.

What the GUI looks like

Unfortunately I'm having no love and can't make it work. For now I just want to get the button to draw a shape then I'll add the button functionality. Here's the code I have so far.

```<code>private void btnDrawShapeActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    Draw shape = new Draw();

    pnlDrawPad.add(shape); //pnlDrawPad is the name of the jPanel

    shape.drawing();

}

import javax.swing.*;
import java.awt.*;

public class Draw extends JPanel{

public Draw(){
    super();
}

public void drawing(){
    repaint();
}

//@Override <-- gives error "method does not override or implement a method from a supertype"
public void paintCompnent(Graphics g){

    super.paintComponent(g);

    g.setColor(Color.RED);
    g.drawString("Hello World!",40,30);
}
</code>```

}

When I click the "Draw Shape" button nothing happens. I've been searching for a couple days now and am not finding the answer. Actually, its making me more confused as to what to do.

How to deal with this?

答:
I found that with NetBeans you don't need to Override the paintComponents() method. Since all the GUI stuff is done when you design it, you merely need to add the drawings to the panel or what ever you need to do. I found you that by declaring and instantiating a 2D graphics object then drawing it to the place you want.

```<code>private void btnDrawShapeActionPerformed(java.awt.event.ActionEvent evt) {

int centerX;
int centerY;

Graphics2D drawFx = (Graphics2D)pnlDrawPad.getGraphics();

drawFx.setColor(Color.ORANGE);

centerX = (int)(458*Math.random());
centerY = (int)(440*Math.random());

drawFx.fillOval(centerX-50, centerY-50, 100, 100);

drawFx.dispose();

}
</code>```

Worked like a charm so now every time I push the draw shape button it draws a shape to the panel in a different location every time. I've since put in the radio button functionality to change shape color and fill and added a button to clear the screen.

Not sure if this is the ideal way to do it but for this stupid simple little program it works well enough and I'm done stressing over it.

Body:
I'm trying to make a simple application to draw shapes to a panel in a jFrame. The GUI is a NetBeans generated jFrame. The application has three panels. the first two hold button groups to select the shape and a color. There's a button to draw the shape to the third panel once the selections are made.

What the GUI looks like

Unfortunately I'm having no love and can't make it work. For now I just want to get the button to draw a shape then I'll add the button functionality. Here's the code I have so far.

private void btnDrawShapeActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    Draw shape = new Draw();

    pnlDrawPad.add(shape); //pnlDrawPad is the name of the jPanel

    shape.drawing();

}

import javax.swing.*;
import java.awt.*;

public class Draw extends JPanel{

public Draw(){
    super();
}

public void drawing(){
    repaint();
}

//@Override <-- gives error "method does not override or implement a method from a supertype"
public void paintCompnent(Graphics g){

    super.paintComponent(g);

    g.setColor(Color.RED);
    g.drawString("Hello World!",40,30);
}

}

When I click the "Draw Shape" button nothing happens. I've been searching for a couple days now and am not finding the answer. Actually, its making me more confused as to what to do.

How to deal with this?

Body:
I found that with NetBeans you don't need to Override the paintComponents() method. Since all the GUI stuff is done when you design it, you merely need to add the drawings to the panel or what ever you need to do. I found you that by declaring and instantiating a 2D graphics object then drawing it to the place you want.

private void btnDrawShapeActionPerformed(java.awt.event.ActionEvent evt) {

int centerX;
int centerY;

Graphics2D drawFx = (Graphics2D)pnlDrawPad.getGraphics();

drawFx.setColor(Color.ORANGE);

centerX = (int)(458*Math.random());
centerY = (int)(440*Math.random());

drawFx.fillOval(centerX-50, centerY-50, 100, 100);

drawFx.dispose();

}

Worked like a charm so now every time I push the draw shape button it draws a shape to the panel in a different location every time. I've since put in the radio button functionality to change shape color and fill and added a button to clear the screen.

Not sure if this is the ideal way to do it but for this stupid simple little program it works well enough and I'm done stressing over it.


问:
Swagger and JWT Token Authentication
I am building some Swagger documentation, all well and good, except that I am wanting to have the page work interactively, so when selecting the editor or UI, if I hit the authorize button, I would call my Authentication URL that builds the JWT token that is then used in subsequent requests.

I am planning to issue the API client an Api Access Key and a Secret Access Key, and want to hit an authentication page that will process these and build the JWT token.

It strikes me that if I can get the correct definition of how to achieve this in Swagger, that I will have a ready-built test client to then use against my fresh new code.

Yes, it's my first time with JWT and I have not yet built the code. Can you say "API-First"?

答:
This is how I used Swagger with JWT Authentication:

Write a Express.js API end point to generate a JWT.

Create a Swagger Path to retrieve the JWT using above end point

In swagger.yaml root level:

```<code>securityDefinitions:
  JWT:
    type: apiKey
    in: header
    name: access_token
</code>```

In swagger.yaml paths:

```<code>security
 -JWT: []
</code>```

This will display an Authorize button in Swagger UI on browser.

Enter JWT generated above in the Authentication Window that pops-up when above Authorize button is clicked

Now JWT will be passed with the request headers

Hope this may help others.

Title: Swagger and JWT Token Authentication

Body:
This is how I used Swagger with JWT Authentication:

Write a Express.js API end point to generate a JWT.

Create a Swagger Path to retrieve the JWT using above end point

In swagger.yaml root level:

securityDefinitions:
  JWT:
    type: apiKey
    in: header
    name: access_token

In swagger.yaml paths:

security
 -JWT: []

This will display an Authorize button in Swagger UI on browser.

Enter JWT generated above in the Authentication Window that pops-up when above Authorize button is clicked

Now JWT will be passed with the request headers

Hope this may help others.


问:
onclick method does not exist error?
this is the description of the error

There should be no spaces in the onClick handler name  The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View.  Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.

```<code>btnClick = (Button) findViewById(R.id.button2);
txtBox1 = (EditText) findViewById(editText9);
txtBox2 = (EditText) findViewById(editText10);

btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }

btnClick = (Button) findViewById(R.id.button3);

        btnClick.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                    ClipboardManager clipboard = (ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
                String text = txtBox2.getText().toString();
                ClipData clip = ClipData.newPlainText("text", text);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getApplicationContext(), "Text Copied",
                        Toast.LENGTH_SHORT).show();

            }

        });

        txtBox2 = (EditText) findViewById(editText10);
        txtBox1 = (EditText) findViewById(editText9);
        btnClick = (Button) findViewById(R.id.button5);

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                txtBox1.setText("");
            }
        });

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                String s = new String(binary);
                txtBox1.setText(s);
            }
        });
</code>```

答:
You have not closed the OnClickListener interface.
Change

```<code>btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }
</code>```

to

```<code>btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }
}
});
</code>```

Note that I have added

}
    });
 to your code. After this line start your next code.

Title: onclick method does not exist error?

Body:
this is the description of the error

There should be no spaces in the onClick handler name  The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View.  Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.

btnClick = (Button) findViewById(R.id.button2);
txtBox1 = (EditText) findViewById(editText9);
txtBox2 = (EditText) findViewById(editText10);

btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }

btnClick = (Button) findViewById(R.id.button3);

        btnClick.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                    ClipboardManager clipboard = (ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
                String text = txtBox2.getText().toString();
                ClipData clip = ClipData.newPlainText("text", text);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getApplicationContext(), "Text Copied",
                        Toast.LENGTH_SHORT).show();

            }

        });

        txtBox2 = (EditText) findViewById(editText10);
        txtBox1 = (EditText) findViewById(editText9);
        btnClick = (Button) findViewById(R.id.button5);

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                txtBox1.setText("");
            }
        });

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                String s = new String(binary);
                txtBox1.setText(s);
            }
        });

Body:
You have not closed the OnClickListener interface.
Change

btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }

to

btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }
}
});

Note that I have added

}
    });
 to your code. After this line start your next code.


答:
Just use different Button variables for different button ids in your xml, don't use same button name to call onClick methods.

For example:

```<code>Button btnClick,btnClick1,btnClick2;
</code>```

For more information please visit this link.

Title: onclick method does not exist error?

Body:
Just use different Button variables for different button ids in your xml, don't use same button name to call onClick methods.

For example:

Button btnClick,btnClick1,btnClick2;

For more information please visit this link.


问:
Filter distinct rows based on the td text using jquery?
I have a loop in my jsp as shown below:

```<code><table>
  <tr>
   <th>Region</th>
   <th>Locations</th>
  </tr>
   <c:forEach var="LocationBean" items="${list}">
    <tr>
    <td>${LocationBean.region_name}</td>
    <td>${LocationBean.location_name}</td>
 </tr>
    </c:forEach>
</table>
</code>```

which gives results something like this:

I need to get only distinct region name,I am very basic to jquery.

答:
You must assign an id to the table like mytable and then use jquery filter method

var uniqueItems = [];
$("#btn").on('click', function() {
  $("#list td")
    .filter(function(index, element) {
      if ($.inArray($(element).text(), uniqueItems) === -1) {
        uniqueItems.push($(element).text());
      } else {
        $(element).parent().remove();
      }

    });
  uniqueItems = [];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Filter duplicate
<table id="list" class="table">
  <tr>
    <th>Region</th>
    <th>Locations</th>
  </tr>
  <tr>
    <td>EAST</td>
    <td>loc1</td>
  </tr>
  <tr>
    <td>EAST</td>
    <td>loc1</td>
  </tr>
  <tr>
    <td>North</td>
    <td>loc2</td>
  </tr>
  <tr>
    <td>West</td>
    <td>loc3</td>
  </tr>
</table></code>```

Body:
I have a loop in my jsp as shown below:

   Region
   Locations

   <c:forEach var="LocationBean" items="${list}">

    ${LocationBean.region_name}
    ${LocationBean.location_name}

    </c:forEach>

which gives results something like this:

I need to get only distinct region name,I am very basic to jquery.

Body:
You must assign an id to the table like mytable and then use jquery filter method

var uniqueItems = [];
$("#btn").on('click', function() {
  $("#list td")
    .filter(function(index, element) {
      if ($.inArray($(element).text(), uniqueItems) === -1) {
        uniqueItems.push($(element).text());
      } else {
        $(element).parent().remove();
      }

    });
  uniqueItems = [];
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<a href="#." class="btn btn-success" id="btn">Filter duplicate</a>
<table id="list" class="table">
  <tr>
    <th>Region</th>
    <th>Locations</th>
  </tr>
  <tr>
    <td>EAST</td>
    <td>loc1</td>
  </tr>
  <tr>
    <td>EAST</td>
    <td>loc1</td>
  </tr>
  <tr>
    <td>North</td>
    <td>loc2</td>
  </tr>
  <tr>
    <td>West</td>
    <td>loc3</td>
  </tr>
</table>


问:
Simple Syntax: Multiple Constraints in Alter Table Statement
If I have this statement:

```<code>ALTER TABLE RecipeBox.Recipe ADD CONSTRAINT AKRecipeBox_Recipe_Name
UNIQUE NONCLUSTERED (Name)
</code>```

How do I add another constraint to this statement? Is this even possible?

Thanks

Using SQL SERVER 2008 Developer Edition

答:
Add a comma, then add the new constraint (without add keyword) like this:</p>

```<code>ALTER TABLE RecipeBox.Recipe ADD CONSTRAINT AKRecipeBox_Recipe_Name
UNIQUE NONCLUSTERED (Name),
CONSTRAINT your_constraint UNIQUE NONCLUSTERED (yourColumn) -- (or whatever type of constraint you're looking for)
</code>```

Body:
If I have this statement:

ALTER TABLE RecipeBox.Recipe ADD CONSTRAINT AKRecipeBox_Recipe_Name
UNIQUE NONCLUSTERED (Name)

How do I add another constraint to this statement? Is this even possible?

Thanks

Using SQL SERVER 2008 Developer Edition

Body:
Add a comma, then add the new constraint (without add keyword) like this:

ALTER TABLE RecipeBox.Recipe ADD CONSTRAINT AKRecipeBox_Recipe_Name
UNIQUE NONCLUSTERED (Name),
CONSTRAINT your_constraint UNIQUE NONCLUSTERED (yourColumn) -- (or whatever type of constraint you're looking for)


问:
Train score diminishes after polynomial regression degree increases
I'm trying to use linear regression to fit a polynomium to a set of points from a sinusoidal signal with some noise added, using linear_model.LinearRegression from sklearn.

As expected, the training and validation scores increase as the degree of the polynomium increases, but after some degree around 20 things start getting weird and the scores start going down, and the model returns polynomiums that don't look at all like the data that I use to train it.

Below are some plots where this can be seen, as well as the code that generated both the regression models and the plots:

How the thing works well until degree=17. Original data VS predictions:

After that it just gets worse:

Validation curve, increasing the degree of the polynomium:

from sklearn.pipeline import make_pipeline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.learning_curve import validation_curve

def make_data(N, err=0.1, rseed=1):
    rng = np.random.RandomState(1)
    x = 10 * rng.rand(N)
    X = x[:, None]
    y = np.sin(x) + 0.1 * rng.randn(N)
    if err > 0:
        y += err * rng.randn(N)
    return X, y

def PolynomialRegression(degree=4):
    return make_pipeline(PolynomialFeatures(degree),
                         LinearRegression())

X, y = make_data(400)

X_test = np.linspace(0, 10, 500)[:, None]
degrees = np.arange(0, 40)

plt.figure(figsize=(16, 8))
plt.scatter(X.flatten(), y)
for degree in degrees:
    y_test = PolynomialRegression(degree).fit(X, y).predict(X_test)
    plt.plot(X_test, y_test, label='degre={0}'.format(degree))
plt.title('Original data VS predicted values for different degrees')
plt.legend(loc='best');

degree = np.arange(0, 40)
train_score, val_score = validation_curve(PolynomialRegression(), X, y,
                                                 'polynomialfeatures__degree',
                                                 degree, cv=7)

plt.figure(figsize=(12, 6))
plt.plot(degree, np.median(train_score, 1), marker='o',
         color='blue', label='training score')
plt.plot(degree, np.median(val_score, 1), marker='o',
         color='red', label='validation score')
plt.legend(loc='best')
plt.ylim(0, 1)
plt.title('Learning curve, increasing the degree of the polynomium')
plt.xlabel('degree')
plt.ylabel('score');
```

I know the expected thing is that the validation score goes down when the complexity of the model increases, but why does the training score goes down as well? What can I be missing here?

答:
Training score is expected to go down as well due to overfitting of the model on training data. Error on validation goes down due to sine function's Taylor series expansion. So, as you increase degree of polynomial, your model improves to fit the sine curve better.

In ideal scenario if you don't have a function that expands to infinite degrees, you see training error going down (not monotonically but in general) and validation error going up after some degree (high for lower degrees -> low for some higher degree -> increasing after that).

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use linear regression to fit a polynomium to a set of points from a sinusoidal signal with some noise added, using linear_model.LinearRegression from sklearn.

As expected, the training and validation scores increase as the degree of the polynomium increases, but after some degree around 20 things start getting weird and the scores start going down, and the model returns polynomiums that don't look at all like the data that I use to train it.

Below are some plots where this can be seen, as well as the code that generated both the regression models and the plots:

How the thing works well until degree=17. Original data VS predictions:

After that it just gets worse:

Validation curve, increasing the degree of the polynomium:

from sklearn.pipeline import make_pipeline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.learning_curve import validation_curve

def make_data(N, err=0.1, rseed=1):
    rng = np.random.RandomState(1)
    x = 10 * rng.rand(N)
    X = x[:, None]
    y = np.sin(x) + 0.1 * rng.randn(N)
    if err > 0:
        y += err * rng.randn(N)
    return X, y

def PolynomialRegression(degree=4):
    return make_pipeline(PolynomialFeatures(degree),
                         LinearRegression())

X, y = make_data(400)

X_test = np.linspace(0, 10, 500)[:, None]
degrees = np.arange(0, 40)

plt.figure(figsize=(16, 8))
plt.scatter(X.flatten(), y)
for degree in degrees:
    y_test = PolynomialRegression(degree).fit(X, y).predict(X_test)
    plt.plot(X_test, y_test, label='degre={0}'.format(degree))
plt.title('Original data VS predicted values for different degrees')
plt.legend(loc='best');

degree = np.arange(0, 40)
train_score, val_score = validation_curve(PolynomialRegression(), X, y,
                                                 'polynomialfeatures__degree',
                                                 degree, cv=7)

plt.figure(figsize=(12, 6))
plt.plot(degree, np.median(train_score, 1), marker='o',
         color='blue', label='training score')
plt.plot(degree, np.median(val_score, 1), marker='o',
         color='red', label='validation score')
plt.legend(loc='best')
plt.ylim(0, 1)
plt.title('Learning curve, increasing the degree of the polynomium')
plt.xlabel('degree')
plt.ylabel('score');

I know the expected thing is that the validation score goes down when the complexity of the model increases, but why does the training score goes down as well? What can I be missing here?


问:
write a query to this..?
Students and Grades. Students contains three columns ID, Name and Marks, Grades-(grade,min_mark,max_mark)

Ketty gives Eve a task to generate a report containing three columns:  Name, Grade and Mark. Ketty doesn't want the NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. higher grades are entered first. If there is more than one student with the same grade (1-10) assigned to them, order those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and list them by their marks in ascending order.

Write a query to help Eve.

Note
Print "NULL"  as the name if the grade is less than 8.

I have written this query :

```<code>select name,grade,marks from students s join grades g on marks between min_mark and max_mark
where grade>7
order by 2 desc,name

select translate(name,name,'NULL'),grade,marks from students s join grades g on marks between min_mark and max_mark
where grade<=7
order by 3 desc
</code>```

but don't know how to join these both queries.

答:
```<code>select case
when grade < 8 then NULL
else
name
end
as name, grade, marks
from students, grades
where marks between min_mark and max_mark
order by grade desc, name asc, marks asc;
</code>```

Title: write a query to this..?

Body:
Students and Grades. Students contains three columns ID, Name and Marks, Grades-(grade,min_mark,max_mark)

Ketty gives Eve a task to generate a report containing three columns:  Name, Grade and Mark. Ketty doesn't want the NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. higher grades are entered first. If there is more than one student with the same grade (1-10) assigned to them, order those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and list them by their marks in ascending order.

Write a query to help Eve.

Note
Print "NULL"  as the name if the grade is less than 8.

I have written this query :

select name,grade,marks from students s join grades g on marks between min_mark and max_mark
where grade>7
order by 2 desc,name

select translate(name,name,'NULL'),grade,marks from students s join grades g on marks between min_mark and max_mark
where grade<=7
order by 3 desc

but don't know how to join these both queries.


问:
use old random number in rand function
I am using random number function in php. If browser loads or refresh, rand() generates new random number. But I need, if rand() generates a random number first time, after that, if browser loads then random number should not replace old one. Means I want first random number in session.

My code is:

```<code>$globalvari = rand();
$_SESSION['globalvari'] = $globalvari;
if ($_SESSION['globalvari'] != '') {
    $globalvari1 = $_SESSION['globalvari'];
    echo $globalvari1;
}
</code>```

But it replace old one.

答:
Try this

```<code> if(!empty($_SESSION['globalvari']) || (isset($_SESSION['globalvari']) && $_SESSION['globalvari'] === 0)){
      $globalvari1=$_SESSION['globalvari'];
      echo $globalvari1;
 }else{
      $globalvari=rand();
      $_SESSION['globalvari']=$globalvari;
 }
</code>```

You're setting it every reload.  So it has to be in the else condition.  Also, use empty because it doesn't care if the index is set in the array or not.

Last empty will trip up on int(0), so you can bypass that with a simple OR and strict comparison.

Rand() A random integer between min (or 0) and max (or getrandmax() inclusive)

Or you can set a range that does not include 0

Title: use old random number in rand function

Body:
I am using random number function in php. If browser loads or refresh, rand() generates new random number. But I need, if rand() generates a random number first time, after that, if browser loads then random number should not replace old one. Means I want first random number in session.

My code is:

$globalvari = rand();
$_SESSION['globalvari'] = $globalvari;
if ($_SESSION['globalvari'] != '') {
    $globalvari1 = $_SESSION['globalvari'];
    echo $globalvari1;
}

But it replace old one.

Body:
Try this

 if(!empty($_SESSION['globalvari']) || (isset($_SESSION['globalvari']) && $_SESSION['globalvari'] === 0)){
      $globalvari1=$_SESSION['globalvari'];
      echo $globalvari1;
 }else{
      $globalvari=rand();
      $_SESSION['globalvari']=$globalvari;
 }

You're setting it every reload.  So it has to be in the else condition.  Also, use empty because it doesn't care if the index is set in the array or not.

Last empty will trip up on int(0), so you can bypass that with a simple OR and strict comparison.

Rand() A random integer between min (or 0) and max (or getrandmax() inclusive)

Or you can set a range that does not include 0


问:
ARKit and AVCamera simultaneously
As there is no autofocus in ARKit, I wanted to load ARKit in a view that is half the screen and second half will have AVFoundation -> AVCamera.
Is it possible to load AVCamera and ARKit simultaneously in same app?
Thanks.</p>

答:
Nope.

ARKit uses AVCapture internally (as explained in the WWDC talk introducing ARKit). Only one AVCaptureSession can be running at a time, so if you run your own capture session it’ll suspend ARKit’s session (and break tracking).

Update: However, in iOS 11.3 (aka "ARKit 1.5"), ARKit enables autofocus by default, and you can choose to disable it with the isAutoFocusEnabled option.

Title: ARKit and AVCamera simultaneously


问:
How to read multiple files and load them into dataframe
I have a list of csv's in a folder called 11 in C:\1.  All the data has same number of columns.

A.csv

```<code>aa    zz    1     AA
aab   qq    3     FF
ca    qq    5     QQ
</code>```

B.csv

```<code>aa    GG    09    VV
aab   HH    03    WW
ca    CC    0     UU
</code>```

How do I read each file in that folder into the dataframe so that it has a empty column between each new data read from csv.

so that it looks like:

```<code>A     B     C     D     E    F     G     H     I
aa    zz    1     AA         aa    GG    09    VV
aab   qq    3     FF         aab   HH    03    WW
ca    qq    5     QQ         ca    CC    0     UU
</code>```

I.e:

```<code>dfs = {i: pd.read_csv('C:\\1\\{}.csv'.format(i)) for i in ['a', 'b']}
print (dfs['a'])
</code>```

Or:

```<code>import os
import pandas as pd
filelist = os.listdir(targetdir)
df_list = [pd.read_table(file) for file in filelist]
big_df = pd.concat(df_list)

    FileNotFoundError: File b'b.csv' does not exist
</code>```

答:
You can add a spacer Data Frame on each file read, like this:

```<code>import os
import pandas as pd

# with directory name 1, located at ~/1:
dir_name = "1"
path = "~"
dfs = []

# with files A.csv, B.csv in ~/1 (e.g. ~/1/A.csv):
for fname in os.listdir(f"{path}/{dir_name}"):

    df = pd.read_csv(f"{path}/{dir_name}/{fname}", header=None)
    spacer = pd.DataFrame([" "]*len(df))
    dfs.append(df)
    dfs.append(spacer)
master = pd.concat(dfs, axis=1)

master
     0   1  2     3  0    0   1  2   3  0
0   aa  zz  1    AA      aa  GG  9  VV
1  aab  qq  3    FF     aab  HH  3  WW
2   ca  qq  5    QQ      ca  CC  0  UU
</code>```

If you really want the alphabetical column names (A, B, C) you specified in your post, use:

```<code>import string
colnames = string.ascii_uppercase
master.columns = [x for x in colnames[:len(master.columns)]]
</code>```

Note: Directory path uses Mac syntax, but it should be easy enough to adapt to Windows.

Body:
I have a list of csv's in a folder called 11 in C:\1.  All the data has same number of columns.

A.csv

aa    zz    1     AA
aab   qq    3     FF
ca    qq    5     QQ

B.csv

aa    GG    09    VV
aab   HH    03    WW
ca    CC    0     UU

How do I read each file in that folder into the dataframe so that it has a empty column between each new data read from csv.

so that it looks like:

A     B     C     D     E    F     G     H     I
aa    zz    1     AA         aa    GG    09    VV
aab   qq    3     FF         aab   HH    03    WW
ca    qq    5     QQ         ca    CC    0     UU

I.e:

dfs = {i: pd.read_csv('C:\\1\\{}.csv'.format(i)) for i in ['a', 'b']}
print (dfs['a'])

Or:

import os
import pandas as pd
filelist = os.listdir(targetdir)
df_list = [pd.read_table(file) for file in filelist]
big_df = pd.concat(df_list)

    FileNotFoundError: File b'b.csv' does not exist

Body:
You can add a spacer Data Frame on each file read, like this:

import os
import pandas as pd

# with directory name 1, located at ~/1:
dir_name = "1"
path = "~"
dfs = []

# with files A.csv, B.csv in ~/1 (e.g. ~/1/A.csv):
for fname in os.listdir(f"{path}/{dir_name}"):

    df = pd.read_csv(f"{path}/{dir_name}/{fname}", header=None)
    spacer = pd.DataFrame([" "]*len(df))
    dfs.append(df)
    dfs.append(spacer)
master = pd.concat(dfs, axis=1)

master
     0   1  2     3  0    0   1  2   3  0
0   aa  zz  1    AA      aa  GG  9  VV
1  aab  qq  3    FF     aab  HH  3  WW
2   ca  qq  5    QQ      ca  CC  0  UU

If you really want the alphabetical column names (A, B, C) you specified in your post, use:

import string
colnames = string.ascii_uppercase
master.columns = [x for x in colnames[:len(master.columns)]]

Note: Directory path uses Mac syntax, but it should be easy enough to adapt to Windows.


答:
You should code like this : </p>

```<code>if(!isset($_SESSION['globalvari'])){// Checks that `$_SESSION['globalvari']` exist. If not exist then below code create `$_SESSION['globalvari']` variable
    $globalvari=rand();
    $_SESSION['globalvari']=$globalvari;
}
$globalvari1=$_SESSION['globalvari'];
echo $globalvari1;
</code>```

Title: use old random number in rand function

Body:
You should code like this :

if(!isset($_SESSION['globalvari'])){// Checks that `$_SESSION['globalvari']` exist. If not exist then below code create `$_SESSION['globalvari']` variable
    $globalvari=rand();
    $_SESSION['globalvari']=$globalvari;
}
$globalvari1=$_SESSION['globalvari'];
echo $globalvari1;


问:
Incorrect splitting of data using sample.split in R and issue with logistic regression
I have 2 issues.

When I try to split my data into test and train sets, using sample.split as below, the sampling is done rather unclearly. What I mean is that the data d, has a length of 392 and so, 4:1 division should show 0.8*392= 313.6 i.e. 313 or 314 rows in test set, but the shown length is 304. Is there something that I might be missing?

```<code>require(caTools)
set.seed(101)
samplev = sample.split(d[,], SplitRatio= 0.80)
train = subset(d, samplev == TRUE)
test = subset(d, samplev == FALSE)
</code>```

I'm trying to use the split data as follows for a logistic regression task in R, as follows-

```<code>#Training
m <- glm(mpg01~ . -name, data= train, family = binomial(link = 'logit'))
out2 <- predict.glm(m, test, type = "response")
class2 <- vector()
for (i in 1:length(out2))
{
  if(out2[i] >= 0.5)
  {
    class2[i] <- 1
  }
  else
  {
    class2[i] <- 0
  }
}
r2 <- table(class2, test$mpg01)  #confusion Matrix
</code>```

The idea is to not use 'name' column in the data for the training. When I try to run the built model on test data, it shows the following-

out2 <- predict.glm(m, test, type = "response")

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :

factor name has new levels amc ambassador sst, amc concord dl 6, amc pacer, amc pacer d/l, amc rebel sst, audi 100 ls, audi 5000, buick century 350, buick century limited, cadillac seville, capri ii, chevrolet bel air, chevrolet cavalier, chevrolet cavalier wagon, chevrolet monte carlo, chevrolet vega 2300, chrysler lebaron town @ country (sw), chrysler new yorker brougham, datsun 510 hatchback, datsun b210 gx, datsun f-10 hatchback, dodge aries wagon (sw), dodge aspen 6, dodge colt hardtop, dodge colt m/m, dodge dart custom, dodge magnum xe, dodge rampage, fiat 124 tc, ford mustang, ford mustang ii, ford ranger, honda civic 1500 gl, maxda rx3, mazda 626, mazda glc 4, mazda glc custom, mercedes-benz 240d, mercedes-benz 280s, mercury capri 2000, mercury marquis, oldsmobile cutlass ciera (diesel), peugeot 505s turbo diesel, plymouth 'cuda 340, plymouth fury gran sedan, plymouth grand fury, plymouth horizon, plymouth horizon miser, plymouth horizon tc3, plymouth satellite, plymo

From my understanding, shouldn't this error not show up since we are not using the 'names' attribute? Or if we are somehow using it when it isn't intended to, what is it that I'm doing wrong?

答:
Issue 1 Answer

The sample.split function is expecting a vector for the first argument, it looks like you are either passing a data.frame or a matrix.  Here is a simple example to show the different behavior.

```<code># Mock up some data
library(caTools)
df0 <- data.frame(
     y = as.factor(rbinom(392, 1, 0.75)),
     x1 = rnorm(392)
)

# sample.split with a data.frame as the first argument does not split 80/20 as expected
set.seed(101)
samplev = sample.split(df0, SplitRatio= 0.80)
train = subset(df0, samplev == TRUE)
test = subset(df0, samplev == FALSE)
nrow(train)
[1] 196
nrow(test)
[1] 196

# feed in your response variable as a vector to get the expected split
set.seed(101)
samplev = sample.split(df0$y, SplitRatio= 0.80)
train = subset(df0, samplev == TRUE)
test = subset(df0, samplev == FALSE)
nrow(train)
[1] 314
nrow(test)
[1] 78
</code>```

Issue 2 Answer

While what you are doing seems reasonable and seems like it should work the way you expect, it does not appear to be how the glm and ultimately model.frame functions handles formulas under the hood.

First off, here is come code that will reproduce what you are doing and the error you are seeing.

```<code>set.seed(123)
df <- data.frame(
    y = as.factor(rbinom(100, 1, 0.5)),
    x1 = rnorm(100),
    x2 = rnorm(100),
    name = c(rep('a',40), rep('b',30), rep('c', 30))
)
train <- df[1:70,]
test <- df[71:100,]
m <- glm(y~ . -name, data= train, family = binomial(link = 'logit'))
out2 <- predict.glm(m, test, type = "response")
</code>```

Now notice that when I call model.frame directly with your formula it is still including the name column.

```<code>head(model.frame(y~ . -name, data = train), 1)
  y        x1        x2 name
1 0 0.2533185 0.7877388    a
</code>```

Whereas a formula that does not include the . columns symbol will not include that extra column.

```<code>head(model.frame(y~ x1 + x2, data = train), 1)
  y        x1        x2
1 0 0.2533185 0.7877388
</code>```

At the end of the day, it appears you'll need to workaround this, either by specifying columns directly in the formula or if you use to continue to use the . columns symbol, then by dropping the columns you wish to exclude.

More specifically, with my simple example, workaround 1 would look like.

```<code>m <- glm(y~ x1 + x2, data= train, family = binomial(link = 'logit'))
out2 <- predict.glm(m, test, type = "response")
</code>```

And workaround option 2 would look like.

```<code>m <- glm(y~ ., data= train[,names(train) != 'name'], family = binomial(link = 'logit'))
out2 <- predict.glm(m, test, type = "response")
</code>```

Body:
I have 2 issues.

When I try to split my data into test and train sets, using sample.split as below, the sampling is done rather unclearly. What I mean is that the data d, has a length of 392 and so, 4:1 division should show 0.8*392= 313.6 i.e. 313 or 314 rows in test set, but the shown length is 304. Is there something that I might be missing?

require(caTools)
set.seed(101)
samplev = sample.split(d[,], SplitRatio= 0.80)
train = subset(d, samplev == TRUE)
test = subset(d, samplev == FALSE)

I'm trying to use the split data as follows for a logistic regression task in R, as follows-

#Training
m <- glm(mpg01~ . -name, data= train, family = binomial(link = 'logit'))
out2 <- predict.glm(m, test, type = "response")
class2 <- vector()
for (i in 1:length(out2))
{
  if(out2[i] >= 0.5)
  {
    class2[i] <- 1
  }
  else
  {
    class2[i] <- 0
  }
}
r2 <- table(class2, test$mpg01)  #confusion Matrix

The idea is to not use 'name' column in the data for the training. When I try to run the built model on test data, it shows the following-

out2 <- predict.glm(m, test, type = "response")

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :

factor name has new levels amc ambassador sst, amc concord dl 6, amc pacer, amc pacer d/l, amc rebel sst, audi 100 ls, audi 5000, buick century 350, buick century limited, cadillac seville, capri ii, chevrolet bel air, chevrolet cavalier, chevrolet cavalier wagon, chevrolet monte carlo, chevrolet vega 2300, chrysler lebaron town @ country (sw), chrysler new yorker brougham, datsun 510 hatchback, datsun b210 gx, datsun f-10 hatchback, dodge aries wagon (sw), dodge aspen 6, dodge colt hardtop, dodge colt m/m, dodge dart custom, dodge magnum xe, dodge rampage, fiat 124 tc, ford mustang, ford mustang ii, ford ranger, honda civic 1500 gl, maxda rx3, mazda 626, mazda glc 4, mazda glc custom, mercedes-benz 240d, mercedes-benz 280s, mercury capri 2000, mercury marquis, oldsmobile cutlass ciera (diesel), peugeot 505s turbo diesel, plymouth 'cuda 340, plymouth fury gran sedan, plymouth grand fury, plymouth horizon, plymouth horizon miser, plymouth horizon tc3, plymouth satellite, plymo

From my understanding, shouldn't this error not show up since we are not using the 'names' attribute? Or if we are somehow using it when it isn't intended to, what is it that I'm doing wrong?

Body:
Issue 1 Answer

The sample.split function is expecting a vector for the first argument, it looks like you are either passing a data.frame or a matrix.  Here is a simple example to show the different behavior.

# Mock up some data
library(caTools)
df0 <- data.frame(
     y = as.factor(rbinom(392, 1, 0.75)),
     x1 = rnorm(392)
)

# sample.split with a data.frame as the first argument does not split 80/20 as expected
set.seed(101)
samplev = sample.split(df0, SplitRatio= 0.80)
train = subset(df0, samplev == TRUE)
test = subset(df0, samplev == FALSE)
nrow(train)
[1] 196
nrow(test)
[1] 196

# feed in your response variable as a vector to get the expected split
set.seed(101)
samplev = sample.split(df0$y, SplitRatio= 0.80)
train = subset(df0, samplev == TRUE)
test = subset(df0, samplev == FALSE)
nrow(train)
[1] 314
nrow(test)
[1] 78

Issue 2 Answer

While what you are doing seems reasonable and seems like it should work the way you expect, it does not appear to be how the glm and ultimately model.frame functions handles formulas under the hood.

First off, here is come code that will reproduce what you are doing and the error you are seeing.

set.seed(123)
df <- data.frame(
    y = as.factor(rbinom(100, 1, 0.5)),
    x1 = rnorm(100),
    x2 = rnorm(100),
    name = c(rep('a',40), rep('b',30), rep('c', 30))
)
train <- df[1:70,]
test <- df[71:100,]
m <- glm(y~ . -name, data= train, family = binomial(link = 'logit'))
out2 <- predict.glm(m, test, type = "response")

Now notice that when I call model.frame directly with your formula it is still including the name column.

head(model.frame(y~ . -name, data = train), 1)
  y        x1        x2 name
1 0 0.2533185 0.7877388    a

Whereas a formula that does not include the . columns symbol will not include that extra column.

head(model.frame(y~ x1 + x2, data = train), 1)
  y        x1        x2
1 0 0.2533185 0.7877388

At the end of the day, it appears you'll need to workaround this, either by specifying columns directly in the formula or if you use to continue to use the . columns symbol, then by dropping the columns you wish to exclude.

More specifically, with my simple example, workaround 1 would look like.

m <- glm(y~ x1 + x2, data= train, family = binomial(link = 'logit'))
out2 <- predict.glm(m, test, type = "response")

And workaround option 2 would look like.

m <- glm(y~ ., data= train[,names(train) != 'name'], family = binomial(link = 'logit'))
out2 <- predict.glm(m, test, type = "response")


问:
php Laravel- A non well formed numeric value encountered (on string)
I have two function in my controller and service. I want to call a function in service. Here is my code :

Controller:

```<code>public function findNeighborhoodGet(): array
{
    $regionCenter = Request::get('region_center');
    $distanceService = \App::make('App\web\one\Infrastructure\Service\Google\Map');
    try {
        $userPoint = $distanceService->getOriginPoint($regionCenter);
    }
 .
 .
 .
 return $result
}
</code>```

my service (Map.php) :

```<code>public function getOriginPoint(string $origin):Point
{
    dd($origin);

    return $this->getPointObject($origin);
}
</code>```

Actually , I get an error :

```<code>A non well formed numeric value encountered
</code>```

at this line:
public function getOriginPoint(string $origin):Point

How to solve it?

答:
I had the same issue on Laravel 5.2 PHP 7.1. If you don't want to update the entire framework, you can do:

```<code>composer update symfony/var-dumper
</code>```

as stated here.

Body:
I have two function in my controller and service. I want to call a function in service. Here is my code :

Controller:

public function findNeighborhoodGet(): array
{
    $regionCenter = Request::get('region_center');
    $distanceService = \App::make('App\web\one\Infrastructure\Service\Google\Map');
    try {
        $userPoint = $distanceService->getOriginPoint($regionCenter);
    }
 .
 .
 .
 return $result
}

my service (Map.php) :

public function getOriginPoint(string $origin):Point
{
    dd($origin);

    return $this->getPointObject($origin);
}

Actually , I get an error :

A non well formed numeric value encountered

at this line:
public function getOriginPoint(string $origin):Point

How to solve it?

Body:
I had the same issue on Laravel 5.2 PHP 7.1. If you don't want to update the entire framework, you can do:

composer update symfony/var-dumper

as stated here.


问:
grep multiple files get count of unique cut
I think I'm close on this, and saw similar questions but couldn't get it to work as I want. So, I have several log files and I would like to count the occurrences of several different service calls by date.

First I tried the below, the cut is just to get the first element (date) and 11th element (name of service call), which is specific to my log file:

```<code>grep -E "invoking webservice" *.log* | cut -d ' ' -f1  -f11 | sort | uniq -c
</code>```

But this returned something that looks like:

```<code>5 log_1.log:2017-12-05 getLegs()
10 log_1.log:2017-12-05 getArms()
7 log_2.log:2017-12-05 getLegs()
13 log_2.log:2017-12-04 getLegs()
</code>```

What I really want is:

```<code>12 2017-12-05 getLegs()
10 2017-12-05 getArms()
13 2017-12-04 getLegs()
</code>```

I've seen examples where they cat * first, but looks like the same problem.

```<code>cat * | grep -E "invoking webservice" *.log* | cut -d ' ' -f1  -f11 | sort | uniq -c
</code>```

What am I doing wrong? As always, thanks a lot!

答:
Your issue seems to be that grep prefixes the matched lines with the filenames. (grep has this behavior when multiple filenames are specified, to disambiguate the results.) You can pass the -h to grep to not print the filenames:

```<code>grep -h "invoking webservice" *.log | cut -d ' ' -f1  -f11 | sort | uniq -c
</code>```

Note that I dropped the -E flag, because it is used to enable extended regex support, and your example doesn't need it.

Alternatively, you could use cat to dump the content of files to standard output, and pipe that to grep. That would work, because it removes the need for filename parameters for grep:

```<code>cat *.log | grep "invoking webservice" | cut -d ' ' -f1  -f11 | sort | uniq -c
</code>```

Body:
I think I'm close on this, and saw similar questions but couldn't get it to work as I want. So, I have several log files and I would like to count the occurrences of several different service calls by date.

First I tried the below, the cut is just to get the first element (date) and 11th element (name of service call), which is specific to my log file:

grep -E "invoking webservice" *.log* | cut -d ' ' -f1  -f11 | sort | uniq -c

But this returned something that looks like:

5 log_1.log:2017-12-05 getLegs()
10 log_1.log:2017-12-05 getArms()
7 log_2.log:2017-12-05 getLegs()
13 log_2.log:2017-12-04 getLegs()

What I really want is:

12 2017-12-05 getLegs()
10 2017-12-05 getArms()
13 2017-12-04 getLegs()

I've seen examples where they cat * first, but looks like the same problem.

cat * | grep -E "invoking webservice" *.log* | cut -d ' ' -f1  -f11 | sort | uniq -c

What am I doing wrong? As always, thanks a lot!

Body:
Your issue seems to be that grep prefixes the matched lines with the filenames. (grep has this behavior when multiple filenames are specified, to disambiguate the results.) You can pass the -h to grep to not print the filenames:

grep -h "invoking webservice" *.log | cut -d ' ' -f1  -f11 | sort | uniq -c

Note that I dropped the -E flag, because it is used to enable extended regex support, and your example doesn't need it.

Alternatively, you could use cat to dump the content of files to standard output, and pipe that to grep. That would work, because it removes the need for filename parameters for grep:

cat *.log | grep "invoking webservice" | cut -d ' ' -f1  -f11 | sort | uniq -c


问:
Number which occurs only once in the array

Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

```<code>a[1..n] = [1,2,3,4,3,1,2]
</code>```

should return 4

答:
Let the number which occurs only once in the array be x

```<code>x <- a[1]
for i <- 2 to n
   x <- x ^ a[i]
return x
</code>```

Since a ^ a = 0 and a ^ 0 = a

Numbers which occur in pair cancel out and the result gets stored in x

Working code in C++

```<code>#include <iostream>

template<typename T, size_t N>
size_t size(T(&a)[N])
{
    return N;
}
int main()
{
   int a [] = {1,2,3,4,3,1,2};
   int x = a[0];
   for (size_t i = 1; i< size(a) ; ++i)
   {
      x = x ^ a[i];
   }
   std::cout << x;
}
</code>```

Body:
Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

a[1..n] = [1,2,3,4,3,1,2]

should return 4

Body:
Let the number which occurs only once in the array be x

x <- a[1]
for i <- 2 to n
   x <- x ^ a[i]
return x

Since a ^ a = 0 and a ^ 0 = a

Numbers which occur in pair cancel out and the result gets stored in x

Working code in C++

#include <iostream>

template<typename T, size_t N>
size_t size(T(&a)[N])
{
    return N;
}
int main()
{
   int a [] = {1,2,3,4,3,1,2};
   int x = a[0];
   for (size_t i = 1; i< size(a) ; ++i)
   {
      x = x ^ a[i];
   }
   std::cout << x;
}


问:
Appending a value from a list to an empty list in python
One list contains values and one is empty. I want to take out two values from the list with data and place it into the empty list using a for loop. I know how to get one value. However, I am not sure how to get the other. Here is my code below:

```<code> all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach']
# The above list is a list of all fruits

# Now lets creat a blank list called favorite fruit
favorite_fruit = []

# The objective is to choose two fruits from the all fruits list and append them to the favorite fruit list

for fruit in all_fruits:
    if fruit == 'apples':
        favorite_fruit.append(fruit)

print favorite_fruit

Output: ['apples']
</code>```

I want the favorite_fruit variable to output ['apples', 'peaches'] or ['apples', 'cherry']. How do I go about doing this? Thanks

答:
You can do this without loop and in one line:

```<code>all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach']

print(list(filter(lambda x:x=='apples' or x=='peach',all_fruits)))
</code>```

output:

```<code>['apples', 'peach']
</code>```

Body:
One list contains values and one is empty. I want to take out two values from the list with data and place it into the empty list using a for loop. I know how to get one value. However, I am not sure how to get the other. Here is my code below:

 all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach']
# The above list is a list of all fruits

# Now lets creat a blank list called favorite fruit
favorite_fruit = []

# The objective is to choose two fruits from the all fruits list and append them to the favorite fruit list

for fruit in all_fruits:
    if fruit == 'apples':
        favorite_fruit.append(fruit)

print favorite_fruit

Output: ['apples']

I want the favorite_fruit variable to output ['apples', 'peaches'] or ['apples', 'cherry']. How do I go about doing this? Thanks

Body:
You can do this without loop and in one line:

all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach']

print(list(filter(lambda x:x=='apples' or x=='peach',all_fruits)))

output:

['apples', 'peach']


答:
You need to create different buttons variables names and ids

For Example

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    mActivity = this;

    btnClick1 = (Button) findViewById(R.id.button1);
    btnClick2 = (Button) findViewById(R.id.button2);
    btnClick3 = (Button) findViewById(R.id.button3);
    btnClick4 = (Button) findViewById(R.id.button4);
    txtBox1 = (EditText) findViewById(editText9);
    txtBox2 = (EditText) findViewById(editText10);

    btnClick1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input1 = txtBox1.getText().toString();
                byte[] bytes = input1.getBytes();
                final StringBuilder binary = new StringBuilder();
                for (byte b : bytes) {
                    int val = b;
                    for (int i = 0; i < 8; i++) {
                        binary.append((val & 128) == 0 ? 0 : 1);
                        val <<= 1;
                    }
                    binary.append(' ');
                    txtBox2.setText(binary);
                }
            }
        });
        btnClick2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboard = (ClipboardManager)
                        getSystemService(Context.CLIPBOARD_SERVICE);
                String text = txtBox2.getText().toString();
                ClipData clip = ClipData.newPlainText("text", text);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getApplicationContext(), "Text Copied",
                        Toast.LENGTH_SHORT).show();

            }
        });
        btnClick3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtBox2.setText("");
                txtBox1.setText("");
            }
        });
        btnClick4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtBox2.setText("");
                String s = new String(binary);
                txtBox1.setText(s);
            }
        });
}
</code>```

Check this

Title: onclick method does not exist error?

Body:
this is the description of the error

There should be no spaces in the onClick handler name  The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View.  Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.

btnClick = (Button) findViewById(R.id.button2);
txtBox1 = (EditText) findViewById(editText9);
txtBox2 = (EditText) findViewById(editText10);

btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }

btnClick = (Button) findViewById(R.id.button3);

        btnClick.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                    ClipboardManager clipboard = (ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
                String text = txtBox2.getText().toString();
                ClipData clip = ClipData.newPlainText("text", text);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getApplicationContext(), "Text Copied",
                        Toast.LENGTH_SHORT).show();

            }

        });

        txtBox2 = (EditText) findViewById(editText10);
        txtBox1 = (EditText) findViewById(editText9);
        btnClick = (Button) findViewById(R.id.button5);

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                txtBox1.setText("");
            }
        });

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                String s = new String(binary);
                txtBox1.setText(s);
            }
        });

Body:
You need to create different buttons variables names and ids

For Example

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    mActivity = this;

    btnClick1 = (Button) findViewById(R.id.button1);
    btnClick2 = (Button) findViewById(R.id.button2);
    btnClick3 = (Button) findViewById(R.id.button3);
    btnClick4 = (Button) findViewById(R.id.button4);
    txtBox1 = (EditText) findViewById(editText9);
    txtBox2 = (EditText) findViewById(editText10);

    btnClick1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input1 = txtBox1.getText().toString();
                byte[] bytes = input1.getBytes();
                final StringBuilder binary = new StringBuilder();
                for (byte b : bytes) {
                    int val = b;
                    for (int i = 0; i < 8; i++) {
                        binary.append((val & 128) == 0 ? 0 : 1);
                        val <<= 1;
                    }
                    binary.append(' ');
                    txtBox2.setText(binary);
                }
            }
        });
        btnClick2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboard = (ClipboardManager)
                        getSystemService(Context.CLIPBOARD_SERVICE);
                String text = txtBox2.getText().toString();
                ClipData clip = ClipData.newPlainText("text", text);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getApplicationContext(), "Text Copied",
                        Toast.LENGTH_SHORT).show();

            }
        });
        btnClick3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtBox2.setText("");
                txtBox1.setText("");
            }
        });
        btnClick4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtBox2.setText("");
                String s = new String(binary);
                txtBox1.setText(s);
            }
        });
}

Check this


问:
How to convert JSON to String in ios Swift?
Here is the code for the below Json output:

```<code>let params : [[String : AnyObject]]  = [["name" : "action", "value" : "pay" ],["name" : "cartJsonData" , "value" : ["total": 1,"rows":[["quantity": “1” ,"title":"Donation for SMSF India - General Fund","price":"1","itemId":"DN001","cost": “1”,”currency":"INR"]]]], ["name" : "center", "value" : "Chennai"], ["name" : "flatNumber", "value" : "503"], ["name" : "panNumber", "value" : ""], ["name" : "payWith"], ["name" : "reminderFrequency","value" : "Monthly"],  ["name" : "shipToAddr1"], ["name" : "shipToAddr2"], ["name" : "shipToCity"], ["name" : "shipToCountryName" , "value" : "India"], ["name" : "shipToEmail", "value" : “01034_186893@gmail.com"], ["name" : "shipToFirstName" , "value": "4480101010"], ["name" : "shipToLastName"], ["name" : "shipToPhone", "value" : "4480101010"], ["name" : "shipToState"], ["name" : "shipToZip"], ["name" : "userId", "value" : “null”], ["name" : "shipToCountry", "value" : "IN"]]

var jsonObject: NSData? = nil

do {
   jsonObject = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
   print(jsonObject) // This will print the below json.
}
catch{}
</code>```

By printing jsonObject, I got this one.

[{ "value": "pay", "name": "action" }, { "value": { "rows": [{
  "price": "1", "quantity": "1", "cost": "1", "currency": "INR",
  "itemId": "DN001", "title": "Donation for SMSF India - General Fund"
  }], "total": 1 }, "name": "cartJsonData" }, { "value": "Chennai",
  "name": "center" }, { "value": "503", "name": "flatNumber" }, {
  "value": "", "name": "panNumber" }, { "name": "payWith" }, { "value":
  "Monthly", "name": "reminderFrequency" }, { "name": "shipToAddr1" }, {
  "name": "shipToAddr2" }, { "name": "shipToCity" }, { "value": "India",
  "name": "shipToCountryName" }, { "value": "01034_186893@gmail.com",
  "name": "shipToEmail" }, { "value": "4480101010", "name":
  "shipToFirstName" }, { "name": "shipToLastName" }, { "value":
  "4480101010", "name": "shipToPhone" }, { "name": "shipToState" }, {
  "name": "shipToZip" }, { "value": "null", "name": "userId" }, {
  "value": "IN", "name": "shipToCountry" }]

And I want the JSON to be in the below format.

[{ “name”: “action”, “value”: “pay” }, { “name”: “cartJsonData”,
  “value”:
  “{\”total\”:1,\”rows\”:[{\”itemId\”:\”DN002\”,\”title\”:\”Donation for
  SMSF India - General
  Fund\”,\”quantity\”:\”100\”,\”currency\”:\”INR\”,\”price\”:\”1\”,\”cost\”:\”100\”}]}”
  }, { “name”: “center”, “value”: “Chennai” }, { “name”: “flatNumber”,
  “value”: “ “ }, { “name”: “panNumber”, “value”: “ASSDDBBDJD” }, {
  “name”: “payWith” }, { “name”: “reminderFrequency”, “value”: “Monthly”
  }, { “name”: “shipToAddr1” }, { “name”: “shipToAddr2” }, { “name”:
  “shipToCity” }, { “name”: “shipToCountryName”, “value”: “India” }, {
  “name”: “shipToEmail”, “value”: “Sudhakar@gmail.com” }, { “name”:
  “shipToFirstName”, “value”: “Raju” }, { “name”: “shipToLastName” }, {
  “name”: “shipToPhone”, “value”: “1234567890” }, { “name”:
  “shipToState” }, { “name”: “shipToZip” }, { “name”: “userId”, “value”:
  “null” }, { “name”: “shipToCountry”, “value”: “IN” }]

How can it be done? Only the value in cartJsonData needs to be changed. Can someone help me on this to solve it?

答:
Swift 4.0

```<code>static func stringify(json: Any, prettyPrinted: Bool = false) -> String {
    var options: JSONSerialization.WritingOptions = []
    if prettyPrinted {
      options = JSONSerialization.WritingOptions.prettyPrinted
    }

    do {
      let data = try JSONSerialization.data(withJSONObject: json, options: options)
      if let string = String(data: data, encoding: String.Encoding.utf8) {
        return string
      }
    } catch {
      print(error)
    }

    return ""
}
</code>```

Usage

```<code>stringify(json: ["message": "Hello."])
</code>```

Body:
Here is the code for the below Json output:

let params : [[String : AnyObject]]  = [["name" : "action", "value" : "pay" ],["name" : "cartJsonData" , "value" : ["total": 1,"rows":[["quantity": “1” ,"title":"Donation for SMSF India - General Fund","price":"1","itemId":"DN001","cost": “1”,”currency":"INR"]]]], ["name" : "center", "value" : "Chennai"], ["name" : "flatNumber", "value" : "503"], ["name" : "panNumber", "value" : ""], ["name" : "payWith"], ["name" : "reminderFrequency","value" : "Monthly"],  ["name" : "shipToAddr1"], ["name" : "shipToAddr2"], ["name" : "shipToCity"], ["name" : "shipToCountryName" , "value" : "India"], ["name" : "shipToEmail", "value" : “01034_186893@gmail.com"], ["name" : "shipToFirstName" , "value": "4480101010"], ["name" : "shipToLastName"], ["name" : "shipToPhone", "value" : "4480101010"], ["name" : "shipToState"], ["name" : "shipToZip"], ["name" : "userId", "value" : “null”], ["name" : "shipToCountry", "value" : "IN"]]

var jsonObject: NSData? = nil

do {
   jsonObject = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
   print(jsonObject) // This will print the below json.
}
catch{}

By printing jsonObject, I got this one.

[{ "value": "pay", "name": "action" }, { "value": { "rows": [{
  "price": "1", "quantity": "1", "cost": "1", "currency": "INR",
  "itemId": "DN001", "title": "Donation for SMSF India - General Fund"
  }], "total": 1 }, "name": "cartJsonData" }, { "value": "Chennai",
  "name": "center" }, { "value": "503", "name": "flatNumber" }, {
  "value": "", "name": "panNumber" }, { "name": "payWith" }, { "value":
  "Monthly", "name": "reminderFrequency" }, { "name": "shipToAddr1" }, {
  "name": "shipToAddr2" }, { "name": "shipToCity" }, { "value": "India",
  "name": "shipToCountryName" }, { "value": "01034_186893@gmail.com",
  "name": "shipToEmail" }, { "value": "4480101010", "name":
  "shipToFirstName" }, { "name": "shipToLastName" }, { "value":
  "4480101010", "name": "shipToPhone" }, { "name": "shipToState" }, {
  "name": "shipToZip" }, { "value": "null", "name": "userId" }, {
  "value": "IN", "name": "shipToCountry" }]

And I want the JSON to be in the below format.

[{ “name”: “action”, “value”: “pay” }, { “name”: “cartJsonData”,
  “value”:
  “{\”total\”:1,\”rows\”:[{\”itemId\”:\”DN002\”,\”title\”:\”Donation for
  SMSF India - General
  Fund\”,\”quantity\”:\”100\”,\”currency\”:\”INR\”,\”price\”:\”1\”,\”cost\”:\”100\”}]}”
  }, { “name”: “center”, “value”: “Chennai” }, { “name”: “flatNumber”,
  “value”: “ “ }, { “name”: “panNumber”, “value”: “ASSDDBBDJD” }, {
  “name”: “payWith” }, { “name”: “reminderFrequency”, “value”: “Monthly”
  }, { “name”: “shipToAddr1” }, { “name”: “shipToAddr2” }, { “name”:
  “shipToCity” }, { “name”: “shipToCountryName”, “value”: “India” }, {
  “name”: “shipToEmail”, “value”: “Sudhakar@gmail.com” }, { “name”:
  “shipToFirstName”, “value”: “Raju” }, { “name”: “shipToLastName” }, {
  “name”: “shipToPhone”, “value”: “1234567890” }, { “name”:
  “shipToState” }, { “name”: “shipToZip” }, { “name”: “userId”, “value”:
  “null” }, { “name”: “shipToCountry”, “value”: “IN” }]

How can it be done? Only the value in cartJsonData needs to be changed. Can someone help me on this to solve it?

Body:
Swift 4.0

static func stringify(json: Any, prettyPrinted: Bool = false) -> String {
    var options: JSONSerialization.WritingOptions = []
    if prettyPrinted {
      options = JSONSerialization.WritingOptions.prettyPrinted
    }

    do {
      let data = try JSONSerialization.data(withJSONObject: json, options: options)
      if let string = String(data: data, encoding: String.Encoding.utf8) {
        return string
      }
    } catch {
      print(error)
    }

    return ""
}

Usage

stringify(json: ["message": "Hello."])


问:
PHP - Display Serial Numbers automatically using for loop
```<code><thead>
    <tr>
       <th> S.No </th>
       <th> Movie Name </th>
       <th> Language </th>
    </tr>
</thead>
   <?php

        $result = mysqli_query($connect,"SELECT * FROM movies ;")or die(mysqli_error());
        $rows = mysqli_fetch_array($result);
        ?>
        <tbody>

        <?php
        $counter=0;
        foreach($result as $rows)
        {
        $counter=$counter+1;
        ?>
        <?php     echo "<tr><td>" . $counter . "</td><td>" . $rows['language'] . "</td><td>" . $rows['movie_name'] . "</td></tr>"; ?>
    <?php  } ?>
         </tbody>
</code>```

I want to display serial numbers in the table automatically for the fetched results . Here the serial number displays correctly for the first five results like 1,2,3,4,5 rows
but on the 2nd page the number shows like 8,9,10,6,7

Where i am making mistake ? I even tried while loop and forloop increment counter. Im using Bootstrap data table to display the results from database.

答:
Try this

You have to declare the $i=1 outside of the while loop and $i++ inside the while loop. So it will display the number of rows available in the database.
You have to use while loop instated of foreach.

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM movies";
$result = mysqli_query($conn, $sql);

//mysqli_close($conn);
?>

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<table>
<thead>
    <tr>
       <th> S.No </th>
       <th> Movie Name </th>
       <th> Language </th>
    </tr>
</thead>
        <tbody>
      <?php
      $i=1;
      if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($rows = mysqli_fetch_assoc($result)) {
            echo "<tr>
                  <td>" . $i . "</td>
                  <td>" . $rows['language'] . "</td>
                  <td>" . $rows['movie_name'] . "</td>
                 </tr>";
            $i++;
        }
    } else {
        echo "0 results";
    }
?>

         </tbody>
</table>
</body>
</html>
</code>```

Body:
        S.No
        Movie Name
        Language

   <?php

        $result = mysqli_query($connect,"SELECT * FROM movies ;")or die(mysqli_error());
        $rows = mysqli_fetch_array($result);
        ?>

        <?php
        $counter=0;
        foreach($result as $rows)
        {
        $counter=$counter+1;
        ?>
        <?php     echo "
" . $counter . "	" . $rows['language'] . "	" . $rows['movie_name'] . "
"; ?>
    <?php  } ?>

I want to display serial numbers in the table automatically for the fetched results . Here the serial number displays correctly for the first five results like 1,2,3,4,5 rows
but on the 2nd page the number shows like 8,9,10,6,7

Where i am making mistake ? I even tried while loop and forloop increment counter. Im using Bootstrap data table to display the results from database.

Body:
Try this

You have to declare the $i=1 outside of the while loop and $i++ inside the while loop. So it will display the number of rows available in the database.
You have to use while loop instated of foreach.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM movies";
$result = mysqli_query($conn, $sql);

//mysqli_close($conn);
?>

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<table>
<thead>
    <tr>
       <th> S.No </th>
       <th> Movie Name </th>
       <th> Language </th>
    </tr>
</thead>
        <tbody>
      <?php
      $i=1;
      if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($rows = mysqli_fetch_assoc($result)) {
            echo "<tr>
                  <td>" . $i . "</td>
                  <td>" . $rows['language'] . "</td>
                  <td>" . $rows['movie_name'] . "</td>
                 </tr>";
            $i++;
        }
    } else {
        echo "0 results";
    }
?>

         </tbody>
</table>
</body>
</html>


问:
DOM manipulation - Center H1 element using javascript
How can I center my h1 using javascript?

h1 is
Instrument track Recommendations
, I tried below and it does not work.

```<code>var centeredH1 = document.getElementsByTagName("h1");
centeredH1.style.textAlign = "center";`
</code>```

I know it would work with an ID using document.getElementById("h1id"); if I had one but I don't have an ID to work with.

答:
getElementsByTagName returns an array-like object. If you have only one element, it will return an array-like object with one element. You need to get the [0] indexed element in that object. But as you have mentioned, it will be better to work with id in this case, if you want to attach styles only to one element.

var centeredH1 = document.getElementsByTagName("h1")[0];
// -------------------------------------------------^^^
centeredH1.style.textAlign = "center";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Test</h1></code>```

Body:
How can I center my h1 using javascript?

h1 is
Instrument track Recommendations
, I tried below and it does not work.

var centeredH1 = document.getElementsByTagName("h1");
centeredH1.style.textAlign = "center";`

I know it would work with an ID using document.getElementById("h1id"); if I had one but I don't have an ID to work with.

Body:
getElementsByTagName returns an array-like object. If you have only one element, it will return an array-like object with one element. You need to get the [0] indexed element in that object. But as you have mentioned, it will be better to work with id in this case, if you want to attach styles only to one element.

var centeredH1 = document.getElementsByTagName("h1")[0];
// -------------------------------------------------^^^
centeredH1.style.textAlign = "center";

<h1>Test</h1>


问:
Intersection of two large word lists
I have two word lists (180k and 260k), and I would like to generate a third file which is the set of words that appear in BOTH lists.

What is the best (most efficient) way of doing this? I've read forums talking about using grep, however I think the word lists are too big for this method.

答:
grep -P '[ A-Za-z0-9]*' file1 | xargs -0 -I {} grep {} file2 > file3

I believe this looks for anything in file1, then checks if what was in file1 is in file2, and puts anything that matches into file3.

Title: Intersection of two large word lists


问:
Google Progressive App (PWA) Can we use IONIC?
I want to build one Google Progressive App (PWA).

Can anyone suggest me that can I use IONIC 3/angular 4 for Google Progressive App?

Or I have to use Polymer?
Thanks

答:
You can easily develop PWA apps using Ionic 3 /Angular. The ionic framework has that feature out of the box. But if you need to develop Google Progressive web Apps then you need to use vanilla javascript. You cannot mix those 2 each other.

You can see how to develop PWA using Ionic 3 /Angular using below links.

What Progressive Web Apps can do for you

How to make PWAs with Ionic