问:
Show/Hide input field inside appended element
I have the following JS/jQuery code to append rows to an existing table. Upon appending, I want to show the input field only when "select" or "radio" is selected as the option type.

When I add multiple rows, the input field appearance/disappearance is dependent upon the first added row. I want it to show/hide only on the row(s) where any of the two options are selected.

Hope that made sense. Any suggestion would be helpful. Thanks!

HTML:

```<code><table id="tbl-formfields" class="table vertical-align table-condensed" >
    <thead>
        <tr>
            <th>Input Type</th>
            <th>Make Required</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody id="tbody">
        <tr id="tr-formField">
            <td>
                <div>
                    <select name="formOptionType[]" id="formOptionType">
                        <option value="">-------------------------------------</option>
                        <option value="text">Text</option>
                        <option value="textarea">Textarea</option>
                        <option value="select">Select Options (Dropdown)</option>
                        <option value="radio">Radio Buttons</option>
                        <option value="checkbox">Checkbox</option>
                    </select>
                </div>
                <div id="block-optionsInput" style="display:none">
                    <label>Options:</label><br>
                    <input id="options" type="text" name="fieldOptions[]" data-role="tagsinput"/>
                </div>
            </td>
            <td>
                <label><input type="checkbox" name="fieldRequired[]"/> Required</label>
            </td>
            <td></td>
        </tr>
    </tbody>
</table>
</code>```

jQuery:

```<code>    //****Repeat form field block****
    var repeatBlock = "#tbody";
    var repeatText = '<tr class="trRepeat">\n\
        <td>\n\
            <select class="optType" name="formOptionType[]">\n\
                <option value="">-------------------------------------</option>\n\
                <option value="text">Text</option>\n\
                <option value="textarea">Textarea</option>\n\
                <option value="select">Select Options (Dropdown)</option>\n\
                <option value="radio">Radio Buttons</option>\n\
                <option value="checkbox">Checkbox</option>\n\
            </select>\n\
            <div class="optBlock" style="display:none">\n\
                <label>Options:</label><br>\n\
                <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput"/>\n\
            </div>\n\
        </td>\n\
        <td><label><input type="checkbox" name="fieldRequired[]"/> Required</label></td>\n\
        <td><a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">\n\
            <span class="glyphicon glyphicon-remove"></span></a>\n\
        </td></tr>';

    $("#btn-addfield").click(function (e) {
        e.preventDefault();
        $(repeatBlock).append(repeatText);
    });
    $(repeatBlock).on('click', '.removeField', function (e) {
        e.preventDefault();
        $(this).parent().parent().remove();
    });

    //****Show input field when dropdown/radio is selected****
    $(repeatBlock).on('change', $(".optType").val(), function (e) {
        e.preventDefault();
        if ($(this).find(".optType").val() === "radio" || $(this).find(".optType").val() === "select") {
            $(this).find(".optBlock").show();
            $(".optInput").tagsinput('refresh');
        } else {
            $(this).find(".optBlock").hide();
        }
    });
</code>```

答:
You are passing $(".optType").val() instead of selector, In the event handler test the selected value and use DOM relationship to traverse and target desired element.

```<code>$(repeatBlock).on('change', '.optType', function (e) {
    e.preventDefault();
    var val = $(this).val()
    if (val === "radio" || val === "select") {
        $(this).closest('tr').find(".optBlock").show();
        $(this).closest('tr').find(".optBlock").find(".optInput").tagsinput('refresh');
    } else {
        $(this).closest('tr').find(".optBlock").hide();
    }
});
</code>```

//****Repeat form field block****
var repeatBlock = "#tbody";
var repeatText = '
\n\
        \n\
            <select class="optType" name="formOptionType[]">\n\
                <option value="">-------------------------------------</option>\n\
                <option value="text">Text</option>\n\
                <option value="textarea">Textarea</option>\n\
                <option value="select">Select Options (Dropdown)</option>\n\
                <option value="radio">Radio Buttons</option>\n\
                <option value="checkbox">Checkbox</option>\n\
            </select>\n\

\n\
                Options:
\n\
                <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput"/>\n\

\n\
        	\n\
        <input type="checkbox" name="fieldRequired[]"/> Required	\n\
        \n\
            \n\

';

$("#btn-addfield").click(function(e) {
  e.preventDefault();
  $(repeatBlock).append(repeatText);
});
$(repeatBlock).on('click', '.removeField', function(e) {
  e.preventDefault();
  $(this).parent().parent().remove();
});

$(repeatBlock).on('change', '.optType', function(e) {
  e.preventDefault();
  var val = $(this).val()
  if (val === "radio" || val === "select") {
    $(this).closest('tr').find(".optBlock").show();
   //$(this).closest('tr').find(".optBlock").find(".optInput").tagsinput('refresh');
  } else {
    $(this).closest('tr').find(".optBlock").hide();
  }
});```
<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>
<button id="btn-addfield">Addfield</button>
<table>
  <tbody id="tbody"></tbody>
</table></code>```

Body:
I have the following JS/jQuery code to append rows to an existing table. Upon appending, I want to show the input field only when "select" or "radio" is selected as the option type.

When I add multiple rows, the input field appearance/disappearance is dependent upon the first added row. I want it to show/hide only on the row(s) where any of the two options are selected.

Hope that made sense. Any suggestion would be helpful. Thanks!

HTML:

            Input Type
            Make Required
            Action

                    <select name="formOptionType[]" id="formOptionType">
                        <option value="">-------------------------------------</option>
                        <option value="text">Text</option>
                        <option value="textarea">Textarea</option>
                        <option value="select">Select Options (Dropdown)</option>
                        <option value="radio">Radio Buttons</option>
                        <option value="checkbox">Checkbox</option>
                    </select>

                    Options:

                    <input id="options" type="text" name="fieldOptions[]" data-role="tagsinput"/>

                <input type="checkbox" name="fieldRequired[]"/> Required

jQuery:

    //****Repeat form field block****
    var repeatBlock = "#tbody";
    var repeatText = '
\n\
        \n\
            <select class="optType" name="formOptionType[]">\n\
                <option value="">-------------------------------------</option>\n\
                <option value="text">Text</option>\n\
                <option value="textarea">Textarea</option>\n\
                <option value="select">Select Options (Dropdown)</option>\n\
                <option value="radio">Radio Buttons</option>\n\
                <option value="checkbox">Checkbox</option>\n\
            </select>\n\

\n\
                Options:
\n\
                <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput"/>\n\

\n\
        	\n\
        <input type="checkbox" name="fieldRequired[]"/> Required	\n\
        \n\
            \n\

';

    $("#btn-addfield").click(function (e) {
        e.preventDefault();
        $(repeatBlock).append(repeatText);
    });
    $(repeatBlock).on('click', '.removeField', function (e) {
        e.preventDefault();
        $(this).parent().parent().remove();
    });

    //****Show input field when dropdown/radio is selected****
    $(repeatBlock).on('change', $(".optType").val(), function (e) {
        e.preventDefault();
        if ($(this).find(".optType").val() === "radio" || $(this).find(".optType").val() === "select") {
            $(this).find(".optBlock").show();
            $(".optInput").tagsinput('refresh');
        } else {
            $(this).find(".optBlock").hide();
        }
    });

Body:
You are passing $(".optType").val() instead of selector, In the event handler test the selected value and use DOM relationship to traverse and target desired element.

$(repeatBlock).on('change', '.optType', function (e) {
    e.preventDefault();
    var val = $(this).val()
    if (val === "radio" || val === "select") {
        $(this).closest('tr').find(".optBlock").show();
        $(this).closest('tr').find(".optBlock").find(".optInput").tagsinput('refresh');
    } else {
        $(this).closest('tr').find(".optBlock").hide();
    }
});

//****Repeat form field block****
var repeatBlock = "#tbody";
var repeatText = '<tr class="trRepeat">\n\
        <td>\n\
            <select class="optType" name="formOptionType[]">\n\
                <option value="">-------------------------------------</option>\n\
                <option value="text">Text</option>\n\
                <option value="textarea">Textarea</option>\n\
                <option value="select">Select Options (Dropdown)</option>\n\
                <option value="radio">Radio Buttons</option>\n\
                <option value="checkbox">Checkbox</option>\n\
            </select>\n\
            <div class="optBlock" style="display:none">\n\
                <label>Options:</label><br>\n\
                <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput"/>\n\
            </div>\n\
        </td>\n\
        <td><label><input type="checkbox" name="fieldRequired[]"/> Required</label></td>\n\
        <td><a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">\n\
            <span class="glyphicon glyphicon-remove"></span></a>\n\
        </td></tr>';

$("#btn-addfield").click(function(e) {
  e.preventDefault();
  $(repeatBlock).append(repeatText);
});
$(repeatBlock).on('click', '.removeField', function(e) {
  e.preventDefault();
  $(this).parent().parent().remove();
});

$(repeatBlock).on('change', '.optType', function(e) {
  e.preventDefault();
  var val = $(this).val()
  if (val === "radio" || val === "select") {
    $(this).closest('tr').find(".optBlock").show();
   //$(this).closest('tr').find(".optBlock").find(".optInput").tagsinput('refresh');
  } else {
    $(this).closest('tr').find(".optBlock").hide();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn-addfield">Addfield</button>
<table>
  <tbody id="tbody"></tbody>
</table>


来源: stackexchange

问:
PHP only sending the first word in my sentense?
I am developing an APi where its suppossed to send a text message to a number ...this should be the message "Your registration for mobile Number has been received. Thank you for staying connected" but the text massage that is sending is only the first word "Your"

here is my code

```<code>    $message ="Your registration for mobile no has been received. Thank you for staying with MbongoCash";

sendTextMessage("0719401837",$message);

function sendTextMessage($phoneNumber,$data)
{

    $url = "http://121.241.242.114/bulksms/bulksms?username=josy-mbongocash&password=Jofar14&type=0&dlr=1&destination=$phoneNumber&source=MbongoCash&message='$data''";
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}
</code>```

Here is the image.
This is the Image screenshot

答:
Try to replace the spaces with %20. </p>

```<code>$message ="Your registration for mobile no has been received. Thank you for staying with MbongoCash";
$message =str_replace(" ", "%20", $message);
// rest of code.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am developing an APi where its suppossed to send a text message to a number ...this should be the message "Your registration for mobile Number has been received. Thank you for staying connected" but the text massage that is sending is only the first word "Your"

here is my code

    $message ="Your registration for mobile no has been received. Thank you for staying with MbongoCash";

sendTextMessage("0719401837",$message);

function sendTextMessage($phoneNumber,$data)
{

    $url = "http://121.241.242.114/bulksms/bulksms?username=josy-mbongocash&password=Jofar14&type=0&dlr=1&destination=$phoneNumber&source=MbongoCash&message='$data''";
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

Here is the image.
This is the Image screenshot

Body:
Try to replace the spaces with %20.

$message ="Your registration for mobile no has been received. Thank you for staying with MbongoCash";
$message =str_replace(" ", "%20", $message);
// rest of code.


问:
Keras dot product layer by last axis
I have Siamese network that produce feature maps for images, how do I get dot product of those feature maps with Keras?

```<code>input_a = Input(input_size)
input_b = Input(input_size)
fe_net_a = model(input_a)
fe_net_b = model(input_b)
</code>```

E.g. if output tensor of fe_net_a and fe_net_b has shape (1, 17, 17, 1024), how to create layer that will produce tensor of shape (1, 17, 17), taking dot product of last axis?

答:
From the keras documentation of the merge.Dot() function, is  this what you are looking for?

```<code>from keras.layers import Input, dot

input_a = Input(input_size)
input_b = Input(input_size)
fe_net_a = model(input_a)
fe_net_b = model(input_b)

fe_ab = dot([fe_net_a,fe_net_b], axes = -1)
</code>```

Does that work for you ?

Title: Keras dot product layer by last axis

Body:
I have Siamese network that produce feature maps for images, how do I get dot product of those feature maps with Keras?

input_a = Input(input_size)
input_b = Input(input_size)
fe_net_a = model(input_a)
fe_net_b = model(input_b)

E.g. if output tensor of fe_net_a and fe_net_b has shape (1, 17, 17, 1024), how to create layer that will produce tensor of shape (1, 17, 17), taking dot product of last axis?

Body:
From the keras documentation of the merge.Dot() function, is  this what you are looking for?

from keras.layers import Input, dot

input_a = Input(input_size)
input_b = Input(input_size)
fe_net_a = model(input_a)
fe_net_b = model(input_b)

fe_ab = dot([fe_net_a,fe_net_b], axes = -1)

Does that work for you ?


问:
View Controller shows black screen instead of fetching users from Firebase database Swift iOS
When I go to the HomeViewController the screen is to totally black. I actually want to fetch the users to put them into TableViewCells. I am using Firebase as a database and Swift as a language. Help me to accomplish this.

```<code>import UIKit
import Firebase

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var users = [User]()

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchUser()
    }

    func fetchUser() {
        FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let user = User(dictionary: dictionary)
                self.users.append(user)

                //this will crash because of background thread, so lets use dispatch_async to fix
                DispatchQueue.main.async(execute: {
                    self.tableView.reloadData()
                })
            }
        }, withCancel: nil)
    }

    func handleCancel() {
        dismiss(animated: true, completion: nil)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath)
        let user = users[indexPath.row]
        cell.textLabel?.text = user.name
        cell.detailTextLabel?.text = user.email
        return cell
    }
}

class UserCell: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

Presenting Home View Controller through SWRevealViewController under LoginButton

```<code>let vc : SWRevealViewController = self.storyboard?.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.present(vc, animated: true, completion: nil)
</code>```

Architecture

答:
By adding this to the ViewDidLoad everything went right.........

```<code>    menuHome.target = SWRevealViewController()
    menuHome.action = #selector(SWRevealViewController.revealToggle(_:))
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

    tableView.delegate = self
    tableView.dataSource = self
</code>```

Body:
When I go to the HomeViewController the screen is to totally black. I actually want to fetch the users to put them into TableViewCells. I am using Firebase as a database and Swift as a language. Help me to accomplish this.

import UIKit
import Firebase

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var users = [User]()

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchUser()
    }

    func fetchUser() {
        FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let user = User(dictionary: dictionary)
                self.users.append(user)

                //this will crash because of background thread, so lets use dispatch_async to fix
                DispatchQueue.main.async(execute: {
                    self.tableView.reloadData()
                })
            }
        }, withCancel: nil)
    }

    func handleCancel() {
        dismiss(animated: true, completion: nil)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath)
        let user = users[indexPath.row]
        cell.textLabel?.text = user.name
        cell.detailTextLabel?.text = user.email
        return cell
    }
}

class UserCell: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Presenting Home View Controller through SWRevealViewController under LoginButton

let vc : SWRevealViewController = self.storyboard?.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.present(vc, animated: true, completion: nil)

Architecture

Body:
By adding this to the ViewDidLoad everything went right.........

    menuHome.target = SWRevealViewController()
    menuHome.action = #selector(SWRevealViewController.revealToggle(_:))
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

    tableView.delegate = self
    tableView.dataSource = self


问:
export USERNAME=root in zsh gives permission error
When I run

```<code>export USERNAME=root
</code>```

in zsh it gives me the following error.

```<code>zsh: failed to change group ID: operation not permitted
</code>```

Any idea why?

PS: I did not manually run this initially, but I came across this when my vim-dispatch plugin threw this error while running a command in vim. Afterwards I was able to reproduce this by just running it in any zsh shell.

答:
The parameter USERNAME corresponds to the real user ID of the shell process. Modifying it also changes the real user ID, effectively changing the permissions of the running shell process. This is of course only possible, if the original user has sufficient privileges. In most cases this probably means that only root is allowed to assign to USERNAME, while any other accounts are not permitted.

For example, consider this shell session:

root@host# echo $USERNAME $UID $EUID $GID $EGID
root 0 0 0 0
root@host# USERNAME=adaephon
adaephon@host% echo $USERNAME $UID $EUID $GID $EGID
adaephon 1000 1000 1000 1000
adaephon@host% USERNAME=root
zsh: failed to change group ID: operation not permitted
adaephon@host% echo $USERNAME $UID $EUID $GID $EGID
adaephon 1000 1000 1000 1000
```

Starting out as root, I can easily drop my privileges to my normal user account. But I cannot switch back to root as adaephon lacks the necessary privileges.

Body:
When I run

export USERNAME=root

in zsh it gives me the following error.

zsh: failed to change group ID: operation not permitted

Any idea why?

PS: I did not manually run this initially, but I came across this when my vim-dispatch plugin threw this error while running a command in vim. Afterwards I was able to reproduce this by just running it in any zsh shell.

Body:
The parameter USERNAME corresponds to the real user ID of the shell process. Modifying it also changes the real user ID, effectively changing the permissions of the running shell process. This is of course only possible, if the original user has sufficient privileges. In most cases this probably means that only root is allowed to assign to USERNAME, while any other accounts are not permitted.

For example, consider this shell session:

root@host# echo $USERNAME $UID $EUID $GID $EGID
root 0 0 0 0
root@host# USERNAME=adaephon
adaephon@host% echo $USERNAME $UID $EUID $GID $EGID
adaephon 1000 1000 1000 1000
adaephon@host% USERNAME=root
zsh: failed to change group ID: operation not permitted
adaephon@host% echo $USERNAME $UID $EUID $GID $EGID
adaephon 1000 1000 1000 1000

Starting out as root, I can easily drop my privileges to my normal user account. But I cannot switch back to root as adaephon lacks the necessary privileges.


问:
'Unable to delete property' on Safari when trying to delete dataset attribute in strict mode
Consider following code:

(function () {
  'use strict';
  delete document.body.dataset.state;
})();
```

where body dataset is empty. Safari treats all DOMStringMap values — well, I guess so — as ReadOnly, and their enumerable, configurable and writable descriptor values are all set to false. This causes the TypeError: Unable to delete property to appear in the mentioned above example.

But in Chrome dataset property descriptor values are set to true (can be checked with Object.getOwnPropertyDescriptor()), and deleting inexistent attribute does not throw the error.

So, what behavior is correct? The spec says about readonly dataset, but writable DOMStringMap, so I assume dataset properties must be deletable. Am I missing something?

答:
Its probably because of strict mode.

Third, strict mode makes attempts to delete undeletable properties
  throw (where before the attempt would simply have no effect):

```<code>'use strict';
delete Object.prototype; // throws a TypeError
</code>```

You may want to take a look at this documentation

Also you can try  set object value to undefined, its a little hairy but works..

Body:
Consider following code:

(function () {
  'use strict';
  delete document.body.dataset.state;
})();

where body dataset is empty. Safari treats all DOMStringMap values — well, I guess so — as ReadOnly, and their enumerable, configurable and writable descriptor values are all set to false. This causes the TypeError: Unable to delete property to appear in the mentioned above example.

But in Chrome dataset property descriptor values are set to true (can be checked with Object.getOwnPropertyDescriptor()), and deleting inexistent attribute does not throw the error.

So, what behavior is correct? The spec says about readonly dataset, but writable DOMStringMap, so I assume dataset properties must be deletable. Am I missing something?

Body:
Its probably because of strict mode.

Third, strict mode makes attempts to delete undeletable properties
  throw (where before the attempt would simply have no effect):

'use strict';
delete Object.prototype; // throws a TypeError

You may want to take a look at this documentation

Also you can try  set object value to undefined, its a little hairy but works..


问:
Html get user local directory path
On my web app i have a textbox where client have to enter a path eg. C:\test and in that folder a file will be generated. The question is instead of manualy writing C:\test is there a way he can get this directory path with window that explores his system - like when uploading file. </p>

答:
The common use case is, the user clicks on a link and a file will be downloaded into his machine. This is usually done with anchor tag and the HTML5 download attribute. Here is an example:

```<code><a href="~/images/abc.jpg" download>Click here to download </a>
</code>```

The download action will be depended on the user's browser settings. In google chrome there is an option

"Ask where to save each file before downloading"

if it is checked, user will get a file explorer pop-up to select the download location.

Title: Html get user local directory path

Body:
The common use case is, the user clicks on a link and a file will be downloaded into his machine. This is usually done with anchor tag and the HTML5 download attribute. Here is an example:

<a href="~/images/abc.jpg" download>Click here to download </a>

The download action will be depended on the user's browser settings. In google chrome there is an option

"Ask where to save each file before downloading"

if it is checked, user will get a file explorer pop-up to select the download location.


问:
C++ "terminating with uncaught exception of type std::out_of_range: vector" error in a merge sort algorithm
I have a c++ code which should use merge sort algorithm to sort a file containing 800,000+ words each on a new line.

What I did ?

To start off, I tried implementing the following merge sort algorithm and tried testing it on a small piece of input. I cannot figure out where I am getting index out of bounds error with the vector. If anyone could help me with this, I would really appreciate

```<code>#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

vector<string> merge(const vector<string>& first,
                     const vector<string>& second) {
    // Write your code to merge vectors first and
    // second onto result.

    vector<string> output;
    int i = 0;
    int j = 0 ;
    int size_first = sizeof(first);
    int size_second = sizeof(second);

    while(i < size_first || j < size_second){
        if (i < size_first && j < size_second){
            if (first.at(i) < second.at(j)){
                output.push_back(first.at(i));
                i++;
            }
            else{
                output.push_back(second.at(i));
                j++;
            }
        }
        else if (i < size_first){
            output.push_back(first.at(i));
            i++;
        }
        else{
            output.push_back(second.at(j));
            j++;
        }

    }
    return output;
}

void mergeSort(vector<string>& words) {
    if (words.size() <= 1)
    {
        return;
    }
    int n = words.size();
    int middle = n/2;

    vector<string> first_half(middle);
    for (int i = 0; i < middle; ++i) {
        first_half[i] = words[i];
    }

    vector<string> second_half(n - middle);
    for (int i = middle; i < n; ++i) {
        second_half[i - middle] = words[i];
    }

    words = merge(first_half, second_half);
}

void sort(vector<string>& words) {

    // Invoke mergeSort  here.
    mergeSort(words);
}

int main(){

    vector<string> names;
    names.push_back("Smith");
    names.push_back("Abinash");
    names.push_back("Ciara");
    names.push_back("Reeta");

    sort(names);

    return 0;

}
</code>```

答:
you are determining the size of the vector wrong:

```<code>int size_first = sizeof(first);
int size_second = sizeof(second);
</code>```

replace it by

```<code>size_t size_first = first.size();
size_t size_second = second.size();
</code>```

Body:
I have a c++ code which should use merge sort algorithm to sort a file containing 800,000+ words each on a new line.

What I did ?

To start off, I tried implementing the following merge sort algorithm and tried testing it on a small piece of input. I cannot figure out where I am getting index out of bounds error with the vector. If anyone could help me with this, I would really appreciate

#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

vector<string> merge(const vector<string>& first,
                     const vector<string>& second) {
    // Write your code to merge vectors first and
    // second onto result.

    vector<string> output;
    int i = 0;
    int j = 0 ;
    int size_first = sizeof(first);
    int size_second = sizeof(second);

    while(i < size_first || j < size_second){
        if (i < size_first && j < size_second){
            if (first.at(i) < second.at(j)){
                output.push_back(first.at(i));
                i++;
            }
            else{
                output.push_back(second.at(i));
                j++;
            }
        }
        else if (i < size_first){
            output.push_back(first.at(i));
            i++;
        }
        else{
            output.push_back(second.at(j));
            j++;
        }

    }
    return output;
}

void mergeSort(vector<string>& words) {
    if (words.size() <= 1)
    {
        return;
    }
    int n = words.size();
    int middle = n/2;

    vector<string> first_half(middle);
    for (int i = 0; i < middle; ++i) {
        first_half[i] = words[i];
    }

    vector<string> second_half(n - middle);
    for (int i = middle; i < n; ++i) {
        second_half[i - middle] = words[i];
    }

    words = merge(first_half, second_half);
}

void sort(vector<string>& words) {

    // Invoke mergeSort  here.
    mergeSort(words);
}

int main(){

    vector<string> names;
    names.push_back("Smith");
    names.push_back("Abinash");
    names.push_back("Ciara");
    names.push_back("Reeta");

    sort(names);

    return 0;

}

Body:
you are determining the size of the vector wrong:

int size_first = sizeof(first);
int size_second = sizeof(second);

replace it by

size_t size_first = first.size();
size_t size_second = second.size();


问:
What Swift property types are allowed in UIApperance compliant custom classes?
I recently tried with no success to add a UIApperance compliant property to one of my Swift classes (ScoreView). You can see the relevant code below:

```<code>private var gaugeThresholds = Array<GaugeThreshold?>(repeating: nil, count: ScoreView.maxGaugeIntervals)

public func gaugeThreshold(forInterval interval: Int) -> GaugeThreshold? {
    return (0 <= interval && interval < ScoreView.maxGaugeIntervals) ? self.gaugeThresholds[interval] : nil
}

public func setGaugeThreshold(_ threshold: GaugeThreshold, forInterval interval: Int) {
    if 0 <= interval && interval < ScoreView.maxGaugeIntervals {
        self.gaugeThresholds[interval] = threshold
    }
}
</code>```

where GaugeThreshold is a Swift struct:

```<code>public struct GaugeThreshold {
    let until: Float
    let color: UIColor

    public init(until: Float, color: UIColor) {
        self.until = until
        self.color = color
    }
}
</code>```

This was failing miserably, and the only reason I can think of for this to fail is the fact that I'm using a custom type for the property instead of one of the standard types.

According to UIAppearanceContainer documentation: The property type may be any standard iOS type: id, NSInteger, NSUInteger, CGFloat, CGPoint, CGSize, CGRect, UIEdgeInsets or UIOffset. But if you browse the list of methods and properties conforming to UIAppearance as of iOS 8.0, you can see there are other types that are working properly as UIImage, UIColor... so does anybody know what makes a type valid for being used as a UIAppearance property?

答:
Of course, nothing like posting to StackOverflow to find out the answer five minutes later. It turns out the key is the id type. Changing

```<code>public struct GaugeThreshold { ...
</code>```

to

```<code>public class GaugeThreshold: NSObject { ...
</code>```

did the trick.

Body:
I recently tried with no success to add a UIApperance compliant property to one of my Swift classes (ScoreView). You can see the relevant code below:

private var gaugeThresholds = Array<GaugeThreshold?>(repeating: nil, count: ScoreView.maxGaugeIntervals)

public func gaugeThreshold(forInterval interval: Int) -> GaugeThreshold? {
    return (0 <= interval && interval < ScoreView.maxGaugeIntervals) ? self.gaugeThresholds[interval] : nil
}

public func setGaugeThreshold(_ threshold: GaugeThreshold, forInterval interval: Int) {
    if 0 <= interval && interval < ScoreView.maxGaugeIntervals {
        self.gaugeThresholds[interval] = threshold
    }
}

where GaugeThreshold is a Swift struct:

public struct GaugeThreshold {
    let until: Float
    let color: UIColor

    public init(until: Float, color: UIColor) {
        self.until = until
        self.color = color
    }
}

This was failing miserably, and the only reason I can think of for this to fail is the fact that I'm using a custom type for the property instead of one of the standard types.

According to UIAppearanceContainer documentation: The property type may be any standard iOS type: id, NSInteger, NSUInteger, CGFloat, CGPoint, CGSize, CGRect, UIEdgeInsets or UIOffset. But if you browse the list of methods and properties conforming to UIAppearance as of iOS 8.0, you can see there are other types that are working properly as UIImage, UIColor... so does anybody know what makes a type valid for being used as a UIAppearance property?

Body:
Of course, nothing like posting to StackOverflow to find out the answer five minutes later. It turns out the key is the id type. Changing

public struct GaugeThreshold { ...

to

public class GaugeThreshold: NSObject { ...

did the trick.


问:
Why use integer casting on process handle object for the 1st param of kernel32.TerminateProcess?
ok I'm doing some test on killing windows process using python binding of windows system calls, there are two methods I am using, but they are doing it different ly, some detail baffles me.

first approach is using win32api

```<code>import win32api,subprocess
proc = subprocess.Popen([ 'notepad' ])
win32api.TerminateProcess(proc._handle, -1)
</code>```

second approach is using ctypes

```<code>import ctypes, subprocess
proc = subprocess.Popen([ 'notepad' ])
ctypes.windll.kernel32.TerminateProcess( proc._handle, -1 )
</code>```

in the second approach, it will not work unless you integer cast the proc._handle like this:

```<code>proc = subprocess.Popen([ 'notepad' ])
int_handle = int(proc._handle)
ctypes.windll.kernel32.TerminateProcess(int_handle, -1 )
</code>```

this int_handle, presumably some sort of process handle number, usually values within 1-1000 on my machine.
by inspecting the proc._handle object using these builtins, I didn't get any terribly useful information:

```<code>print "dir() of handle >>",dir(proc._handle)    # ['Close', 'Detach']
print "type() of handle >>",type(proc._handle)  # <type '_subprocess_handle'>
</code>```

Sysinternals handle.exe didn't give too much info as well.

```<code>notepad.exe pid: 8688 HOST\user
4: Event
8: WaitCompletionPacket
C: IoCompletion
10: TpWorkerFactory
14: IRTimer
   ...
</code>```

My question:

What excatly is this integer stored in int_handle?

why can it obtain the handle value doing a integer casting on proc._handle object?

and Why passing this number to kernel32.TerminateProcess?

答:
See the MSDN topic on Handles and Objects for an overview of the various types of objects in the system and how handles are used to reference them. Kernel objects such as Process objects exist in kernel address space. User-mode programs cannot directly reference kernel memory. Instead each process has a kernel-object handle table that maps handle values such as 4, 8, 12 and so on to kernel objects. For example, when you call CreateProcess, the call returns handles for the Process and its primary Thread.  You can also call OpenProcess or OpenThread to open a handle for an existing process or thread by ID. Call CloseHandle to close a handle that's no longer needed.

(Kernel File objects, such as from calling CreateFile, are also referenced via handles. However, CPython uses the C runtime's low I/O file descriptors instead, such as 0, 1, 2 and so on, i.e.  Unix/POSIX file descriptors. On Unix everything is a file, whereas on Windows everything is an object. The C runtime maintains a private mapping of file descriptors to Windows File handles. Other object types are not mapped to Unix file descriptors. Using the low I/O file descriptors and C standard I/O makes it simpler to support both Unix and Windows. That said, there is at least one proposed patch with the ambitious goal of rewriting Python 3's I/O support on Windows to use the Windows API and File handles directly.)

In Python 2, subprocess uses a _subprocess_handle type on Windows to automatically close a handle when it's no longer referenced. This type defines an __int__ method to support converting the handle value to an integer, but it doesn't subclass int, so it's not an integer itself. For your particular problem with ctypes, the default argument conversion only converts integer arguments to C int values, which is why you have to use int(proc._handle).

However, using the default integer conversion is a mistake. You should define TerminateProcess.argtypes = (ctypes.c_void_p, ctypes.c_uint). While real kernel handles are always in the 32-bit range, even on a 64-bit system, fake handles such as (HANDLE)-1 (which is used to reference the current process without having to open a real handle) do use the full pointer range. Thus on 64-bit systems the upper DWORD of real kernel handles should be zero, and for pseudo-handles such as (HANDLE)-1, the non-zero upper DWORD must be preserved. In 2.x, ctypes doesn't zero the stack memory for arguments, and using the default C int type only writes the lower DWORD of the stack QWORD. For reliability you must either manually wrap arguments as pointers or define all HANDLE type arguments (including HMODULE, HWND, etc) as a pointer type such as ctypes.c_void_p or wintypes.HANDLE.

Using ctypes.windll is also problematic, since it caches DLLs, which cache function pointers. This leaves your script or module at the mercy of global state and can lead to conflicting argtypes, restype, and errcheck definitions. It also doesn't allow enabling the per thread protected storage for the last error value. Here's an example ctypes definition that's more reliable:

```<code>import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.TerminateProcess.argtypes = (wintypes.HANDLE, wintypes.UINT)

if __name__ == '__main__':
    import subprocess

    p = subprocess.Popen('notepad')
    if not kernel32.TerminateProcess(int(p._handle), 1):
        raise ctypes.WinError(ctypes.get_last_error())
</code>```

OwnerDisplayName: Hiagara

Body:
ok I'm doing some test on killing windows process using python binding of windows system calls, there are two methods I am using, but they are doing it different ly, some detail baffles me.

first approach is using win32api

import win32api,subprocess
proc = subprocess.Popen([ 'notepad' ])
win32api.TerminateProcess(proc._handle, -1)

second approach is using ctypes

import ctypes, subprocess
proc = subprocess.Popen([ 'notepad' ])
ctypes.windll.kernel32.TerminateProcess( proc._handle, -1 )

in the second approach, it will not work unless you integer cast the proc._handle like this:

proc = subprocess.Popen([ 'notepad' ])
int_handle = int(proc._handle)
ctypes.windll.kernel32.TerminateProcess(int_handle, -1 )

this int_handle, presumably some sort of process handle number, usually values within 1-1000 on my machine.
by inspecting the proc._handle object using these builtins, I didn't get any terribly useful information:

print "dir() of handle >>",dir(proc._handle)    # ['Close', 'Detach']
print "type() of handle >>",type(proc._handle)  # <type '_subprocess_handle'>

Sysinternals handle.exe didn't give too much info as well.

notepad.exe pid: 8688 HOST\user
4: Event
8: WaitCompletionPacket
C: IoCompletion
10: TpWorkerFactory
14: IRTimer
   ...

My question:

What excatly is this integer stored in int_handle?

why can it obtain the handle value doing a integer casting on proc._handle object?

and Why passing this number to kernel32.TerminateProcess?

Body:
See the MSDN topic on Handles and Objects for an overview of the various types of objects in the system and how handles are used to reference them. Kernel objects such as Process objects exist in kernel address space. User-mode programs cannot directly reference kernel memory. Instead each process has a kernel-object handle table that maps handle values such as 4, 8, 12 and so on to kernel objects. For example, when you call CreateProcess, the call returns handles for the Process and its primary Thread.  You can also call OpenProcess or OpenThread to open a handle for an existing process or thread by ID. Call CloseHandle to close a handle that's no longer needed.

(Kernel File objects, such as from calling CreateFile, are also referenced via handles. However, CPython uses the C runtime's low I/O file descriptors instead, such as 0, 1, 2 and so on, i.e.  Unix/POSIX file descriptors. On Unix everything is a file, whereas on Windows everything is an object. The C runtime maintains a private mapping of file descriptors to Windows File handles. Other object types are not mapped to Unix file descriptors. Using the low I/O file descriptors and C standard I/O makes it simpler to support both Unix and Windows. That said, there is at least one proposed patch with the ambitious goal of rewriting Python 3's I/O support on Windows to use the Windows API and File handles directly.)

In Python 2, subprocess uses a _subprocess_handle type on Windows to automatically close a handle when it's no longer referenced. This type defines an __int__ method to support converting the handle value to an integer, but it doesn't subclass int, so it's not an integer itself. For your particular problem with ctypes, the default argument conversion only converts integer arguments to C int values, which is why you have to use int(proc._handle).

However, using the default integer conversion is a mistake. You should define TerminateProcess.argtypes = (ctypes.c_void_p, ctypes.c_uint). While real kernel handles are always in the 32-bit range, even on a 64-bit system, fake handles such as (HANDLE)-1 (which is used to reference the current process without having to open a real handle) do use the full pointer range. Thus on 64-bit systems the upper DWORD of real kernel handles should be zero, and for pseudo-handles such as (HANDLE)-1, the non-zero upper DWORD must be preserved. In 2.x, ctypes doesn't zero the stack memory for arguments, and using the default C int type only writes the lower DWORD of the stack QWORD. For reliability you must either manually wrap arguments as pointers or define all HANDLE type arguments (including HMODULE, HWND, etc) as a pointer type such as ctypes.c_void_p or wintypes.HANDLE.

Using ctypes.windll is also problematic, since it caches DLLs, which cache function pointers. This leaves your script or module at the mercy of global state and can lead to conflicting argtypes, restype, and errcheck definitions. It also doesn't allow enabling the per thread protected storage for the last error value. Here's an example ctypes definition that's more reliable:

import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.TerminateProcess.argtypes = (wintypes.HANDLE, wintypes.UINT)

if __name__ == '__main__':
    import subprocess

    p = subprocess.Popen('notepad')
    if not kernel32.TerminateProcess(int(p._handle), 1):
        raise ctypes.WinError(ctypes.get_last_error())


问:
UITableViewCell accessoryView not displaying
Im totally unsure why my accessory view is not working. I simply want some text to appear to the right of the UITableViewCell (as well as the left), but only the text on the left is displaying.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"];

  if (cell==nil){
      cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease];
      UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 60, 30)];

      cell.textLabel.text = @"left text";
      label.text = @"right text";

      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

      cell.accessoryView = label;
      [label release];

  }
  return cell;
}
</code>```

Any ideas? Thanks.

答: Also remember: accessoryType property is ignored if you have custom accessoryView. So, this line of code is excess.</p>

Body:
Im totally unsure why my accessory view is not working. I simply want some text to appear to the right of the UITableViewCell (as well as the left), but only the text on the left is displaying.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"];

  if (cell==nil){
      cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease];
      UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 60, 30)];

      cell.textLabel.text = @"left text";
      label.text = @"right text";

      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

      cell.accessoryView = label;
      [label release];

  }
  return cell;
}

Any ideas? Thanks.


问:
How do I use PowerShell with Gitlab CI in Gitlab Pages?
How do I use PowerShell commands/scripts with Gitlab CI in a .gitlab-ci.yml file which is used to deploy to gitlab pages?

I am trying to execute the build.ps1 file from .gitlab-ci.yml, but when it reaches the build.ps1 line, it gives an error saying
/bin/bash: line 5: .build.ps1: command not found

I am trying to use the PowerShell script to convert a file in my repo and have the converted file deployed to gitlab pages using .gitlab-ci.yml

Here is my code:

.gitlab.yml

```<code>pages:
  stage: deploy
  script:
  - mkdir .public
  - .\build.ps1
  - cp -r * .public
  - mv .public public
  artifacts:
    paths:
    - public
  only:
  - master
</code>```

答:
I have been able to figure out a solution to my own question.

Solution

To Run PowerShell Command/Script from a .gitlab-ci.yml file on a gitlab.com using the Gitlab CI, you need to make sure that the contents of your .gitlab-ci.yml file is as shown below.

Note: The .gitlab-ci.yml below works without having to install a Gitlab Runner on your own machine and has been tested on the http://gitlab.com website.

```<code>image: philippheuer/docker-gitlab-powershell

pages:
  stage: deploy
  script:
  - mkdir .public
  # run PowerShell Script
  - powershell -File build.ps1
  # run PowerShell Command
  - powershell -Command "Get-Date"
  - cp -r * .public
  - mv .public public
  artifacts:
    paths:
    - public
  only:
  - master
</code>```

Body:
How do I use PowerShell commands/scripts with Gitlab CI in a .gitlab-ci.yml file which is used to deploy to gitlab pages?

I am trying to execute the build.ps1 file from .gitlab-ci.yml, but when it reaches the build.ps1 line, it gives an error saying
/bin/bash: line 5: .build.ps1: command not found

I am trying to use the PowerShell script to convert a file in my repo and have the converted file deployed to gitlab pages using .gitlab-ci.yml

Here is my code:

.gitlab.yml

pages:
  stage: deploy
  script:
  - mkdir .public
  - .\build.ps1
  - cp -r * .public
  - mv .public public
  artifacts:
    paths:
    - public
  only:
  - master

Body:
I have been able to figure out a solution to my own question.

Solution

To Run PowerShell Command/Script from a .gitlab-ci.yml file on a gitlab.com using the Gitlab CI, you need to make sure that the contents of your .gitlab-ci.yml file is as shown below.

Note: The .gitlab-ci.yml below works without having to install a Gitlab Runner on your own machine and has been tested on the http://gitlab.com website.

image: philippheuer/docker-gitlab-powershell

pages:
  stage: deploy
  script:
  - mkdir .public
  # run PowerShell Script
  - powershell -File build.ps1
  # run PowerShell Command
  - powershell -Command "Get-Date"
  - cp -r * .public
  - mv .public public
  artifacts:
    paths:
    - public
  only:
  - master


问:
Comparing MySql variables
I am trying to make a addition to my website where admins can ban people, but my code isn't working. I have looked everywhere but i can't find a fix. Can anyone help me? Here is my code.

```<code><?php

    $con = mysql_connect("localhost", "root", "");
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("users", $con);
    $objGet = mysql_query("SELECT `blocked`  FROM `users` WHERE `username` LIKE '$username'");

    if (mysql_num_rows($objGet) === "1") {
        echo '<script>alert("Account Suspended")</script>';
        header('Location: userAccount.php?logoutSubmit=1');
    } else {
        //Do Nothing
    }
    ?>
</code>```

Error :

Warning: mysql_num_rows() expects parameter 1 to be resource, string
  given in C:\xampp\htdocs\index.php on line 50

Ok i got the code working with completely modified code but it works

答:
I think the problem is with this line:

```<code>if(mysql_num_rows($objGet) === "1") {
</code>```

mysql_num_rows() returns an integer, but you're comparing it against a string with the identity check ===, which will always return false.

Maybe this would be a better comparison:

```<code>if(mysql_num_rows($objGet) > 0) {
</code>```

Title: Comparing MySql variables

Body:
I am trying to make a addition to my website where admins can ban people, but my code isn't working. I have looked everywhere but i can't find a fix. Can anyone help me? Here is my code.

<?php

    $con = mysql_connect("localhost", "root", "");
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("users", $con);
    $objGet = mysql_query("SELECT `blocked`  FROM `users` WHERE `username` LIKE '$username'");

    if (mysql_num_rows($objGet) === "1") {
        echo '';
        header('Location: userAccount.php?logoutSubmit=1');
    } else {
        //Do Nothing
    }
    ?>

Error :

Warning: mysql_num_rows() expects parameter 1 to be resource, string
  given in C:\xampp\htdocs\index.php on line 50

Ok i got the code working with completely modified code but it works

Body:
I think the problem is with this line:

if(mysql_num_rows($objGet) === "1") {

mysql_num_rows() returns an integer, but you're comparing it against a string with the identity check ===, which will always return false.

Maybe this would be a better comparison:

if(mysql_num_rows($objGet) > 0) {


问:
destroying object doesn't remove delegate from invocation list
I have a little problem with my objects...
I have an object with one delegate inside to which it subscribe in constructor.
When I destroy this object the invocation list still tell me that it has one subscriber in. and when and create this object again I find two subscriber in (the old that I have destroyed and the new one).
How can I solve this problem and remove the subscriber in the list cleanly?

Here is the code for test:(two button to destroy and create object inside)

```<code>public partial class Form1 : Form
{
    testdelegate thisdelegatetest;
    public Form1()
    {
        InitializeComponent();
        thisdelegatetest = new testdelegate();//create object
        Timer mytimer = new Timer();//timer to see something BEGIN
        mytimer.Interval = 1000;
        mytimer.Tick += new EventHandler(mytimer_Tick);
        mytimer.Start();//timer to see something END
    }
    protected void mytimer_Tick(object sender, EventArgs e)
    {//each 1second look at the list invocation
        lb_IndelList.Text = "actual subscribers : " + testdelegate.dl_myfunctionthatcopy.GetInvocationList().Count().ToString();
    }
    private void DestroyObject_Click(object sender, EventArgs e)
    {//destroy object
    /*edit*/
        thisdelegatetest.Delete();
        thisdelegatetest = null;//dereferencing for GC
    /*edit*/
    }

    private void CreateObject_Click(object sender, EventArgs e)
    {//create object
        thisdelegatetest = new testdelegate();
    }

}
public class testdelegate
{
    public delegate void del_copysomething(int newvaluetocopy);
    internal static del_copysomething dl_myfunctionthatcopy;
    public int valueforallobject = 0;

    public testdelegate()//ctor
    {
        dl_myfunctionthatcopy += new del_copysomething(copythisint);
    }
    /*edit*/
    public void Delete()
    {
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
    }
    /*edit*/
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
    }
}
</code>```

Thanks for your help.

答:
```<code>private void DestroyObject_Click(object sender, EventArgs e)
{//destroy object
    thisdelegatetest = null;
}
</code>```

This does not really destroy the object. Objects are "destroyed" (freed) by the garbage collector.

In fact, it cannot be marked as collectable because the static delegate still references it. Thus, the destructor is never called. You have remove the subscriber manually, e.g. through a public method.

Body:
I have a little problem with my objects...
I have an object with one delegate inside to which it subscribe in constructor.
When I destroy this object the invocation list still tell me that it has one subscriber in. and when and create this object again I find two subscriber in (the old that I have destroyed and the new one).
How can I solve this problem and remove the subscriber in the list cleanly?

Here is the code for test:(two button to destroy and create object inside)

public partial class Form1 : Form
{
    testdelegate thisdelegatetest;
    public Form1()
    {
        InitializeComponent();
        thisdelegatetest = new testdelegate();//create object
        Timer mytimer = new Timer();//timer to see something BEGIN
        mytimer.Interval = 1000;
        mytimer.Tick += new EventHandler(mytimer_Tick);
        mytimer.Start();//timer to see something END
    }
    protected void mytimer_Tick(object sender, EventArgs e)
    {//each 1second look at the list invocation
        lb_IndelList.Text = "actual subscribers : " + testdelegate.dl_myfunctionthatcopy.GetInvocationList().Count().ToString();
    }
    private void DestroyObject_Click(object sender, EventArgs e)
    {//destroy object
    /*edit*/
        thisdelegatetest.Delete();
        thisdelegatetest = null;//dereferencing for GC
    /*edit*/
    }

    private void CreateObject_Click(object sender, EventArgs e)
    {//create object
        thisdelegatetest = new testdelegate();
    }

}
public class testdelegate
{
    public delegate void del_copysomething(int newvaluetocopy);
    internal static del_copysomething dl_myfunctionthatcopy;
    public int valueforallobject = 0;

    public testdelegate()//ctor
    {
        dl_myfunctionthatcopy += new del_copysomething(copythisint);
    }
    /*edit*/
    public void Delete()
    {
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
    }
    /*edit*/
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
    }
}

Thanks for your help.

Body:
private void DestroyObject_Click(object sender, EventArgs e)
{//destroy object
    thisdelegatetest = null;
}

This does not really destroy the object. Objects are "destroyed" (freed) by the garbage collector.

In fact, it cannot be marked as collectable because the static delegate still references it. Thus, the destructor is never called. You have remove the subscriber manually, e.g. through a public method.


问:
BehaviorSubject with class instance
I understand how to use BehaviorSubject when it comes to simple types such as int string bool etc. But I have just attempted to implement a BehaviorSubject for a class instance, and I am very certain that my approach is wrong...

This is what I currently have (which works by the way):

```<code>//user.model.ts
export class User {
    public accesstoken: string;
    public details: UserDetails;
    public subscriptions: Channel[];
    private loaded: boolean;
}

//user.service.ts
export class UserService {
    public activeUser: BehaviorSubject<User>;
    ...

    // called when we want to update the users details
    public updateUserDetailsFromServer(){
        ...
        // set the instance to the new data.
        this.activeUser.getValue().details = data.details;
        // now update the BehaviorSubject (this feels so wrong)
        this.activeUser.next(this.activeUser.getValue());
        ...
    }
}
</code>```

I am certain that there is a far cleaner way to implement this.

答:
To simplify matters, I didn't create a User class. But it should be easy to replace the object with your implementation.

const { Observable, Subject } = Rx;
const input$ = new Subject();

const user = {
  token: null,
  loaded: false,
  details: {}
};

const user$ = input$
  .startWith(Object.create(user))
  .scan((activeUser, { details }) => {
    Object.assign(activeUser.details, details);
    return activeUser;
  })
  .subscribe(x => console.log(x));

input$.next({ details: { name: 'Bob' } });
input$.next({ details: { role: 'Admin' } });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script></code>```

EDIT: Since using a class was part of your question:

const { Observable, Subject } = Rx;
const input$ = new Subject();

class User {
  constructor() {
    this.token = null;
    this.loaded = false;
    this.details = {};
  }
}

const user$ = input$
  .startWith(new User())
  .scan((activeUser, { details }) => {
    Object.assign(activeUser.details, details);
    return activeUser;
  })
  .subscribe(x => console.log(x));

input$.next({ details: { name: 'Bob' } });
input$.next({ details: { role: 'Admin' } });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script></code>```

I would not advise you to use Observables like that. Especially, using a BehaviorSubject and then just pulling data from it with getValue(). As shown above, I would suggest using scan to hold the current value for the user.

In your case the input$ can be one or multiple (merged) streams that can update the active user (for example your http stream). This way, anything that is interested in updated to the active user, can then just subscribe to the user$.

Title: BehaviorSubject with class instance

Body:
I understand how to use BehaviorSubject when it comes to simple types such as int string bool etc. But I have just attempted to implement a BehaviorSubject for a class instance, and I am very certain that my approach is wrong...

This is what I currently have (which works by the way):

//user.model.ts
export class User {
    public accesstoken: string;
    public details: UserDetails;
    public subscriptions: Channel[];
    private loaded: boolean;
}

//user.service.ts
export class UserService {
    public activeUser: BehaviorSubject<User>;
    ...

    // called when we want to update the users details
    public updateUserDetailsFromServer(){
        ...
        // set the instance to the new data.
        this.activeUser.getValue().details = data.details;
        // now update the BehaviorSubject (this feels so wrong)
        this.activeUser.next(this.activeUser.getValue());
        ...
    }
}

I am certain that there is a far cleaner way to implement this.

Body:
To simplify matters, I didn't create a User class. But it should be easy to replace the object with your implementation.

const { Observable, Subject } = Rx;
const input$ = new Subject();

const user = {
  token: null,
  loaded: false,
  details: {}
};

const user$ = input$
  .startWith(Object.create(user))
  .scan((activeUser, { details }) => {
    Object.assign(activeUser.details, details);
    return activeUser;
  })
  .subscribe(x => console.log(x));

input$.next({ details: { name: 'Bob' } });
input$.next({ details: { role: 'Admin' } });

<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

EDIT: Since using a class was part of your question:

const { Observable, Subject } = Rx;
const input$ = new Subject();

class User {
  constructor() {
    this.token = null;
    this.loaded = false;
    this.details = {};
  }
}

const user$ = input$
  .startWith(new User())
  .scan((activeUser, { details }) => {
    Object.assign(activeUser.details, details);
    return activeUser;
  })
  .subscribe(x => console.log(x));

input$.next({ details: { name: 'Bob' } });
input$.next({ details: { role: 'Admin' } });

<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

I would not advise you to use Observables like that. Especially, using a BehaviorSubject and then just pulling data from it with getValue(). As shown above, I would suggest using scan to hold the current value for the user.

In your case the input$ can be one or multiple (merged) streams that can update the active user (for example your http stream). This way, anything that is interested in updated to the active user, can then just subscribe to the user$.


问:
Subversion NoClassFoundDefError
While using subversion several files where placed into 1 package.
Every thing was working perfectly at this point.

Afterwards somebody replaced that package with 5 other ones and divided all the files amongst them.

And now after "updating" the proper files do appear. With the name of the 1 package gone.

But now i keep getting the error:“java.lang.NoClassDefFoundError/first package name/Main

Where the first package stands for the package that has long been deleted.
For the person who changed this, the program just works fine.

I can only get to compile the program when i delete every package again and replace all of it with 1 package like it was at the start...

Pretty much tried everything, re-install, clean & build, etc...

Any input appreciated.

答: Try searching for files in your project directory containing the old package name. Looks like some project metadata that's not under version control wasn't updated. Then either find and fix it in Netbeans or close Netbeans and edit the files directly (backup first, of course).</p>

ContentLicense: CC BY-SA 2.5

Title: Subversion NoClassFoundDefError


问:
Merging partial duplicate cases without losing data
I have a question in regards to preparing my dataset for research.

I have a dataset in SPSS 20 in long format as I am researching on individual level over multiple years. However some individuals were added twice to my dataset because there were differences in some variables matched to those individuals (5000 individuals with 25 variables per individual). I would like to merge those duplicates so that I can run my analysis over time. For those variables that differ between the duplicates I would like spss to make additional variables when all the duplicates are merged.

Is this at all possible and if yes HOW?

答:
I suggest following steps>

create auxiliary variable "PrimaryLast" with procedure Data->Identify Duplicate Cases by... , set "Define matching cases by" to your case ID

create 2 new auxiliary datasets with Data->Select Cases with condition "PrimaryLast = 0" and "PrimaryLast = 1" and selection "Copy selected cases to new dataset"

merge both auxiliary datasets with procedure Data -> Merge Files-> Add Variables, rename duplicated variable names in left box and move them in right box and select your case ID as key

don't forget to control if you made "full outer join", in case you lost non-duplicated cases and have only duplicated cases in your dataset, just merge datasets from step 2. in different order in step 3.


问:
setClientIdentifier on oracle Connection from java application
how to set client identifier to oracle connection from java application. My stack is hibernate 4.3.6 and spring 4.1.0. Transaction are managed by spring with annotation @Transactional

My first try does't work

```<code>    @Autowired
private QueryDslUtil queryDslUtil;

@Autowired
private SessionFactory sessionFactory;

@Override
@Transactional(readOnly = true)
public void test(String kod) {

    Session tmpSession = sessionFactory.getCurrentSession();
    tmpSession.doWork(connection -> {
        Properties prop = new Properties();
        prop.put("userId", "mito");
        connection.setClientInfo(prop);
    });

    Objects.requireNonNull(kod);
    QOrganizacia source = QOrganizacia.organizacia;
    queryDslUtil.from(source).where(source.kod.eq(kod)).uniqueResult(source);
}
</code>```

my datasource is provided by weblogic server via jndi register or c3po in dev enviroment and I use oracle driver v 11.2.0.1.0

Thanks for help.

答:
solved on weblogic server:</p>

```<code>@Override
@Transactional(readOnly = true)
public void log(String kod) {

    Session tmpSession = sessionFactory.getCurrentSession();
    tmpSession.doWork(connection -> {
        WebLogicNativeJdbcExtractor wlne = new WebLogicNativeJdbcExtractor();
        Connection oracleConnection = wlne.getNativeConnection(connection);
        LOGGER.debug("in work...");
        LOGGER.debug("is oracleConnection {}", oracleConnection instanceof OracleConnection);
        LOGGER.debug("oracleConnection casted {}", oracleConnection);
        String metric[] = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX];
        metric[OracleConnection.END_TO_END_ACTION_INDEX] = "I'm ACTION ";
        metric[OracleConnection.END_TO_END_MODULE_INDEX] = "i'm MODULE";
        metric[OracleConnection.END_TO_END_CLIENTID_INDEX] = "user";
        ((OracleConnection )oracleConnection).setEndToEndMetrics(metric, (short) 0);
    });

    Objects.requireNonNull(kod);
    QOrganizacia source = QOrganizacia.organizacia;
    queryDslUtil.from(source).where(source.nazov.eq(kod)).uniqueResult(source);
}
</code>```

Body:
how to set client identifier to oracle connection from java application. My stack is hibernate 4.3.6 and spring 4.1.0. Transaction are managed by spring with annotation @Transactional

My first try does't work

    @Autowired
private QueryDslUtil queryDslUtil;

@Autowired
private SessionFactory sessionFactory;

@Override
@Transactional(readOnly = true)
public void test(String kod) {

    Session tmpSession = sessionFactory.getCurrentSession();
    tmpSession.doWork(connection -> {
        Properties prop = new Properties();
        prop.put("userId", "mito");
        connection.setClientInfo(prop);
    });

    Objects.requireNonNull(kod);
    QOrganizacia source = QOrganizacia.organizacia;
    queryDslUtil.from(source).where(source.kod.eq(kod)).uniqueResult(source);
}

my datasource is provided by weblogic server via jndi register or c3po in dev enviroment and I use oracle driver v 11.2.0.1.0

Thanks for help.

Body:
solved on weblogic server:

@Override
@Transactional(readOnly = true)
public void log(String kod) {

    Session tmpSession = sessionFactory.getCurrentSession();
    tmpSession.doWork(connection -> {
        WebLogicNativeJdbcExtractor wlne = new WebLogicNativeJdbcExtractor();
        Connection oracleConnection = wlne.getNativeConnection(connection);
        LOGGER.debug("in work...");
        LOGGER.debug("is oracleConnection {}", oracleConnection instanceof OracleConnection);
        LOGGER.debug("oracleConnection casted {}", oracleConnection);
        String metric[] = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX];
        metric[OracleConnection.END_TO_END_ACTION_INDEX] = "I'm ACTION ";
        metric[OracleConnection.END_TO_END_MODULE_INDEX] = "i'm MODULE";
        metric[OracleConnection.END_TO_END_CLIENTID_INDEX] = "user";
        ((OracleConnection )oracleConnection).setEndToEndMetrics(metric, (short) 0);
    });

    Objects.requireNonNull(kod);
    QOrganizacia source = QOrganizacia.organizacia;
    queryDslUtil.from(source).where(source.nazov.eq(kod)).uniqueResult(source);
}


问:
Type mismatch in key from map: expected org.apache.hadoop.io.Text, received org.apache.hadoop.io.IntWritable
I am trying to run a map reducer in java for a comma separated file containing data about an AIRLINE which crashed.

The data contains the following columns and a sample data is also provided :

```<code>passengerid,survived(s=0,d=1),pclass,name,sex,age,sibsp,parch,ticket,fare,cabin,embarked
1,0,3,"Braund Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S,2,1,1,"Cumings Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C,
3,1,3,"Heikkinen Miss. Laina",female,26,0,0,STON/O2. 3101282,7.925,,S,
4,1,1,"Futrelle Mrs. Jacques Heath (Lily May Peel)",female,35,1,0,113803,53.1,C123,S,
5,0,3,"Allen Mr. William Henry",male,35,0,0,373450,8.05,,S,
6,0,3,"Moran Mr. James",male,,0,0,330877,8.4583,,Q,
7,0,1,"McCarthy Mr. Timothy J",male,54,0,0,17463,51.8625,E46,S,
8,0,3,"Palsson Master. Gosta Leonard",male,2,3,1,349909,21.075,,S,
9,1,3,"Johnson Mrs. Oscar W (Elisabeth Vilhelmina Berg)",female,27,0,2,347742,11.1333,,S,
10,1,2,"Nasser Mrs. Nicholas (Adele Achem)",female,14,1,0,237736,30.0708,,C,
11,1,3,"Sandstrom Miss. Marguerite Rut",female,4,1,1,PP 9549,16.7,G6,S,
12,1,1,"Bonnell Miss. Elizabeth",female,58,0,0,113783,26.55,C103,S,
...
</code>```

My objective is to find the average age of people died in this crash.
Here's my code snippets and the errors i encountered:

Airline.airlineDriver.java:

```<code>package Airline;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import Airline.airlineMapper;
import Airline.airlineReducer;

public class airlineDriver {

public static void main(String[] args) throws IOException,
ClassNotFoundException, InterruptedException, URISyntaxException {
    // TODO Auto-generated method stub
    Configuration conf = new Configuration();

    Job j = Job.getInstance(conf);// getConf()
    j.setJobName("Airline Job");
    j.setJarByClass(airlineDriver.class );
    j.setMapperClass(airlineMapper.class );
    j.setNumReduceTasks(2);
    j.setReducerClass(airlineReducer.class);
    j.setMapOutputKeyClass(IntWritable.class);
    j.setMapOutputValueClass(Text.class);
    j.setOutputKeyClass(Text.class);
    j.setOutputValueClass(FloatWritable.class);

    FileInputFormat.addInputPath(j, new Path(args[0]));
    FileOutputFormat.setOutputPath(j, new Path(args[1]));

    System.exit(j.waitForCompletion(true) ? 0 : 1);
   }

  }
</code>```

Airline.airlineMapper.java:

```<code>package Airline;
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class airlineMapper extends Mapper<LongWritable,  Text,
IntWritable,Text> {
@Override
protected void map(LongWritable key, Text
value,org.apache.hadoop.mapreduce.Mapper.Context context)throws IOException,
InterruptedException {
    String inputstring = value.toString(); //converts input Text value to String
    IntWritable resKEY = new IntWritable();
    Text resVALUE = new Text();
    String str[] = inputstring.split(","); //splits it into array
    int bool = Integer.parseInt(str[1]); //fetch survived(s=0) or dead(d=1)
    if (bool == 1){
        resVALUE.set(str[5]);
        resKEY.set(bool);
        context.write(resKEY,resVALUE); //write key value pair to partitioner and reducer
}  }
}
</code>```

Airline.airlineReducer.java :

```<code>package Airline;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
public class airlineReducer extends Reducer<IntWritable,Text, Text,
FloatWritable> {

@Override
public void reduce(IntWritable key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
    float y = 0;  //numerator for avgage
    float avgage =0;
    int counter = 0;  //denominator for avgage
    String a = "Average age";
    for(Text x : values)  //passes value to x one-by-one
    {
        String z = x.toString();   //converts text to string
        if((!z.equals(""))&&(!z.equals(null))){  //eliminating any empty string (**possible source of error)
        y +=Float.parseFloat(z);  //converting age to float since csf contains floating point ages
        counter++; //incrementing counter for total no. of people(records)

    }else{continue;  //if a null or empty string is encountered loop may skip the iteration and continue to next record
    //in case few fields are left empty
    }//**possible source of error
        }
    avgage = y/counter;    //average formula
    context.write(new Text(a), new FloatWritable(avgage) ); //wirting output data

    }
    }
</code>```

Even on making repeated changes in code i am still getting errors like:

```<code>Error: java.lang.ArrayIndexOutOfBoundsException: 1
at Airline.airlineMapper.map(airlineMapper.java:18)
at Airline.airlineMapper.map(airlineMapper.java:1)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs
(UserGroupInformation.java:1693)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
</code>```

plz help

答:
As @RameshMaharjan answered The correct mapper and reducer class would be:

Airline.airlineMapper (THE CODE WHICH I MENTIONED BEFORE IS ALSO COMMENTED BELOW. THESE CHECKS str.length==12 and str[5].matches("\\d+") CAN BE USED WITH THE PREVIOUS CODE AND IT MUST WORK JUST FINE) :

```<code>package Airline;
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer.Context;
public class airlineMapper extends
Mapper<LongWritable,Text,Text,IntWritable> {
Text gender = new Text();
IntWritable age = new IntWritable();

protected void map(LongWritable key,Text value,Context context)throws
IOException, InterruptedException {
    String inputstring = value.toString();
       String str[]=inputstring.split(",");
             if(str.length==12){
                 gender.set(str[4]);
             if(str[1].equals("0") ){
               if(str[5].matches("\\d+")){
                  int i=Integer.parseInt(str[5]);
                    age.set(i);
        }
       }
     }
        context.write(gender, age);

     //String inputstring = value.toString();
     // String[] str = inputstring.split(",");
     // IntWritable resKEY = new IntWritable();
     // Text resVALUE = new Text();
     //
     // int bool = Integer.parseInt(str[1]);
     // if (bool == 1 && str[5].length() >= 1){
     //     resVALUE.set(str[5]);
     //     resKEY.set(bool);
     // context.write(resKEY,resVALUE);
     // }
      }}
</code>```

Airline.airlineReducer (THE IMPORTANT THING TO NOTICE IN THE PREVIOUS MAP-REDUCE CODE IS, I TRIED TO CHECK THE STRING IN REDUCER PHASE, WHICH SHOULD BE DONE IN THE MAPPER PHASE ITSELF. as @RAMESHMAHARJAN pointed out before) :

```<code>package Airline;
import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
public class airlineReducer extends Reducer<Text,IntWritable, Text,
IntWritable> {

@Override
public void reduce( Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
    int sum = 0;
     int total_people=0;
     for (IntWritable val : values) {
     total_people+=1;
     sum += val.get();
     }
     sum=sum/total_people;
     context.write(key, new IntWritable(sum));

    //float y = 0;
    //float avgage =0;
    //int counter = 0;
    //String a = "Average age";
    //Text resKEY = new Text();
    //FloatWritable resVALUE = new FloatWritable();
    //  for(Text x : values)
    //  {
    //      String z = x.toString();
    //
    //      y +=Float.parseFloat(z);
    //      counter++;
    //
    //
    //  }
    //  avgage = y/counter;
    //  resKEY.set(a);
    //  resVALUE.set(avgage);
    //  context.write(resKEY, resVALUE );

}
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run a map reducer in java for a comma separated file containing data about an AIRLINE which crashed.

The data contains the following columns and a sample data is also provided :

passengerid,survived(s=0,d=1),pclass,name,sex,age,sibsp,parch,ticket,fare,cabin,embarked
1,0,3,"Braund Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S,2,1,1,"Cumings Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C,
3,1,3,"Heikkinen Miss. Laina",female,26,0,0,STON/O2. 3101282,7.925,,S,
4,1,1,"Futrelle Mrs. Jacques Heath (Lily May Peel)",female,35,1,0,113803,53.1,C123,S,
5,0,3,"Allen Mr. William Henry",male,35,0,0,373450,8.05,,S,
6,0,3,"Moran Mr. James",male,,0,0,330877,8.4583,,Q,
7,0,1,"McCarthy Mr. Timothy J",male,54,0,0,17463,51.8625,E46,S,
8,0,3,"Palsson Master. Gosta Leonard",male,2,3,1,349909,21.075,,S,
9,1,3,"Johnson Mrs. Oscar W (Elisabeth Vilhelmina Berg)",female,27,0,2,347742,11.1333,,S,
10,1,2,"Nasser Mrs. Nicholas (Adele Achem)",female,14,1,0,237736,30.0708,,C,
11,1,3,"Sandstrom Miss. Marguerite Rut",female,4,1,1,PP 9549,16.7,G6,S,
12,1,1,"Bonnell Miss. Elizabeth",female,58,0,0,113783,26.55,C103,S,
...

My objective is to find the average age of people died in this crash.
Here's my code snippets and the errors i encountered:

Airline.airlineDriver.java:

package Airline;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import Airline.airlineMapper;
import Airline.airlineReducer;

public class airlineDriver {

public static void main(String[] args) throws IOException,
ClassNotFoundException, InterruptedException, URISyntaxException {
    // TODO Auto-generated method stub
    Configuration conf = new Configuration();

    Job j = Job.getInstance(conf);// getConf()
    j.setJobName("Airline Job");
    j.setJarByClass(airlineDriver.class );
    j.setMapperClass(airlineMapper.class );
    j.setNumReduceTasks(2);
    j.setReducerClass(airlineReducer.class);
    j.setMapOutputKeyClass(IntWritable.class);
    j.setMapOutputValueClass(Text.class);
    j.setOutputKeyClass(Text.class);
    j.setOutputValueClass(FloatWritable.class);

    FileInputFormat.addInputPath(j, new Path(args[0]));
    FileOutputFormat.setOutputPath(j, new Path(args[1]));

    System.exit(j.waitForCompletion(true) ? 0 : 1);
   }

  }

Airline.airlineMapper.java:

package Airline;
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class airlineMapper extends Mapper<LongWritable,  Text,
IntWritable,Text> {
@Override
protected void map(LongWritable key, Text
value,org.apache.hadoop.mapreduce.Mapper.Context context)throws IOException,
InterruptedException {
    String inputstring = value.toString(); //converts input Text value to String
    IntWritable resKEY = new IntWritable();
    Text resVALUE = new Text();
    String str[] = inputstring.split(","); //splits it into array
    int bool = Integer.parseInt(str[1]); //fetch survived(s=0) or dead(d=1)
    if (bool == 1){
        resVALUE.set(str[5]);
        resKEY.set(bool);
        context.write(resKEY,resVALUE); //write key value pair to partitioner and reducer
}  }
}

Airline.airlineReducer.java :

package Airline;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
public class airlineReducer extends Reducer<IntWritable,Text, Text,
FloatWritable> {

@Override
public void reduce(IntWritable key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
    float y = 0;  //numerator for avgage
    float avgage =0;
    int counter = 0;  //denominator for avgage
    String a = "Average age";
    for(Text x : values)  //passes value to x one-by-one
    {
        String z = x.toString();   //converts text to string
        if((!z.equals(""))&&(!z.equals(null))){  //eliminating any empty string (**possible source of error)
        y +=Float.parseFloat(z);  //converting age to float since csf contains floating point ages
        counter++; //incrementing counter for total no. of people(records)

    }else{continue;  //if a null or empty string is encountered loop may skip the iteration and continue to next record
    //in case few fields are left empty
    }//**possible source of error
        }
    avgage = y/counter;    //average formula
    context.write(new Text(a), new FloatWritable(avgage) ); //wirting output data

    }
    }

Even on making repeated changes in code i am still getting errors like:

Error: java.lang.ArrayIndexOutOfBoundsException: 1
at Airline.airlineMapper.map(airlineMapper.java:18)
at Airline.airlineMapper.map(airlineMapper.java:1)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs
(UserGroupInformation.java:1693)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)

plz help

Body:
As @RameshMaharjan answered The correct mapper and reducer class would be:

Airline.airlineMapper (THE CODE WHICH I MENTIONED BEFORE IS ALSO COMMENTED BELOW. THESE CHECKS str.length==12 and str[5].matches("\\d+") CAN BE USED WITH THE PREVIOUS CODE AND IT MUST WORK JUST FINE) :

package Airline;
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer.Context;
public class airlineMapper extends
Mapper<LongWritable,Text,Text,IntWritable> {
Text gender = new Text();
IntWritable age = new IntWritable();

protected void map(LongWritable key,Text value,Context context)throws
IOException, InterruptedException {
    String inputstring = value.toString();
       String str[]=inputstring.split(",");
             if(str.length==12){
                 gender.set(str[4]);
             if(str[1].equals("0") ){
               if(str[5].matches("\\d+")){
                  int i=Integer.parseInt(str[5]);
                    age.set(i);
        }
       }
     }
        context.write(gender, age);

     //String inputstring = value.toString();
     // String[] str = inputstring.split(",");
     // IntWritable resKEY = new IntWritable();
     // Text resVALUE = new Text();
     //
     // int bool = Integer.parseInt(str[1]);
     // if (bool == 1 && str[5].length() >= 1){
     //     resVALUE.set(str[5]);
     //     resKEY.set(bool);
     // context.write(resKEY,resVALUE);
     // }
      }}

Airline.airlineReducer (THE IMPORTANT THING TO NOTICE IN THE PREVIOUS MAP-REDUCE CODE IS, I TRIED TO CHECK THE STRING IN REDUCER PHASE, WHICH SHOULD BE DONE IN THE MAPPER PHASE ITSELF. as @RAMESHMAHARJAN pointed out before) :

package Airline;
import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
public class airlineReducer extends Reducer<Text,IntWritable, Text,
IntWritable> {

@Override
public void reduce( Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
    int sum = 0;
     int total_people=0;
     for (IntWritable val : values) {
     total_people+=1;
     sum += val.get();
     }
     sum=sum/total_people;
     context.write(key, new IntWritable(sum));

    //float y = 0;
    //float avgage =0;
    //int counter = 0;
    //String a = "Average age";
    //Text resKEY = new Text();
    //FloatWritable resVALUE = new FloatWritable();
    //  for(Text x : values)
    //  {
    //      String z = x.toString();
    //
    //      y +=Float.parseFloat(z);
    //      counter++;
    //
    //
    //  }
    //  avgage = y/counter;
    //  resKEY.set(a);
    //  resVALUE.set(avgage);
    //  context.write(resKEY, resVALUE );

}
}


问:
How to change global variable when you change parameter
What am I doing wrong here? The solution works but the first instance when you change the type_name I can see it hits the if statement but the counter still goes to +1 previous count.

```<code>type_name = "bar"
counter = 1

class Foo(object):
    """
    if type is different in the argument, reset counter to 0.
    Otherwise increament counter by 1.
    """

    def __init__(self, model_name):
        self.model_name = model_name
        self.counter = counter
        self.reset()

    def reset(self):
        global counter, type_name
        print self.model_name, type_name
        if type_name != self.model_name:
            print "here..."
            counter = 1
            type_name = self.model_name
            print counter
        else:
            counter += 1
        print type_name

print "--------------------------"
d = Foo("bar")
print d.counter

print "--------------------------"
new_instances = []
for i in range(0, 10):
    new_instances.append(Foo("bar"))

print new_instances[5].counter
print new_instances[8].counter

print "-------------------------- taste starts here ... "
c = Foo("test")
print c.counter

print "--------------------------"
e = Foo("test")
print e.counter

print "--------------------------"
f = Foo("test")
print f.counter

print "--------------------------"
dd = Foo("bar")
print dd.counter

print "--------------------------"
ddd = Foo("bar")
</code>```

I want to reset count whenever I change the type_name.

答:
You're reseting the global counter but accessing the instance variable self.counter which was set at __init__; at an earlier time. reset is only called afterwards. You should reset both in your reset method:

```<code>def reset(self):
    ...
    self.counter = counter = 1
</code>```

On another note, I don't see why you need global here. You can make counter and type_name class variables and reset them when you need to. You'll then only have to deal with one counter at a time: that on the instance or that on the class.

Body:
What am I doing wrong here? The solution works but the first instance when you change the type_name I can see it hits the if statement but the counter still goes to +1 previous count.

type_name = "bar"
counter = 1

class Foo(object):
    """
    if type is different in the argument, reset counter to 0.
    Otherwise increament counter by 1.
    """

    def __init__(self, model_name):
        self.model_name = model_name
        self.counter = counter
        self.reset()

    def reset(self):
        global counter, type_name
        print self.model_name, type_name
        if type_name != self.model_name:
            print "here..."
            counter = 1
            type_name = self.model_name
            print counter
        else:
            counter += 1
        print type_name

print "--------------------------"
d = Foo("bar")
print d.counter

print "--------------------------"
new_instances = []
for i in range(0, 10):
    new_instances.append(Foo("bar"))

print new_instances[5].counter
print new_instances[8].counter

print "-------------------------- taste starts here ... "
c = Foo("test")
print c.counter

print "--------------------------"
e = Foo("test")
print e.counter

print "--------------------------"
f = Foo("test")
print f.counter

print "--------------------------"
dd = Foo("bar")
print dd.counter

print "--------------------------"
ddd = Foo("bar")

I want to reset count whenever I change the type_name.

Body:
You're reseting the global counter but accessing the instance variable self.counter which was set at __init__; at an earlier time. reset is only called afterwards. You should reset both in your reset method:

def reset(self):
    ...
    self.counter = counter = 1

On another note, I don't see why you need global here. You can make counter and type_name class variables and reset them when you need to. You'll then only have to deal with one counter at a time: that on the instance or that on the class.


问:
How to open an local pdf using InAppBrowser
I have downloaded an pdf file from the server using Transfer Plugin and i am trying to open the file using InAppBrower plugin i am not getting anything. i mean nothing is happening.

```<code>fileTransfer.download(url, this.file.dataDirectory + file.filename,false,{
        headers: {
            'authorization': 'bearer xxxx'
        }
    }).then((entry) => {
      console.log('download complete: ' + entry.toURL());
      console.log(entry.nativeURL);
      const browser = this.iab.create(entry.nativeURL, '_system', 'location=yes'); //here the inappbrowser plugin code.
    }, (error) => {
      // handle error
      console.log(error);
      console.log('ERROR');
    });
</code>```

my console.log(entry.nativeURL); prints this path file:///data/user/0/com.schneider.and/files/Attendance_Policy_Ver_1.0.pdf

答:
Try putting the nativeUrl in the browserURL and see if you could jump to the exact .pdf....

Then try

fileTransfer.download(url, this.file.dataDirectory + file.filename,false,{
        headers: {
            'authorization': 'bearer xxxx'
        }
    }).then((entry) => {
      console.log('download complete: ' + entry.toURL());
      console.log(entry.nativeURL);
      let browser=new InApp Browser(entry.nativeURL,'_blank');
    }, (error) => {
      // handle error
      console.log(error);
      console.log('ERROR');
    });```
</div>
</div>
</p>

<p>And import InAppBrowser from  'ionic-native'</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import {InAppBrowser} from 'ionic-native';</code>```

Body:
I have downloaded an pdf file from the server using Transfer Plugin and i am trying to open the file using InAppBrower plugin i am not getting anything. i mean nothing is happening.

fileTransfer.download(url, this.file.dataDirectory + file.filename,false,{
        headers: {
            'authorization': 'bearer xxxx'
        }
    }).then((entry) => {
      console.log('download complete: ' + entry.toURL());
      console.log(entry.nativeURL);
      const browser = this.iab.create(entry.nativeURL, '_system', 'location=yes'); //here the inappbrowser plugin code.
    }, (error) => {
      // handle error
      console.log(error);
      console.log('ERROR');
    });

my console.log(entry.nativeURL); prints this path file:///data/user/0/com.schneider.and/files/Attendance_Policy_Ver_1.0.pdf

Body:
Try putting the nativeUrl in the browserURL and see if you could jump to the exact .pdf....

Then try

fileTransfer.download(url, this.file.dataDirectory + file.filename,false,{
        headers: {
            'authorization': 'bearer xxxx'
        }
    }).then((entry) => {
      console.log('download complete: ' + entry.toURL());
      console.log(entry.nativeURL);
      let browser=new InApp Browser(entry.nativeURL,'_blank');
    }, (error) => {
      // handle error
      console.log(error);
      console.log('ERROR');
    });

And import InAppBrowser from  'ionic-native'

import {InAppBrowser} from 'ionic-native';


问:
Can't echo value in file python
For example, I have a file python

work1.py

```<code>from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)
</code>```

And i have a file php to run file python via shell_exec function

```<code> <?php
$result=shell_exec("sudo python work1.py");
echo $result;
?>
</code>```

But when i run, nothing display. So what's problem? Please help me. Thanks.

答:
Try it like this:</p>

```<code><?php
$result= shell_exec(sudo /usr/bin/python3 work1.py);
echo $result;
?>
</code>```

Title: Can't echo value in file python

Body:
For example, I have a file python

work1.py

from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)

And i have a file php to run file python via shell_exec function

 <?php
$result=shell_exec("sudo python work1.py");
echo $result;
?>

But when i run, nothing display. So what's problem? Please help me. Thanks.

Body:
Try it like this:

<?php
$result= shell_exec(sudo /usr/bin/python3 work1.py);
echo $result;
?>


问:
Scraping an alt tag using Python and BeautifulSoup
New to Python, and BeautifulSoup and I am trying to scrape the number of stars that a reviewer leaves a restaurant on Yelp.

So far, I have the following code:

```<code>import requests
from bs4 import BeautifulSoup as soup

url = "https://www.yelp.com/biz/monkey-house-cafe-huntington-beach"
r = requests.get(url)
page_soup = soup(r.content, "lxml")

review_container = page_soup.findAll("div", {"class": "review-content"})
review_container[0]
</code>```

When I run that code in Jupyter Notebook, I get the following, that corresponds to the most recent review:

```<code><div class="review-content">
<div class="biz-rating biz-rating-large clearfix">
<div>
<div class="i-stars i-stars--regular-5 rating-large" title="5.0 star rating">
<img alt="5.0 star rating" class="offscreen" height="303" src="https://s3-media1.fl.yelpcdn.com/assets/srv0/yelp_design_web/41341496d9db/assets/img/stars/stars.png" width="84"/>
</div>
</div>
<span class="rating-qualifier">
    5/10/2017
</span>
</div>
<p lang="en">This place is really fun and cute. I was happy to discover it.. <br/><br/>They also have beer and wine here, which is kind of a nice bonus. The sangria is good..</p>
</div>
</code>```

My question is how can I get the number of stars from each review?

I am thinking that it would be best to scrape the contents of the img alt tag but I am not sure how to do this.

Body:
New to Python, and BeautifulSoup and I am trying to scrape the number of stars that a reviewer leaves a restaurant on Yelp.

So far, I have the following code:

import requests
from bs4 import BeautifulSoup as soup

url = "https://www.yelp.com/biz/monkey-house-cafe-huntington-beach"
r = requests.get(url)
page_soup = soup(r.content, "lxml")

review_container = page_soup.findAll("div", {"class": "review-content"})
review_container[0]

When I run that code in Jupyter Notebook, I get the following, that corresponds to the most recent review:

    5/10/2017

This place is really fun and cute. I was happy to discover it..

They also have beer and wine here, which is kind of a nice bonus. The sangria is good..

My question is how can I get the number of stars from each review?

I am thinking that it would be best to scrape the contents of the img alt tag but I am not sure how to do this.

Body: float(review_container[0].find("img")["alt"][:3])


答:
```<code>$result=shell_exec(sudo python work1.py);
</code>```

I think a syntax error occurs here, you may try:

```<code>$result=shell_exec('sudo python work1.py');
</code>```

Title: Can't echo value in file python

Body:
$result=shell_exec(sudo python work1.py);

I think a syntax error occurs here, you may try:

$result=shell_exec('sudo python work1.py');