问:
Using Selenium to Login to Page
I'm trying to write a simple program using Python 2.7 and Selenium to automate checking my Presidents Choice MasterCard balance. However, I can't figure out how to deal with the hidden 'Go' button. My code works fine up to that point.

Check Banking

```<code>import time
import os
import subprocess
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import ui

user_id = raw_input('Enter your account number')
#password = raw_input('Enter your password')

driver = webdriver.Chrome()  # Optional argument, if not specified will search path.

def regular():

    site = driver.get('https://www.pcfinancial.ca/');

    sign_in_to = driver.find_element_by_xpath('//*[@id="lnkSignInOp"]').click()
    select = driver.find_element_by_xpath('//*[@id="PCM"]/a').click()
    select2 = driver.find_element_by_xpath('//*[@id="PCM"]/a').click()

    go = driver.find_element_by_xpath('//*[@id="ctl00_uscHeader_btnRegister"]').click()

regular()
</code>```

答:
You are doing it in a wrong way. You are clicking the PCM and after that PCM you are Clicking PCM again. Although you can select one option from drop down list.

Your go button id is also wrong.

your code should be look like below ---

```<code>import time
import os
import subprocess
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import ui

user_id = raw_input('Enter your account number')
#password = raw_input('Enter your password')

driver = webdriver.Chrome()  # Optional argument, if not specified will search path.

def regular():

    site = driver.get('https://www.pcfinancial.ca/');

    sign_in_to = driver.find_element_by_xpath('//*[@id="lnkSignInOp"]').click()
    select = driver.find_element_by_xpath('//*[@id="PCM"]/a').click()

    go = driver.find_element_by_xpath('//*[@id="util-go"]').click()

regular()
</code>```

IF you want to select PC points option then click on below element instead of  Pc Master card

```<code>select2 = driver.find_element_by_xpath('//*[@id="PCP"]/a').click()
</code>```

Title: Using Selenium to Login to Page

Body:
I'm trying to write a simple program using Python 2.7 and Selenium to automate checking my Presidents Choice MasterCard balance. However, I can't figure out how to deal with the hidden 'Go' button. My code works fine up to that point.

Check Banking

import time
import os
import subprocess
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import ui

user_id = raw_input('Enter your account number')
#password = raw_input('Enter your password')

driver = webdriver.Chrome()  # Optional argument, if not specified will search path.

def regular():

    site = driver.get('https://www.pcfinancial.ca/');

    sign_in_to = driver.find_element_by_xpath('//*[@id="lnkSignInOp"]').click()
    select = driver.find_element_by_xpath('//*[@id="PCM"]/a').click()
    select2 = driver.find_element_by_xpath('//*[@id="PCM"]/a').click()

    go = driver.find_element_by_xpath('//*[@id="ctl00_uscHeader_btnRegister"]').click()

regular()

Body:
You are doing it in a wrong way. You are clicking the PCM and after that PCM you are Clicking PCM again. Although you can select one option from drop down list.

Your go button id is also wrong.

your code should be look like below ---

import time
import os
import subprocess
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import ui

user_id = raw_input('Enter your account number')
#password = raw_input('Enter your password')

driver = webdriver.Chrome()  # Optional argument, if not specified will search path.

def regular():

    site = driver.get('https://www.pcfinancial.ca/');

    sign_in_to = driver.find_element_by_xpath('//*[@id="lnkSignInOp"]').click()
    select = driver.find_element_by_xpath('//*[@id="PCM"]/a').click()

    go = driver.find_element_by_xpath('//*[@id="util-go"]').click()

regular()

IF you want to select PC points option then click on below element instead of  Pc Master card

select2 = driver.find_element_by_xpath('//*[@id="PCP"]/a').click()


来源: stackexchange

问:
How instantiate case class from Map[String, String]
Lets say I have

```<code>case class Sample(i:Int, b:Boolean)
</code>```

and

```<code>Map[String, String]("i" => "1", "b" => "false")
</code>```

What is most concise way to instantiate any case class(if all fields are in map), signature like this:

```<code> get[T](map:[String, String]) : T
</code>```

Probably shapeless can help acomplish this task, but I am almost unfamiliar with it. Thanks!

答:
If not using Shapeless is an option for you, you could do it in a simple way without it. Here is a sample implementation where I use the Try Monad and a pattern matching to transform the Map into your case class:

```<code>  (Try("1".toInt), Try("false".toBoolean)) match {
    case (Success(intVal), Success(boolVal)) =>
      Sample(intVal, boolVal)
    case _ => // Log and ignore the values
  }
</code>```

Of course this is a bit verbose than the Shapeless version, but if you do not want to use a full library just for this simple use case, you could always do it using Scala library!

ContentLicense: CC BY-SA 3.0

Body:
Lets say I have

case class Sample(i:Int, b:Boolean)

and

Map[String, String]("i" => "1", "b" => "false")

What is most concise way to instantiate any case class(if all fields are in map), signature like this:

 get[T](map:[String, String]) : T

Probably shapeless can help acomplish this task, but I am almost unfamiliar with it. Thanks!

Body:
If not using Shapeless is an option for you, you could do it in a simple way without it. Here is a sample implementation where I use the Try Monad and a pattern matching to transform the Map into your case class:

  (Try("1".toInt), Try("false".toBoolean)) match {
    case (Success(intVal), Success(boolVal)) =>
      Sample(intVal, boolVal)
    case _ => // Log and ignore the values
  }

Of course this is a bit verbose than the Shapeless version, but if you do not want to use a full library just for this simple use case, you could always do it using Scala library!


问:
Warnings in boost::priority_queue
When I try to build "priority_queue_example.cpp" it get these warnings(and so errors) pointing to  "priority_queue_example.h" on the line where my priority_queue is declared. The warnings are,

```<code>1>  priority_queue_example.cpp
1>c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(102): error C2220: warning treated as error - no 'object' file generated
1>c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(102): warning
C4100: 'rhs' : unreferenced formal parameter
1>          c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(102) : while compiling class template member function 'boost::heap::detail::size_holder<false,size_t>::size_holder(const boost::heap::detail::size_holder<false,size_t> &)'
1>          c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(189) : see reference to function template instantiation 'boost::heap::detail::size_holder<false,size_t>::size_holder(const boost::heap::detail::size_holder<false,size_t> &)' being compiled
1>          c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(151) : see reference to class template instantiation 'boost::heap::detail::size_holder<false,size_t>' being compiled
1>          c:\Projects\lib\boost\boost\heap\priority_queue.hpp(65) : see reference to class template instantiation 'boost::heap::detail::heap_base<T,myObjectPtrCompare,false,unsigned __int64,false>' being compiled
1>          with
1>          [
1>              T=myObject *
1>          ]
1>          c:\Projects\priority_queue_example.h(193) : see reference to class template instantiation 'boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>' being compiledcompare<ObjectPtrCompare>,boost::parameter::void_,boost::parameter::void
</code>```

My priority_queue is declared as,

```<code>mutable boost::heap::priority_queue<myObject*, boost::heap::compare<myObjectPtrCompare> > hp;
</code>```

I'm not sure what this means. Can I fix this?

This is my comparison class defined,

```<code>struct myObjectPtrCompare
{
    bool operator()(const myObject* lhs, const myObject* rhs) const
    {
        return (lhs->getProp() < rhs->getProp());
    }
};
</code>```

答:
Boost is not warning-free with /W4. That means that there could be spurious warnings, even if your code is corect.

You can disable specific warnings as specified in this article: https://learn.microsoft.com/en-us/visualstudio/ide/how-to-suppress-compiler-warnings

In Solution Explorer, choose the project or source file in which you want to suppress warnings.

On the menu bar, choose View, Property Pages.

Choose the Configuration Properties category, choose the C/C++ category, and then choose the Advanced page.

Perform one of the following steps:

In the Disable Specific Warnings box, specify the error codes of the warnings that you want to suppress, separated by a semicolon.

In the Disable Specific Warnings box, choose Edit to display more options.

Choose the OK button, and then rebuild the solution.

Title: Warnings in boost::priority_queue

Body:
When I try to build "priority_queue_example.cpp" it get these warnings(and so errors) pointing to  "priority_queue_example.h" on the line where my priority_queue is declared. The warnings are,

1>  priority_queue_example.cpp
1>c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(102): error C2220: warning treated as error - no 'object' file generated
1>c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(102): warning
C4100: 'rhs' : unreferenced formal parameter
1>          c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(102) : while compiling class template member function 'boost::heap::detail::size_holder<false,size_t>::size_holder(const boost::heap::detail::size_holder<false,size_t> &)'
1>          c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(189) : see reference to function template instantiation 'boost::heap::detail::size_holder<false,size_t>::size_holder(const boost::heap::detail::size_holder<false,size_t> &)' being compiled
1>          c:\Projects\lib\boost\boost\heap\detail\stable_heap.hpp(151) : see reference to class template instantiation 'boost::heap::detail::size_holder<false,size_t>' being compiled
1>          c:\Projects\lib\boost\boost\heap\priority_queue.hpp(65) : see reference to class template instantiation 'boost::heap::detail::heap_base<T,myObjectPtrCompare,false,unsigned __int64,false>' being compiled
1>          with
1>          [
1>              T=myObject *
1>          ]
1>          c:\Projects\priority_queue_example.h(193) : see reference to class template instantiation 'boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>' being compiledcompare<ObjectPtrCompare>,boost::parameter::void_,boost::parameter::void

My priority_queue is declared as,

mutable boost::heap::priority_queue<myObject*, boost::heap::compare<myObjectPtrCompare> > hp;

I'm not sure what this means. Can I fix this?

This is my comparison class defined,

struct myObjectPtrCompare
{
    bool operator()(const myObject* lhs, const myObject* rhs) const
    {
        return (lhs->getProp() < rhs->getProp());
    }
};


问:
Finding an integer key of a Python dict that is closest to a given integer
I have a dictionary where the keys are integers.  I have another integer.  I want to find the value corresponding to the key in the dict that is closest to the given integer.  Is there an efficient way to do this?

Maybe a different data structure (binary tree) would be more efficient?

答:
Best you're going to get on this is probably O(n) runtime.</p>

```<code>def closestKey(dic, key):
    diff = {k:abs(k - key) for k in dic}
    return min(diff, key=diff.get)
</code>```

Body:
Best you're going to get on this is probably O(n) runtime.

def closestKey(dic, key):
    diff = {k:abs(k - key) for k in dic}
    return min(diff, key=diff.get)


答:
I don't see any other way to do it other than iterating over the entire dictionary and then seeing which key was the closest by recording min_diff, as well as the key itself as variables.

Alternatively, you could try using an ordered dict to save some time, but either way it'll run in linear time.

Title: Finding an integer key of a Python dict that is closest to a given integer

Body:
I have a dictionary where the keys are integers.  I have another integer.  I want to find the value corresponding to the key in the dict that is closest to the given integer.  Is there an efficient way to do this?

Maybe a different data structure (binary tree) would be more efficient?


问:
How to add one to the value of the record based on the previous record
Hypothetically,In the table which had 1000 records，but there are one column(Digital type) without value,just like
this

then I want to update table like
this

I hope you give me some advice,appreciate greatly!

答:
Well, even if it is a string field, assuming you want to insert a number as in the picture you can use the following example for reference:

```<code>DROP TABLE test_table;

CREATE TABLE test_table
    (`col_1` varchar(10), `col_2` varchar(10))
;

INSERT INTO test_table
    (`col_1`, `col_2`)
VALUES
    ('A', null),
    ('B', null),
    ('C', null),
    ('D', null),
    ('E', null)
;
</code>```

and then query to the update the null col_2

```<code>SET @new_value := 999;

update test_table set col_2 = @new_value:=@new_value + 1;

select * from test_table;
</code>```

Basically I define the new value to be 1 minus my start (1000 -1 = 999) with SET @new_value := 999; and then during the update I set @new_value to be equal to itself + 1 which then set to col_2.  The update continues onto the next row which then sets to 1000 + 1, and so on.

Body:
Well, even if it is a string field, assuming you want to insert a number as in the picture you can use the following example for reference:

DROP TABLE test_table;

CREATE TABLE test_table
    (`col_1` varchar(10), `col_2` varchar(10))
;

INSERT INTO test_table
    (`col_1`, `col_2`)
VALUES
    ('A', null),
    ('B', null),
    ('C', null),
    ('D', null),
    ('E', null)
;

and then query to the update the null col_2

SET @new_value := 999;

update test_table set col_2 = @new_value:=@new_value + 1;

select * from test_table;

Basically I define the new value to be 1 minus my start (1000 -1 = 999) with SET @new_value := 999; and then during the update I set @new_value to be equal to itself + 1 which then set to col_2.  The update continues onto the next row which then sets to 1000 + 1, and so on.


问:
Number which occurs only once in the array

Possible Duplicate:

  Finding a single number in a list

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

Example

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

should return 4

答:
zerkms' answer in C++</p>

```<code>int a[] = { 1,2,3,4,3,1,2 };

int i = std::accumulate(a, a + 7, 0, std::bit_xor<int>());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  Finding a single number in a list

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

Example

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

should return 4

Body:
zerkms' answer in C++

int a[] = { 1,2,3,4,3,1,2 };

int i = std::accumulate(a, a + 7, 0, std::bit_xor<int>());


问:
Trying to copy all strings from char*[] but get segmentation fault
I am trying to figure out why I am getting a segmentation fault when trying to copy the arguments from one array of strings to another but just leaving out the > </p>

```<code>int main(){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = 4*sizeof(args)/sizeof(args);
     char *temp[size];
     int i;

     printf("SIZE: %d\n", size);
     for(i = 0; i < size; ++i){
            if(strcmp(args[i], ">") > 0 || strcmp(args[i], ">") < 0 ){
                strcpy(temp[i],args[i]);

            }
            printf("arg: %s\n", temp[i]);
     }
</code>```

答: Your code crashes here at strcpy(temp[i],args[i]); as temp[i] has uninitialised values. You need allocate memory and store the address in temp[i] before calling strcpy

Body:
I am trying to figure out why I am getting a segmentation fault when trying to copy the arguments from one array of strings to another but just leaving out the >

int main(){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = 4*sizeof(args)/sizeof(args);
     char *temp[size];
     int i;

     printf("SIZE: %d\n", size);
     for(i = 0; i < size; ++i){
            if(strcmp(args[i], ">") > 0 || strcmp(args[i], ">") < 0 ){
                strcpy(temp[i],args[i]);

            }
            printf("arg: %s\n", temp[i]);
     }


问:
Unknown JavaScript syntax when defining an object
I came across some JavaScript syntax I haven't seen before. Can someone help point me in the right direction, I'm not even sure what I could google to learn more :/

```<code>$.variable = function() {
  return a(b, [{
    key: "setPeriod",
    value: function(t) {
      this.variable.period = t;
    }
  }, {
    key: "location",
    get: function() {
      return "earth";
    }
  }])
}

$.variable.setPeriod("test");
$.variable.location;
</code>```

My question is what is this structure where an object is defined via a list. Also not sure what the difference between value and get is. Any help would be appreciated.

Here's an example of a snippet:

https://pastebin.com/zymW2XZw

答:
Here my guess about what happens to this list of objects :

var o = s([{
  key: "attribute",
  value: "default"
}, {
  key: "getAttribute",
  value: function () {
    return this.attribute;
  }
}, {
  key: "setAttribute",
  value: function (value) {
    this.attribute = value;
  }
}]);

console.log(o.getAttribute());
o.setAttribute("custom");
console.log(o.getAttribute());

function s (members) {
  var o = {};
  members.forEach(function (member) {
    o[member.key] = member.value;
  });
  return o;
}```

I guess the framework needs to preprocess the object's members for some obscure reasons related to the framework internal mecanism.

Body:
I came across some JavaScript syntax I haven't seen before. Can someone help point me in the right direction, I'm not even sure what I could google to learn more :/

$.variable = function() {
  return a(b, [{
    key: "setPeriod",
    value: function(t) {
      this.variable.period = t;
    }
  }, {
    key: "location",
    get: function() {
      return "earth";
    }
  }])
}

$.variable.setPeriod("test");
$.variable.location;

My question is what is this structure where an object is defined via a list. Also not sure what the difference between value and get is. Any help would be appreciated.

Here's an example of a snippet:

https://pastebin.com/zymW2XZw

Body:
Here my guess about what happens to this list of objects :

var o = s([{
  key: "attribute",
  value: "default"
}, {
  key: "getAttribute",
  value: function () {
    return this.attribute;
  }
}, {
  key: "setAttribute",
  value: function (value) {
    this.attribute = value;
  }
}]);

console.log(o.getAttribute());
o.setAttribute("custom");
console.log(o.getAttribute());

function s (members) {
  var o = {};
  members.forEach(function (member) {
    o[member.key] = member.value;
  });
  return o;
}

I guess the framework needs to preprocess the object's members for some obscure reasons related to the framework internal mecanism.


问:
Polymers this.async vs Promise.then vs setTimeout
Whats the difference between Polymers this.async, Promise.then and setTimeout function?

My understanding:

this.async and Promise.then moves a Task to the end of the current Stack and setTimeout is handled as new Task and executed in the next loop when the eventloop takes a new task from the queue?

Please correct me if I am wrong.

答:
TLDR: Yes, but note this.async uses setTimeout if a timeout is specified.

Polymer.Async.run (this.async) without timeout - queues a microtask (via a MutationObserver callback)

Polymer.Async.run (this.async) with timeout - queues a macrotask

Promise.then - queues a microtask

setTimeout - queues a macrotask

Difference between microtask and macrotask within an event loop context


问:
Ansible EC2 Snapshots
I'm trying to automate the EC2 snapshots using the Ansible. I wrote the following play to gather the facts:

```<code>- hosts: localhost
  connection: local
  tasks:
    - name: Gathering the facts...
        ec2_remote_facts:
        aws_secret_key: bcv.jdbvdjbvdfjbv
        aws_access_key: dfnvdfnbvdfjbvndfj
        region: us-west-2
      register: ec2_facts

- name: printing the results
  debug: var=ec2_facts
</code>```

Above play works fine and returns the following output:

```<code>ok: [localhost] => {
    "ec2_facts": {
    "changed": false,
    "instances": [
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-12-08T08:52:21.000Z",
                    "delete_on_termination": true,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-0f0026ee65c5452e4"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-e5d10780",
                    "name": "default"
                }
            ],
            "hypervisor": "xen",
            "id": "i-0409acd413bb9db0f",
            "image_id": "ami-03445933",
            "instance_profile": null,
            "interfaces": [
                {
                    "id": "eni-1ea57b3d",
                    "mac_address": "02:04:f4:3a:92:34"
                }
            ],
            "kernel": null,
            "key_name": "ansible-test",
            "launch_time": "2017-12-08T08:52:20.000Z",
            "monitoring_state": "disabled",
            "persistent": false,
            "placement": {
                "tenancy": "default",
                "zone": "us-west-2b"
            },
            "private_dns_name": "ip-172-31-41-48.us-west-2.compute.internal",
            "private_ip_address": "172.31.41.48",
            "public_dns_name": "ec2-x-x-x-x.us-west-2.compute.amazonaws.com",
            "public_ip_address": "x.x.x.x",
            "ramdisk": null,
            "region": "us-west-2",
            "requester_id": null,
            "root_device_type": "ebs",
            "source_destination_check": "true",
            "spot_instance_request_id": null,
            "state": "running",
            "tags": {},
            "virtualization_type": "hvm",
            "vpc_id": "vpc-4a77992f"
        },
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-12-08T11:43:45.000Z",
                    "delete_on_termination": false,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-036a851b5b96ac359"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-c63677a3",
                    "name": "test"
                }
            ],
            "hypervisor": "xen",
            "id": "i-05b9ecfe5fa30be49",
            "image_id": "ami-02c71d7a",
            "instance_profile": null,
            "interfaces": [
                {
                    "id": "eni-e2d40dc1",
                    "mac_address": "02:7c:b1:08:45:e8"
                }
            ],
            "kernel": null,
            "key_name": "ansible-test",
            "launch_time": "2017-12-08T11:43:44.000Z",
            "monitoring_state": "disabled",
            "persistent": false,
            "placement": {
                "tenancy": "default",
                "zone": "us-west-2b"
            },
            "private_dns_name": "ip-172-31-35-159.us-west-2.compute.internal",
            "private_ip_address": "172.31.35.159",
            "public_dns_name": "ec2-x-x-x-x.us-west-2.compute.amazonaws.com",
            "public_ip_address": "x.x.x.x",
            "ramdisk": null,
            "region": "us-west-2",
            "requester_id": null,
            "root_device_type": "ebs",
            "source_destination_check": "true",
            "spot_instance_request_id": null,
            "state": "running",
            "tags": {},
            "virtualization_type": "hvm",
            "vpc_id": "vpc-4a77992f"
        }
    ]
}
}
</code>```

I have two running test instances in my AWS account and above output shows the correct information. Now using the above facts, I want to snapshot the EBS volumes attached to the respective instances. But theami_launch_index value always returns 0 even if there are multiple instances. So i believe I cannot dynamically select the instances and attached EBS volumes to snapshot it. Following is the play I've wrote to snapshot the instances based on the above facts:

```<code>- name: Snapshoting the instance...
  ec2_snapshot:
    aws_secret_key: bcv.jdbvdjbvdfjbv
    aws_access_key: dfnvdfnbvdfjbvndfj
    region: us-west-2
    instance_id: "{{ item.id }}"
    device_name: "{{ item['device_name'] }}"
    description: "Snapshot test by"
  with_items: "{{ ec2_facts.instances }}"
</code>```

So can anyone please help me to solve the issue?

答:
AFAIK snapshots are for volumes, not for instances.

Why not just take all volume_id's and snapshot them?

```<code>- name: Snapshoting the instance...
  ec2_snapshot:
    region: us-west-2
    volume_id: "{{ item }}"
    description: "Snapshot test by"
  with_items: "{{ ec2_facts | json_query('instances[].block_device_mapping[].volume_id') }}"
</code>```

Title: Ansible EC2 Snapshots

Body:
I'm trying to automate the EC2 snapshots using the Ansible. I wrote the following play to gather the facts:

- hosts: localhost
  connection: local
  tasks:
    - name: Gathering the facts...
        ec2_remote_facts:
        aws_secret_key: bcv.jdbvdjbvdfjbv
        aws_access_key: dfnvdfnbvdfjbvndfj
        region: us-west-2
      register: ec2_facts

- name: printing the results
  debug: var=ec2_facts

Above play works fine and returns the following output:

ok: [localhost] => {
    "ec2_facts": {
    "changed": false,
    "instances": [
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-12-08T08:52:21.000Z",
                    "delete_on_termination": true,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-0f0026ee65c5452e4"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-e5d10780",
                    "name": "default"
                }
            ],
            "hypervisor": "xen",
            "id": "i-0409acd413bb9db0f",
            "image_id": "ami-03445933",
            "instance_profile": null,
            "interfaces": [
                {
                    "id": "eni-1ea57b3d",
                    "mac_address": "02:04:f4:3a:92:34"
                }
            ],
            "kernel": null,
            "key_name": "ansible-test",
            "launch_time": "2017-12-08T08:52:20.000Z",
            "monitoring_state": "disabled",
            "persistent": false,
            "placement": {
                "tenancy": "default",
                "zone": "us-west-2b"
            },
            "private_dns_name": "ip-172-31-41-48.us-west-2.compute.internal",
            "private_ip_address": "172.31.41.48",
            "public_dns_name": "ec2-x-x-x-x.us-west-2.compute.amazonaws.com",
            "public_ip_address": "x.x.x.x",
            "ramdisk": null,
            "region": "us-west-2",
            "requester_id": null,
            "root_device_type": "ebs",
            "source_destination_check": "true",
            "spot_instance_request_id": null,
            "state": "running",
            "tags": {},
            "virtualization_type": "hvm",
            "vpc_id": "vpc-4a77992f"
        },
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-12-08T11:43:45.000Z",
                    "delete_on_termination": false,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-036a851b5b96ac359"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-c63677a3",
                    "name": "test"
                }
            ],
            "hypervisor": "xen",
            "id": "i-05b9ecfe5fa30be49",
            "image_id": "ami-02c71d7a",
            "instance_profile": null,
            "interfaces": [
                {
                    "id": "eni-e2d40dc1",
                    "mac_address": "02:7c:b1:08:45:e8"
                }
            ],
            "kernel": null,
            "key_name": "ansible-test",
            "launch_time": "2017-12-08T11:43:44.000Z",
            "monitoring_state": "disabled",
            "persistent": false,
            "placement": {
                "tenancy": "default",
                "zone": "us-west-2b"
            },
            "private_dns_name": "ip-172-31-35-159.us-west-2.compute.internal",
            "private_ip_address": "172.31.35.159",
            "public_dns_name": "ec2-x-x-x-x.us-west-2.compute.amazonaws.com",
            "public_ip_address": "x.x.x.x",
            "ramdisk": null,
            "region": "us-west-2",
            "requester_id": null,
            "root_device_type": "ebs",
            "source_destination_check": "true",
            "spot_instance_request_id": null,
            "state": "running",
            "tags": {},
            "virtualization_type": "hvm",
            "vpc_id": "vpc-4a77992f"
        }
    ]
}
}

I have two running test instances in my AWS account and above output shows the correct information. Now using the above facts, I want to snapshot the EBS volumes attached to the respective instances. But theami_launch_index value always returns 0 even if there are multiple instances. So i believe I cannot dynamically select the instances and attached EBS volumes to snapshot it. Following is the play I've wrote to snapshot the instances based on the above facts:

- name: Snapshoting the instance...
  ec2_snapshot:
    aws_secret_key: bcv.jdbvdjbvdfjbv
    aws_access_key: dfnvdfnbvdfjbvndfj
    region: us-west-2
    instance_id: "{{ item.id }}"
    device_name: "{{ item['device_name'] }}"
    description: "Snapshot test by"
  with_items: "{{ ec2_facts.instances }}"

So can anyone please help me to solve the issue?

Body:
AFAIK snapshots are for volumes, not for instances.

Why not just take all volume_id's and snapshot them?

- name: Snapshoting the instance...
  ec2_snapshot:
    region: us-west-2
    volume_id: "{{ item }}"
    description: "Snapshot test by"
  with_items: "{{ ec2_facts | json_query('instances[].block_device_mapping[].volume_id') }}"


问:
Does Android Studio have column guide for commit message?
There is a convention on git commit messages to define the maximum characters per line (50 in the first line, 72 on the rest). Sourcetree have an option to enable a line at a configurable position. The image below shows an example of a column in Sourcetree configured at 72 characters.

Does Android Studio have something like that to allow me do visually identify if my line is too long like the example in Sourcetree?

答:
Since IntelliJ IDEA is the base for Android Studio, you can use a plugin.

Here:

Git Commit Message Plugin, which allows you to create Git commit messages with a structure defined within a template, that is customized by the user himself.

or Git Commit Template Code tools, which does have a breakLines() function (so no visual aid here: the message will be formatted)

ContentLicense: CC BY-SA 4.0


问:
Best choice to build a website like http://www.pageflakes.com/
What is the best language and approach  to build the widgets website like http://www.pageflakes.com/. By best I mean rapid development, performance, smoothness and by approach I mean that some one will use drag and drop plug in jQuery (some issues) etc.

Two functionality will be main in my site:

selecting the widget and then dragging on the specified position i like

saving the state without login for the user.

答:
You don't mention your existing language skills which might be the most important detail here. Also, are you prepared to learn a new language/framework for this project?

Some generic advice assuming you would be using Java: since the site in consideration looks more like a web application as opposed to a "web site", a framework which supports rich controls/Ajax natively might work wonders here. A GWT based framework like SmartGWT might be an interesting candidate.


问:
How to make two buttons on the same row in eclipse programmatically?
```<code>LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

btnControl = new Button(this);
    btnControl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnControl.setPadding(0,40,0,40);//x,y,w,h
    btnControl.setBackgroundColor(Color.parseColor("#1C344E"));
    btnControl.setTextColor(Color.WHITE);
    setMargins(btnControl, 50, 50, 50, 50);

btnLogs = new Button(this);
        btnLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnLogs.setPadding(0,40,0,40);//x,y,w,h
        btnLogs.setBackgroundColor(Color.parseColor("#1C344E"));
        btnLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnLogs.setId(5);
        btnLogs.setOnClickListener(this);

        btnTermLogs = new Button(this);
        btnTermLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnTermLogs.setPadding(0,40,0,40);//x,y,w,h
        btnTermLogs.setBackgroundColor(Color.parseColor("#CC6675"));
        btnTermLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnTermLogs.setId(6);
        btnTermLogs.setOnClickListener(this);

btnLogout = new Button(this);
    btnLogout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnLogout.setPadding(0,40,0,40);//x,y,w,h
    btnLogout.setBackgroundColor(Color.parseColor("#CC6675"));
    btnLogout.setTextColor(Color.WHITE);

    table.addView(btnLogs);
        table.addView(btnTermLogs);
</code>```

I want the two buttons to be aligned together horizontally. However it just align themselves vertically which i dont want.

My buttons look like this:

what i want is to look like this:

答:
You can create another XML file, that contains a horizontal LinearLayout, then inflate it and insert the two buttons into it, and then add the whole horizontal LinearLayout to the vertical LinearLayout:

Create an XML file e.g. horizontal_layout.xml:

```<code><LinearLayout
    android:id="@+id/horizontal_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

// You will insert the buttons programmatically.

</LinearLayout>
</code>```

In your Activity use this method to inflate the Layout:

```<code>    LinearLayout verticalLinearLayout = rootView.findViewById(R.id.vertical_linear_layout);

// Add the first vertical Button regularly.
Button firstVerticalButton = new Button(Activity.this);
firstVerticalButton.setText("Vertical");
verticalLinearLayout.addView(firstVerticalButton);

// Inflate the horizontal LinearLayout and add the two horizontal buttons.
LinearLayout horizontalLinearLayout = getLayoutInflater().inflate(R.layout.horizontal_layout,
        linearLayout, false);

Button horizontalOne = new Button(Activity.this);
horizontalOne.setText("Horizontal");
LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
childParam1.weight = 0.5f;
horizontalOne.setLayoutParams(childParam);

Button horizontalTwo = new Button(Activity.this);
horizontalTwo.setText("Horizontal");
LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
childParam1.weight = 0.5f;
horizontalTwo.setLayoutParams(childParam2);

horizontalLinearLayout.addView(horizontalOne);
horizontalLinearLayout.addView(horizontalTwo);

// Insert the inflated layout to the main layout.
verticalLinearLayout.addView(horizontalLinearLayout);

// Add the second vertical Button
Button secondVerticalButton = new Button(Activity.this);
secondVerticalButton.setText("Vertical");
verticalLinearLayout.addView(secondVerticalButton);
</code>```

Body:
LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

btnControl = new Button(this);
    btnControl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnControl.setPadding(0,40,0,40);//x,y,w,h
    btnControl.setBackgroundColor(Color.parseColor("#1C344E"));
    btnControl.setTextColor(Color.WHITE);
    setMargins(btnControl, 50, 50, 50, 50);

btnLogs = new Button(this);
        btnLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnLogs.setPadding(0,40,0,40);//x,y,w,h
        btnLogs.setBackgroundColor(Color.parseColor("#1C344E"));
        btnLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnLogs.setId(5);
        btnLogs.setOnClickListener(this);

        btnTermLogs = new Button(this);
        btnTermLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnTermLogs.setPadding(0,40,0,40);//x,y,w,h
        btnTermLogs.setBackgroundColor(Color.parseColor("#CC6675"));
        btnTermLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnTermLogs.setId(6);
        btnTermLogs.setOnClickListener(this);

btnLogout = new Button(this);
    btnLogout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnLogout.setPadding(0,40,0,40);//x,y,w,h
    btnLogout.setBackgroundColor(Color.parseColor("#CC6675"));
    btnLogout.setTextColor(Color.WHITE);

    table.addView(btnLogs);
        table.addView(btnTermLogs);

I want the two buttons to be aligned together horizontally. However it just align themselves vertically which i dont want.

My buttons look like this:

what i want is to look like this:

Body:
You can create another XML file, that contains a horizontal LinearLayout, then inflate it and insert the two buttons into it, and then add the whole horizontal LinearLayout to the vertical LinearLayout:

Create an XML file e.g. horizontal_layout.xml:

<LinearLayout
    android:id="@+id/horizontal_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

// You will insert the buttons programmatically.

</LinearLayout>

In your Activity use this method to inflate the Layout:

    LinearLayout verticalLinearLayout = rootView.findViewById(R.id.vertical_linear_layout);

// Add the first vertical Button regularly.
Button firstVerticalButton = new Button(Activity.this);
firstVerticalButton.setText("Vertical");
verticalLinearLayout.addView(firstVerticalButton);

// Inflate the horizontal LinearLayout and add the two horizontal buttons.
LinearLayout horizontalLinearLayout = getLayoutInflater().inflate(R.layout.horizontal_layout,
        linearLayout, false);

Button horizontalOne = new Button(Activity.this);
horizontalOne.setText("Horizontal");
LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
childParam1.weight = 0.5f;
horizontalOne.setLayoutParams(childParam);

Button horizontalTwo = new Button(Activity.this);
horizontalTwo.setText("Horizontal");
LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
childParam1.weight = 0.5f;
horizontalTwo.setLayoutParams(childParam2);

horizontalLinearLayout.addView(horizontalOne);
horizontalLinearLayout.addView(horizontalTwo);

// Insert the inflated layout to the main layout.
verticalLinearLayout.addView(horizontalLinearLayout);

// Add the second vertical Button
Button secondVerticalButton = new Button(Activity.this);
secondVerticalButton.setText("Vertical");
verticalLinearLayout.addView(secondVerticalButton);


问:
Using R code: Converting date in integer format 20081028
While converting integer value 20081028 to date format, I have written a code:

```<code>lakers<-as.Date(lakers$date, "%Y%m%d")
</code>```

I am getting error to converting char to date.

Can you help me. Where I am doing wrong

Following are the details of the code error.

lakers$date<-as.Date(lakers$date,"%Y%m%d")

Error in charToDate(x) :
  character string is not in a standard unambiguous format

while if I use R code :

lakers$Date = as.POSIXct.Date(lakers$Date, "%Y%m%d")

Then the following error I am getting.

Error in $<-.data.frame(*tmp*, Date, value = numeric(0)) :
  replacement has 0 rows, data has 34624

Note down my sample data.

head(lakers)

```<code>date opponent game_type  time period     etype team    player result points
</code>```

1 20081028    POR    home    12:00   1      jump ball    OFF           0
2 20081028   POR      home 11:39      1      shot  LAL           Pau Gasol

Please help me.

答:
It needs it be in a standard date format first. Try:</p>

```<code>Lakers$Date = as.POSIXct.Date(Lakers$Date, "%Y%m%d")
</code>```

Body:
While converting integer value 20081028 to date format, I have written a code:

lakers<-as.Date(lakers$date, "%Y%m%d")

I am getting error to converting char to date.

Can you help me. Where I am doing wrong

Following are the details of the code error.

lakers$date<-as.Date(lakers$date,"%Y%m%d")

Error in charToDate(x) :
  character string is not in a standard unambiguous format

while if I use R code :

lakers$Date = as.POSIXct.Date(lakers$Date, "%Y%m%d")

Then the following error I am getting.

Error in $<-.data.frame(*tmp*, Date, value = numeric(0)) :
  replacement has 0 rows, data has 34624

Note down my sample data.

head(lakers)

date opponent game_type  time period     etype team    player result points

1 20081028    POR    home    12:00   1      jump ball    OFF           0
2 20081028   POR      home 11:39      1      shot  LAL           Pau Gasol

Please help me.

Body:
It needs it be in a standard date format first. Try:

Lakers$Date = as.POSIXct.Date(Lakers$Date, "%Y%m%d")


问:
Pass data from html object to another according to its id in my data base
So i have two files: index.php and details modal.php. In the index .php file I managed to create a dynamic  object that displays the title, price and image of a product that is stored in my database. That right there is perfect. As you can see in the image each product has a button that says Detalles (Details) which was generated dynamically.That button opens little window on top of the page(called detailsmodal.php). I want to show the data that is in there depending on the product that I chose. I have tried calling the data from the databse but it can only call the data of product one( meaning that if I click on product 2 it still shows the data of product 1) how can I fix that?
Here are some screenshots and my index.php and detailsmodal.php code.

In this image on the left is what is shown on detailsmodal.php

In this image on the left is what is shown on index.php.

index.php

<?php
require_once'core/init.php';
include'includes/head.php';
?>

<?php
include('includes/navigation.php');
?>

<?php
include('includes/headerfull.php');
?>

<?php
include('includes/leftbar.php');

?>
<?php
$sql =  "SELECT * FROM products WHERE featured = 1";
$featured= $db->query($sql);
?>

Main

Productos destacados

  <?php while($product= mysqli_fetch_assoc($featured)):?>

<?php echo $product['title']?>

   <img src="<?php echo $product['image']?>" id="producto2"   imagenProducto" alt=<?php echo $product['title']?> class="img-thumb" />

Precio del Mercado <s>₡<?php echo $product['list_price']?></s>

Nuestro precio: ₡<?php echo $product['price']?>

   <button type="button" class="btn butn-sm btn-success" data-toggle="modal" data-target="#details-1">Detalles</button>
   <?php include('includes/detailsmodal.php');?>

  <?php endwhile;?>

 <?php

?>

 <?php

include('includes/rightbar.php');
?>

 <?php
include('includes/footer.php');
?>
 ```
</div>
</div>
</p>

<p>detailsmodal.php</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="modal fade details-1" id="details-1" tabindex="-1" role="dialog" aria-labelledby="details-1" aria-hidden="true">
 <div class="modal-dialog modal-lg">
 <div class="modal-content">
  <div class="modal-header">
   <button class="close" type="button" data-dismiss="modal" arial-label="Close">
    <span aria-hidden="true">×</span>
   </button>
   <h4 class="modal-title text-center"><?php echo $product['title']?>

   </h4>
  </div>
  <div class="modal-body">
   <div class="container-fluid">
    <div class="row">
     <div class="col-sm-6">
      <div class="center-block">
       <img src="images/products/planta1.png" alt="Levis Jeans" id="viewProducto" class="details img-responsive">
      </div>
     </div>
     <div class="col-sm-6"></div>
     <h4>Detalles</h4>
     <p><?php echo $product['description']?></p>
     <hr>
     <p>Precio :<?php echo $product['price']?></p>
     <p>Marca: N/A</p>
     <form action="add_cart.php" method="post">
      <div class="form-group">
       <div class="col-xs-3">
        <label for="quantity">Cantidad:</label>
        <input type="text" class="form-control" id="quantity" name="quantity">
        <p>Disponibles: 3</p>
       <div class="form-group">
       <label for="size"></label>
       Size:<select name="size" id="size" class="form-control">
        <option value="36">36</option>
        <option value="40">40</option>
        <option value="50">50</option>
        <option value="30">30</option>
       </select>
      </div>

       </div>

      </div>

     </form>
    </div>
   </div>
  </div>
  <div class="modal-footer">
  <button class="btn btn-default" data-dismiss="modal">Cerrar</button>
  <button class="btn btn-warning" type="submit"><img class="cartPNG" src="images/logos/cart.png"> Agregar a Carrito</button>
 </div>
 </div>

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

答:
Just because you have give all modal with same id so it will call always first modal with same id.Just look at updated code.

<?php
require_once'core/init.php';
include'includes/head.php';
?>

<?php
include('includes/navigation.php');
?>

<?php
include('includes/headerfull.php');
?>

<?php
include('includes/leftbar.php');

?>
<?php
$sql =  "SELECT * FROM products WHERE featured = 1";
$featured= $db->query($sql);
?>

Main

Productos destacados

  <?php while($product= mysqli_fetch_assoc($featured)):?>

<?php echo $product['title']?>

   <img src="<?php echo $product['image']?>" id="producto2"   imagenProducto" alt=<?php echo $product['title']?> class="img-thumb" />

Precio del Mercado <s>₡<?php echo $product['list_price']?></s>

Nuestro precio: ₡<?php echo $product['price']?>

   <button type="button" class="btn butn-sm btn-success" data-toggle="modal" data-target="#details-<?php echo $product['id'];?>">Detalles</button>
   <?php include('includes/detailsmodal.php');?>

  <?php endwhile;?>

 <?php

?>

 <?php

include('includes/rightbar.php');
?>

 <?php
include('includes/footer.php');
?>

//modal.php file

<div class="modal fade details-1" id="details-<?php echo $product['id'];?>" tabindex="-1" role="dialog" aria-labelledby="details-1" aria-hidden="true">

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

<?php echo $product['title']?>

Detalles

<?php echo $product['description']?>

Precio :<?php echo $product['price']?>

Marca: N/A

     <form action="add_cart.php" method="post">

        Cantidad:
        <input type="text" class="form-control" id="quantity" name="quantity">

Disponibles: 3

       Size:<select name="size" id="size" class="form-control">
        <option value="36">36</option>
        <option value="40">40</option>
        <option value="50">50</option>
        <option value="30">30</option>
       </select>

     </form>

  <button class="btn btn-default" data-dismiss="modal">Cerrar</button>
  <button class="btn btn-warning" type="submit"> Agregar a Carrito</button>

```

Body:
So i have two files: index.php and details modal.php. In the index .php file I managed to create a dynamic  object that displays the title, price and image of a product that is stored in my database. That right there is perfect. As you can see in the image each product has a button that says Detalles (Details) which was generated dynamically.That button opens little window on top of the page(called detailsmodal.php). I want to show the data that is in there depending on the product that I chose. I have tried calling the data from the databse but it can only call the data of product one( meaning that if I click on product 2 it still shows the data of product 1) how can I fix that?
Here are some screenshots and my index.php and detailsmodal.php code.

In this image on the left is what is shown on detailsmodal.php

In this image on the left is what is shown on index.php.

index.php

<?php
require_once'core/init.php';
include'includes/head.php';
?>

<?php
include('includes/navigation.php');
?>

<?php
include('includes/headerfull.php');
?>

<?php
include('includes/leftbar.php');

?>
<?php
$sql =  "SELECT * FROM products WHERE featured = 1";
$featured= $db->query($sql);
?>

Main

Productos destacados

  <?php while($product= mysqli_fetch_assoc($featured)):?>

<?php echo $product['title']?>

   <img src="<?php echo $product['image']?>" id="producto2"   imagenProducto" alt=<?php echo $product['title']?> class="img-thumb" />

Precio del Mercado <s>₡<?php echo $product['list_price']?></s>

Nuestro precio: ₡<?php echo $product['price']?>

   <button type="button" class="btn butn-sm btn-success" data-toggle="modal" data-target="#details-1">Detalles</button>
   <?php include('includes/detailsmodal.php');?>

  <?php endwhile;?>

 <?php

?>

 <?php

include('includes/rightbar.php');
?>

 <?php
include('includes/footer.php');
?>

detailsmodal.php

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

<?php echo $product['title']?>

Detalles

<?php echo $product['description']?>

Precio :<?php echo $product['price']?>

Marca: N/A

     <form action="add_cart.php" method="post">

        Cantidad:
        <input type="text" class="form-control" id="quantity" name="quantity">

Disponibles: 3

       Size:<select name="size" id="size" class="form-control">
        <option value="36">36</option>
        <option value="40">40</option>
        <option value="50">50</option>
        <option value="30">30</option>
       </select>

     </form>

  <button class="btn btn-default" data-dismiss="modal">Cerrar</button>
  <button class="btn btn-warning" type="submit"> Agregar a Carrito</button>

Body:
Just because you have give all modal with same id so it will call always first modal with same id.Just look at updated code.

<?php
require_once'core/init.php';
include'includes/head.php';
?>
<!--Navegacion-->
<?php
include('includes/navigation.php');
?>
<!-- Cabecera-->
<?php
include('includes/headerfull.php');
?>
<!--left side bar-->
<?php
include('includes/leftbar.php');

?>
<?php
$sql =  "SELECT * FROM products WHERE featured = 1";
$featured= $db->query($sql);
?>

<!--Detalles-->

 <!--main content-->
 <div class="col-md-8">Main
 <div class="row">
  <h2 id="textoTitulo" class="text-center">Productos destacados</h2>
  <?php while($product= mysqli_fetch_assoc($featured)):?>

  <div class="col-md-3">
   <h4><?php echo $product['title']?></h4>
   <img src="<?php echo $product['image']?>" id="producto2"   imagenProducto" alt=<?php echo $product['title']?> class="img-thumb" />
   <p class="list-price text-danger">Precio del Mercado <s>₡<?php echo $product['list_price']?></s></p>
   <p class="price">Nuestro precio: ₡<?php echo $product['price']?></p>
   <button type="button" class="btn butn-sm btn-success" data-toggle="modal" data-target="#details-<?php echo $product['id'];?>">Detalles</button>
   <?php include('includes/detailsmodal.php');?>

  </div>
  <?php endwhile;?>

  </div>
 </div>
 <!--Detalles-->
 <?php

?>
<!--right-->
 <?php

include('includes/rightbar.php');
?>
 <!--pie-->
 <?php
include('includes/footer.php');
?>

//modal.php file

<div class="modal fade details-1" id="details-<?php echo $product['id'];?>" tabindex="-1" role="dialog" aria-labelledby="details-1" aria-hidden="true">
 <div class="modal-dialog modal-lg">
 <div class="modal-content">
  <div class="modal-header">
   <button class="close" type="button" data-dismiss="modal" arial-label="Close">
    <span aria-hidden="true">&times;</span>
   </button>
   <h4 class="modal-title text-center"><?php echo $product['title']?>

   </h4>
  </div>
  <div class="modal-body">
   <div class="container-fluid">
    <div class="row">
     <div class="col-sm-6">
      <div class="center-block">
       <img src="images/products/planta1.png" alt="Levis Jeans" id="viewProducto" class="details img-responsive">
      </div>
     </div>
     <div class="col-sm-6"></div>
     <h4>Detalles</h4>
     <p><?php echo $product['description']?></p>
     <hr>
     <p>Precio :<?php echo $product['price']?></p>
     <p>Marca: N/A</p>
     <form action="add_cart.php" method="post">
      <div class="form-group">
       <div class="col-xs-3">
        <label for="quantity">Cantidad:</label>
        <input type="text" class="form-control" id="quantity" name="quantity">
        <p>Disponibles: 3</p>
       <div class="form-group">
       <label for="size"></label>
       Size:<select name="size" id="size" class="form-control">
        <option value="36">36</option>
        <option value="40">40</option>
        <option value="50">50</option>
        <option value="30">30</option>
       </select>
      </div>

       </div>

      </div>

     </form>
    </div>
   </div>
  </div>
  <div class="modal-footer">
  <button class="btn btn-default" data-dismiss="modal">Cerrar</button>
  <button class="btn btn-warning" type="submit"><img class="cartPNG" src="images/logos/cart.png"> Agregar a Carrito</button>
 </div>
 </div>

 </div>
</div>


问:
Angular 2: sequence and parallel service calls
I came across a topic of sequence and parallel service calls. For sequence call, we can use flatmap/mergemap and for parallel calls, we can use forkjoin.

Below are my queries

1) what is the difference between flatmap and mergemap? Is there any specific reason to use either of it.

2) How do I add multiple sequences for 4-5 calls? what differentiates flatmap and mergemap If I use multiple subscribe?

```<code>this.service1.getCountry(
  .mergeMap(country => this.service1.getState(country[0]))
  .subscribe(state = > state.json());
);
</code>```

3) forkjoin is used to join multiple parallel service calls. what if I use a method and call multiple services in that method instead of using forkjoin. Any specific reason why to go with forkJoin

答:
flatMap === mergeMap. flatMap is simply alias to mergeMap operator. (https://github.com/ReactiveX/rxjs/blob/master/src/add/operator/mergeMap.ts#L5-L6) there are discussions to deprecate one alias, but so far in v5 both are available.

You may interested in concurrency param in mergeMap operator (https://github.com/ReactiveX/rxjs/blob/master/spec/operators/mergeMap-spec.ts#L308-L325) which subscribes multiple inner observable.

it depends on usecases. If supplied observable gauranteed to emit and wait for completion, forkJoin might be feasible. But if any of observable completes without emission, forkJoin will short-curcuit and completes. In opposite, mergeMap is more intended to flatten inner observable's emission into higher observable. So in case of forkJoin you'll get array of value emisssion for each innerobservables, while mergeMap will emit single values as soon as each inner observable emits.

Body:
I came across a topic of sequence and parallel service calls. For sequence call, we can use flatmap/mergemap and for parallel calls, we can use forkjoin.

Below are my queries

1) what is the difference between flatmap and mergemap? Is there any specific reason to use either of it.

2) How do I add multiple sequences for 4-5 calls? what differentiates flatmap and mergemap If I use multiple subscribe?

this.service1.getCountry(
  .mergeMap(country => this.service1.getState(country[0]))
  .subscribe(state = > state.json());
);

3) forkjoin is used to join multiple parallel service calls. what if I use a method and call multiple services in that method instead of using forkjoin. Any specific reason why to go with forkJoin


问:
Python turtle.Terminator error
When i am using turtle module to draw a circle with this simple function:

```<code>def draw_shape(self):
    canvas = Screen()
    t = Turtle()
    t.circle(self.r)
    canvas.exitonclick()
</code>```

For the first time when i call this function it opens a new window and draw a circle, i click on it to exit and when i try to again call this function from menu in console i got an error:

```<code>Original exception was:
Traceback (most recent call last):
  File "main.py", line 136, in <module>
    main()
  File "main.py", line 132, in main
    OPTIONS[user_input][1](shapes)
  File "main.py", line 48, in handle_sixth_menu_option
    t = Turtle()
  File "/usr/lib/python3.6/turtle.py", line 3816, in __init__
    visible=visible)
  File "/usr/lib/python3.6/turtle.py", line 2557, in __init__
    self._update()
  File "/usr/lib/python3.6/turtle.py", line 2660, in _update
    self._update_data()
  File "/usr/lib/python3.6/turtle.py", line 2646, in _update_data
    self.screen._incrementudc()
  File "/usr/lib/python3.6/turtle.py", line 1292, in _incrementudc
    raise Terminator
turtle.Terminator
</code>```

答:
You can try the following:

```<code>def draw_shape(self):
    import turtle as t
    canvas = Screen()
    t.circle(self.r)
    canvas.exitonclick()
</code>```

The reason your code wasn't working was because of the fact that you had already deleted or exited the instance of the turtle in the def function already once before by clicking on exit. Hence by using import turtle as t you are calling it again and creating a new instance.

Title: Python turtle.Terminator error

Body:
When i am using turtle module to draw a circle with this simple function:

def draw_shape(self):
    canvas = Screen()
    t = Turtle()
    t.circle(self.r)
    canvas.exitonclick()

For the first time when i call this function it opens a new window and draw a circle, i click on it to exit and when i try to again call this function from menu in console i got an error:

Original exception was:
Traceback (most recent call last):
  File "main.py", line 136, in <module>
    main()
  File "main.py", line 132, in main
    OPTIONS[user_input][1](shapes)
  File "main.py", line 48, in handle_sixth_menu_option
    t = Turtle()
  File "/usr/lib/python3.6/turtle.py", line 3816, in __init__
    visible=visible)
  File "/usr/lib/python3.6/turtle.py", line 2557, in __init__
    self._update()
  File "/usr/lib/python3.6/turtle.py", line 2660, in _update
    self._update_data()
  File "/usr/lib/python3.6/turtle.py", line 2646, in _update_data
    self.screen._incrementudc()
  File "/usr/lib/python3.6/turtle.py", line 1292, in _incrementudc
    raise Terminator
turtle.Terminator

Body:
You can try the following:

def draw_shape(self):
    import turtle as t
    canvas = Screen()
    t.circle(self.r)
    canvas.exitonclick()

The reason your code wasn't working was because of the fact that you had already deleted or exited the instance of the turtle in the def function already once before by clicking on exit. Hence by using import turtle as t you are calling it again and creating a new instance.


问:
How to speed up transition for bootstrap nav-collapse
Hi I have the following html code for bootstrap nav-collapse, Sometimes when I click on the menu it's takes time to open and when I click on the menu name it also takes time to close and sometimes it will stuck  and close by itself. Is it a bug or something else? I have applied transition to it.
I need it to be smooth when the click the menu, it should open smoothly and close smoothly. Is there anything i am missing in it?

I am using Internet Explorer as my browser

HTML:

```<code><div class="navbar">
  <div class="navbar-inner">
    <div class="container">
      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <a rel="nofollow" class="btn btn-navbar collapsed" data-toggle="collapse" data-target=".nav-collapse" title="Toggle menu">
        <span class="menu-name">Menu</span>
        <span class="menu-bars">
                    <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        </span>
      </a>
      <!-- Everything you want hidden at 940px or less, place within here -->
      <div class="nav-collapse collapse" style="height: 0px;">
        <ul class="nav" id="topMenu" data-submenu="horizontal">
          <li class=" active " style="">
            <a rel="nofollow" href="//ss-template-blog03.simplesite.com/434337774">FRONT PAGE</a>
          </li>
          <li class="  " style="">
            <a rel="nofollow" href="//ss-template-blog03.simplesite.com/434337775">BLOG</a>
          </li>
          <li class="  " style="">
            <a rel="nofollow" href="//ss-template-blog03.simplesite.com/434337777">CONTACT</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>
</code>```

CSS

```<code>.collapse {
  position: relative;
  height: 0px;
  overflow: hidden;
  -webkit-transition: height .100s ease;
  -moz-transition: height .35s ease;
  -o-transition: height .35s ease;
  transition: height .35s ease;
}
</code>```

My image of the menu:

答:
You can try the following code for your nav-collapse.

For more help on bootstrap nav-collapse read this Documentation

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

Link1

Link2

Link3

```

Body:
Hi I have the following html code for bootstrap nav-collapse, Sometimes when I click on the menu it's takes time to open and when I click on the menu name it also takes time to close and sometimes it will stuck  and close by itself. Is it a bug or something else? I have applied transition to it.
I need it to be smooth when the click the menu, it should open smoothly and close smoothly. Is there anything i am missing in it?

I am using Internet Explorer as my browser

HTML:

        Menu

            FRONT PAGE

            BLOG

            CONTACT

CSS

.collapse {
  position: relative;
  height: 0px;
  overflow: hidden;
  -webkit-transition: height .100s ease;
  -moz-transition: height .35s ease;
  -o-transition: height .35s ease;
  transition: height .35s ease;
}

My image of the menu:

Body:
You can try the following code for your nav-collapse.

For more help on bootstrap nav-collapse read this Documentation

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Brand</a>
    </div>
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Link1</a></li>
        <li><a href="#">Link2</a></li>
        <li><a href="#">Link3</a></li>
      </ul>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container-fluid -->
</nav>


问:
npm install getting failed for angular 2
I'm newbie to angular 2. From reading some resources I had done with the following steps for my angular 2 application.
1)Create a folder named "DemoThree".
2)From the command prompt taken a hit over "ng new ThirdApp"
ThirdApp is my application name. Even It got succeded.
Find the image below for successfully creation of application.

3)When I hit the command "npm start" I'm facing an error list in command prompt as like below image

4)From the errors, I understood that I'm not getting package.json file. How could I get that file ?

I had seen lot of commands related to getting package.json file, of them one is one is by using npm init.
But when I tried with init. It's asking to provide me all the values of keys like description, version, name,script,dependencies.

How to resolve my error list from the prompt ?

5)After facing that error I thought that I need to install anguar cli which get all dependencies by using npm install -g @angular/cli
Got succeeded here.

6)Again I tried with npm install. No use faced the same poin 3 error image.

Please suggest me where I was doing mistake.

答:
You need to change your directory cd ThirdApp before npm start

Rather use ng serve for running your application on port 4200


问:
How can I add background music in a windows form for c++?
I've tried a many different ways but nothing works.

I've already marked the windows media player option in the COM section, and I have the WMPLib library added.

```<code>using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace WMPLib;

namespace {
    bool turno =true; // true= X false = O
        int contador=0;
}
/// <summary>
/// Resumen de MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
    **WindowsMediaPlayer^ player = gcnew WindowsMediaPlayer();**
  //This is the problem i have an error in the equal sign
public:
    MyForm(void)
    {
        InitializeComponent();

    }
private: System::Void MyForm_Load(System::Object^  sender, System::EventArgs^  e) {

         }
</code>```

答:
The type is AxWindowsMediaPlayer, not WindowsMediaPlayer, that is why you get the error.

If you add the player in the form designer, you don’t need to create (genew) another instance, the designer has created one for you.

Then set the URL property, and then call play() method on the Ctlcontrols property to play the media.

```<code>this->axWindowsMediaPlayer1->URL = L"a.wma";
this->axWindowsMediaPlayer1->Ctlcontrols->play();
</code>```

Body:
I've tried a many different ways but nothing works.

I've already marked the windows media player option in the COM section, and I have the WMPLib library added.

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace WMPLib;

namespace {
    bool turno =true; // true= X false = O
        int contador=0;
}
///
/// Resumen de MyForm
///
public ref class MyForm : public System::Windows::Forms::Form
{
    **WindowsMediaPlayer^ player = gcnew WindowsMediaPlayer();**
  //This is the problem i have an error in the equal sign
public:
    MyForm(void)
    {
        InitializeComponent();

    }
private: System::Void MyForm_Load(System::Object^  sender, System::EventArgs^  e) {

         }

Body:
The type is AxWindowsMediaPlayer, not WindowsMediaPlayer, that is why you get the error.

If you add the player in the form designer, you don’t need to create (genew) another instance, the designer has created one for you.

Then set the URL property, and then call play() method on the Ctlcontrols property to play the media.

this->axWindowsMediaPlayer1->URL = L"a.wma";
this->axWindowsMediaPlayer1->Ctlcontrols->play();


问:
CSS background (svg/base64) gets stretched horizontally upon orientation change
I am trying to make a Phonegap application using HTML/CSS3/Jquery and JS.
I have made certain divs which have a background image (a css embedded base-64 encoded svg image). However, this background image gets stretched upon device orientation change. (from portrait to landscape).

i have set the following css properties:

```<code>#top-bar #settings {
    background: url(data:image/svg+xml;base64,[image_data]) no-repeat;
    background-size: 50% 50%;
    background-position: center;
    width: 10%;
    height: 100%;
    position: relative;
    float: right;
    right: 0;
}
</code>```

I have also observed that this behaviour is not visible in my desktop browsers or in certain other Android phones. My phone (where i see the problem is a Galaxy s3 rooted with cyanogen 10.1.3)

Is there any way to stop this from happening? I want the background to look same in any conditions.

答:
The problem are the relative attributes.

```<code>background-size: 50% 50%;

width: 10%;
height: 100%;
</code>```

Those give you different total sizes if the screens width & height is changing without keeping the aspect ratio!

Just keep the background width size at 50%. If no second size is set, it has the initial value "auto", which keeps the aspect ratio of the image.

```<code>background-size: 50%;
</code>```

This should solve your problem.

Body:
I am trying to make a Phonegap application using HTML/CSS3/Jquery and JS.
I have made certain divs which have a background image (a css embedded base-64 encoded svg image). However, this background image gets stretched upon device orientation change. (from portrait to landscape).

i have set the following css properties:

#top-bar #settings {
    background: url(data:image/svg+xml;base64,[image_data]) no-repeat;
    background-size: 50% 50%;
    background-position: center;
    width: 10%;
    height: 100%;
    position: relative;
    float: right;
    right: 0;
}

I have also observed that this behaviour is not visible in my desktop browsers or in certain other Android phones. My phone (where i see the problem is a Galaxy s3 rooted with cyanogen 10.1.3)

Is there any way to stop this from happening? I want the background to look same in any conditions.

Body:
The problem are the relative attributes.

background-size: 50% 50%;

width: 10%;
height: 100%;

Those give you different total sizes if the screens width & height is changing without keeping the aspect ratio!

Just keep the background width size at 50%. If no second size is set, it has the initial value "auto", which keeps the aspect ratio of the image.

background-size: 50%;

This should solve your problem.


问:
Asp.net MVC Razor not encoding html
My understanding is that the Razor markup will encode html strings, but I tried testing it out with following code in MVC view and it did not encode the html strings.

While the first encoded string is behaving correctly since its not handled by Razor engine, but the second string is not being encoded by Razor, and also the <> part at start in last string is not being encoded by Razor.

Question : Why are second and third strings not being encoded by Razor, or am I missing something about how Razor renders html strings?

Razor markup in a MVC View

```<code><script type="text/javascript"></script>
<br />
@("<script type='text/javascript'></script>")
<br />
@("<><script type="text/javascript"></script>")
</code>```

Rendering of above Razor markup

UPDATE 1

I believe that the following is happening, but not sure (that is, Razor is encoding stuff but its not obvious to user who sees the browser rendered version)

I think the line just after first br that starts with @ is being encoded by Razor and then the browser is decoding it. Also, the third line just after the second br is being encoded by Razor with the already encoded part being doubly encoded, so when browser decodes it, it remains singly encoded but the <> was single encoded so it gets decoded by browser to <>. Does that sound right?

UPDATE 2

When I looked up in Chrome dev tool the response output, it indeed showed that Razor was encoding the strings in parenthesis. The output in Chrome dev tool for the request is as below. So, what I mentioned in UPDATE 1 is what is actually happening. The last string is doubly encoded as the the > is appearing as >And the first string is singly encoded.

So, I was 100% correct in what I suspected was happening in UPDATE 1.

```<code><script type="text/javascript"></script>
<br />
<script type='text/javascript'></script>
<br />
<><script type="text/javascript"></script>
</code>```

答:
If you want to render string(which contains html) to your view as html not string than use @Html.Raw function

from MSDN @Html.Raw -- Returns markup that is not HTML encoded.

This will render html as text

```<code><script type="text/javascript"></script>
</code>```

This will render as html and parse as html document

```<code>@Html.Raw("<script type='text/javascript'></script>")
</code>```

This will render string as it is

```<code>@Html.Raw("<><script type="text/javascript"></script>")
</code>```

Please let me know if your query fix,

Title: Asp.net MVC Razor not encoding html

Body:
My understanding is that the Razor markup will encode html strings, but I tried testing it out with following code in MVC view and it did not encode the html strings.

While the first encoded string is behaving correctly since its not handled by Razor engine, but the second string is not being encoded by Razor, and also the <> part at start in last string is not being encoded by Razor.

Question : Why are second and third strings not being encoded by Razor, or am I missing something about how Razor renders html strings?

Razor markup in a MVC View

@("")

@("<>")

Rendering of above Razor markup

UPDATE 1

I believe that the following is happening, but not sure (that is, Razor is encoding stuff but its not obvious to user who sees the browser rendered version)

I think the line just after first br that starts with @ is being encoded by Razor and then the browser is decoding it. Also, the third line just after the second br is being encoded by Razor with the already encoded part being doubly encoded, so when browser decodes it, it remains singly encoded but the <> was single encoded so it gets decoded by browser to <>. Does that sound right?

UPDATE 2

When I looked up in Chrome dev tool the response output, it indeed showed that Razor was encoding the strings in parenthesis. The output in Chrome dev tool for the request is as below. So, what I mentioned in UPDATE 1 is what is actually happening. The last string is doubly encoded as the the > is appearing as &gt;And the first string is singly encoded.

So, I was 100% correct in what I suspected was happening in UPDATE 1.

<>&lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

Body:
If you want to render string(which contains html) to your view as html not string than use @Html.Raw function

from MSDN @Html.Raw -- Returns markup that is not HTML encoded.

This will render html as text

&lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

This will render as html and parse as html document

@Html.Raw("<script type='text/javascript'></script>")

This will render string as it is

@Html.Raw("<>&lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;")

Please let me know if your query fix,


问:
Upload_Path_Handler file path for Django ImageField cannot retrieve image in HTML file
I've attempted to use Upload_Path_Handler in order to allow for dynamic folder names (such as the upload date, item ID, etc.) in saving image files uploaded by users, so as to prevent duplicate instances.

The problem is that the directory which I've returned is too 'deep' to be retrieved through the HTML file, in that, it begins with the name of the app (in this case, 'vault'). The broken path served for the image in the HTML file is as follows:

```<code><img src="vault/static/vault/images/recordimages/r_1/2017-12-09_03-27-42/300x300.jpg">
</code>```

However, by using inspector element to exclude the app name 'vault' at the beginning, I am able to successfully retrieve the image:

```<code><img src="/static/vault/images/recordimages/r_1/2017-12-09_03-27-42/300x300.jpg">
</code>```

The broken path is served in the raw html file as:

```<code><img src="{{ record.w_image }}">
</code>```

And the model referenced, w_image, is as follows in models.py:

```<code>w_image = models.ImageField(null=False, blank=True, verbose_name='Record Image:', upload_to=upload_path_handler)
</code>```

Then, of course, is upload_path_handler:

```<code>def upload_path_handler(self, filename):
    return "vault/static/vault/images/recordimages/r_{id}/{date}/{file}".format(id=self.id, file=filename, date=datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S'))
</code>```

If I were to begin the return path at /static/, it would then instead save the images in WebsiteName/static/../.. as opposed to WebsiteName/vault/static/../.. (Remember, the aim here is to keep the /static/ directory a subdirectory of our app, 'vault')

How can I allow for the image to be retrievable without compromising on the path as a subdirectory of 'vault'?

答:
You should write image url, like this:</p>

```<code><img src="{{ record.w_image.url }}">
</code>```

Body:
I've attempted to use Upload_Path_Handler in order to allow for dynamic folder names (such as the upload date, item ID, etc.) in saving image files uploaded by users, so as to prevent duplicate instances.

The problem is that the directory which I've returned is too 'deep' to be retrieved through the HTML file, in that, it begins with the name of the app (in this case, 'vault'). The broken path served for the image in the HTML file is as follows:

However, by using inspector element to exclude the app name 'vault' at the beginning, I am able to successfully retrieve the image:

The broken path is served in the raw html file as:

And the model referenced, w_image, is as follows in models.py:

w_image = models.ImageField(null=False, blank=True, verbose_name='Record Image:', upload_to=upload_path_handler)

Then, of course, is upload_path_handler:

def upload_path_handler(self, filename):
    return "vault/static/vault/images/recordimages/r_{id}/{date}/{file}".format(id=self.id, file=filename, date=datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S'))

If I were to begin the return path at /static/, it would then instead save the images in WebsiteName/static/../.. as opposed to WebsiteName/vault/static/../.. (Remember, the aim here is to keep the /static/ directory a subdirectory of our app, 'vault')

How can I allow for the image to be retrievable without compromising on the path as a subdirectory of 'vault'?

Body:
You should write image url, like this:

<img src="{{ record.w_image.url }}">


问:
Javascript and the Django 'static' template tag
I've got a wee site set up to play some sounds a list of which are passed forward by my view. I'm going to go straight into the code:

```<code>var sounds = "{{js_sounds|escapejs}}";
sounds = JSON.parse(sounds);
var howls = {};

sounds.forEach(function(sound){
    howls[sound] = new Howl({
        src: ["{% static 'audio/"+sound+".mp3' %}"]
    });

    $(document).on('click', '#'+sound+'_btn_play', function(){
        howls[sound].play();
    });
    $(document).on('click', '#'+sound+'_btn_stop', function(){
        howls[sound].stop();
    });
}
</code>```

Not the neatest solution - the html template also creates a bunch of buttons and things for playing the sounds, which my Javascript references in those on click functions. I'm also using the Javascript Howler library to simplify the playing of the sounds.

Now, when I was testing this locally it worked perfectly, but after I deployed, a problem arose in the line src: ["{% static 'audio/"+sound+".mp3' %}"]. It seems like this is being executed weirdly, because rather than inserting the sound into the Django tag and executing it as one string, it seems to be executing it as: src: ["{% static 'audio/%22%2Bsound%2B%22.mp3' %}"], i.e. attempting to parse the "+ as part of the string.

I'm struggling to figure out why it's doing this when deployed but not locally. Also, any feedback on how to make this process better (perhaps not using template tags in Javascript, that doesn't feel right) would be much appreciated, but really I'm just looking for any way to pass this sound value to the tag in Javascript.

答:
The Django tags are evaluated by the server whilst the javascript is evaluated by the client browser. As a result the sound variable has not yet been determined when the static tag is executed.

One approach you could take is to iterate through sounds using a Django template for loop and store each static reference in a JSON dictionary. Then your javascript could lookup the required value from that:

```<code>var my_references = {
{% for sound in sounds %}
    "{{ sound }}":"{% static 'audio/"+sound+".mp3' %}",
{% endfor %}
};

...

src: [my_references[sound]]
</code>```

Body:
I've got a wee site set up to play some sounds a list of which are passed forward by my view. I'm going to go straight into the code:

var sounds = "{{js_sounds|escapejs}}";
sounds = JSON.parse(sounds);
var howls = {};

sounds.forEach(function(sound){
    howls[sound] = new Howl({
        src: ["{% static 'audio/"+sound+".mp3' %}"]
    });

    $(document).on('click', '#'+sound+'_btn_play', function(){
        howls[sound].play();
    });
    $(document).on('click', '#'+sound+'_btn_stop', function(){
        howls[sound].stop();
    });
}

Not the neatest solution - the html template also creates a bunch of buttons and things for playing the sounds, which my Javascript references in those on click functions. I'm also using the Javascript Howler library to simplify the playing of the sounds.

Now, when I was testing this locally it worked perfectly, but after I deployed, a problem arose in the line src: ["{% static 'audio/"+sound+".mp3' %}"]. It seems like this is being executed weirdly, because rather than inserting the sound into the Django tag and executing it as one string, it seems to be executing it as: src: ["{% static 'audio/%22%2Bsound%2B%22.mp3' %}"], i.e. attempting to parse the "+ as part of the string.

I'm struggling to figure out why it's doing this when deployed but not locally. Also, any feedback on how to make this process better (perhaps not using template tags in Javascript, that doesn't feel right) would be much appreciated, but really I'm just looking for any way to pass this sound value to the tag in Javascript.

Body:
The Django tags are evaluated by the server whilst the javascript is evaluated by the client browser. As a result the sound variable has not yet been determined when the static tag is executed.

One approach you could take is to iterate through sounds using a Django template for loop and store each static reference in a JSON dictionary. Then your javascript could lookup the required value from that:

var my_references = {
{% for sound in sounds %}
    "{{ sound }}":"{% static 'audio/"+sound+".mp3' %}",
{% endfor %}
};

...

src: [my_references[sound]]


问:
firebase with map activity app error crashes
I want to add Firebase to google map activity but I put the following code to anywhere in the main activity but it still crashes app both on emulator and actual mobile here the code for firebase

```<code>FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
</code>```

When I move these 2 lines the app work perfectly again and when I add these 2 line to different normal app works fine no problem
Here is my class name and definition:

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
           GoogleApiClient.ConnectionCallbacks,
           GoogleApiClient.OnConnectionFailedListener,
           LocationListener {
</code>```

thank you

答:
during the different version of dependency and firebase version.. check on:

```<code>enter code here
</code>```

compile 'com.google.firebase:firebase-database:11.4.2'

compile 'com.google.firebase:firebase-auth:11.4.2'

compile 'com.google.android.gms:play-services-maps:11.4.2'

Body:
I want to add Firebase to google map activity but I put the following code to anywhere in the main activity but it still crashes app both on emulator and actual mobile here the code for firebase

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

When I move these 2 lines the app work perfectly again and when I add these 2 line to different normal app works fine no problem
Here is my class name and definition:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
           GoogleApiClient.ConnectionCallbacks,
           GoogleApiClient.OnConnectionFailedListener,
           LocationListener {

thank you

Body:
during the different version of dependency and firebase version.. check on:

enter code here

compile 'com.google.firebase:firebase-database:11.4.2'

compile 'com.google.firebase:firebase-auth:11.4.2'

compile 'com.google.android.gms:play-services-maps:11.4.2'


问:
FullCalendar does not apply css on changeView in Vaadin framework
I'm building a calendar plugin for Vaadin (see https://vaadin.com/). Everythng works fine, the stylesheets are applied EXCEPT when I programatically change the view. The view changes but the Fullcalendar styles do not apply correctly! See sample screenshot.List View after changeView called

I need to hit refresh for the styles to apply correctly.

(If I just change the view using the full calendar 'built in' buttons at the top right, the styles are applied.)
Using FullCalendar V3.7.0 and and Scheduler trial 1.9.0

Vaadin is a GWT framework,  using V6.8.

GWT code for calling changeView:

```<code>private native void changeView(JavaScriptObject cal,String view,String nid)
/*-{
    cal.fullCalendar("changeView",view);
    //cal.trigger( "create" ); trying to fix the not-applying .css problem
}-*/;
</code>```

'cal' is the original selector returned by jQuery.
Any ideas how to fix this?

答: Found the problem. It was due to the Vaadin framework removing FC's style class from the topmost element. To fix, I simply added these back using the framework's setStyleName("fc fc-unthemed fc-ltr");.</p>

Body:
I'm building a calendar plugin for Vaadin (see https://vaadin.com/). Everythng works fine, the stylesheets are applied EXCEPT when I programatically change the view. The view changes but the Fullcalendar styles do not apply correctly! See sample screenshot.List View after changeView called

I need to hit refresh for the styles to apply correctly.

(If I just change the view using the full calendar 'built in' buttons at the top right, the styles are applied.)
Using FullCalendar V3.7.0 and and Scheduler trial 1.9.0

Vaadin is a GWT framework,  using V6.8.

GWT code for calling changeView:

private native void changeView(JavaScriptObject cal,String view,String nid)
/*-{
    cal.fullCalendar("changeView",view);
    //cal.trigger( "create" ); trying to fix the not-applying .css problem
}-*/;

'cal' is the original selector returned by jQuery.
Any ideas how to fix this?


问:
how do i read two bytes in correct order from serial port using win32 api?

I am using using win32 api, visual studio 2008. i am able to read bytes from serial port but not the way i intend it to be, I am passing in data from arduino in x,y format. But my code below sometimes read y first then x. How can i read data in the correct order, i mean in x,y order. in case anyone is interested coordinates will be passed to another function and mouse cursor will be move accordingly. Here is my code:

```<code>int _tmain( int argc, TCHAR *argv[] )

{
    HANDLE hComm;
    DWORD bytesRead = 0;
    POINT mouseCoords;  /*structur to hold mouse coordinates*/
    DCB dcb = {0};      /*Device Control Block, used to configure serial port settings
                          here we initialize dcb structure to zero. Good practice!*/
    COMMTIMEOUTS ct;

    int loop = 1;
    int counter = 10;

    /*get handle to serial port*/
    hComm = CreateFile(g_pcCommPort,
                       GENERIC_WRITE | GENERIC_READ,
                       0,                           /* must be opened with exclusive-access */
                       NULL,                        /* default security attributes*/
                       OPEN_EXISTING,               /*  must use OPEN_EXISTING for serial ports*/
                       0,                           /*non overlapped I/O, blocking*/
                       NULL );                      /*hTemplate must be NULL for comm devices*/

    /*Make sure that serial port is successfuly opened*/
    if ( hComm == INVALID_HANDLE_VALUE ) {
            errMsg(TEXT("Cannot access serial port!"));
        return 0;
    }

    ASSERT("Serial port access successful!");

    /*get serial port status i.e default settings and make
      sure we can access them*/
    if ( !(GetCommState(hComm, &dcb))) {
        errMsg(TEXT("Cannot access current DCB settings!"));
        return 0;
    }

    ASSERT("DCB settings access successful!");

    /*print dcb settings so that we can get an idea of default settings*/
    printCommSettings(dcb);

    /*Since we were successful in accessing the com port
      we can go ahead and set it manually to our desired
      settings*/
    if ( !(setupSerialPort(&dcb))) {
        errMsg(TEXT("Cannot setup serial port!"));
        return 0;
    }

    ASSERT("DCB config successful!");

    /*lets print configuration after setting up the
      serial port just to make sure everything is ok*/
    printCommSettings(dcb);

    ct.ReadIntervalTimeout = 50;
    ct.ReadTotalTimeoutConstant = 50;
    ct.ReadTotalTimeoutMultiplier = 10;
    ct.WriteTotalTimeoutConstant = 50;
    ct.WriteTotalTimeoutMultiplier = 10;

    if(SetCommTimeouts(hComm, &ct) == 0) {
         errMsg(TEXT("Cannot setup comm timout!"));
    }

while (loop)
{
  if ( !(ReadFile(hComm,g_buffer,5,&bytesRead,NULL)) ) {    loop = 0; }
    printf("Message Read: %s==%d\r", g_buffer, bytesRead);

} /*while loop*/

    if ( !(CloseHandle(hComm))) {
        errMsg(TEXT("Serial port handle error!"));
    }

    NEWLINE;

    return 0;
}
</code>```

EDIT:
these are serial port settings:
"9600,N,8,1"

I am passing in 10,12 and this is what i am getting:
OUTPUT:

Message Read: ,12

Message Read: 10,12

Message Read: 12

Message Read: 0,12

Message Read: 2

Message Read: ,12

Message Read: 10,12

Message Read: 12

Message Read: 0,12

Message Read: 2

Message Read: ,12

Message Read: 10,12

答:
It looks like you figured out that you're not passing two bytes across the serial port, but in fact you're sending ASCII. And based on your sample output, I don't see the Y coming in before the X (that would show up as 12,10 instead of 10,12.

What's actually happening is that the reads are not always completing when you expect them to. You get part of the message in one read and the next part in the next read.

What you need to do is synchronize the transmission with some character(s) not found in your message text. For example, if you sent (10,12) then you would know that the ( was the start of your numbers and ) was the end. That way you could read enough characters in your buffer until you had a ( followed by a ) then parse the characters between them, and discard the part of the buffer ending in the ) character.

Body:
I am using using win32 api, visual studio 2008. i am able to read bytes from serial port but not the way i intend it to be, I am passing in data from arduino in x,y format. But my code below sometimes read y first then x. How can i read data in the correct order, i mean in x,y order. in case anyone is interested coordinates will be passed to another function and mouse cursor will be move accordingly. Here is my code:

int _tmain( int argc, TCHAR *argv[] )

{
    HANDLE hComm;
    DWORD bytesRead = 0;
    POINT mouseCoords;  /*structur to hold mouse coordinates*/
    DCB dcb = {0};      /*Device Control Block, used to configure serial port settings
                          here we initialize dcb structure to zero. Good practice!*/
    COMMTIMEOUTS ct;

    int loop = 1;
    int counter = 10;

    /*get handle to serial port*/
    hComm = CreateFile(g_pcCommPort,
                       GENERIC_WRITE | GENERIC_READ,
                       0,                           /* must be opened with exclusive-access */
                       NULL,                        /* default security attributes*/
                       OPEN_EXISTING,               /*  must use OPEN_EXISTING for serial ports*/
                       0,                           /*non overlapped I/O, blocking*/
                       NULL );                      /*hTemplate must be NULL for comm devices*/

    /*Make sure that serial port is successfuly opened*/
    if ( hComm == INVALID_HANDLE_VALUE ) {
            errMsg(TEXT("Cannot access serial port!"));
        return 0;
    }

    ASSERT("Serial port access successful!");

    /*get serial port status i.e default settings and make
      sure we can access them*/
    if ( !(GetCommState(hComm, &dcb))) {
        errMsg(TEXT("Cannot access current DCB settings!"));
        return 0;
    }

    ASSERT("DCB settings access successful!");

    /*print dcb settings so that we can get an idea of default settings*/
    printCommSettings(dcb);

    /*Since we were successful in accessing the com port
      we can go ahead and set it manually to our desired
      settings*/
    if ( !(setupSerialPort(&dcb))) {
        errMsg(TEXT("Cannot setup serial port!"));
        return 0;
    }

    ASSERT("DCB config successful!");

    /*lets print configuration after setting up the
      serial port just to make sure everything is ok*/
    printCommSettings(dcb);

    ct.ReadIntervalTimeout = 50;
    ct.ReadTotalTimeoutConstant = 50;
    ct.ReadTotalTimeoutMultiplier = 10;
    ct.WriteTotalTimeoutConstant = 50;
    ct.WriteTotalTimeoutMultiplier = 10;

    if(SetCommTimeouts(hComm, &ct) == 0) {
         errMsg(TEXT("Cannot setup comm timout!"));
    }

while (loop)
{
  if ( !(ReadFile(hComm,g_buffer,5,&bytesRead,NULL)) ) {    loop = 0; }
    printf("Message Read: %s==%d\r", g_buffer, bytesRead);

} /*while loop*/

    if ( !(CloseHandle(hComm))) {
        errMsg(TEXT("Serial port handle error!"));
    }

    NEWLINE;

    return 0;
}

EDIT:
these are serial port settings:
"9600,N,8,1"

I am passing in 10,12 and this is what i am getting:
OUTPUT:

Message Read: ,12

Message Read: 10,12

Message Read: 12

Message Read: 0,12

Message Read: 2

Message Read: ,12

Message Read: 10,12

Message Read: 12

Message Read: 0,12

Message Read: 2

Message Read: ,12

Message Read: 10,12