问:
How to update customer TIN Number in Opencart
Am new in OpenCart MVC, I have page called my_account.tpl. In this page am displaying customer name and tin_number.

If customers want to change their tin_number just fill the TIN Number field and click save, it will update oc_customer tabel.

I tried but data's not update.

Following view, model, and controller codes

View: my_account.tpl

```<code><form action="<?php echo $action;?>" method="POST" enctype="multipart/form-data" class="form-horizontal">
            <div class="col-md-9 col-lg-6 col-sm-12">

                <?php foreach($customerData as $customer) { ?>

                <div class="form-group">
                    <label>Name:</label>
                    <input type="text" style="display: none" placeholder="ID" name="id" value="<?php echo $result['tin_number'];?>">
                    <input type="text" name="name" value="<?php echo $customer['name']; ?>" placeholder="Name" class="form-control" disabled>
                </div>

                <div class="form-group">
                    <label>TIN Number:</label>
                    <input type="text" name="tin_number" value="<?php echo $customer['tin_number']; ?>" placeholder="TIN Number" class="form-control">
                </div>

                <?php } ?>
                <div class="form-group">
                    <input type="submit" name="save" value="<?php echo 'Save'; ?>" class="btn btn-primary">
                </div>

            </div>
        </form>
</code>```

Controller: my_account.php

```<code>public function edit() {

        /*form edit my_account*/
         if(isset($_GET['tin_number']))
        {
            $tin_number=$_GET['tin_number'];
        }
        $this->load->model('account/customer');
        $data['delivery_point']=$this->model_account_customer->getcustomerId($tin_number);
        $data['action'] = $this->url->link('account/my_account', '', 'SSL');

        if ($this->request->server['REQUEST_METHOD'] == 'POST')
        {
            $this->model_account_customer->editCustomerTin($this->request->post);
            $this->response->redirect($this->url->link('account/home', '', 'SSL'));
            echo "<script>javascript: alert('test msgbox')></script>";
        }
        /*form edit my_account*/

}
</code>```

Model: my_account.php

```<code>public function editCustomerTin($data)
    {
         $query = $this->db->query("UPDATE " . DB_PREFIX . "customer set tin_number='".$data['tin_number']."' where customer_id=".$data['id']);
    }
</code>```

答:
I got the answer it working in another function see below the coding

controller my_account.php

```<code> public function index() {

        $this->load->language('account/account');
        $this->document->setTitle($this->language->get('heading_title'));

        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('Home'),
            'href' => $this->url->link('common/home')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('Previous'),
            'href' => $this->url->link('common/home', '', 'SSL')
        );

        if (isset($this->session->data['success'])) {
            $data['success'] = $this->session->data['success'];

            unset($this->session->data['success']);
        } else {
            $data['success'] = '';
        }

        $data['heading_title'] = $this->language->get('heading_title');
        $url = '';

        $this->load->model('account/customer');

        //$data['customerData']=array();
        $results=$this->model_account_customer->getCustomerByTin();

        foreach($results as $result)
        {

        $query1 = $this->db->query("SELECT concat(firstname,' ',lastname) as name,tin_number,invoice_no_overwrite FROM " . DB_PREFIX . "customer where customer_id='".$_COOKIE['customerId']."'");
        $customer_name= $query1->row['name'];
        $tin_number= $query1->row['tin_number'];
        $invoice_no_overwrite= $query1->row['invoice_no_overwrite'];

            $data['customerData'][0] = array(
                'name'      => $customer_name,
                'invoice_no_overwrite'=> $invoice_no_overwrite,
                'tin_number'=>$tin_number
                );
        }

        //var_dump($data['CustomerData']);

        /*form edit my_account*/
        if ($this->request->server['REQUEST_METHOD'] == 'POST')
        {
           $this->model_account_customer->editCustomerTin($this->request->post);
            $this->response->redirect($this->url->link('account/my_account', '', 'SSL'));
        }

        /*form edit my_account*/

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/my_account.tpl')) {
            $this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/my_account.tpl', $data));
        } else {
            $this->response->setOutput($this->load->view('default/template/account/my_account.tpl', $data));
        }

    }
</code>```

I don't know how its happen can any one teach me...?

Body:
Am new in OpenCart MVC, I have page called my_account.tpl. In this page am displaying customer name and tin_number.

If customers want to change their tin_number just fill the TIN Number field and click save, it will update oc_customer tabel.

I tried but data's not update.

Following view, model, and controller codes

View: my_account.tpl

<form action="<?php echo $action;?>" method="POST" enctype="multipart/form-data" class="form-horizontal">

                <?php foreach($customerData as $customer) { ?>

                    Name:
                    <input type="text" style="display: none" placeholder="ID" name="id" value="<?php echo $result['tin_number'];?>">
                    <input type="text" name="name" value="<?php echo $customer['name']; ?>" placeholder="Name" class="form-control" disabled>

                    TIN Number:
                    <input type="text" name="tin_number" value="<?php echo $customer['tin_number']; ?>" placeholder="TIN Number" class="form-control">

                <?php } ?>

                    <input type="submit" name="save" value="<?php echo 'Save'; ?>" class="btn btn-primary">

        </form>

Controller: my_account.php

public function edit() {

        /*form edit my_account*/
         if(isset($_GET['tin_number']))
        {
            $tin_number=$_GET['tin_number'];
        }
        $this->load->model('account/customer');
        $data['delivery_point']=$this->model_account_customer->getcustomerId($tin_number);
        $data['action'] = $this->url->link('account/my_account', '', 'SSL');

        if ($this->request->server['REQUEST_METHOD'] == 'POST')
        {
            $this->model_account_customer->editCustomerTin($this->request->post);
            $this->response->redirect($this->url->link('account/home', '', 'SSL'));
            echo "";
        }
        /*form edit my_account*/

}

Model: my_account.php

public function editCustomerTin($data)
    {
         $query = $this->db->query("UPDATE " . DB_PREFIX . "customer set tin_number='".$data['tin_number']."' where customer_id=".$data['id']);
    }

Body:
I got the answer it working in another function see below the coding

controller my_account.php

 public function index() {

        $this->load->language('account/account');
        $this->document->setTitle($this->language->get('heading_title'));

        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('Home'),
            'href' => $this->url->link('common/home')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('Previous'),
            'href' => $this->url->link('common/home', '', 'SSL')
        );

        if (isset($this->session->data['success'])) {
            $data['success'] = $this->session->data['success'];

            unset($this->session->data['success']);
        } else {
            $data['success'] = '';
        }

        $data['heading_title'] = $this->language->get('heading_title');
        $url = '';

        $this->load->model('account/customer');

        //$data['customerData']=array();
        $results=$this->model_account_customer->getCustomerByTin();

        foreach($results as $result)
        {

        $query1 = $this->db->query("SELECT concat(firstname,' ',lastname) as name,tin_number,invoice_no_overwrite FROM " . DB_PREFIX . "customer where customer_id='".$_COOKIE['customerId']."'");
        $customer_name= $query1->row['name'];
        $tin_number= $query1->row['tin_number'];
        $invoice_no_overwrite= $query1->row['invoice_no_overwrite'];

            $data['customerData'][0] = array(
                'name'      => $customer_name,
                'invoice_no_overwrite'=> $invoice_no_overwrite,
                'tin_number'=>$tin_number
                );
        }

        //var_dump($data['CustomerData']);

        /*form edit my_account*/
        if ($this->request->server['REQUEST_METHOD'] == 'POST')
        {
           $this->model_account_customer->editCustomerTin($this->request->post);
            $this->response->redirect($this->url->link('account/my_account', '', 'SSL'));
        }

        /*form edit my_account*/

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/my_account.tpl')) {
            $this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/my_account.tpl', $data));
        } else {
            $this->response->setOutput($this->load->view('default/template/account/my_account.tpl', $data));
        }

    }

I don't know how its happen can any one teach me...?


来源: stackexchange

问:
Dismissing the keyboard when a button is pressed, programmatically with swift?
How can I dismiss the keyboard when a button is pressed, programmatically with swift? </p>

答:
Setting the UITextfield delegate programmatically swift 2.2
Add UITextFieldDelegate in your class.

https://stackoverflow.com/a/31689406/5576747

ContentLicense: CC BY-SA 3.0


问:
Transform array by cutting in half but extend elements
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

```<code># source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]
</code>```

How would you achieve it?

答:
```<code>s = [[1, 'blue'], [2, 'red'], [3, 'yellow'], [4, 'green'], [5, 'orange'], [6, 'black']]

# Split into two sections
s1 = s[0...s.length/2]
s2 = s[s.length/2..-1]

# Compile
p s1.each_with_index.map { |x, i| x + s2[i] }
#[[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]
</code>```

Body:
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

# source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]

How would you achieve it?


问:
setting string properties in js
Is it possible to somehow attach additional properties to strings in js? I am picturing something along the lines of

```<code>var s = "Hello World";
s.x = 'bar';

console.log(s.x);
</code>```

Unfortunately, s.x is undefined after the assignment.

I know this question seems a little of. Why would you want to attach additional properties to a string after all? In my case the reasoning is as following: I am using a (questionably designed) library, which provides a function to create an xhr request given an url. The url is then passed to a callback function with the result.

Picture the library (xhr-function) similar to:

```<code>var xhr = function(url, cb){
    $.ajax({
        url: url,
        success: function(data){
            // do library stuff

            // my code goes here
        }
    })
}
</code>```

Part of the framework is, that the callback function is not passed as a function but copied into the success handler body. This way I am able to access the url parameter in the my code goes here-section.

Now in my cb-handler, I need additional data other than just the url. Is there a way to hack this on to the url parameter? Unfortunately I can't change the library :(

I was planning to do something like:

```<code>var xhr = function(url, cb){
    $.ajax({
        url: url,
        success: function(data){
            // do library stuff

            // my code goes here
            // access url.foo
        }
    })
}

var url = 'https://example.com'
url.foo = 'bar'
xhr(url);
</code>```

答:
according to  skilldrick on duplicate SO Question why can i add new attr to string obj

```<code>var s = new String("hello world!");
s.x = 5;
console.log(s.x); //5
console.log(s); //[object Object]
console.log(s.toString()); //hello world!
</code>```

I still wouldn't advice it tho; (not exactly intuitive behaviour)

Title: setting string properties in js

Body:
Is it possible to somehow attach additional properties to strings in js? I am picturing something along the lines of

var s = "Hello World";
s.x = 'bar';

console.log(s.x);

Unfortunately, s.x is undefined after the assignment.

I know this question seems a little of. Why would you want to attach additional properties to a string after all? In my case the reasoning is as following: I am using a (questionably designed) library, which provides a function to create an xhr request given an url. The url is then passed to a callback function with the result.

Picture the library (xhr-function) similar to:

var xhr = function(url, cb){
    $.ajax({
        url: url,
        success: function(data){
            // do library stuff

            // my code goes here
        }
    })
}

Part of the framework is, that the callback function is not passed as a function but copied into the success handler body. This way I am able to access the url parameter in the my code goes here-section.

Now in my cb-handler, I need additional data other than just the url. Is there a way to hack this on to the url parameter? Unfortunately I can't change the library :(

I was planning to do something like:

var xhr = function(url, cb){
    $.ajax({
        url: url,
        success: function(data){
            // do library stuff

            // my code goes here
            // access url.foo
        }
    })
}

var url = 'https://example.com'
url.foo = 'bar'
xhr(url);

Body:
according to  skilldrick on duplicate SO Question why can i add new attr to string obj

var s = new String("hello world!");
s.x = 5;
console.log(s.x); //5
console.log(s); //[object Object]
console.log(s.toString()); //hello world!

I still wouldn't advice it tho; (not exactly intuitive behaviour)


问:
TensorFlow : Error building pip package
I am trying to build TensorFlow from source. After configuring the installation, when I try to build to the pip package with the following command,

$ bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package

I get the following error message:

```<code>ERROR: /workspace/tensorflow/core/BUILD:1312:1: Executing genrule //tensorflow/core:version_info_gen failed: bash failed: error executing command
(cd /root/.cache/bazel/_bazel_root/eab0d61a99b6696edb3d2aff87b585e8/execroot/workspace && \
exec env - \
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
/bin/bash -c 'source external/bazel_tools/tools/genrule/genrule-setup.sh; tensorflow/tools/git/gen_git_source.py --generate tensorflow/tools/git/gen
/spec.json tensorflow/tools/git/gen/head tensorflow/tools/git/gen/branch_ref "bazel-out/host/genfiles/tensorflow/core/util/version_info.cc"'): com.goo
gle.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
Traceback (most recent call last):
File "tensorflow/tools/git/gen_git_source.py", line 260, in <module>
generate(args.generate)
File "tensorflow/tools/git/gen_git_source.py", line 212, in generate
git_version = get_git_version(data["path"])
File "tensorflow/tools/git/gen_git_source.py", line 152, in get_git_version
str("--work-tree=" + git_base_path), "describe", "--long", "--tags"
File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Target //tensorflow/tools/pip_package:build_pip_package failed to build
INFO: Elapsed time: 8.567s, Critical Path: 7.90s
</code>```

What's going wrong?

(Ubuntu 14.04, CPU only)

答:
Your build appears to be encountering an error in

```<code>tensorflow/tools/git/gen_git_source.py
</code>```

at line 152. At this stage in the build the script is trying to get the git version number of your tensor flow repo. Have you used git to check out your tensor flow repo? Are the .git files present in the /tensorflow/ root dir? Maybe you need to update your version of git?

Looks similar to this question: Build Error Tensorflow

Title: TensorFlow : Error building pip package

Body:
I am trying to build TensorFlow from source. After configuring the installation, when I try to build to the pip package with the following command,

$ bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package

I get the following error message:

ERROR: /workspace/tensorflow/core/BUILD:1312:1: Executing genrule //tensorflow/core:version_info_gen failed: bash failed: error executing command
(cd /root/.cache/bazel/_bazel_root/eab0d61a99b6696edb3d2aff87b585e8/execroot/workspace && \
exec env - \
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
/bin/bash -c 'source external/bazel_tools/tools/genrule/genrule-setup.sh; tensorflow/tools/git/gen_git_source.py --generate tensorflow/tools/git/gen
/spec.json tensorflow/tools/git/gen/head tensorflow/tools/git/gen/branch_ref "bazel-out/host/genfiles/tensorflow/core/util/version_info.cc"'): com.goo
gle.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
Traceback (most recent call last):
File "tensorflow/tools/git/gen_git_source.py", line 260, in <module>
generate(args.generate)
File "tensorflow/tools/git/gen_git_source.py", line 212, in generate
git_version = get_git_version(data["path"])
File "tensorflow/tools/git/gen_git_source.py", line 152, in get_git_version
str("--work-tree=" + git_base_path), "describe", "--long", "--tags"
File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Target //tensorflow/tools/pip_package:build_pip_package failed to build
INFO: Elapsed time: 8.567s, Critical Path: 7.90s

What's going wrong?

(Ubuntu 14.04, CPU only)

Body:
Your build appears to be encountering an error in

tensorflow/tools/git/gen_git_source.py

at line 152. At this stage in the build the script is trying to get the git version number of your tensor flow repo. Have you used git to check out your tensor flow repo? Are the .git files present in the /tensorflow/ root dir? Maybe you need to update your version of git?

Looks similar to this question: Build Error Tensorflow


问:
SSHA password encryption on OpenLDAP
My current problem is that i cannot stop OpenLDAP to store passwords as plaintext. In an older openLDAP version , i entered following configuration in the slapd.conf

```<code>ppolicy_hash_cleartext
password-hash {SSHA} {SHA}
</code>```

So once a password was sent from my application as plaintext, the ldap was encrypting it and storing it encrypted.

Unfortunately i was not able to configure OpenLDAP 2.4.40. I found out that the slapd.conf does not exist anymore in the newer version and instead the configuration is taking place in the cn=config.ldif file.

I tried to add again the same configuration there but it seems that it has no effect.

EDIT : I added with ldapmodify the olcPasswordHash: {SSHA} entry in olcBackend={0}mdb.ldif , olcDatabase={1}mdb.ldif , olcDatabase={0}config.ldif and cn=config.ldif , still my passwords that are sent as plaintext are stored as plaintext.

答:
Took some time, but figured out finally.

Load schema describing ppolicy attributes.

```<code>ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/ppolicy.ldif
</code>```

Create a ppolicy_module.ldif with the following content and make sure that the ppolicy.la is located under the defined olcModulePath. Store the file under /etc/ldap

```<code>dn: cn=module,cn=config
objectClass: olcModuleList
cn: module
olcModuleLoad: ppolicy.la
olcModulePath: /usr/lib/ldap
</code>```

Add the ppolicy_module.ldif

```<code>ldapadd -Y EXTERNAL -H ldapi:/// -f ppolicy_module.ldif
</code>```

Create a ppolicy-overlay.ldif file with the following content. Make sure of the olcDatabase number . In this case it is olcDatabase={1}mdb . Store the file under /etc/ldap

```<code>dn: olcOverlay=ppolicy,olcDatabase={1}mdb,cn=config
objectClass: olcPPolicyConfig
olcOverlay: ppolicy
olcPPolicyDefault: cn=ppolicy,ou=policies,dc=example,dc=com
olcPPolicyUseLockout: FALSE
olcPPolicyHashCleartext: TRUE
</code>```

Add LDIF file.

```<code>ldapadd -Y EXTERNAL -H ldapi:/// -f ./ppolicy-overlay.ldif
</code>```

Restart ldap.

More details under:
https://fedorahosted.org/sssd/wiki/openldap_ppolicy

Title: SSHA password encryption on OpenLDAP

Body:
My current problem is that i cannot stop OpenLDAP to store passwords as plaintext. In an older openLDAP version , i entered following configuration in the slapd.conf

ppolicy_hash_cleartext
password-hash {SSHA} {SHA}

So once a password was sent from my application as plaintext, the ldap was encrypting it and storing it encrypted.

Unfortunately i was not able to configure OpenLDAP 2.4.40. I found out that the slapd.conf does not exist anymore in the newer version and instead the configuration is taking place in the cn=config.ldif file.

I tried to add again the same configuration there but it seems that it has no effect.

EDIT : I added with ldapmodify the olcPasswordHash: {SSHA} entry in olcBackend={0}mdb.ldif , olcDatabase={1}mdb.ldif , olcDatabase={0}config.ldif and cn=config.ldif , still my passwords that are sent as plaintext are stored as plaintext.

Body:
Took some time, but figured out finally.

Load schema describing ppolicy attributes.

ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/ppolicy.ldif

Create a ppolicy_module.ldif with the following content and make sure that the ppolicy.la is located under the defined olcModulePath. Store the file under /etc/ldap

dn: cn=module,cn=config
objectClass: olcModuleList
cn: module
olcModuleLoad: ppolicy.la
olcModulePath: /usr/lib/ldap

Add the ppolicy_module.ldif

ldapadd -Y EXTERNAL -H ldapi:/// -f ppolicy_module.ldif

Create a ppolicy-overlay.ldif file with the following content. Make sure of the olcDatabase number . In this case it is olcDatabase={1}mdb . Store the file under /etc/ldap

dn: olcOverlay=ppolicy,olcDatabase={1}mdb,cn=config
objectClass: olcPPolicyConfig
olcOverlay: ppolicy
olcPPolicyDefault: cn=ppolicy,ou=policies,dc=example,dc=com
olcPPolicyUseLockout: FALSE
olcPPolicyHashCleartext: TRUE

Add LDIF file.

ldapadd -Y EXTERNAL -H ldapi:/// -f ./ppolicy-overlay.ldif

Restart ldap.

More details under:
https://fedorahosted.org/sssd/wiki/openldap_ppolicy


问:
Looping nested array Object in ListView React native
I currently trying to play around with react-native..

I want to make a list view that get the dataSource from var which contain an object that have nested array inside.

var questionArray = [
  {
    question: "What is the emotion of the user? choose all that apply!",
    answerArray: [
      { name: "Cheerful", status: true, answered: false },
      { name: "Impulsive", status: false, answered: false },
      { name: "Firm", status: false, answered: false },
      { name: "Merry", status: true, answered: false },
      { name: "Jumpy", status: false, answered: false },
      { name: "Energetic", status: false, answered: false },
      { name: "Glowing", status: false, answered: false },
      { name: "Animated", status: false, answered: false },
      { name: "Lively", status: false, answered: false },
      { name: "Creepy", status: false, answered: false },
      { name: "Excited", status: true, answered: false },
      { name: "Tense", status: false, answered: false },
      { name: "Unrestful", status: false, answered: false },
      { name: "Pleased", status: true, answered: false },
      { name: "Unrestful", status: false, answered: false },
      { name: "Hasty", status: false, answered: false },
      { name: "Delighted", status: true, answered: false },
      { name: "Hedonistic", status: false, answered: false },
      { name: "Eager", status: false, answered: false },
      { name: "Joyful", status: false, answered: false },
    ]
  },
  {
    question: "What is the best way to describe this person's character? Choose all that apply.",
answerArray: [
      { name: "Cheerful", status: true, answered: false },
      { name: "Impulsive", status: false, answered: false },
      { name: "Firm", status: false, answered: false },
      { name: "Merry", status: true, answered: false },
      { name: "Jumpy", status: false, answered: false },
      { name: "Energetic", status: false, answered: false },
      { name: "Glowing", status: false, answered: false },
      { name: "Animated", status: false, answered: false },
      { name: "Lively", status: false, answered: false },
      { name: "Creepy", status: false, answered: false },
      { name: "Excited", status: true, answered: false },
      { name: "Tense", status: false, answered: false },
      { name: "Unrestful", status: false, answered: false },
      { name: "Pleased", status: true, answered: false },
      { name: "Unrestful", status: false, answered: false },
      { name: "Hasty", status: false, answered: false },
      { name: "Delighted", status: true, answered: false },
      { name: "Hedonistic", status: false, answered: false },
      { name: "Eager", status: false, answered: false },
      { name: "Joyful", status: false, answered: false },
    ]
  }
];```
</div>
</div>
</p>

<p>and I called this variable inside render ListView which trigger renderRow function..</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-js lang-js prettyprint-override"><code> _renderRow( rowData, sectionID, rowID ) {
    return (
      <View>
        <Text>{rowData.question}</Text>
        <Text>{rowData.answerArray[0].name}</Text>
      </View>
    );
  }

  render() {
    return (
        <View>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderRow.bind(this)}
          />
        </View>
    );
  }</code>```

How do I render the loop inside this listView ?
Even the when I hard coded the index like above code, it's not working..

Thank you.

答:
You should make two separate Components: Question & Answer

I've made a Codepen for you as an example, using your data

At first, I pass the questionsArray as prop to the ListView Component:

```<code>class Application extends React.Component {
  render() {
    return (
      <div>
        { questionsArray.map((question, key) => <ListView key={`listview-${key}`} question={question} />) }
      </div>
    );
  }
}
</code>```

Then, you can pass the answers to the ListViewItem Component, like this:

```<code>class ListView extends React.Component {
  render() {
    return (
      <div>
        {this.props.question.question}
        {this.props.question.answerArray.map((answer, key) => <ListViewItem answer={answer} />)}
      </div>
    );
  }
}
</code>```

This is the ListViewItem:

```<code>class ListViewItem extends React.Component {
  render() {
    return (
      <div>
        {this.props.answer.name}
      </div>
    );
  }
}
</code>```

Body:
I currently trying to play around with react-native..

I want to make a list view that get the dataSource from var which contain an object that have nested array inside.

var questionArray = [
  {
    question: "What is the emotion of the user? choose all that apply!",
    answerArray: [
      { name: "Cheerful", status: true, answered: false },
      { name: "Impulsive", status: false, answered: false },
      { name: "Firm", status: false, answered: false },
      { name: "Merry", status: true, answered: false },
      { name: "Jumpy", status: false, answered: false },
      { name: "Energetic", status: false, answered: false },
      { name: "Glowing", status: false, answered: false },
      { name: "Animated", status: false, answered: false },
      { name: "Lively", status: false, answered: false },
      { name: "Creepy", status: false, answered: false },
      { name: "Excited", status: true, answered: false },
      { name: "Tense", status: false, answered: false },
      { name: "Unrestful", status: false, answered: false },
      { name: "Pleased", status: true, answered: false },
      { name: "Unrestful", status: false, answered: false },
      { name: "Hasty", status: false, answered: false },
      { name: "Delighted", status: true, answered: false },
      { name: "Hedonistic", status: false, answered: false },
      { name: "Eager", status: false, answered: false },
      { name: "Joyful", status: false, answered: false },
    ]
  },
  {
    question: "What is the best way to describe this person's character? Choose all that apply.",
answerArray: [
      { name: "Cheerful", status: true, answered: false },
      { name: "Impulsive", status: false, answered: false },
      { name: "Firm", status: false, answered: false },
      { name: "Merry", status: true, answered: false },
      { name: "Jumpy", status: false, answered: false },
      { name: "Energetic", status: false, answered: false },
      { name: "Glowing", status: false, answered: false },
      { name: "Animated", status: false, answered: false },
      { name: "Lively", status: false, answered: false },
      { name: "Creepy", status: false, answered: false },
      { name: "Excited", status: true, answered: false },
      { name: "Tense", status: false, answered: false },
      { name: "Unrestful", status: false, answered: false },
      { name: "Pleased", status: true, answered: false },
      { name: "Unrestful", status: false, answered: false },
      { name: "Hasty", status: false, answered: false },
      { name: "Delighted", status: true, answered: false },
      { name: "Hedonistic", status: false, answered: false },
      { name: "Eager", status: false, answered: false },
      { name: "Joyful", status: false, answered: false },
    ]
  }
];

and I called this variable inside render ListView which trigger renderRow function..

 _renderRow( rowData, sectionID, rowID ) {
    return (
      <View>
        <Text>{rowData.question}</Text>
        <Text>{rowData.answerArray[0].name}</Text>
      </View>
    );
  }

  render() {
    return (
        <View>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderRow.bind(this)}
          />
        </View>
    );
  }

How do I render the loop inside this listView ?
Even the when I hard coded the index like above code, it's not working..

Thank you.

Body:
You should make two separate Components: Question & Answer

I've made a Codepen for you as an example, using your data

At first, I pass the questionsArray as prop to the ListView Component:

class Application extends React.Component {
  render() {
    return (
      <div>
        { questionsArray.map((question, key) => <ListView key={`listview-${key}`} question={question} />) }
      </div>
    );
  }
}

Then, you can pass the answers to the ListViewItem Component, like this:

class ListView extends React.Component {
  render() {
    return (
      <div>
        {this.props.question.question}
        {this.props.question.answerArray.map((answer, key) => <ListViewItem answer={answer} />)}
      </div>
    );
  }
}

This is the ListViewItem:

class ListViewItem extends React.Component {
  render() {
    return (
      <div>
        {this.props.answer.name}
      </div>
    );
  }
}


问:
Invoking a rest api client
I have created a rest api in eclipse as a maven project.
MobileAnalyticsModel class for rest api is

```<code>package org.subhayya.amazonws.mobileanalytics;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class MobileAnalyticsModel {

    private String name;
    private Date created;
    private String location;
    private String prize;
    private String requirement;

    public MobileAnalyticsModel() {

    }
    public MobileAnalyticsModel(String name, String location, String prize, String requirement) {

        this.name = name;
        this.location = location;
        this.prize = prize;
        this.requirement = requirement;
        this.created = new Date();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPrize() {
        return prize;
    }

    public void setPrize(String prize) {
        this.prize = prize;
    }

    public String getRequirement() {
        return requirement;
    }

    public void setRequirement(String requirement) {
        this.requirement = requirement;
    }
}
</code>```

this is the json response of the created api:

and
this is my sample test code for invoking rest api:

```<code>package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;

public class SampleTestREstClient {

    public static void main(String[] args) {

        Client client = ClientBuilder.newClient( );
        String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                .request(MediaType.APPLICATION_JSON)
                .get(String.class);

        System.out.println(reponse);
    }}
</code>```

then i got full json response.. as

```<code> [{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]
</code>```

But I want to have the single parameter as my output, for e.g., name, location or requirement.I am creating client invoking code also in the same maven project. So I wrote my code as below

```<code>Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
        client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                    .request(MediaType.APPLICATION_JSON)
                    .get(MobileAnalyticsModel.class);

System.out.println(reponse.getName());
</code>```

But I am getting exception, So I changed it to System.out.println(reponse);
) get atleast JSON response, then also getting error.

how do I get single name parameter from the JSON response? I am new to this rest api..please help me to fix this as soon as possible.thanks in advance

答:
You can also check the below link to convert json to object.

Parse a JSON response as an object

Title: Invoking a rest api client

Body:
I have created a rest api in eclipse as a maven project.
MobileAnalyticsModel class for rest api is

package org.subhayya.amazonws.mobileanalytics;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class MobileAnalyticsModel {

    private String name;
    private Date created;
    private String location;
    private String prize;
    private String requirement;

    public MobileAnalyticsModel() {

    }
    public MobileAnalyticsModel(String name, String location, String prize, String requirement) {

        this.name = name;
        this.location = location;
        this.prize = prize;
        this.requirement = requirement;
        this.created = new Date();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPrize() {
        return prize;
    }

    public void setPrize(String prize) {
        this.prize = prize;
    }

    public String getRequirement() {
        return requirement;
    }

    public void setRequirement(String requirement) {
        this.requirement = requirement;
    }
}

this is the json response of the created api:

and
this is my sample test code for invoking rest api:

package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;

public class SampleTestREstClient {

    public static void main(String[] args) {

        Client client = ClientBuilder.newClient( );
        String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                .request(MediaType.APPLICATION_JSON)
                .get(String.class);

        System.out.println(reponse);
    }}

then i got full json response.. as

 [{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]

But I want to have the single parameter as my output, for e.g., name, location or requirement.I am creating client invoking code also in the same maven project. So I wrote my code as below

Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
        client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
                    .request(MediaType.APPLICATION_JSON)
                    .get(MobileAnalyticsModel.class);

System.out.println(reponse.getName());

But I am getting exception, So I changed it to System.out.println(reponse);
) get atleast JSON response, then also getting error.

how do I get single name parameter from the JSON response? I am new to this rest api..please help me to fix this as soon as possible.thanks in advance


问:
SQL - Creating a query return comprised of various foreign keys
I have a task set which requires the rooting and removal of demo accounts in a database.
I have created a query where all the demo accounts are returned but there are fields within this query that have various children/keys.
I now want to create a query where I collect all the demo accounts as well as return all entries where the dependencies are returned so a delete statement can be created and run to remove any entries that relate to these accounts.

What is the best method of retrieving all this data in one place so a delete statement can run off minimal code?

Here is my statement for finding the Demo accounts;

```<code>Select ct.id as 'cutomer id', c.id as 'client id', ct.name, da.demo_account_status, da.demo_expiry_date, c.enabled from client c
join customer ct on ct.client_id = c.id
join demo_account da on da.client_id = c.id
join demo_account_extend_survey das on das.demo_account_id = da.id
where da.demo_account_status = 'DEMO_ACCOUNT_EXPIRED'
and c.enabled = 0
group by ct.id;
</code>```

Example data of the below looks like this;

233477  26412   customer name   DEMO_ACCOUNT_EXPIRED    2016-11-10  0

233478  26412   customer name   DEMO_ACCOUNT_EXPIRED    2016-11-10  0

233479  26412   customer name   DEMO_ACCOUNT_EXPIRED    2016-11-10  0

233480  26412   customer name   DEMO_ACCOUNT_EXPIRED    2016-11-10  0

And the this attempted statement is for gathering all foreign key/children ID's in one place so that a delete can be done at a later stage.

```<code>select ct.id, p.id, c.id, cc.id, ca.id, si.id, isi.id, ct.billing_address_id from customer ct
join client c on c.id=ct.client_id
join person p on p.id = c.id
join customer_contact cc on cc.customer_id = ct.id
join customer_account ca on ca.customer_id = ct.id
join sales_invoice si on si.customer_id = ct.id
join issued_customer_credit_note_tx isi on isi.customer_id = ct.id
join address ad on ad.id = ct.billing_address_id
where c.id =
</code>```

答:
Add a CASCADE DELETE constraint.

Read more on Cascade Delete

Give us some sample data and table so we can help you with your delete script

Body:
I have a task set which requires the rooting and removal of demo accounts in a database.
I have created a query where all the demo accounts are returned but there are fields within this query that have various children/keys.
I now want to create a query where I collect all the demo accounts as well as return all entries where the dependencies are returned so a delete statement can be created and run to remove any entries that relate to these accounts.

What is the best method of retrieving all this data in one place so a delete statement can run off minimal code?

Here is my statement for finding the Demo accounts;

Select ct.id as 'cutomer id', c.id as 'client id', ct.name, da.demo_account_status, da.demo_expiry_date, c.enabled from client c
join customer ct on ct.client_id = c.id
join demo_account da on da.client_id = c.id
join demo_account_extend_survey das on das.demo_account_id = da.id
where da.demo_account_status = 'DEMO_ACCOUNT_EXPIRED'
and c.enabled = 0
group by ct.id;

Example data of the below looks like this;

233477  26412   customer name   DEMO_ACCOUNT_EXPIRED    2016-11-10  0

233478  26412   customer name   DEMO_ACCOUNT_EXPIRED    2016-11-10  0

233479  26412   customer name   DEMO_ACCOUNT_EXPIRED    2016-11-10  0

233480  26412   customer name   DEMO_ACCOUNT_EXPIRED    2016-11-10  0

And the this attempted statement is for gathering all foreign key/children ID's in one place so that a delete can be done at a later stage.

select ct.id, p.id, c.id, cc.id, ca.id, si.id, isi.id, ct.billing_address_id from customer ct
join client c on c.id=ct.client_id
join person p on p.id = c.id
join customer_contact cc on cc.customer_id = ct.id
join customer_account ca on ca.customer_id = ct.id
join sales_invoice si on si.customer_id = ct.id
join issued_customer_credit_note_tx isi on isi.customer_id = ct.id
join address ad on ad.id = ct.billing_address_id
where c.id =


问:
Adding external 3D(.OBJ & .MTL) Objects to ARToolkit
I have been working on the ARToolkit sdk for android since some time.

In the ARToolkit SDK, I have worked on ARBaseLib and ARSimpleNativeCarsProj and implemented successfully. But I am trying to add external 3d Objects(.obj and .mtl) and I am unable to render the new object files.

I have also looked into the source code provided in this link,
https://github.com/kosiara/artoolkit-android-studio-example
but the problem here is the 3D object(Cube) has been created in using the draw(), openGL libraries function, instead i would want to add an external 3D Object.

More Explanation:
Okey, SimpleNativeCarsProj comes along with two 3D Objects(.OBJ and .MTL) in the assets/Data folder. CASE1 I tried replacing the existing 3Dobject with another 3D Objects, App Crashes on the launch CASE2 As I worked around a little, these files are pushed to the cache folder on the app load, I invalidated the caches and restarted android studio, rebuilt and ran the app, still the app crashes on the launch. Technically I am unable to Replace/Delete/Add another 3D Object files to SimpleNativeCarsProject

Any headsup would be appreciated.

答: Give ArToolKitJpctBaseLib a try. It is a wrapper on ArToolKit + jPCT-AE (a 3d Engine on Android) aims to simplify creation of AR apps for Android.</p>


问:
Xamarin.Forms: Move to .NET Standard
My Xamarin.Forms project targets PCL profile 259. I recently read a lot of moving to .NET Standard, but it looks very painful to do.

Currently I develop in Visual Studio 2015 Update 3. But will give VS 2017 a try soon.

My solution consists of:

Common PCL library

Android specific project

iOS specific project

My Questions:

How can I convert from Profile 259 to latest .NET Standard?

Is there some official converson guide from Xamarin / Microsoft Team already available?

My Xamarin.Forms Android and iOS Apps are built in VSTS. Does VSTS support .NET Standard or would I end up in build errors?

Thanks in advance for any good solution.

答:
To change a PCL to .NET Standard you just need to go to the Properties of your PCL and select Target .NET Standard Platform

Then create a project.json file, if it didn't already create one for you and insert the following.

```<code>{
  "supports": {},
  "dependencies": {
    "NETStandard.Library": "1.6.0",
    "Xamarin.Forms": "2.3.4.192-pre2"
  },
  "frameworks": {
    "netstandard1.3": {
      "imports": "portable-net45+win8+wpa81"
    }
  }
}
</code>```

You need the imports to allow non .NET Standard libraries to be added.

In VS 2017 it gets different. While the above will continue to work, you can have a full .NET Standard library as a csproj (no longer an xproj), and have it happily work with Xamarin.

However, there is no automatic conversion (that I know of), so what I normally do, is edit the csproj and completely replace it with the following. Just delete everything in that file and put the following.

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard1.3</TargetFramework>
    <AssemblyName>MyLibraryName</AssemblyName>
    <PackageId>MyLibraryName</PackageId>
    <NetStandardImplicitPackageVersion>1.6.0</NetStandardImplicitPackageVersion>
    <PackageTargetFallback>$(PackageTargetFallback);portable-win+net45+wp8+win81+wpa8</PackageTargetFallback>
  </PropertyGroup>
</Project>
</code>```

You will then have to add your references and NuGet packages manually, again. With the PackageTargetFallback, this line is similar to the imports in project.json.

In regards to VSTS, I know that the first method with VS2015 works just fine, as I have done it myself. The VS2017 method should work with VSTS, however I haven't personally tried that just yet.

Title: Xamarin.Forms: Move to .NET Standard

Body:
To change a PCL to .NET Standard you just need to go to the Properties of your PCL and select Target .NET Standard Platform

Then create a project.json file, if it didn't already create one for you and insert the following.

{
  "supports": {},
  "dependencies": {
    "NETStandard.Library": "1.6.0",
    "Xamarin.Forms": "2.3.4.192-pre2"
  },
  "frameworks": {
    "netstandard1.3": {
      "imports": "portable-net45+win8+wpa81"
    }
  }
}

You need the imports to allow non .NET Standard libraries to be added.

In VS 2017 it gets different. While the above will continue to work, you can have a full .NET Standard library as a csproj (no longer an xproj), and have it happily work with Xamarin.

However, there is no automatic conversion (that I know of), so what I normally do, is edit the csproj and completely replace it with the following. Just delete everything in that file and put the following.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard1.3</TargetFramework>
    <AssemblyName>MyLibraryName</AssemblyName>
    <PackageId>MyLibraryName</PackageId>
    <NetStandardImplicitPackageVersion>1.6.0</NetStandardImplicitPackageVersion>
    <PackageTargetFallback>$(PackageTargetFallback);portable-win+net45+wp8+win81+wpa8</PackageTargetFallback>
  </PropertyGroup>
</Project>

You will then have to add your references and NuGet packages manually, again. With the PackageTargetFallback, this line is similar to the imports in project.json.

In regards to VSTS, I know that the first method with VS2015 works just fine, as I have done it myself. The VS2017 method should work with VSTS, however I haven't personally tried that just yet.


问:
Visual Studio 2015 warns System.Runtime not found (but VS2013 is fine)
In Visual Studio 2015, I open a project that was created with Visual Studio 2013. Rebuild this project and see the following warning:

```<code>The referenced component 'System.Runtime' could not be found.
</code>```

Looking at the References item in Solution Explorer, click System.Runtime, the Property window shows empty as below:

In Visual Studio 2013, it shows:

And this DLL does exist in the foler:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\Facades

So Visual Studio 2013 didn't whow warnings when I build the project, but Visual Studio 2015 does.

Is this a bug or I miss something in Visual Studio 2015?

答: Include System.Runtime.InteropServices.RuntimeInformation instead of System.Runtime. It worked for me.

Body:
In Visual Studio 2015, I open a project that was created with Visual Studio 2013. Rebuild this project and see the following warning:

The referenced component 'System.Runtime' could not be found.

Looking at the References item in Solution Explorer, click System.Runtime, the Property window shows empty as below:

In Visual Studio 2013, it shows:

And this DLL does exist in the foler:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\Facades

So Visual Studio 2013 didn't whow warnings when I build the project, but Visual Studio 2015 does.

Is this a bug or I miss something in Visual Studio 2015?


问:
how can i give the order by in s3 database
```<code>if(!$_GET){
    echo "{'success':false, 'error':'No query parameters submitted'}";
    return;
}

// 1. Include the SimpleDB class if it does not exist
if (!class_exists('SimpleDB'))require_once('sdb.php');

// 2. Set awsAccessKey and awsSecretKey to your values
require_once('config.inc.php');

// create connection
$sdb = new SimpleDB(awsAccessKey, awsSecretKey);
$condition = "";
$status = "";

//$params = json_decode(stripslashes($_POST['hash']));
$params = $_GET;
foreach($params as $key => $value){
    $condition .= " " . $key . " = '" . $value . "' and" ;
}

$condition = preg_replace('/and$/', "", $condition);

$query = "select * from $domain";

if($condition!= " _empty_ = '' "){
    $query .= " where $condition ";
}

$fileHash = '{';
if($files = $sdb->select($domain, $query)){
    $status = 'true';
    $fileHash .= "'files' : ".json_encode($files).", ";
}else{
    $status = 'false';
    $fileHash .= "'files' : [], ";
    $fileHash .= "'error' : 'No records retrieved from SimpleDB ".json_encode($sdb->ErrorCode)."', ";
}
$fileHash .= "'success':".$status."}";
echo $fileHash;
</code>```

my json response
    {
        'files': [{
            "Name": "4cf0dadfddfe6",
            "Attributes": {
                "title": "Earrings!",
                "file_size": "135023",
                "url": "http:\/\/dtzhqpwfdzscm.cloudfront.net\/4cf0dadfddfe6.jpg",
                "file_name": "4cf0dadfddfe6.jpg",
                "time_stamp": "1290853092",
                "file_type": "image\/jpeg",
                "content_obj_type": "upload",
                "thumb": "http:\/\/dtzhqpwfdzscm.cloudfront.net\/4cf0dadfde32b.jpg",
                "width": "176.04166666666669",
                "height": "171",
                "userid": "4",
                "gibid": "54",
                "contentid": "4cf0dadfddfe6",
                "qqfile": "il_570xN.182320055.jpg",
                "original_name": "il_570xN.182320055.jpg",
                "y": "72",
                "x": "535",
                "on_floor": "false",
                "success": "true",
                "gibview": "O",
                "avatar_url": "",
                "crop_url": ""
            }
        }],
        'success': true
    }

i want to sort by time_stamp how can i do this .? or any good article for learning s3 database please suggest.

答:
Like in any other sql dialect - sorting can be performed with ORDER BY clause:

```<code>ORDER BY time_stamp
</code>```

http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/index.html?UsingSelect.html

ContentLicense: CC BY-SA 2.5

Body:
if(!$_GET){
    echo "{'success':false, 'error':'No query parameters submitted'}";
    return;
}

// 1. Include the SimpleDB class if it does not exist
if (!class_exists('SimpleDB'))require_once('sdb.php');

// 2. Set awsAccessKey and awsSecretKey to your values
require_once('config.inc.php');

// create connection
$sdb = new SimpleDB(awsAccessKey, awsSecretKey);
$condition = "";
$status = "";

//$params = json_decode(stripslashes($_POST['hash']));
$params = $_GET;
foreach($params as $key => $value){
    $condition .= " " . $key . " = '" . $value . "' and" ;
}

$condition = preg_replace('/and$/', "", $condition);

$query = "select * from $domain";

if($condition!= " _empty_ = '' "){
    $query .= " where $condition ";
}

$fileHash = '{';
if($files = $sdb->select($domain, $query)){
    $status = 'true';
    $fileHash .= "'files' : ".json_encode($files).", ";
}else{
    $status = 'false';
    $fileHash .= "'files' : [], ";
    $fileHash .= "'error' : 'No records retrieved from SimpleDB ".json_encode($sdb->ErrorCode)."', ";
}
$fileHash .= "'success':".$status."}";
echo $fileHash;

my json response
    {
        'files': [{
            "Name": "4cf0dadfddfe6",
            "Attributes": {
                "title": "Earrings!",
                "file_size": "135023",
                "url": "http:\/\/dtzhqpwfdzscm.cloudfront.net\/4cf0dadfddfe6.jpg",
                "file_name": "4cf0dadfddfe6.jpg",
                "time_stamp": "1290853092",
                "file_type": "image\/jpeg",
                "content_obj_type": "upload",
                "thumb": "http:\/\/dtzhqpwfdzscm.cloudfront.net\/4cf0dadfde32b.jpg",
                "width": "176.04166666666669",
                "height": "171",
                "userid": "4",
                "gibid": "54",
                "contentid": "4cf0dadfddfe6",
                "qqfile": "il_570xN.182320055.jpg",
                "original_name": "il_570xN.182320055.jpg",
                "y": "72",
                "x": "535",
                "on_floor": "false",
                "success": "true",
                "gibview": "O",
                "avatar_url": "",
                "crop_url": ""
            }
        }],
        'success': true
    }

i want to sort by time_stamp how can i do this .? or any good article for learning s3 database please suggest.

Body:
Like in any other sql dialect - sorting can be performed with ORDER BY clause:

ORDER BY time_stamp

http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/index.html?UsingSelect.html


问:
Android project cannot run why

I download the project from https://developer.android.com/training/implementing-navigation/nav-drawer.html Its name is NavigationDrawer.zip

答:
Project Sync
         The project 'NavigationDrawer' is not a Gradle-based project

I think this the answer,the project is not built by Gradle

Title: Android project cannot run why


问:
UIPickerView with null data
Here is my code

```<code>    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
        picker1 = [[UIPickerView alloc] init];
        [self.view addSubview:picker1];

        picker1.delegate=self;
        picker1.dataSource=self;
        picker1.tag = 1;

       Array = [[NSMutableArray alloc] init];
             [self  webservice];

    }
    -(void)webservice
    {

        NSLog(@"dropdown method is call");

        NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                            "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                            "<soap:Body>\n"
                            "<ShowValue xmlns=\"http://tempuri.org/\">\n"
                            “</ShowValue>\n"
                            "</soap:Body>\n"
                            "</soap:Envelope>"];

        envalope=[NSString stringWithFormat:envalope];
        NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
        NSString *url=@"http://ShowService.asmx";

        NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

        [request2 addValue:@"http://tempuri.org/ShowValue" forHTTPHeaderField:@"SOAPAction"];
        [request2 setHTTPMethod:@"POST"];
        [request2 setHTTPBody:envelope];
        [request2 setValue:@"text/xml; charset=utf-8"
        forHTTPHeaderField:@"Content-Type"];
        [request2 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

        NSURLConnection *connection1 = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
        if (connection1){
            resservice = [NSMutableData data];
            NSLog(@"connection Establish.");

        }
        else{
            NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
        }

    }

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {

        [resservice setLength:0];

    }
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

       [rresservice appendData:data];

    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {

        NSString *theXml1 = [[NSString alloc] initWithBytes:[ resservicemutableBytes] length:[ resservice length] encoding:NSUTF8StringEncoding];
        NSLog(@"The final result 1--- :%@",theXml1);

        NSArray * jsonarr1 =[NSJSONSerialization JSONObjectWithData:[theXml1 dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        NSLog(@"print array :%@",jsonarr1);
        for (NSDictionary * d in jsonarr1)
        {
            if ([d objectForKey:@"SH"]!=[NSNull null])
            {
                [picker1 reloadAllComponents];
                self.shapestring=[NSString stringWithFormat:@"%@",[d objectForKey:@"SHP"]];
                NSLog(@"pVALUE FOR :%@",self.shapestring);
                [_customPickerArrayshap addObject:self.shapestring];
                NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArrayshap.count);
                [picker1 reloadAllComponents];
                NSLog(@"Array for shape%@",_customPickerArrayshap);

            }

        if(xmlParser1)
        {

        }
        xmlParser1 = [[NSXMLParser alloc] initWithData: resshap];
        [xmlParser1 setDelegate:self];
        [xmlParser1 setShouldResolveExternalEntities:YES];
        [xmlParser1 parse];
        //[theXml release];
    }
    }
    -(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *)attributeDict {
        if( [elementName isEqualToString:@"ShowResult"])
        {
            if (!soapResults1)
            {
                soapResults1 = [[NSMutableString alloc] init];
            }
            elementFound1 = YES;
        }
    }
    -(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
    {
        if (elementFound1)
        {
            [soapResults1 appendString: string];

            NSArray * jsonarr1 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr1);
            for (NSDictionary * d in jsonarr1)
            {
                if ([d objectForKey:@"SH"]!=[NSNull null])
                {
                [picker1 reloadAllComponents];
                    self.shapestring=[NSString stringWithFormat:@"%@",[d objectForKey:@"SH"]];

                  [picker1 reloadAllComponents];
                }
                else
                {self.shapestring=@"";
                                }
            }
        }
            i        }
        }

    -(void)parser:(NSXMLParser *)parser
    didEndElement:(NSString *)elementName
     namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qName
    {
        if ([elementName isEqualToString:@"ShowResult"])
        {

                   [soapResults1 setString:@""];
            elementFound1 = FALSE;
        }
    }
    - (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
            return 1;
        }
    - (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
            return Array.count;

    }
    - (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    {
            return _Array[row];

    }
    -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
           [self.Array objectAtIndex:row];

    }
</code>```

error is:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

In my IOS Application Programming,I'm getting soap response from server then parse soap response in array and assign array to PickerView, then nothing is add in UIPickerView and Following error Occure and application is crashed.Even response come from server is ok and also add in array.here i'm getting response from server than assign it to an array.response also valid getting from server not null.

答:
As datasource for picker is "Array"

Replace

```<code>[_customPickerArrayshap addObject:self.shapestring];
</code>```

With

```<code>[Array addObject:self.shapestring];
</code>```

Title: UIPickerView with null data

Body:
Here is my code

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
        picker1 = [[UIPickerView alloc] init];
        [self.view addSubview:picker1];

        picker1.delegate=self;
        picker1.dataSource=self;
        picker1.tag = 1;

       Array = [[NSMutableArray alloc] init];
             [self  webservice];

    }
    -(void)webservice
    {

        NSLog(@"dropdown method is call");

        NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                            "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                            "<soap:Body>\n"
                            "<ShowValue xmlns=\"http://tempuri.org/\">\n"
                            “</ShowValue>\n"
                            "</soap:Body>\n"
                            "</soap:Envelope>"];

        envalope=[NSString stringWithFormat:envalope];
        NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
        NSString *url=@"http://ShowService.asmx";

        NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

        [request2 addValue:@"http://tempuri.org/ShowValue" forHTTPHeaderField:@"SOAPAction"];
        [request2 setHTTPMethod:@"POST"];
        [request2 setHTTPBody:envelope];
        [request2 setValue:@"text/xml; charset=utf-8"
        forHTTPHeaderField:@"Content-Type"];
        [request2 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

        NSURLConnection *connection1 = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
        if (connection1){
            resservice = [NSMutableData data];
            NSLog(@"connection Establish.");

        }
        else{
            NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
        }

    }

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {

        [resservice setLength:0];

    }
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

       [rresservice appendData:data];

    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {

        NSString *theXml1 = [[NSString alloc] initWithBytes:[ resservicemutableBytes] length:[ resservice length] encoding:NSUTF8StringEncoding];
        NSLog(@"The final result 1--- :%@",theXml1);

        NSArray * jsonarr1 =[NSJSONSerialization JSONObjectWithData:[theXml1 dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        NSLog(@"print array :%@",jsonarr1);
        for (NSDictionary * d in jsonarr1)
        {
            if ([d objectForKey:@"SH"]!=[NSNull null])
            {
                [picker1 reloadAllComponents];
                self.shapestring=[NSString stringWithFormat:@"%@",[d objectForKey:@"SHP"]];
                NSLog(@"pVALUE FOR :%@",self.shapestring);
                [_customPickerArrayshap addObject:self.shapestring];
                NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArrayshap.count);
                [picker1 reloadAllComponents];
                NSLog(@"Array for shape%@",_customPickerArrayshap);

            }

        if(xmlParser1)
        {

        }
        xmlParser1 = [[NSXMLParser alloc] initWithData: resshap];
        [xmlParser1 setDelegate:self];
        [xmlParser1 setShouldResolveExternalEntities:YES];
        [xmlParser1 parse];
        //[theXml release];
    }
    }
    -(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *)attributeDict {
        if( [elementName isEqualToString:@"ShowResult"])
        {
            if (!soapResults1)
            {
                soapResults1 = [[NSMutableString alloc] init];
            }
            elementFound1 = YES;
        }
    }
    -(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
    {
        if (elementFound1)
        {
            [soapResults1 appendString: string];

            NSArray * jsonarr1 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr1);
            for (NSDictionary * d in jsonarr1)
            {
                if ([d objectForKey:@"SH"]!=[NSNull null])
                {
                [picker1 reloadAllComponents];
                    self.shapestring=[NSString stringWithFormat:@"%@",[d objectForKey:@"SH"]];

                  [picker1 reloadAllComponents];
                }
                else
                {self.shapestring=@"";
                                }
            }
        }
            i        }
        }

    -(void)parser:(NSXMLParser *)parser
    didEndElement:(NSString *)elementName
     namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qName
    {
        if ([elementName isEqualToString:@"ShowResult"])
        {

                   [soapResults1 setString:@""];
            elementFound1 = FALSE;
        }
    }
    - (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
            return 1;
        }
    - (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
            return Array.count;

    }
    - (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    {
            return _Array[row];

    }
    -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
           [self.Array objectAtIndex:row];

    }

error is:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

In my IOS Application Programming,I'm getting soap response from server then parse soap response in array and assign array to PickerView, then nothing is add in UIPickerView and Following error Occure and application is crashed.Even response come from server is ok and also add in array.here i'm getting response from server than assign it to an array.response also valid getting from server not null.

Body:
As datasource for picker is "Array"

Replace

[_customPickerArrayshap addObject:self.shapestring];

With

[Array addObject:self.shapestring];


问:
How to show and hide side menu in angular2
In my application i have to implement hide and show side menu. By default the page menu is open while clicking the toggle menu i have to hide the side menu. How can i implement this.

what i have is:

app.component.html, nav.component.html

        Name

```
</div>
</div>
</p>

<p>Myservice.ts</p>

```export class GlobalService {
public collapse;

constructor() { }

setValue(val: boolean) {
    this.collapse = val;
}

getValue() {
    return this.collapse;
}
```

<p>EDIT</p>

<p>app.component.html</p>

```

```

<p>app.component.ts</p>

```import { GlobalService } from "path";

export class AppComponent {
toggle() {
this.globalService.setValue(false);

 }
}
```

how can i hide this list(in nav.html) while clicking menu toggle (app.compnent.html)? Any help will really appreciable. i am new to angular.

答:
For this ,

You can make a CommonService to store the state of menu or and use that Service to make toggle you menu.

You can also use @Input @Output , in case you are having parent child relation between components.

Method will depend on how is your project/file structure.

Body:
In my application i have to implement hide and show side menu. By default the page menu is open while clicking the toggle menu i have to hide the side menu. How can i implement this.

what i have is:

app.component.html, nav.component.html

        Name

Myservice.ts

export class GlobalService {
public collapse;

constructor() { }

setValue(val: boolean) {
    this.collapse = val;
}

getValue() {
    return this.collapse;
}

EDIT

app.component.html

app.component.ts

import { GlobalService } from "path";

export class AppComponent {
toggle() {
this.globalService.setValue(false);

 }
}

how can i hide this list(in nav.html) while clicking menu toggle (app.compnent.html)? Any help will really appreciable. i am new to angular.


问:
Laravel 5 Paginate + Infinite Scroll jQuery
I am trying to use paginate() to achieve infinite scroll. I think the easiest way is using the 'infinite-scroll' to achieve this. If you have any other suggestion how to do it without infinite-scroll library, just using jQuery, I'd be happy to know..

I am returning the variable to view like this:

```<code>public function index()
 {
    $posts = Post::with('status' == 'verified')
                      ->paginate(30);

    return view ('show')->with(compact('posts'));
 }
</code>```

My View:

```<code><div id="content" class="col-md-10">
    @foreach (array_chunk($posts->all(), 3) as $row)
        <div class="post row">
            @foreach($row as $post)
                <div class="item col-md-4">
                    <!-- SHOW POST -->
                </div>
            @endforeach
        </div>
    @endforeach
    {!! $posts->render() !!}
 </div>
</code>```

Javascript Part:

```<code>$(document).ready(function() {
  (function() {
     var loading_options = {
        finishedMsg: "<div class='end-msg'>End of content!</div>",
        msgText: "<div class='center'>Loading news items...</div>",
        img: "/assets/img/ajax-loader.gif"
     };

     $('#content').infinitescroll({
         loading: loading_options,
         navSelector: "ul.pagination",
         nextSelector: "ul.pagination  li:last a",   // is this where it's failing?
         itemSelector: "#content div.item"
     });
   });
});
</code>```

However, this doesn't work. The ->render() part is working because I am getting [<[1]2]3]>] part. However, the infinite scroll doesn't work. I also don't get any errors in the console.

[<[1]2]3]>] is like this in the view:source:

```<code><ul class="pagination">
       <li class="disabled"><span>«</span> </li>                    //   «
       <li class="active"><span>1</span></li>                       //   1
       <li><a href="http://test.dev/?page=2">2</a></li>             //   2
       <li><a href="http://test.dev/?page=3">3</a></li>             //   3
       <li><a href="http://test.dev/?page=2" rel="next">»</a></li>  //   »
</ul>
</code>```

答:
Easy and helpful is this tutorial - http://laraget.com/blog/implementing-infinite-scroll-pagination-using-laravel-and-jscroll

Final script could looks like this one

```<code>{!! HTML::script('assets/js/jscroll.js') !!}
<script>
    $('.link-pagination').hide();
    $(function () {
        $('.infinite-scroll').jscroll({
            autoTrigger: true,
            loadingHtml: '<img class="center-block" src="/imgs/icons/loading.gif" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
            padding: 0,
            nextSelector: '.pagination li.active + li a',
            contentSelector: 'div.infinite-scroll',
            callback: function() {
                $('.link-pagination').remove();
            }
        });
    });
</script>
</code>```

You just need to use laravel's pagination

```<code>{!! $restaurants->links() !!}
</code>```

Body:
I am trying to use paginate() to achieve infinite scroll. I think the easiest way is using the 'infinite-scroll' to achieve this. If you have any other suggestion how to do it without infinite-scroll library, just using jQuery, I'd be happy to know..

I am returning the variable to view like this:

public function index()
 {
    $posts = Post::with('status' == 'verified')
                      ->paginate(30);

    return view ('show')->with(compact('posts'));
 }

My View:

    @foreach (array_chunk($posts->all(), 3) as $row)

            @foreach($row as $post)

            @endforeach

    @endforeach
    {!! $posts->render() !!}

Javascript Part:

$(document).ready(function() {
  (function() {
     var loading_options = {
        finishedMsg: "
End of content!
",
        msgText: "
Loading news items...
",
        img: "/assets/img/ajax-loader.gif"
     };

     $('#content').infinitescroll({
         loading: loading_options,
         navSelector: "ul.pagination",
         nextSelector: "ul.pagination  li:last a",   // is this where it's failing?
         itemSelector: "#content div.item"
     });
   });
});

However, this doesn't work. The ->render() part is working because I am getting [<[1]2]3]>] part. However, the infinite scroll doesn't work. I also don't get any errors in the console.

[<[1]2]3]>] is like this in the view:source:

«
                    //   «

1
                       //   1

2
             //   2

3
             //   3

»
  //   »

Body:
Easy and helpful is this tutorial - http://laraget.com/blog/implementing-infinite-scroll-pagination-using-laravel-and-jscroll

Final script could looks like this one

{!! HTML::script('assets/js/jscroll.js') !!}
<script>
    $('.link-pagination').hide();
    $(function () {
        $('.infinite-scroll').jscroll({
            autoTrigger: true,
            loadingHtml: '<img class="center-block" src="/imgs/icons/loading.gif" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
            padding: 0,
            nextSelector: '.pagination li.active + li a',
            contentSelector: 'div.infinite-scroll',
            callback: function() {
                $('.link-pagination').remove();
            }
        });
    });
</script>

You just need to use laravel's pagination

{!! $restaurants->links() !!}


问:
Possible to run Fabric and TestFlight apps side-by-side?
I have an app that I'd like 2 different versions deployed on the same phone.

Can this be achieved using TestFlight and Fabric, or a script for changing the bundle identifier on deploy possible?

答:
You probably want two different build configurations for your app/target.
Then you open the Build Settings in Xcode and change the bundle identifier there.

If the two versions of your app differ in other parts, you could also introduce your own custom build setting, see image below:

You can access that new build setting in code with this line. Change NEW_SETTING for the name of your new setting.

```<code>NSString *myCustomSetting = [[NSBundle mainBundle] infoDictionary][@"NEW_SETTING"];
</code>```

Then your app can behave differently depending on the value of that build setting.

Body:
You probably want two different build configurations for your app/target.
Then you open the Build Settings in Xcode and change the bundle identifier there.

If the two versions of your app differ in other parts, you could also introduce your own custom build setting, see image below:

You can access that new build setting in code with this line. Change NEW_SETTING for the name of your new setting.

NSString *myCustomSetting = [[NSBundle mainBundle] infoDictionary][@"NEW_SETTING"];

Then your app can behave differently depending on the value of that build setting.


问:
Binary Semaphore not working if release() comes before acquire()
I am writing a test code where i found if we put release() before acquire() then Binary Semaphore functionality is broken.

I checked and found more then one thread passes acquire() and increase the count to N where N is number of threads and thus contradicting binary semaphore.

```<code>import java.util.concurrent.Semaphore;

/**
 * Consider an ATM cubicle with 1 ATM, Semaphore can make sure only 1 person
 * can access simultaneously.
 *
 * Here if relese() comes before then this binary semaphore is not working.
 */
public class SemaphoreTest {

    // max 4 people
    static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {

        System.out.println("Total available Semaphore permits : " + semaphore.availablePermits());

        MyATMThread t1 = new MyATMThread("A",semaphore);
        t1.start();

        MyATMThread t2 = new MyATMThread("B",semaphore);
        t2.start();

        MyATMThread t3 = new MyATMThread("C",semaphore);
        t3.start();

        MyATMThread t4 = new MyATMThread("D",semaphore);
        t4.start();

        MyATMThread t5 = new MyATMThread("E",semaphore);
        t5.start();

        MyATMThread t6 = new MyATMThread("F",semaphore);
        t6.start();

    }
}

class MyATMThread extends Thread {

    String name = "";
    Semaphore semaphore = null;

    MyATMThread(String name,Semaphore s) {
        this.name = name;
        this.semaphore=s;
    }

    public void run() {

        try {

            System.out.println(name + " : acquiring lock...");
            System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());
            semaphore.release();
            semaphore.acquire();
            System.out.println(name + " : got the permit!");

            try {

                for (int i = 1; i <= 5; i++) {

                    System.out.println(name + " : is performing operation " + i + ", available Semaphore permits : "
                            + semaphore.availablePermits());

                    // sleep 1 second
                    Thread.sleep(1000);

                }

            } finally {

                // calling release() after a successful acquire()
                System.out.println(name + " : releasing lock...");
                semaphore.release();
                System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());

            }

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}
</code>```

Can some one explain this behavior ?

答:
The release() method is used to increment permits since, from the docs:

There is no requirement that a thread that releases a permit must
  have acquired that permit by calling acquire.  Correct usage of a
  semaphore is established by programming convention in the application.

In other words:

semaphore.release(10), Will add 10 more permits to current permits

Body:
I am writing a test code where i found if we put release() before acquire() then Binary Semaphore functionality is broken.

I checked and found more then one thread passes acquire() and increase the count to N where N is number of threads and thus contradicting binary semaphore.

import java.util.concurrent.Semaphore;

/**
 * Consider an ATM cubicle with 1 ATM, Semaphore can make sure only 1 person
 * can access simultaneously.
 *
 * Here if relese() comes before then this binary semaphore is not working.
 */
public class SemaphoreTest {

    // max 4 people
    static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {

        System.out.println("Total available Semaphore permits : " + semaphore.availablePermits());

        MyATMThread t1 = new MyATMThread("A",semaphore);
        t1.start();

        MyATMThread t2 = new MyATMThread("B",semaphore);
        t2.start();

        MyATMThread t3 = new MyATMThread("C",semaphore);
        t3.start();

        MyATMThread t4 = new MyATMThread("D",semaphore);
        t4.start();

        MyATMThread t5 = new MyATMThread("E",semaphore);
        t5.start();

        MyATMThread t6 = new MyATMThread("F",semaphore);
        t6.start();

    }
}

class MyATMThread extends Thread {

    String name = "";
    Semaphore semaphore = null;

    MyATMThread(String name,Semaphore s) {
        this.name = name;
        this.semaphore=s;
    }

    public void run() {

        try {

            System.out.println(name + " : acquiring lock...");
            System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());
            semaphore.release();
            semaphore.acquire();
            System.out.println(name + " : got the permit!");

            try {

                for (int i = 1; i <= 5; i++) {

                    System.out.println(name + " : is performing operation " + i + ", available Semaphore permits : "
                            + semaphore.availablePermits());

                    // sleep 1 second
                    Thread.sleep(1000);

                }

            } finally {

                // calling release() after a successful acquire()
                System.out.println(name + " : releasing lock...");
                semaphore.release();
                System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());

            }

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}

Can some one explain this behavior ?


问:
Electron / NodeJS and application freezing on setInterval / async code
I'm working on an electron application that performs a screenshot capture every 3 seconds with the electron api, and writes it to a given target path. I've set up a separate BrowserWindow where the capturing code runs in (see code structure below) a setInterval() "loop", but whenever the capture happens, the app freezes for a moment. I think it is the call to source.thumbnail.toPng() or writeScreenshot() method in the file ScreenCapturer.jshtml.js.

I set up this structure as I though this was the way to go, but apparently this is not. WebWorkers won't help me either as I need node modules such as fs, path and desktopCapturer (from electron).

How would one do this type of task without blocking the main thread every time the interval code (as seen in file ScreenCapturer.jshtml.js) runs (because I thought the renderer processes were separate processes?)

My code as reference

main.js (main process)

```<code>// all the imports and other
// will only show the import that matters
import ScreenCapturer from './lib/capture/ScreenCapturer';

app.on('ready', () => {
   // Where I spawn my main UI
   mainWindow = new BrowserWindow({...});
   mainWindow.loadURL(...);
   // Other startup stuff

   // Hee comes the part where I call function to start capturing
   initCapture();
});

function initCapture() {
    const sc = new ScreenCapturer();
    sc.startTakingScreenshots();
}
</code>```

ScreenCapturer.js (module used by main process)

```<code>'use strict';

/* ******************************************************************** */
/* IMPORTS */
import { app, BrowserWindow, ipcMain } from 'electron';
import url from 'url';
import path from 'path';
/* VARIABLES */
let rendererWindow;
/*/********************************************************************///
/*///*/

/* ******************************************************************** */
/* SCREENCAPTURER */
export default class ScreenCapturer {
    constructor() {
        rendererWindow = new BrowserWindow({
            show: true, width: 400, height: 600,
            'node-integration': true,
            webPreferences: {
                webSecurity: false
            }
        });
        rendererWindow.on('close', () => {
            rendererWindow = null;
        });
    }

    startTakingScreenshots(interval) {
        rendererWindow.webContents.on('did-finish-load', () => {
            rendererWindow.openDevTools();
            rendererWindow.webContents.send('capture-screenshot', path.join('e:', 'temp'));
        });
        rendererWindow.loadURL(
            url.format({
                pathname: path.join(__dirname, 'ScreenCapturer.jshtml.html'),
                protocol: 'file:',
                slashes: true
            })
        );
    }
}
/*/********************************************************************///
/*///*/
</code>```

ScreenCapturer.jshtml.js (the thml file loaded in the renderer browser window)

```<code><html>
    <body>
        <script>require('./ScreenCapturer.jshtml.js')</script>
    </body>
</html>
</code>```

ScreenCapturer.jshtml.js (the js file loaded from the html file in the renderer process)

```<code>import { ipcRenderer, desktopCapturer, screen } from 'electron';
import path from 'path';
import fs from 'fs';
import moment from 'moment';
let mainSource;

function getMainSource(mainSource, desktopCapturer, screen, done) {
    if(mainSource === undefined) {
        const options = {
            types: ['screen'],
            thumbnailSize: screen.getPrimaryDisplay().workAreaSize
        };
        desktopCapturer.getSources(options, (err, sources) => {
            if (err) return console.log('Cannot capture screen:', err);
            const isMainSource = source => source.name === 'Entire screen' || source.name === 'Screen 1';
            done(sources.filter(isMainSource)[0]);
        });
    } else {
        done(mainSource);
    }
}
function writeScreenshot(png, filePath) {
    fs.writeFile(filePath, png, err => {
        if (err) { console.log('Cannot write file:', err); }
        return;
    });
}

ipcRenderer.on('capture-screenshot', (evt, targetPath) => {
    setInterval(() => {
        getMainSource(mainSource, desktopCapturer, screen, source => {
            const png = source.thumbnail.toPng();
            const filePath = path.join(targetPath, `${moment().format('yyyyMMdd_HHmmss')}.png`);
            writeScreenshot(png, filePath);
        });
    }, 3000);
});
</code>```

答:
I walked away from using the API's delivered by electron. I'd recommend using desktop-screenshot package -> https://www.npmjs.com/package/desktop-screenshot. This worked cross platform (linux, mac, win) for me.
Note on windows we need the hazardous package, because otherwise when packaging your electron app with an asar it won't be able to execute the script inside desktop-screenshot. More info on the hazardous package's page.

Below is how my code now roughly works, please don't copy/paste because it might not fit your solution!! However it might give an indication on how you could solve it.

```<code>/* ******************************************************************** */
/* MODULE IMPORTS */
import { remote, nativeImage } from 'electron';
import path from 'path';
import os from 'os';
import { exec } from 'child_process';
import moment from 'moment';
import screenshot from 'desktop-screenshot';
/* */
/*/********************************************************************///
/* ******************************************************************** */
/* CLASS */
export default class ScreenshotTaker {
    constructor() {
        this.name = "ScreenshotTaker";
    }
    start(cb) {
        const fileName = `cap_${moment().format('YYYYMMDD_HHmmss')}.png`;
        const destFolder = global.config.app('capture.screenshots');
        const outputPath = path.join(destFolder, fileName);
        const platform = os.platform();
        if(platform === 'win32') {
            this.performWindowsCapture(cb, outputPath);
        }
        if(platform === 'darwin') {
            this.performMacOSCapture(cb, outputPath);
        }
        if(platform === 'linux') {
            this.performLinuxCapture(cb, outputPath);
        }
    }
    performLinuxCapture(cb, outputPath) {
        // debian
        exec(`import -window root "${outputPath}"`, (error, stdout, stderr) => {
            if(error) {
                cb(error, null, outputPath);
            } else {
                cb(null, stdout, outputPath);
            }
        });
    }
    performMacOSCapture(cb, outputPath) {
        this.performWindowsCapture(cb, outputPath);
    }
    performWindowsCapture(cb, outputPath) {
        require('hazardous');
        screenshot(outputPath, (err, complete) => {
            if(err) {
                cb(err, null, outputPath);
            } else {
                cb(null, complete, outputPath);
            }
        });
    }
}
/*/********************************************************************///
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working on an electron application that performs a screenshot capture every 3 seconds with the electron api, and writes it to a given target path. I've set up a separate BrowserWindow where the capturing code runs in (see code structure below) a setInterval() "loop", but whenever the capture happens, the app freezes for a moment. I think it is the call to source.thumbnail.toPng() or writeScreenshot() method in the file ScreenCapturer.jshtml.js.

I set up this structure as I though this was the way to go, but apparently this is not. WebWorkers won't help me either as I need node modules such as fs, path and desktopCapturer (from electron).

How would one do this type of task without blocking the main thread every time the interval code (as seen in file ScreenCapturer.jshtml.js) runs (because I thought the renderer processes were separate processes?)

My code as reference

main.js (main process)

// all the imports and other
// will only show the import that matters
import ScreenCapturer from './lib/capture/ScreenCapturer';

app.on('ready', () => {
   // Where I spawn my main UI
   mainWindow = new BrowserWindow({...});
   mainWindow.loadURL(...);
   // Other startup stuff

   // Hee comes the part where I call function to start capturing
   initCapture();
});

function initCapture() {
    const sc = new ScreenCapturer();
    sc.startTakingScreenshots();
}

ScreenCapturer.js (module used by main process)

'use strict';

/* ******************************************************************** */
/* IMPORTS */
import { app, BrowserWindow, ipcMain } from 'electron';
import url from 'url';
import path from 'path';
/* VARIABLES */
let rendererWindow;
/*/********************************************************************///
/*///*/

/* ******************************************************************** */
/* SCREENCAPTURER */
export default class ScreenCapturer {
    constructor() {
        rendererWindow = new BrowserWindow({
            show: true, width: 400, height: 600,
            'node-integration': true,
            webPreferences: {
                webSecurity: false
            }
        });
        rendererWindow.on('close', () => {
            rendererWindow = null;
        });
    }

    startTakingScreenshots(interval) {
        rendererWindow.webContents.on('did-finish-load', () => {
            rendererWindow.openDevTools();
            rendererWindow.webContents.send('capture-screenshot', path.join('e:', 'temp'));
        });
        rendererWindow.loadURL(
            url.format({
                pathname: path.join(__dirname, 'ScreenCapturer.jshtml.html'),
                protocol: 'file:',
                slashes: true
            })
        );
    }
}
/*/********************************************************************///
/*///*/

ScreenCapturer.jshtml.js (the thml file loaded in the renderer browser window)

ScreenCapturer.jshtml.js (the js file loaded from the html file in the renderer process)

import { ipcRenderer, desktopCapturer, screen } from 'electron';
import path from 'path';
import fs from 'fs';
import moment from 'moment';
let mainSource;

function getMainSource(mainSource, desktopCapturer, screen, done) {
    if(mainSource === undefined) {
        const options = {
            types: ['screen'],
            thumbnailSize: screen.getPrimaryDisplay().workAreaSize
        };
        desktopCapturer.getSources(options, (err, sources) => {
            if (err) return console.log('Cannot capture screen:', err);
            const isMainSource = source => source.name === 'Entire screen' || source.name === 'Screen 1';
            done(sources.filter(isMainSource)[0]);
        });
    } else {
        done(mainSource);
    }
}
function writeScreenshot(png, filePath) {
    fs.writeFile(filePath, png, err => {
        if (err) { console.log('Cannot write file:', err); }
        return;
    });
}

ipcRenderer.on('capture-screenshot', (evt, targetPath) => {
    setInterval(() => {
        getMainSource(mainSource, desktopCapturer, screen, source => {
            const png = source.thumbnail.toPng();
            const filePath = path.join(targetPath, `${moment().format('yyyyMMdd_HHmmss')}.png`);
            writeScreenshot(png, filePath);
        });
    }, 3000);
});

Body:
I walked away from using the API's delivered by electron. I'd recommend using desktop-screenshot package -> https://www.npmjs.com/package/desktop-screenshot. This worked cross platform (linux, mac, win) for me.
Note on windows we need the hazardous package, because otherwise when packaging your electron app with an asar it won't be able to execute the script inside desktop-screenshot. More info on the hazardous package's page.

Below is how my code now roughly works, please don't copy/paste because it might not fit your solution!! However it might give an indication on how you could solve it.

/* ******************************************************************** */
/* MODULE IMPORTS */
import { remote, nativeImage } from 'electron';
import path from 'path';
import os from 'os';
import { exec } from 'child_process';
import moment from 'moment';
import screenshot from 'desktop-screenshot';
/* */
/*/********************************************************************///
/* ******************************************************************** */
/* CLASS */
export default class ScreenshotTaker {
    constructor() {
        this.name = "ScreenshotTaker";
    }
    start(cb) {
        const fileName = `cap_${moment().format('YYYYMMDD_HHmmss')}.png`;
        const destFolder = global.config.app('capture.screenshots');
        const outputPath = path.join(destFolder, fileName);
        const platform = os.platform();
        if(platform === 'win32') {
            this.performWindowsCapture(cb, outputPath);
        }
        if(platform === 'darwin') {
            this.performMacOSCapture(cb, outputPath);
        }
        if(platform === 'linux') {
            this.performLinuxCapture(cb, outputPath);
        }
    }
    performLinuxCapture(cb, outputPath) {
        // debian
        exec(`import -window root "${outputPath}"`, (error, stdout, stderr) => {
            if(error) {
                cb(error, null, outputPath);
            } else {
                cb(null, stdout, outputPath);
            }
        });
    }
    performMacOSCapture(cb, outputPath) {
        this.performWindowsCapture(cb, outputPath);
    }
    performWindowsCapture(cb, outputPath) {
        require('hazardous');
        screenshot(outputPath, (err, complete) => {
            if(err) {
                cb(err, null, outputPath);
            } else {
                cb(null, complete, outputPath);
            }
        });
    }
}
/*/********************************************************************///